From 9e6598e05421f759a09f1d80dd270dd7cbef6c1f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:17:39 -0800 Subject: [PATCH 001/104] fix(db): declare and restore the workflow_edges block FK indexes Deleting a workflow_blocks row runs two ON DELETE CASCADE lookups on workflow_edges (WHERE source_block_id = $1 / target_block_id = $1). Only the composite (workflow_id, *_block_id) indexes are declared, and they cannot serve that lookup, so a database without 0043's single-column fk_idx pair seq-scans the whole edges table twice per deleted block inside the workflow row lock. Schema-pushed databases never get the pair, and a drifted one can lose it: a 700-block delete against 164k edges takes 7.5 s locally without the indexes and 8 ms with them. Declare both indexes in schema.ts and add a concurrent, replay-safe migration that is a no-op where they already exist. --- .../0467_workflow_edges_block_fk_indexes.sql | 39 + .../db/migrations/meta/0467_snapshot.json | 36209 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 9 +- packages/db/schema.ts | 7 + 4 files changed, 36263 insertions(+), 1 deletion(-) create mode 100644 packages/db/migrations/0467_workflow_edges_block_fk_indexes.sql create mode 100644 packages/db/migrations/meta/0467_snapshot.json diff --git a/packages/db/migrations/0467_workflow_edges_block_fk_indexes.sql b/packages/db/migrations/0467_workflow_edges_block_fk_indexes.sql new file mode 100644 index 00000000000..84b8759bc05 --- /dev/null +++ b/packages/db/migrations/0467_workflow_edges_block_fk_indexes.sql @@ -0,0 +1,39 @@ +-- Restores the single-column indexes on workflow_edges(source_block_id) and (target_block_id). +-- +-- Both block-id columns reference workflow_blocks(id) ON DELETE CASCADE, so Postgres looks up +-- `WHERE source_block_id = $1` and `WHERE target_block_id = $1` once per deleted block. The +-- composite (workflow_id, *_block_id) indexes cannot serve that lookup, so a database without +-- these seq-scans the whole edges table twice per deleted block, inside the transaction that holds +-- the workflow row lock. 0043 created both indexes but schema.ts never declared them, so databases +-- built from the schema (and any that drifted) lack them; IF NOT EXISTS keeps this a no-op where +-- 0043's indexes survive. +-- +-- Replay-safety: as 0463. workflow_edges is hot, so the builds are CONCURRENTLY below an embedded +-- COMMIT, and a replay moves only an INVALID index left by a failed build aside to be dropped, +-- keeping a valid one. +DO $$ +DECLARE + idx text; +BEGIN + FOREACH idx IN ARRAY ARRAY['workflow_edges_source_block_fk_idx', 'workflow_edges_target_block_fk_idx'] LOOP + IF EXISTS ( + SELECT 1 FROM pg_index WHERE indexrelid = to_regclass(idx || '_failed') + AND (indisvalid OR indrelid <> to_regclass('workflow_edges')) + ) THEN + RAISE EXCEPTION 'Refusing to drop unexpected recovery index %', idx || '_failed'; + END IF; + IF EXISTS ( + SELECT 1 FROM pg_index WHERE indexrelid = to_regclass(idx) + AND indrelid = to_regclass('workflow_edges') AND NOT indisvalid + ) THEN + EXECUTE format('ALTER INDEX %I RENAME TO %I', idx, idx || '_failed'); + END IF; + END LOOP; +END $$;--> statement-breakpoint +COMMIT;--> statement-breakpoint +SET lock_timeout = 0;--> statement-breakpoint +DROP INDEX CONCURRENTLY IF EXISTS "workflow_edges_source_block_fk_idx_failed";--> statement-breakpoint +DROP INDEX CONCURRENTLY IF EXISTS "workflow_edges_target_block_fk_idx_failed";--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "workflow_edges_source_block_fk_idx" ON "workflow_edges" USING btree ("source_block_id");--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "workflow_edges_target_block_fk_idx" ON "workflow_edges" USING btree ("target_block_id");--> statement-breakpoint +SET lock_timeout = '5s'; diff --git a/packages/db/migrations/meta/0467_snapshot.json b/packages/db/migrations/meta/0467_snapshot.json new file mode 100644 index 00000000000..461b514a3b4 --- /dev/null +++ b/packages/db/migrations/meta/0467_snapshot.json @@ -0,0 +1,36209 @@ +{ + "id": "290a9786-74fe-45a6-83f4-654ec9be5d6f", + "prevId": "07d41644-bec7-4c3d-b3f7-427c697db700", + "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": {} + }, + "credential_personal_token_identity_unique": { + "name": "credential_personal_token_identity_unique", + "columns": [ + { + "expression": "workspace_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": "type = 'personal_token'", + "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 + }, + "whitelabel_settings": { + "name": "whitelabel_settings", + "type": "json", + "primaryKey": false, + "notNull": 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.waitlist": { + "name": "waitlist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "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()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "waitlist_email_unique": { + "name": "waitlist_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "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_dispatch_queue": { + "name": "workspace_file_search_dispatch_queue", + "schema": "", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "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": { + "workspace_file_search_dispatch_queue_schedule_idx": { + "name": "workspace_file_search_dispatch_queue_schedule_idx", + "columns": [ + { + "expression": "last_dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "first" + }, + { + "expression": "enqueued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_queue_workspace_fk": { + "name": "workspace_file_search_queue_workspace_fk", + "tableFrom": "workspace_file_search_dispatch_queue", + "tableTo": "workspace", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.workspace_file_search_index": { + "name": "workspace_file_search_index", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "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'" + }, + "partial": { + "name": "partial", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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 + }, + "dispatched_at": { + "name": "dispatched_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": { + "workspace_file_search_index_workspace_status_idx": { + "name": "workspace_file_search_index_workspace_status_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_content_updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_index_pending_dispatch_idx": { + "name": "workspace_file_search_index_pending_dispatch_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_index\".\"status\" = 'pending' AND \"workspace_file_search_index\".\"dispatched_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_index_active_dispatch_idx": { + "name": "workspace_file_search_index_active_dispatch_idx", + "columns": [ + { + "expression": "workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dispatched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"workspace_file_search_index\".\"status\" = 'pending' AND \"workspace_file_search_index\".\"dispatched_at\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_index_file_fk": { + "name": "workspace_file_search_index_file_fk", + "tableFrom": "workspace_file_search_index", + "tableTo": "workspace_files", + "columnsFrom": [ + "file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_index_workspace_fk": { + "name": "workspace_file_search_index_workspace_fk", + "tableFrom": "workspace_file_search_index", + "tableTo": "workspace", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_index_pk": { + "name": "workspace_file_search_index_pk", + "columns": [ + "file_id", + "source_content_updated_at" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "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_search_segment": { + "name": "workspace_file_search_segment", + "schema": "", + "columns": { + "file_id": { + "name": "file_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_content_updated_at": { + "name": "source_content_updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "line_number": { + "name": "line_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "segment_number": { + "name": "segment_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "segment_start": { + "name": "segment_start", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "line_length": { + "name": "line_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "workspace_file_search_segment_workspace_revision_idx": { + "name": "workspace_file_search_segment_workspace_revision_idx", + "columns": [ + { + "expression": "workspace_id", + "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, + "concurrently": false, + "method": "btree", + "with": {} + }, + "workspace_file_search_segment_workspace_content_trgm_idx": { + "name": "workspace_file_search_segment_workspace_content_trgm_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": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": { + "workspace_file_search_segment_file_fk": { + "name": "workspace_file_search_segment_file_fk", + "tableFrom": "workspace_file_search_segment", + "tableTo": "workspace_files", + "columnsFrom": [ + "file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_file_search_segment_workspace_fk": { + "name": "workspace_file_search_segment_workspace_fk", + "tableFrom": "workspace_file_search_segment", + "tableTo": "workspace", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_file_search_segment_pk": { + "name": "workspace_file_search_segment_pk", + "columns": [ + "file_id", + "source_content_updated_at", + "line_number", + "segment_number" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "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 + } + }, + "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": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index f9987538a97..de42422c078 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3263,6 +3263,13 @@ "when": 1795086561892, "tag": "0466_workspace_source", "breakpoints": true + }, + { + "idx": 467, + "version": "7", + "when": 1795151802047, + "tag": "0467_workflow_edges_block_fk_indexes", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/packages/db/schema.ts b/packages/db/schema.ts index 7d1c3189736..b36ab1d045b 100644 --- a/packages/db/schema.ts +++ b/packages/db/schema.ts @@ -555,6 +555,13 @@ export const workflowEdges = pgTable( table.workflowId, table.targetBlockId ), + /** + * Serve the `ON DELETE CASCADE` lookups (`WHERE source_block_id = $1`) Postgres runs once + * per deleted `workflow_blocks` row; the composite indexes above lead with `workflow_id` + * and cannot, so without these every deleted block seq-scans the whole edges table. + */ + sourceBlockFkIdx: index('workflow_edges_source_block_fk_idx').on(table.sourceBlockId), + targetBlockFkIdx: index('workflow_edges_target_block_fk_idx').on(table.targetBlockId), }) ) From 3a63bf00064f31cb8cb7f1d09b836a75a4fe1ff8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:11:21 -0800 Subject: [PATCH 002/104] perf(workflow-persistence): save the normalized graph as a diff saveWorkflowToNormalizedTables deleted every block, edge and subflow of the workflow and re-inserted them all, so a one-field edit paid a delete (and its foreign-key cascade checks) per stored block inside the workflow row lock that source apply, operations apply and Copilot edits hold. Read the stored rows FOR UPDATE (the rows the delete locked), diff them by id against the new state, and write only the difference: unchanged rows are left alone with their timestamps, changed rows are rewritten in one confined upsert per table, new ids are plain inserts (so an id another workflow owns still fails with the unique violation callers map to a conflict), and removed rows are deleted after edges are retargeted. The resulting rows are the ones the full replace left, and the signature is unchanged for every caller. The integration suite saves random edit sequences both ways and compares the rows, and proves a one-field edit rewrites one block. bench-normalized-save measures edit, shrink and grow at 5/50/300/700 blocks: a one-field edit at 700 blocks drops from 40 ms to 10 ms with the edge FK indexes, and from 10.5 s to 10 ms without them. --- .../normalized-save.integration.ts | 299 ++++++++++++++++++ apps/sim/scripts/bench-normalized-save.ts | 185 +++++++++++ packages/workflow-persistence/src/save.ts | 299 +++++++++++++----- 3 files changed, 709 insertions(+), 74 deletions(-) create mode 100644 apps/sim/lib/workflows/persistence/normalized-save.integration.ts create mode 100644 apps/sim/scripts/bench-normalized-save.ts diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts new file mode 100644 index 00000000000..2354fd84143 --- /dev/null +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -0,0 +1,299 @@ +/** + * The normalized-table save against real Postgres. It writes only the difference between the + * stored graph and the new one, and must leave exactly the rows a delete-all and re-insert would: + * random edit sequences (add, remove, modify, move into a subflow, retarget and drop edges, replace a block + * under the edges it keeps) are + * saved both ways and the rows compared. A one-field edit rewrites one row, and an id owned by another + * workflow is still refused with the unique violation callers map to a conflict. + */ +import { db } from '@sim/db' +import { user, workflow, workflowBlocks, workflowEdges, workflowSubflows } from '@sim/db/schema' +import { getPostgresErrorCode } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { DbOrTx } from '@sim/workflow-persistence/types' +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { asc, eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +const ownerId = generateId() + +/** Deterministic PRNG (mulberry32) so a failing sequence replays from its seed. */ +function seededRandom(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function functionBlock(id: string, name: string, x: number, parentId?: string): BlockState { + return { + id, + type: 'function', + name, + position: { x, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: { code: { id: 'code', type: 'code', value: `return '${name}'` } }, + data: parentId ? { parentId, extent: 'parent' } : {}, + } +} + +function containerBlock(id: string, type: 'loop' | 'parallel', name: string): BlockState { + return { + id, + type, + name, + position: { x: 0, y: 400 }, + enabled: true, + outputs: {}, + subBlocks: {}, + data: type === 'loop' ? { loopType: 'for', count: 3 } : { parallelType: 'count', count: 2 }, + } +} + +function stateOf(blocks: BlockState[], edges: WorkflowState['edges']): WorkflowState { + return { + blocks: Object.fromEntries(blocks.map((block) => [block.id, block])), + edges, + loops: {}, + parallels: {}, + } +} + +async function insertWorkflow(): Promise { + const id = generateId() + const now = new Date() + await db.insert(workflow).values({ + id, + userId: ownerId, + name: 'Normalized save fixture', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + return id +} + +/** Every stored row of the workflow except the database-stamped timestamps, ordered by id. */ +async function storedRows(executor: DbOrTx, workflowId: string) { + const [blocks, edges, subflows] = await Promise.all([ + executor + .select() + .from(workflowBlocks) + .where(eq(workflowBlocks.workflowId, workflowId)) + .orderBy(asc(workflowBlocks.id)), + executor + .select() + .from(workflowEdges) + .where(eq(workflowEdges.workflowId, workflowId)) + .orderBy(asc(workflowEdges.id)), + executor + .select() + .from(workflowSubflows) + .where(eq(workflowSubflows.workflowId, workflowId)) + .orderBy(asc(workflowSubflows.id)), + ]) + return { + blocks: blocks.map(({ createdAt, updatedAt, ...row }) => row), + edges: edges.map(({ createdAt, ...row }) => row), + subflows: subflows.map(({ createdAt, updatedAt, ...row }) => row), + } +} + +async function blockUpdatedAt(workflowId: string): Promise> { + const rows = await db + .select({ id: workflowBlocks.id, updatedAt: workflowBlocks.updatedAt }) + .from(workflowBlocks) + .where(eq(workflowBlocks.workflowId, workflowId)) + return new Map(rows.map((row) => [row.id, row.updatedAt.getTime()])) +} + +/** The rows the delete-all and re-insert save left: clear the graph, then save into it. */ +async function fullReplaceRows(workflowId: string, state: WorkflowState) { + return db.transaction(async (tx) => { + await tx.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) + await tx.delete(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)) + await tx.delete(workflowSubflows).where(eq(workflowSubflows.workflowId, workflowId)) + expect(await saveWorkflowToNormalizedTables(workflowId, state, tx)).toEqual({ success: true }) + return storedRows(tx, workflowId) + }) +} + +/** One random edit of the kinds a source apply, operations apply or Copilot edit makes. */ +function mutate(state: WorkflowState, random: () => number): WorkflowState { + const blocks = Object.values(state.blocks).map((block) => structuredClone(block)) + let edges = state.edges.map((edge) => ({ ...edge })) + const pick = (items: T[]): T | undefined => items[Math.floor(random() * items.length)] + const functions = blocks.filter((block) => block.type === 'function') + const containers = blocks.filter((block) => block.type !== 'function') + const edit = Math.floor(random() * 10) + + if (edit === 0 || functions.length < 2) { + const id = generateId() + blocks.push(functionBlock(id, `Block ${id.slice(0, 6)}`, Math.floor(random() * 2000))) + } else if (edit === 1) { + const removed = pick(blocks) + if (removed) { + const gone = new Set([ + removed.id, + ...blocks.filter((b) => b.data?.parentId === removed.id).map((b) => b.id), + ]) + edges = edges.filter((edge) => !gone.has(edge.source) && !gone.has(edge.target)) + return stateOf( + blocks.filter((block) => !gone.has(block.id)), + edges + ) + } + } else if (edit === 9) { + const replaced = pick(functions) + if (replaced) { + const replacement = functionBlock(generateId(), replaced.name, replaced.position.x) + for (const edge of edges) { + if (edge.source === replaced.id) edge.source = replacement.id + if (edge.target === replaced.id) edge.target = replacement.id + } + return stateOf([...blocks.filter((block) => block !== replaced), replacement], edges) + } + } else if (edit === 2) { + const target = pick(functions) + if (target) target.subBlocks.code = { id: 'code', type: 'code', value: `return ${random()}` } + } else if (edit === 3) { + const target = pick(blocks) + if (target) target.position = { x: Math.floor(random() * 2000), y: Math.floor(random() * 900) } + } else if (edit === 4) { + const child = pick(functions) + const container = pick(containers) + if (child && container) child.data = { parentId: container.id, extent: 'parent' } + else if (child) child.data = {} + } else if (edit === 5) { + const id = generateId() + blocks.push(containerBlock(id, random() < 0.5 ? 'loop' : 'parallel', `Group ${id.slice(0, 6)}`)) + } else if (edit === 6) { + const source = pick(blocks) + const target = pick(blocks) + if (source && target && source.id !== target.id) { + edges.push({ id: generateId(), source: source.id, target: target.id }) + } + } else if (edit === 7) { + const edge = pick(edges) + const target = pick(blocks) + if (edge && target && target.id !== edge.source) { + edge.target = target.id + edge.sourceHandle = random() < 0.5 ? 'error' : undefined + } + } else { + const dropped = pick(edges) + edges = edges.filter((edge) => edge !== dropped) + const renamed = pick(blocks) + if (renamed) { + renamed.name = `${renamed.name}!` + renamed.enabled = !renamed.enabled + } + } + return stateOf(blocks, edges) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Normalized save fixture', + email: `${ownerId}@normalized-save.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) +}) + +afterAll(async () => { + await db.delete(user).where(eq(user.id, ownerId)) +}) + +describe('saveWorkflowToNormalizedTables', () => { + it.each([1, 2, 3, 4])( + 'leaves the rows a full replace leaves across random edit sequences (seed %i)', + async (seed) => { + const random = seededRandom(seed) + const workflowId = await insertWorkflow() + const loopId = generateId() + let state = stateOf( + [ + containerBlock(loopId, 'loop', 'Loop'), + ...Array.from({ length: 12 }, (_, index) => + functionBlock( + generateId(), + `Seed ${index}`, + index * 100, + index < 3 ? loopId : undefined + ) + ), + ], + [] + ) + expect(await saveWorkflowToNormalizedTables(workflowId, state)).toEqual({ success: true }) + + for (let step = 0; step < 40; step++) { + state = mutate(state, random) + expect(await saveWorkflowToNormalizedTables(workflowId, state)).toEqual({ success: true }) + const diffed = await storedRows(db, workflowId) + expect(diffed, `seed ${seed} step ${step}`).toEqual( + await fullReplaceRows(workflowId, state) + ) + } + } + ) + + it('rewrites only the block a one-field edit changed', async () => { + const workflowId = await insertWorkflow() + const blocks = Array.from({ length: 20 }, (_, index) => + functionBlock(generateId(), `Block ${index}`, index * 100) + ) + const edges = blocks + .slice(1) + .map((block, index) => ({ id: generateId(), source: blocks[index].id, target: block.id })) + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, edges))).toEqual({ + success: true, + }) + const before = await blockUpdatedAt(workflowId) + + const edited = structuredClone(blocks) + edited[7].subBlocks.code = { id: 'code', type: 'code', value: 'return 42' } + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(edited, edges))).toEqual({ + success: true, + }) + + const after = await blockUpdatedAt(workflowId) + const rewritten = [...after].filter(([id, at]) => before.get(id) !== at).map(([id]) => id) + expect(rewritten).toEqual([edited[7].id]) + }) + + it('refuses a block id another workflow owns and leaves the stored graph as it was', async () => { + const owner = await insertWorkflow() + const workflowId = await insertWorkflow() + const claimed = functionBlock(generateId(), 'Claimed', 0) + const kept = functionBlock(generateId(), 'Kept', 0) + expect(await saveWorkflowToNormalizedTables(owner, stateOf([claimed], []))).toEqual({ + success: true, + }) + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf([kept], []))).toEqual({ + success: true, + }) + const before = await storedRows(db, workflowId) + + const refused = await db + .transaction((tx) => saveWorkflowToNormalizedTables(workflowId, stateOf([claimed], []), tx)) + .then( + () => undefined, + (error: unknown) => error + ) + + expect(getPostgresErrorCode(refused)).toBe('23505') + expect(await storedRows(db, workflowId)).toEqual(before) + expect((await storedRows(db, owner)).blocks.map((block) => block.name)).toEqual(['Claimed']) + }) +}) diff --git a/apps/sim/scripts/bench-normalized-save.ts b/apps/sim/scripts/bench-normalized-save.ts new file mode 100644 index 00000000000..df26ce8bd17 --- /dev/null +++ b/apps/sim/scripts/bench-normalized-save.ts @@ -0,0 +1,185 @@ +#!/usr/bin/env bun +/** + * Benchmarks `saveWorkflowToNormalizedTables`, the write every draft replace (source apply, + * operations apply, Copilot edits) runs inside the workflow row lock. For each graph size it + * times a one-field edit, a shrink to 10 blocks and a grow back, against a disposable test + * database. Measurement only: nothing asserts on timings. + * + * Usage (from apps/sim): + * DATABASE_URL=postgresql://127.0.0.1:5432/sim_bench_test \ + * BENCH_REPORT_PATH=/tmp/save-bench.json bun scripts/bench-normalized-save.ts [--background-edges 160000] + * + * `--background-edges` seeds other workflows' edges first, so foreign-key cascade lookups that + * lack an index pay a realistic table scan. Fixtures are removed at the end. + */ +import { writeFile } from 'node:fs/promises' +import { parseArgs } from 'node:util' +import { db, user, workflow, workflowBlocks, workflowEdges } from '@sim/db' +import { assertDisposableTestDatabaseUrl } from '@sim/db/testing/test-infrastructure' +import { createLogger } from '@sim/logger' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq, sql } from 'drizzle-orm' + +const logger = createLogger('BenchNormalizedSave') + +const SIZES = [5, 50, 300, 700] +const REPEATS = 5 +const SHRUNK_SIZE = 10 + +interface BenchRow { + blocks: number + oneFieldEditMs: number + shrinkMs: number + growMs: number +} + +function graph(size: number): WorkflowState { + const blocks: BlockState[] = [] + let loopId: string | undefined + for (let index = 0; index < size; index++) { + const id = generateId() + if (index % 7 === 0) { + loopId = id + blocks.push({ + id, + type: 'loop', + name: `Loop ${index}`, + position: { x: index * 50, y: 400 }, + enabled: true, + outputs: {}, + subBlocks: {}, + data: { loopType: 'for', count: 3 }, + }) + continue + } + blocks.push({ + id, + type: index % 2 ? 'function' : 'agent', + name: `Block ${index}`, + position: { x: index * 50, y: 0 }, + enabled: true, + outputs: { result: { type: 'json' } }, + subBlocks: { + code: { id: 'code', type: 'code', value: `return ${index}` }, + prompt: { id: 'prompt', type: 'long-input', value: `Step ${index} of the bench graph` }, + }, + data: index % 7 === 1 && loopId ? { parentId: loopId, extent: 'parent' } : {}, + }) + } + const edges = blocks + .slice(1) + .filter((block) => block.type !== 'loop') + .map((block, index) => ({ id: generateId(), source: blocks[index].id, target: block.id })) + return { + blocks: Object.fromEntries(blocks.map((block) => [block.id, block])), + edges, + loops: {}, + parallels: {}, + } +} + +function median(values: number[]): number { + const sorted = [...values].sort((a, b) => a - b) + return sorted[Math.floor(sorted.length / 2)] +} + +async function timedSave(workflowId: string, state: WorkflowState): Promise { + const started = performance.now() + const result = await saveWorkflowToNormalizedTables(workflowId, state) + if (!result.success) throw new Error(result.error) + return performance.now() - started +} + +function withEdit(state: WorkflowState, round: number): WorkflowState { + const edited = structuredClone(state) + const target = Object.values(edited.blocks).find((block) => block.type === 'function') + if (target) target.subBlocks.code = { id: 'code', type: 'code', value: `return ${round}` } + return edited +} + +function shrunk(state: WorkflowState): WorkflowState { + const kept = Object.values(state.blocks) + .filter((block) => !block.data?.parentId && block.type !== 'loop') + .slice(0, SHRUNK_SIZE) + const ids = new Set(kept.map((block) => block.id)) + return { + ...state, + blocks: Object.fromEntries(kept.map((block) => [block.id, block])), + edges: state.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)), + } +} + +async function seedBackgroundEdges(ownerId: string, count: number): Promise { + const perWorkflow = 400 + for (let seeded = 0; seeded < count; seeded += perWorkflow) { + const workflowId = await insertWorkflow(ownerId, 'Bench background') + await db.execute(sql` + INSERT INTO ${workflowBlocks} (id, workflow_id, type, name, position_x, position_y) + SELECT ${workflowId} || '_b' || g, ${workflowId}, 'function', 'f', 0, 0 + FROM generate_series(0, ${perWorkflow}) g`) + await db.execute(sql` + INSERT INTO ${workflowEdges} (id, workflow_id, source_block_id, target_block_id) + SELECT ${workflowId} || '_e' || g, ${workflowId}, ${workflowId} || '_b' || g, + ${workflowId} || '_b' || (g + 1) + FROM generate_series(0, ${perWorkflow - 1}) g`) + } + await db.execute(sql`ANALYZE workflow_blocks, workflow_edges`) +} + +async function insertWorkflow(ownerId: string, name: string): Promise { + const id = generateId() + const now = new Date() + await db + .insert(workflow) + .values({ id, userId: ownerId, name, lastSynced: now, createdAt: now, updatedAt: now }) + return id +} + +async function main() { + const { values } = parseArgs({ + options: { 'background-edges': { type: 'string', default: '0' } }, + }) + assertDisposableTestDatabaseUrl(process.env.DATABASE_URL ?? '') + const reportPath = process.env.BENCH_REPORT_PATH + const ownerId = generateId() + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Save bench', + email: `${ownerId}@save-bench.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + + const rows: BenchRow[] = [] + try { + await seedBackgroundEdges(ownerId, Number(values['background-edges'])) + for (const size of SIZES) { + const workflowId = await insertWorkflow(ownerId, `Bench ${size}`) + const full = graph(size) + await timedSave(workflowId, full) + const edits: number[] = [] + for (let round = 0; round < REPEATS; round++) { + edits.push(await timedSave(workflowId, withEdit(full, round))) + } + const shrinkMs = await timedSave(workflowId, shrunk(full)) + const growMs = await timedSave(workflowId, full) + rows.push({ blocks: size, oneFieldEditMs: median(edits), shrinkMs, growMs }) + } + } finally { + await db.delete(user).where(eq(user.id, ownerId)) + } + + const report = { backgroundEdges: Number(values['background-edges']), repeats: REPEATS, rows } + logger.info('Normalized save benchmark', report) + if (reportPath) await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`) + process.exit(0) +} + +main().catch((error) => { + logger.error('Normalized save benchmark failed', { error }) + process.exit(1) +}) diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index 8b9da592308..5d1096ffb2d 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -7,99 +7,250 @@ import { normalizeWorkflowEdgeTargetHandle, SUBFLOW_TYPES, } from '@sim/workflow-types/workflow' -import type { InferInsertModel } from 'drizzle-orm' -import { eq } from 'drizzle-orm' +import type { InferInsertModel, SQL } from 'drizzle-orm' +import { and, eq, inArray, sql } from 'drizzle-orm' +import type { PgInsertValue } from 'drizzle-orm/pg-core' import { pruneWorkflowSourceMeta } from './source-meta' import { generateLoopBlocks, generateParallelBlocks } from './subflow-helpers' import type { DbOrTx } from './types' const logger = createLogger('WorkflowPersistenceSave') -type SubflowInsert = InferInsertModel +type GraphTable = typeof workflowBlocks | typeof workflowEdges | typeof workflowSubflows +type BlockRow = InferInsertModel +type EdgeRow = InferInsertModel +type SubflowRow = InferInsertModel +/** Columns the database stamps; the save never compares them. */ +const UNCOMPARED_COLUMNS = new Set(['createdAt', 'updatedAt']) + +/** A table's rows split into what the save inserts, rewrites and deletes. */ +interface RowPlan { + inserts: Row[] + updates: Row[] + deleteIds: string[] +} + +function toBlockRow(workflowId: string, block: BlockState): BlockRow { + return { + id: block.id, + workflowId, + type: block.type, + name: block.name || '', + positionX: String(block.position?.x || 0), + positionY: String(block.position?.y || 0), + enabled: block.enabled ?? true, + horizontalHandles: block.horizontalHandles ?? true, + isWide: false, + advancedMode: block.advancedMode ?? false, + triggerMode: block.triggerMode ?? false, + height: String(block.height || 0), + subBlocks: block.subBlocks || {}, + outputs: block.outputs || {}, + errorEnabled: block.errorEnabled ?? false, + /** + * Persisted verbatim, including a disabled policy, so the configured + * numbers survive switching retry off and back on. Whether it runs is + * decided by `resolveBlockRetryConfig` at execution time. + */ + retry: block.retry ?? null, + data: block.data || {}, + locked: block.locked ?? false, + } +} + +function toSubflowRows(workflowId: string, blocks: Record): SubflowRow[] { + return [ + ...Object.values(generateLoopBlocks(blocks)).map((loop) => ({ + id: loop.id, + workflowId, + type: SUBFLOW_TYPES.LOOP, + config: loop, + })), + ...Object.values(generateParallelBlocks(blocks)).map((parallel) => ({ + id: parallel.id, + workflowId, + type: SUBFLOW_TYPES.PARALLEL, + config: parallel, + })), + ] +} + +function sortedKeys(_key: string, value: unknown): unknown { + if (value === null || typeof value !== 'object' || Array.isArray(value)) return value + const record = value as Record + return Object.fromEntries( + Object.keys(record) + .sort() + .map((key) => [key, record[key]]) + ) +} + +/** + * A column value as it reads back from Postgres: jsonb drops `undefined` members and ignores + * key order, so both sides serialize to JSON with sorted keys. + */ +function storedForm(value: unknown): string { + return JSON.stringify(value ?? null, sortedKeys) +} + +function rowChanged(stored: Record, desired: Record): boolean { + for (const [column, value] of Object.entries(desired)) { + if (UNCOMPARED_COLUMNS.has(column)) continue + if (storedForm(stored[column]) !== storedForm(value)) return true + } + return false +} + +/** + * Diffs the desired rows against the stored ones by id. A repeated desired id goes to the + * inserts, so Postgres refuses it with the same unique violation a full re-insert raised. + */ +function planRows( + stored: readonly (Record & { id: string })[], + desired: readonly Row[] +): RowPlan { + const storedById = new Map(stored.map((row) => [row.id, row])) + const seen = new Set() + const plan: RowPlan = { inserts: [], updates: [], deleteIds: [] } + for (const row of desired) { + const current = storedById.get(row.id) + if (!current || seen.has(row.id)) { + plan.inserts.push(row) + } else if (rowChanged(current, row)) { + plan.updates.push(row) + } + seen.add(row.id) + } + for (const row of stored) { + if (!seen.has(row.id)) plan.deleteIds.push(row.id) + } + return plan +} + +const BLOCK_UPDATE_SET = { + type: sql`excluded.type`, + name: sql`excluded.name`, + positionX: sql`excluded.position_x`, + positionY: sql`excluded.position_y`, + enabled: sql`excluded.enabled`, + horizontalHandles: sql`excluded.horizontal_handles`, + isWide: sql`excluded.is_wide`, + advancedMode: sql`excluded.advanced_mode`, + triggerMode: sql`excluded.trigger_mode`, + errorEnabled: sql`excluded.error_enabled`, + retry: sql`excluded.retry`, + locked: sql`excluded.locked`, + height: sql`excluded.height`, + subBlocks: sql`excluded.sub_blocks`, + outputs: sql`excluded.outputs`, + data: sql`excluded.data`, + updatedAt: sql`now()`, +} as const + +const EDGE_UPDATE_SET = { + sourceBlockId: sql`excluded.source_block_id`, + targetBlockId: sql`excluded.target_block_id`, + sourceHandle: sql`excluded.source_handle`, + targetHandle: sql`excluded.target_handle`, +} as const + +const SUBFLOW_UPDATE_SET = { + type: sql`excluded.type`, + config: sql`excluded.config`, + updatedAt: sql`now()`, +} as const + +/** + * Rewrites rows the transaction holds in `workflowId`, one statement per table. The update is + * confined to this workflow, so a row it skips aborts the save instead of vanishing. + */ +async function updateRows( + tx: DbOrTx, + table: T, + workflowId: string, + rows: PgInsertValue[], + set: Partial> +): Promise { + if (rows.length === 0) return + const written = await tx + .insert(table) + .values(rows) + .onConflictDoUpdate({ target: table.id, set, setWhere: eq(table.workflowId, workflowId) }) + .returning({ id: table.id }) + if (written.length !== rows.length) { + throw new Error(`Failed to update ${rows.length - written.length} stored workflow graph rows`) + } +} + +async function deleteRows( + tx: DbOrTx, + table: GraphTable, + workflowId: string, + ids: string[] +): Promise { + if (ids.length === 0) return + await tx.delete(table).where(and(eq(table.workflowId, workflowId), inArray(table.id, ids))) +} + +/** + * Makes the workflow's normalized block, edge and subflow rows match `state`, leaving the rows a + * delete-all and re-insert would leave. Only the difference is written: 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. + * + * 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 + * `ON DELETE CASCADE` never removes an edge the new state keeps. + */ export async function saveWorkflowToNormalizedTables( workflowId: string, state: WorkflowState, externalTx?: DbOrTx ): Promise<{ success: boolean; error?: string }> { const blockRecords = state.blocks as Record - const canonicalLoops = generateLoopBlocks(blockRecords) - const canonicalParallels = generateParallelBlocks(blockRecords) + const desiredBlocks = Object.values(blockRecords).map((block) => toBlockRow(workflowId, block)) + const desiredEdges: EdgeRow[] = state.edges.map((edge) => ({ + id: edge.id, + workflowId, + sourceBlockId: edge.source, + targetBlockId: edge.target, + sourceHandle: normalizeWorkflowEdgeSourceHandle(edge.sourceHandle) ?? null, + targetHandle: normalizeWorkflowEdgeTargetHandle(edge.targetHandle) ?? null, + })) + const desiredSubflows = toSubflowRows(workflowId, blockRecords) const execute = async (tx: DbOrTx) => { - await Promise.all([ - tx.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)), - tx.delete(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)), - tx.delete(workflowSubflows).where(eq(workflowSubflows.workflowId, workflowId)), + const [storedBlocks, storedEdges, storedSubflows] = await Promise.all([ + tx + .select() + .from(workflowBlocks) + .where(eq(workflowBlocks.workflowId, workflowId)) + .for('update'), + tx.select().from(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)).for('update'), + tx + .select() + .from(workflowSubflows) + .where(eq(workflowSubflows.workflowId, workflowId)) + .for('update'), ]) + const blocks = planRows(storedBlocks, desiredBlocks) + const edges = planRows(storedEdges, desiredEdges) + const subflows = planRows(storedSubflows, desiredSubflows) - if (Object.keys(state.blocks).length > 0) { - const blockInserts = Object.values(state.blocks).map((block) => ({ - id: block.id, - workflowId, - type: block.type, - name: block.name || '', - positionX: String(block.position?.x || 0), - positionY: String(block.position?.y || 0), - enabled: block.enabled ?? true, - horizontalHandles: block.horizontalHandles ?? true, - advancedMode: block.advancedMode ?? false, - triggerMode: block.triggerMode ?? false, - height: String(block.height || 0), - subBlocks: block.subBlocks || {}, - outputs: block.outputs || {}, - errorEnabled: block.errorEnabled ?? false, - /** - * Persisted verbatim, including a disabled policy, so the configured - * numbers survive switching retry off and back on. Whether it runs is - * decided by `resolveBlockRetryConfig` at execution time. - */ - retry: block.retry ?? null, - data: block.data || {}, - parentId: block.data?.parentId || null, - extent: block.data?.extent || null, - locked: block.locked ?? false, - })) - - await tx.insert(workflowBlocks).values(blockInserts) - } + await deleteRows(tx, workflowEdges, workflowId, edges.deleteIds) + await deleteRows(tx, workflowSubflows, workflowId, subflows.deleteIds) - if (state.edges.length > 0) { - const edgeInserts = state.edges.map((edge) => ({ - id: edge.id, - workflowId, - sourceBlockId: edge.source, - targetBlockId: edge.target, - sourceHandle: normalizeWorkflowEdgeSourceHandle(edge.sourceHandle), - targetHandle: normalizeWorkflowEdgeTargetHandle(edge.targetHandle), - })) - - await tx.insert(workflowEdges).values(edgeInserts) - } + if (blocks.inserts.length > 0) await tx.insert(workflowBlocks).values(blocks.inserts) + await updateRows(tx, workflowBlocks, workflowId, blocks.updates, BLOCK_UPDATE_SET) - const subflowInserts: SubflowInsert[] = [] - - Object.values(canonicalLoops).forEach((loop) => { - subflowInserts.push({ - id: loop.id, - workflowId, - type: SUBFLOW_TYPES.LOOP, - config: loop, - }) - }) - - Object.values(canonicalParallels).forEach((parallel) => { - subflowInserts.push({ - id: parallel.id, - workflowId, - type: SUBFLOW_TYPES.PARALLEL, - config: parallel, - }) - }) - - if (subflowInserts.length > 0) { - await tx.insert(workflowSubflows).values(subflowInserts) - } + if (edges.inserts.length > 0) await tx.insert(workflowEdges).values(edges.inserts) + await updateRows(tx, workflowEdges, workflowId, edges.updates, EDGE_UPDATE_SET) + + await deleteRows(tx, workflowBlocks, workflowId, blocks.deleteIds) + + if (subflows.inserts.length > 0) await tx.insert(workflowSubflows).values(subflows.inserts) + await updateRows(tx, workflowSubflows, workflowId, subflows.updates, SUBFLOW_UPDATE_SET) const savedBlockIds = new Set(Object.keys(state.blocks)) await pruneWorkflowSourceMeta(tx, workflowId, { blocks: (id) => savedBlockIds.has(id) }) From bde2ffbdf7f24aa57fd4e90b924defe48a6b570d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:28:39 -0800 Subject: [PATCH 003/104] fix(workflow-code): check the preview flag after authorization, with FEATURE_NOT_ENABLED The workflow-code flag check was copied into ten use cases, and three ran it in resolveContext before authorizeWorkspaceOperation: with the flag off, a caller with no access got 403 for a real workflow or workspace id and 404 for a made-up one, and the 403 named no cause. An operation now declares the rollout flag it ships behind (feature on defineWorkspaceOperation); the shared use-case wrapper checks it last in the authorize phase, so execute, authorize and HEAD answer the same, an unreachable workspace stays concealed, and a member is refused with the new FEATURE_NOT_ENABLED 403 detail code. The per-use-case copies are gone. --- apps/docs/openapi-v2-billing.json | 3 +- apps/docs/openapi-v2-files-audit.json | 3 +- apps/docs/openapi-v2-knowledge.json | 3 +- apps/docs/openapi-v2-logs.json | 3 +- apps/docs/openapi-v2-resources.json | 3 +- apps/docs/openapi-v2-tables.json | 3 +- apps/docs/openapi-v2-workflows.json | 3 +- .../[workflowId]/source/feature-flag.test.ts | 8 +- .../authorized-workspace-use-case.ts | 7 +- .../core/application/feature-availability.ts | 47 ++++++ apps/sim/lib/core/application/forbidden.ts | 2 + apps/sim/lib/core/application/index.ts | 1 + .../core/application/workspace-operation.ts | 6 + .../application/apply-workflow-source.ts | 3 - .../application/code-availability.ts | 11 +- .../lib/workflows/application/operations.ts | 15 ++ .../application/read-source-catalog.ts | 2 - .../application/read-source-resources.ts | 14 +- .../application/read-workflow-source.ts | 22 +-- .../source-feature-gate.integration.ts | 150 ++++++++++++++++++ apps/sim/lib/workflows/code/feature-flag.ts | 39 +---- .../application/apply-workspace-source.ts | 2 - .../application/operations.ts | 12 +- .../application/read-workspace-source.ts | 2 - .../application/stage-blobs.ts | 4 - 25 files changed, 270 insertions(+), 98 deletions(-) create mode 100644 apps/sim/lib/core/application/feature-availability.ts create mode 100644 apps/sim/lib/workflows/application/source-feature-gate.integration.ts diff --git a/apps/docs/openapi-v2-billing.json b/apps/docs/openapi-v2-billing.json index e56e81b0ced..32c4e406312 100644 --- a/apps/docs/openapi-v2-billing.json +++ b/apps/docs/openapi-v2-billing.json @@ -572,7 +572,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-files-audit.json b/apps/docs/openapi-v2-files-audit.json index 154b5ae207e..995979d490c 100644 --- a/apps/docs/openapi-v2-files-audit.json +++ b/apps/docs/openapi-v2-files-audit.json @@ -4714,7 +4714,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-knowledge.json b/apps/docs/openapi-v2-knowledge.json index 8a465eac04a..f9e17feb793 100644 --- a/apps/docs/openapi-v2-knowledge.json +++ b/apps/docs/openapi-v2-knowledge.json @@ -6130,7 +6130,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-logs.json b/apps/docs/openapi-v2-logs.json index ab1cac9efb9..69ab7abd928 100644 --- a/apps/docs/openapi-v2-logs.json +++ b/apps/docs/openapi-v2-logs.json @@ -1066,7 +1066,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index e1e0914ece9..09a62bdb1e0 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -16186,7 +16186,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-tables.json b/apps/docs/openapi-v2-tables.json index 44dfcb42fc4..4ee8a0156ac 100644 --- a/apps/docs/openapi-v2-tables.json +++ b/apps/docs/openapi-v2-tables.json @@ -5978,7 +5978,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 880fc7ad740..3800efe3d8a 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -9496,7 +9496,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/feature-flag.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/feature-flag.test.ts index 0aa0a306395..1dd943c34bb 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/feature-flag.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/feature-flag.test.ts @@ -1,8 +1,8 @@ /** * The two source reads are `headSafe: false`, so a `HEAD` runs only the use case's authorize * phase. These run the real use cases behind both routes with the `workflow-code` flag off, so a - * `HEAD` answers the same 403 its `GET` does instead of a 200 that says the feature is reachable. - * The flag is rolled out by organization, so both resolve the (existing) workspace first. + * `HEAD` answers the same 403 its `GET` does instead of a 200 that says the feature is reachable, + * and the `GET` names the cause (`FEATURE_NOT_ENABLED`) so a client tells it from a role refusal. */ import { V2_OPERATION_RATE_LIMIT_ALLOWED, @@ -81,5 +81,9 @@ describe.each(routes)('$name while workflows as code is off', ({ handler, url, c ) expect(response.status).toBe(403) + if (method === 'GET') { + const body = await response.json() + expect(body.error.details).toEqual({ code: 'FEATURE_NOT_ENABLED' }) + } }) }) diff --git a/apps/sim/lib/core/application/authorized-workspace-use-case.ts b/apps/sim/lib/core/application/authorized-workspace-use-case.ts index 5cfc0516f49..9e1e5697dce 100644 --- a/apps/sim/lib/core/application/authorized-workspace-use-case.ts +++ b/apps/sim/lib/core/application/authorized-workspace-use-case.ts @@ -12,6 +12,7 @@ import { resolvePrincipalAuditAttribution } from '@sim/auth/principal' import { createLogger } from '@sim/logger' import { toNumberOrNull, toStringOrNull } from '@sim/utils/coerce' import { runDeclaredContentOperation } from '@/lib/core/application/content-delivery' +import { requireOperationFeature } from '@/lib/core/application/feature-availability' import type { ApplicationOperation, OperationUseCase } from '@/lib/core/application/operation' import { authorizeWorkspaceOperation, @@ -246,7 +247,8 @@ export function defineAuthorizedWorkspaceUseCase< /** * Everything that runs before the business transaction: allowed-principal * check, canonical load, asserted-scope comparison, current workspace and - * resource access checks. + * resource access checks, then the operation's rollout flag, last so a + * caller who cannot reach the workspace never learns whether it is on. * * `execute` and `authorize` share it rather than each spelling it out, so a * `HEAD` probe cannot answer a different question from the `GET` it stands @@ -281,6 +283,9 @@ export function defineAuthorizedWorkspaceUseCase< authorizationOptions ) await resourceAuthorization?.(executionContext) + if (definition.operation.feature) { + await requireOperationFeature(definition.operation.feature, principal, context) + } return executionContext } diff --git a/apps/sim/lib/core/application/feature-availability.ts b/apps/sim/lib/core/application/feature-availability.ts new file mode 100644 index 00000000000..bede10b5402 --- /dev/null +++ b/apps/sim/lib/core/application/feature-availability.ts @@ -0,0 +1,47 @@ +import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal' +import { ForbiddenOperationError } from '@/lib/core/application/forbidden' +import type { WorkspaceAuthorizationContext } from '@/lib/core/application/workspace-authorization' +import { type FeatureFlagName, isFeatureEnabled } from '@/lib/core/config/feature-flags' + +/** + * A rollout flag an operation is available behind. Declared on the operation + * (`feature` on `defineWorkspaceOperation`), so the shared use-case wrapper + * checks it after authorization: a caller who cannot reach the workspace is + * refused (and concealed) exactly as if the feature were on, and only a caller + * who could run the operation learns that it is off. + */ +export interface OperationFeature { + readonly flag: FeatureFlagName + /** What a caller who may run the operation is told while the flag is off for them. */ + readonly unavailableMessage: string +} + +type FeatureScope = Pick + +/** + * Whether `feature` is rolled out where an operation runs: its workspace, that + * workspace's organization, or the principal's user, each matched against the + * flag's allowlists. + */ +export function isOperationFeatureEnabled( + feature: OperationFeature, + principal: Principal, + context: FeatureScope +): Promise { + return isFeatureEnabled(feature.flag, { + orgId: context.workspaceOrganizationId, + workspaceId: context.workspaceId, + userId: resolvePrincipalSubjectUserId(principal), + }) +} + +/** Throws `FEATURE_NOT_ENABLED` unless {@link isOperationFeatureEnabled} holds. */ +export async function requireOperationFeature( + feature: OperationFeature, + principal: Principal, + context: FeatureScope +): Promise { + if (!(await isOperationFeatureEnabled(feature, principal, context))) { + throw new ForbiddenOperationError('FEATURE_NOT_ENABLED', feature.unavailableMessage) + } +} diff --git a/apps/sim/lib/core/application/forbidden.ts b/apps/sim/lib/core/application/forbidden.ts index d44a69f37d6..ffc4b375b73 100644 --- a/apps/sim/lib/core/application/forbidden.ts +++ b/apps/sim/lib/core/application/forbidden.ts @@ -79,6 +79,8 @@ export const FORBIDDEN_DETAIL_CODES = [ 'READ_ONLY_API_KEY', /** The organization's identity provider owns this membership, so Sim will not change it. */ 'SCIM_MANAGED_MEMBERSHIP', + /** The operation's feature is not rolled out to this workspace, its organization or the caller. */ + 'FEATURE_NOT_ENABLED', ] as const export type ForbiddenDetailCode = (typeof FORBIDDEN_DETAIL_CODES)[number] diff --git a/apps/sim/lib/core/application/index.ts b/apps/sim/lib/core/application/index.ts index 6fb4a6a78bf..b5e74741f53 100644 --- a/apps/sim/lib/core/application/index.ts +++ b/apps/sim/lib/core/application/index.ts @@ -10,6 +10,7 @@ export { type WorkspaceUseCaseAuditEntry, type WorkspaceUseCaseAuditRollup, } from '@/lib/core/application/authorized-workspace-use-case' +export { isOperationFeatureEnabled } from '@/lib/core/application/feature-availability' export { FORBIDDEN_DETAIL_CODES, type ForbiddenDetailCode, diff --git a/apps/sim/lib/core/application/workspace-operation.ts b/apps/sim/lib/core/application/workspace-operation.ts index 9ee15574e3e..a71c6b58e29 100644 --- a/apps/sim/lib/core/application/workspace-operation.ts +++ b/apps/sim/lib/core/application/workspace-operation.ts @@ -1,6 +1,7 @@ import type { DelegatedPrincipal, DelegatedServiceId, Principal } from '@sim/auth/principal' import type { PermissionType } from '@sim/platform-authz/workspace' import type { ContentDeliveryDeclaration } from '@/lib/core/application/content-delivery' +import type { OperationFeature } from '@/lib/core/application/feature-availability' import type { ApplicationOperation, OAuthOperationPolicy, @@ -53,6 +54,11 @@ export interface WorkspaceOperation< readonly workspaceApiKey: WorkspaceApiKeyPolicy readonly principalKinds: PrincipalKinds readonly delegatedServices?: DelegatedServices + /** + * The rollout flag the operation is available behind, checked after + * authorization so an unreachable workspace stays concealed while it is off. + */ + readonly feature?: OperationFeature } type WorkspaceApiKeyPrincipalConsistency< diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 428edf4a5e5..0851776197c 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -61,7 +61,6 @@ import { type SourceReference, } from '@/lib/workflows/application/source-evaluate' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { type PrintedSource, printStoredSource, @@ -253,7 +252,6 @@ export const applyWorkflowSource = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.applySource, resolveContext: resolvePrincipalWorkflowContext, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const facts = analyticsFacts(principal, input, 'apply', context.workspaceId) try { await requireMutableWorkflow(context.workflowId) @@ -309,7 +307,6 @@ export const createWorkflowFromSource = defineAuthorizedWorkflowUseCase({ resolveContext: ({ input }: { input: CreateWorkflowFromSourceInput }) => resolveActiveWorkspaceApplicationContext(input.workspaceId), async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const { folderId } = await resolveWorkflowFolderPath( context.workspaceId, input.folderPath ?? '/' diff --git a/apps/sim/lib/workflows/application/code-availability.ts b/apps/sim/lib/workflows/application/code-availability.ts index 3a3eba35ce3..4e33eb848ee 100644 --- a/apps/sim/lib/workflows/application/code-availability.ts +++ b/apps/sim/lib/workflows/application/code-availability.ts @@ -1,5 +1,9 @@ -import { defineAuthorizedWorkspaceUseCase, defineWorkspaceOperation } from '@/lib/core/application' -import { isWorkflowCodeEnabledFor } from '@/lib/workflows/code/feature-flag' +import { + defineAuthorizedWorkspaceUseCase, + defineWorkspaceOperation, + isOperationFeatureEnabled, +} from '@/lib/core/application' +import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/application/operations' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' /** permission-group-exempt: reports rollout availability only; source operations enforce their own policies. */ @@ -30,5 +34,6 @@ export const readWorkflowCodeAvailability = defineAuthorizedWorkspaceUseCase({ resolveContext: ({ input }: { input: { workspaceId: string } }) => resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: { delegation: { audience: 'sim:workspaces', isWithinScope: () => true } }, - execute: ({ principal, context }) => isWorkflowCodeEnabledFor(principal, context), + execute: ({ principal, context }) => + isOperationFeatureEnabled(WORKFLOW_CODE_FEATURE, principal, context), }) diff --git a/apps/sim/lib/workflows/application/operations.ts b/apps/sim/lib/workflows/application/operations.ts index f1e4b45966c..73ac154c7a6 100644 --- a/apps/sim/lib/workflows/application/operations.ts +++ b/apps/sim/lib/workflows/application/operations.ts @@ -1,5 +1,15 @@ +import type { OperationFeature } from '@/lib/core/application/feature-availability' import { defineWorkspaceOperation } from '@/lib/core/application/workspace-operation' +/** + * Workflows and workspaces as code (the source catalog and resources, workflow and workspace + * source read and apply) ship behind the `workflow-code` flag; every source operation declares it. + */ +export const WORKFLOW_CODE_FEATURE = { + flag: 'workflow-code', + unavailableMessage: 'Workflows as code is in preview and not enabled for this workspace', +} as const satisfies OperationFeature + const ALL_WORKFLOW_PRINCIPAL_POLICY = { principalKinds: [ 'session', @@ -77,6 +87,7 @@ export const workflowOperations = { // permission-group-exempt: workflow source is the workflow definition in another form, governed by workspace role like `read` readSource: defineWorkspaceOperation({ id: 'workflows.source.read', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:read', minimumRole: 'read', workspaceApiKey: 'allow', @@ -92,6 +103,7 @@ export const workflowOperations = { // permission-group-exempt: the source catalog is the block catalog in another shape; withholding it hides the product rather than restricting it readSourceCatalog: defineWorkspaceOperation({ id: 'workflows.source.catalog.read', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:read', minimumRole: 'read', workspaceApiKey: 'allow', @@ -112,6 +124,7 @@ export const workflowOperations = { // permission-group-exempt: the manifest as a whole stays readable to every member; each section is omitted in the use case when its capability is withheld (see visibleSections) readSourceResources: defineWorkspaceOperation({ id: 'workflows.source.resources.read', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:read', minimumRole: 'read', workspaceApiKey: 'allow', @@ -231,6 +244,7 @@ export const workflowOperations = { */ applySource: defineWorkspaceOperation({ id: 'workflows.source.apply', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:write', minimumRole: 'write', workspaceApiKey: 'deny', @@ -242,6 +256,7 @@ export const workflowOperations = { // permission-group-exempt: creating a workflow from source is governed by workspace role and the same block gates as apply createFromSource: defineWorkspaceOperation({ id: 'workflows.source.create', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:write', minimumRole: 'write', workspaceApiKey: 'deny', diff --git a/apps/sim/lib/workflows/application/read-source-catalog.ts b/apps/sim/lib/workflows/application/read-source-catalog.ts index b488a3ce30a..4725be38589 100644 --- a/apps/sim/lib/workflows/application/read-source-catalog.ts +++ b/apps/sim/lib/workflows/application/read-source-catalog.ts @@ -16,7 +16,6 @@ import { storedCatalogTypes, toolInputIds, } from '@/lib/workflows/code/catalog/workspace' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' interface ReadBlockCatalogInput { workspaceId: string @@ -67,7 +66,6 @@ export const readSourceCatalog = defineAuthorizedWorkspaceUseCase({ loadCatalogWorkspaceContext(input.workspaceId), authorizationOptions: { delegation: catalogDelegationPolicy }, execute: async ({ principal, input, context }): Promise => { - await requireWorkflowCodeEnabled(principal, context) const [gate, storedTypes] = await Promise.all([ resolveCatalogGate(principal, context, { customBlockInputs: true }), input.workflowId ? loadStoredTypes(context.workspaceId, input.workflowId) : undefined, diff --git a/apps/sim/lib/workflows/application/read-source-resources.ts b/apps/sim/lib/workflows/application/read-source-resources.ts index 5c9578a5be1..a985ca1b2f0 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.ts @@ -31,7 +31,6 @@ import type { StaticPermissionGroupCapability } from '@/lib/permission-groups/ca import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions' import { isColumnType } from '@/lib/table/column-types' import { workflowOperations } from '@/lib/workflows/application/operations' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { loadEnvNames, loadVisibleCredentials } from '@/lib/workflows/code/resources' import { extractInputFieldsFromBlocks } from '@/lib/workflows/input-format' import { INPUT_DEFINITION_TRIGGER_TYPES } from '@/lib/workflows/triggers/input-definition-triggers' @@ -237,17 +236,8 @@ function capped(rows: T[]): { rows: T[]; truncated: boolean } { */ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ operation: workflowOperations.readSourceResources, - resolveContext: async ({ - principal, - input, - }: { - principal: Principal - input: ReadSourceResourcesInput - }) => { - const context = await resolveActiveWorkspaceApplicationContext(input.workspaceId) - await requireWorkflowCodeEnabled(principal, context) - return context - }, + resolveContext: ({ input }: { input: ReadSourceResourcesInput }) => + resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: { delegation: sourceResourcesDelegationPolicy }, execute: async ({ principal, context }): Promise => { const workspaceId = context.workspaceId diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index 275490daa53..8ffd3670c30 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -1,4 +1,4 @@ -import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal' +import { resolvePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import { mapWithConcurrency } from '@sim/utils/concurrency' import { compareStrings } from '@sim/utils/string' @@ -36,7 +36,6 @@ import { import { recordSourceRead } from '@/lib/workflows/application/source-analytics' import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { type PrintedSource, printStoredSource, @@ -222,11 +221,7 @@ async function printLoadedSource( */ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.readSource, - resolveContext: async (args: { principal: Principal; input: GetWorkflowSourceInput }) => { - const context = await resolvePrincipalWorkflowContext(args) - await requireWorkflowCodeEnabled(args.principal, context) - return context - }, + resolveContext: resolvePrincipalWorkflowContext, async execute({ principal, input, context }): Promise { const [stored, gate, sourceMeta, prefetched] = await Promise.all([ loadStoredSource(context), @@ -270,17 +265,8 @@ export type WorkflowSourceRead = */ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.readSource, - resolveContext: async ({ - principal, - input, - }: { - principal: Principal - input: ReadWorkflowSourcesInput - }) => { - const context = await resolveActiveWorkspaceApplicationContext(input.workspaceId) - await requireWorkflowCodeEnabled(principal, context) - return context - }, + resolveContext: ({ input }: { input: ReadWorkflowSourcesInput }) => + resolveActiveWorkspaceApplicationContext(input.workspaceId), async execute({ principal, input, context }): Promise> { const { workspaceId } = context const createdBy = resolvePrincipalSubjectUserId(principal) ?? null diff --git a/apps/sim/lib/workflows/application/source-feature-gate.integration.ts b/apps/sim/lib/workflows/application/source-feature-gate.integration.ts new file mode 100644 index 00000000000..8d136214719 --- /dev/null +++ b/apps/sim/lib/workflows/application/source-feature-gate.integration.ts @@ -0,0 +1,150 @@ +/** + * Real PostgreSQL coverage for the `workflow-code` preview gate on the source operations. The + * gate answers only after authorization, so with the flag off a caller who cannot reach the + * workspace sees the same concealed not-found for a real workflow or workspace as for a made-up + * one (no existence or rollout oracle), and a member who can reach it is told the feature is off + * with `FEATURE_NOT_ENABLED`, on `authorize` (what a `HEAD` runs) as on `execute`. + */ + +import { db } from '@sim/db' +import { permissions, user, workflow, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock' +import { generateId } from '@sim/utils/id' +import { inArray } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { concealCrossTenantResourceError } from '@/lib/api/server/routes/resource-concealment' +import { forbiddenErrorDetails } from '@/lib/core/application/forbidden' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { readSourceCatalog } from '@/lib/workflows/application/read-source-catalog' +import { readSourceResources } from '@/lib/workflows/application/read-source-resources' +import { + readWorkflowSource, + readWorkflowSources, +} from '@/lib/workflows/application/read-workflow-source' +import { readWorkspaceSource } from '@/lib/workspace-source/application/read-workspace-source' + +vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) + +const ownerId = generateId() +const outsiderId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const member = createSessionPrincipal({ userId: ownerId }) +const outsider = createSessionPrincipal({ userId: outsiderId }) + +/** What a v2 route answers for a failure: the concealed orchestration code and any 403 cause. */ +async function answer(run: Promise) { + try { + await run + } catch (error) { + const shown = concealCrossTenantResourceError(error, 'Not found') + if (!(shown instanceof OrchestrationError)) throw error + return { code: shown.code, details: forbiddenErrorDetails(shown) } + } + throw new Error('Expected the operation to be refused') +} + +const NOT_FOUND = { code: 'not_found', details: undefined } +const FEATURE_OFF = { code: 'forbidden', details: { code: 'FEATURE_NOT_ENABLED' } } + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [ownerId, outsiderId].map((id) => ({ + id, + name: 'Source feature gate fixture', + email: `${id}@source-feature-gate.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Source feature gate', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values({ + id: generateId(), + entityType: 'workspace', + entityId: workspaceId, + userId: ownerId, + permissionType: 'admin', + }) + await db.insert(workflow).values({ + id: workflowId, + workspaceId, + userId: ownerId, + name: 'Gated', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) +}) + +beforeEach(() => { + featureFlagsMockFns.mockIsFeatureEnabled.mockResolvedValue(false) +}) + +afterAll(async () => { + await deleteWorkspaceFixture(db, inArray(workspace.id, [workspaceId])) + await db.delete(user).where(inArray(user.id, [ownerId, outsiderId])) +}) + +describe('workflow-code gate with the flag off', () => { + it('conceals a real workflow from an outsider exactly as a made-up one', async () => { + const real = await answer( + readWorkflowSource.execute({ principal: outsider, input: { workflowId } }) + ) + const fake = await answer( + readWorkflowSource.execute({ principal: outsider, input: { workflowId: generateId() } }) + ) + expect(real).toEqual(NOT_FOUND) + expect(fake).toEqual(NOT_FOUND) + }) + + it('conceals a real workspace from an outsider exactly as a made-up one', async () => { + for (const useCase of [readSourceResources, readSourceCatalog, readWorkspaceSource]) { + const real = await answer(useCase.execute({ principal: outsider, input: { workspaceId } })) + const fake = await answer( + useCase.execute({ principal: outsider, input: { workspaceId: generateId() } }) + ) + expect(real).toEqual(NOT_FOUND) + expect(fake).toEqual(NOT_FOUND) + } + const real = await answer( + readWorkflowSources.execute({ + principal: outsider, + input: { workspaceId, workflowIds: [workflowId] }, + }) + ) + expect(real).toEqual(NOT_FOUND) + }) + + it('tells a member the feature is off with FEATURE_NOT_ENABLED on authorize and execute', async () => { + const workflowInput = { principal: member, input: { workflowId } } + const workspaceInput = { principal: member, input: { workspaceId } } + expect(await answer(readWorkflowSource.execute(workflowInput))).toEqual(FEATURE_OFF) + expect(await answer(readWorkflowSource.authorize(workflowInput))).toEqual(FEATURE_OFF) + for (const useCase of [readSourceResources, readSourceCatalog, readWorkspaceSource]) { + expect(await answer(useCase.execute(workspaceInput))).toEqual(FEATURE_OFF) + expect(await answer(useCase.authorize(workspaceInput))).toEqual(FEATURE_OFF) + } + }) + + it('serves a member once the flag is on for the workspace', async () => { + featureFlagsMockFns.mockIsFeatureEnabled.mockImplementation( + async (flag: string, scope?: unknown) => + flag === 'workflow-code' && + typeof scope === 'object' && + scope !== null && + 'workspaceId' in scope && + scope.workspaceId === workspaceId + ) + const source = await readWorkflowSource.execute({ principal: member, input: { workflowId } }) + expect(source.workflowId).toBe(workflowId) + }) +}) diff --git a/apps/sim/lib/workflows/code/feature-flag.ts b/apps/sim/lib/workflows/code/feature-flag.ts index 09095726d7d..d419691d3cf 100644 --- a/apps/sim/lib/workflows/code/feature-flag.ts +++ b/apps/sim/lib/workflows/code/feature-flag.ts @@ -1,6 +1,4 @@ -import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal' import { isFeatureEnabled } from '@/lib/core/config/feature-flags' -import { OrchestrationError } from '@/lib/core/orchestration/types' /** * Where a workflows-as-code surface runs: the workspace, its organization (null for a personal @@ -16,42 +14,9 @@ export interface WorkflowCodeScope { /** * Workflows and workspaces as code (the SDK block catalog and resources, workflow source and * workspace source read and apply, the Code tab) ship behind one `workflow-code` flag, rolled out - * globally or by organization, workspace or user; every surface of the feature gates through here. + * globally or by organization, workspace or user. Source operations declare it as + * `WORKFLOW_CODE_FEATURE`; surfaces outside an operation (the Code tab, Copilot entitlements) ask here. */ export function isWorkflowCodeEnabled(scope: WorkflowCodeScope): Promise { return isFeatureEnabled('workflow-code', scope) } - -/** Where a source use case runs: a workspace and that workspace's organization. */ -interface WorkflowCodeContext { - workspaceId: string - workspaceOrganizationId: string | null -} - -/** - * Whether workflows as code is enabled where a use case runs: its workspace, that workspace's - * organization, or the principal's user. - */ -export function isWorkflowCodeEnabledFor( - principal: Principal, - context: WorkflowCodeContext -): Promise { - return isWorkflowCodeEnabled({ - orgId: context.workspaceOrganizationId, - workspaceId: context.workspaceId, - userId: resolvePrincipalSubjectUserId(principal), - }) -} - -/** Throws `forbidden` unless {@link isWorkflowCodeEnabledFor} holds. */ -export async function requireWorkflowCodeEnabled( - principal: Principal, - context: WorkflowCodeContext -): Promise { - if (!(await isWorkflowCodeEnabledFor(principal, context))) { - throw new OrchestrationError( - 'forbidden', - 'Workflows as code is in preview and not enabled for this workspace' - ) - } -} 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 b52fab2aa4c..d52a56207a3 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -11,7 +11,6 @@ import { } from '@sim/workspace-code' import { isResourceKeyed } from '@sim/workspace-code/kinds/registry' import { defineAuthorizedWorkspaceUseCase, principalAuditSource } from '@/lib/core/application' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { recordWorkspaceSourceApplied } from '@/lib/workspace-source/application/analytics' import { sourceContext } from '@/lib/workspace-source/application/context' import { @@ -246,7 +245,6 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const ctx: ApplyContext = { ...sourceContext(principal, context), ...(input.provenance ? { provenance: input.provenance } : {}), diff --git a/apps/sim/lib/workspace-source/application/operations.ts b/apps/sim/lib/workspace-source/application/operations.ts index 79584c70008..2d5690bb88f 100644 --- a/apps/sim/lib/workspace-source/application/operations.ts +++ b/apps/sim/lib/workspace-source/application/operations.ts @@ -1,7 +1,9 @@ import { defineWorkspaceOperation } from '@/lib/core/application/workspace-operation' +import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/application/operations' -const SOURCE_PRINCIPAL_POLICY = { +const SOURCE_OPERATION_POLICY = { principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'workspace_api_key'], + feature: WORKFLOW_CODE_FEATURE, } as const /** @@ -21,7 +23,7 @@ export const workspaceSourceOperations = { minimumRole: 'read', workspaceApiKey: 'allow', capability: 'none', - ...SOURCE_PRINCIPAL_POLICY, + ...SOURCE_OPERATION_POLICY, }), // permission-group-exempt: each change runs through the use case that owns it, which applies that kind's capability apply: defineWorkspaceOperation({ @@ -30,7 +32,7 @@ export const workspaceSourceOperations = { minimumRole: 'write', workspaceApiKey: 'allow', capability: 'none', - ...SOURCE_PRINCIPAL_POLICY, + ...SOURCE_OPERATION_POLICY, }), // permission-group-exempt: staged bytes are inert until an apply writes them through the use case that owns each kind stageBlobs: defineWorkspaceOperation({ @@ -39,7 +41,7 @@ export const workspaceSourceOperations = { minimumRole: 'write', workspaceApiKey: 'allow', capability: 'none', - ...SOURCE_PRINCIPAL_POLICY, + ...SOURCE_OPERATION_POLICY, }), // permission-group-exempt: it reports which of the caller's own staged hashes are absent findMissingBlobs: defineWorkspaceOperation({ @@ -48,6 +50,6 @@ export const workspaceSourceOperations = { minimumRole: 'write', workspaceApiKey: 'allow', capability: 'none', - ...SOURCE_PRINCIPAL_POLICY, + ...SOURCE_OPERATION_POLICY, }), } as const diff --git a/apps/sim/lib/workspace-source/application/read-workspace-source.ts b/apps/sim/lib/workspace-source/application/read-workspace-source.ts index 4513b3b8055..a3c88f69b6b 100644 --- a/apps/sim/lib/workspace-source/application/read-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/read-workspace-source.ts @@ -11,7 +11,6 @@ import { } from '@sim/workspace-code' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { sourceContext } from '@/lib/workspace-source/application/context' import { refusalDiagnostic } from '@/lib/workspace-source/application/errors' import { kindLimitFinding, overKindLimit } from '@/lib/workspace-source/application/findings' @@ -132,7 +131,6 @@ export const readWorkspaceSource = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const ctx = sourceContext(principal, context) const requested = new Set(input.kinds ?? APPLY_ORDER) const kinds = APPLY_ORDER.filter((kind) => requested.has(kind)) diff --git a/apps/sim/lib/workspace-source/application/stage-blobs.ts b/apps/sim/lib/workspace-source/application/stage-blobs.ts index f3a50d06bb2..f2dcc4e877a 100644 --- a/apps/sim/lib/workspace-source/application/stage-blobs.ts +++ b/apps/sim/lib/workspace-source/application/stage-blobs.ts @@ -10,7 +10,6 @@ import { sha256Hex } from '@sim/security/hash' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' -import { requireWorkflowCodeEnabled } from '@/lib/workflows/code/feature-flag' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' import { assertStagingFits, @@ -52,7 +51,6 @@ export const admitSourceBlobStage = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, context }) { - await requireWorkflowCodeEnabled(principal, context) const target = stagingScopeOf(principal, context.workspaceId) assertStagingFits(await stagedUsage(target), { count: 1, bytes: 1 }) return { workspaceId: context.workspaceId } @@ -82,7 +80,6 @@ export const stageSourceBlobs = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const { maxBlobBytes, maxBlobBytesPerRequest, maxBlobsPerRequest } = WORKSPACE_SOURCE_LIMITS if (input.blobs.length === 0) { throw new OrchestrationError('validation', 'Send at least one binary file to stage.') @@ -141,7 +138,6 @@ export const findMissingSourceBlobs = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }) { - await requireWorkflowCodeEnabled(principal, context) if (input.blobs.length > WORKSPACE_SOURCE_LIMITS.maxStagedBlobs) { throw new OrchestrationError( 'payload_too_large', From 1e2320d4a9bc8b79aefc92f87a284bbe8ed54418 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:36:43 -0800 Subject: [PATCH 004/104] fix(realtime): a subblock flush can no longer be confirmed and then lost to a graph replace The flush read-modified-wrote a block's subBlocks with no workflow row lock and confirmed without checking the update hit a row. A keystroke landing between a source apply's locked re-read and its delete-and-reinsert was confirmed, then overwritten; one landing after the delete updated nothing and was still confirmed. The flush now takes the workflow row lock (no key update, so a blind replace's foreign-key checks cannot deadlock with it) before reading, which serializes it with every read-then-rewrite writer, and reports a retryable failure when its update affected no row, as after a blind replace. --- .../src/handlers/subblocks.integration.ts | 200 ++++++++++++++++++ apps/realtime/src/handlers/subblocks.ts | 21 +- 2 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 apps/realtime/src/handlers/subblocks.integration.ts diff --git a/apps/realtime/src/handlers/subblocks.integration.ts b/apps/realtime/src/handlers/subblocks.integration.ts new file mode 100644 index 00000000000..920ed258ef9 --- /dev/null +++ b/apps/realtime/src/handlers/subblocks.integration.ts @@ -0,0 +1,200 @@ +/** + * Real PostgreSQL coverage for a canvas keystroke racing a whole-graph replace. A source apply + * locks the workflow row, re-reads the graph, then deletes and re-inserts every block from what it + * read; a revert to a deployed version deletes and re-inserts without the lock. A keystroke flushed + * inside either window must survive the replace or be reported to its sender as failed (the client + * retries a retryable failure): it may never be confirmed and then vanish. + * + * Drives the real `subblock-update` handler (real permission checks and flush) with only the + * socket and the room manager stood in, and runs the replace's SQL sequence by hand at each + * interleaving point. + */ +import { db, runOutsideTransactionContext } from '@sim/db' +import { permissions, user, workflow, workflowBlocks, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { generateId } from '@sim/utils/id' +import { and, eq, isNull, sql } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { setupSubblocksHandlers } from '@/handlers/subblocks' +import type { IRoomManager } from '@/rooms' + +const userId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const blockId = generateId() +const SOCKET_ID = 'socket-typing' +const BEFORE = 'before the apply' +const TYPED = 'typed during the apply' + +type Outcome = 'operation-confirmed' | 'operation-failed' +type Handler = (payload: unknown) => Promise + +/** The sender's socket, the room manager the handler reads, and the outcome its flush emits. */ +function connect() { + const handlers: Record = {} + let settle: (outcome: Outcome) => void = () => {} + const outcome = new Promise((resolve) => { + settle = resolve + }) + const emitTo = (room: string) => ({ + emit: (event: string) => { + if (room === SOCKET_ID && (event === 'operation-confirmed' || event === 'operation-failed')) { + settle(event) + } + }, + }) + const socket = { + id: SOCKET_ID, + userId, + on: (event: string, handler: Handler) => { + handlers[event] = handler + }, + emit: () => {}, + } + const roomManager = { + isReady: () => true, + getRoomForSocket: async () => ({ type: 'workflow', id: workflowId }), + getUserSession: async () => ({ userId, userName: 'Typist' }), + hasRoom: async () => true, + getRoomUsers: async () => [{ socketId: SOCKET_ID, userId, role: 'write' }], + updateUserActivity: async () => {}, + io: { to: (room: string) => ({ ...emitTo(room), except: () => emitTo(room) }) }, + } + setupSubblocksHandlers( + socket as unknown as Parameters[0], + roomManager as unknown as IRoomManager + ) + return { handlers, outcome } +} + +async function storedValue(): Promise { + const [row] = await db + .select({ subBlocks: workflowBlocks.subBlocks }) + .from(workflowBlocks) + .where(eq(workflowBlocks.id, blockId)) + const subBlocks = row?.subBlocks as Record | undefined + return subBlocks?.code?.value +} + +/** Resolves once `settled` resolves or another session is waiting on a lock. */ +async function untilSettledOrBlocked(settled: Promise): Promise { + let done = false + void settled.then(() => { + done = true + }) + for (let attempt = 0; attempt < 200 && !done; attempt++) { + const [{ waiting }] = await db.execute<{ waiting: number }>( + sql`select count(*)::int as waiting from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock'` + ) + if (waiting > 0) return + await new Promise((resolve) => setTimeout(resolve, 10)) + } +} + +type Writer = 'locking' | 'blind' +type Point = 'after-reread' | 'after-delete' + +/** + * A whole-graph replace, statement for statement: a `locking` writer (a source apply) locks the + * live workflow row and re-reads the blocks first, a `blind` one (a revert to a deployed version) + * does not; both then delete every block and re-insert the graph they started from. `interleave` + * runs at `point` inside it, on its own connections, as the realtime server's flush would. + */ +async function replaceGraph(writer: Writer, point: Point, interleave: () => Promise) { + await db.transaction(async (tx) => { + if (writer === 'locking') { + await tx + .select({ id: workflow.id }) + .from(workflow) + .where(and(eq(workflow.id, workflowId), isNull(workflow.archivedAt))) + .limit(1) + .for('update') + } + const read = await tx + .select() + .from(workflowBlocks) + .where(eq(workflowBlocks.workflowId, workflowId)) + if (point === 'after-reread') await runOutsideTransactionContext(interleave) + await tx.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) + if (point === 'after-delete') await runOutsideTransactionContext(interleave) + await tx.insert(workflowBlocks).values(read) + }) +} + +describe('subblock flush racing a whole-graph replace', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Subblock race fixture', + email: `${userId}@subblock-race.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Subblock race', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(permissions).values({ + id: generateId(), + entityType: 'workspace', + entityId: workspaceId, + userId, + permissionType: 'write', + }) + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: 'Subblock race', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + }) + + beforeEach(async () => { + await db.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) + await db.insert(workflowBlocks).values({ + id: blockId, + workflowId, + type: 'function', + name: 'Function 1', + positionX: '0', + positionY: '0', + subBlocks: { code: { id: 'code', type: 'code', value: BEFORE } }, + }) + }) + + afterAll(async () => { + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) + }) + + it.each<[Writer, Point]>([ + ['locking', 'after-reread'], + ['locking', 'after-delete'], + ['blind', 'after-delete'], + ])('never confirms a keystroke a %s replace then loses (keystroke %s)', async (writer, point) => { + const { handlers, outcome } = connect() + await replaceGraph(writer, point, async () => { + await handlers['subblock-update']({ + workflowId, + blockId, + subblockId: 'code', + value: TYPED, + timestamp: Date.now(), + operationId: generateId(), + }) + await untilSettledOrBlocked(outcome) + }) + const reported = await outcome + const stored = await storedValue() + expect({ reported, stored }).not.toEqual({ reported: 'operation-confirmed', stored: BEFORE }) + if (reported === 'operation-confirmed') expect(stored).toBe(TYPED) + }) +}) diff --git a/apps/realtime/src/handlers/subblocks.ts b/apps/realtime/src/handlers/subblocks.ts index 93e7411d148..3c84cea5dd5 100644 --- a/apps/realtime/src/handlers/subblocks.ts +++ b/apps/realtime/src/handlers/subblocks.ts @@ -282,6 +282,21 @@ async function flushSubblockUpdate( let updateSuccessful = false let blockLocked = false await db.transaction(async (tx) => { + // Every read-then-rewrite writer of this graph (a source apply, `persistWorkflowOperation`, + // another flush) holds the workflow row lock from its read to its commit, so taking it first + // keeps this read-modify-write out of such a writer's window, where it would be lost. + // `no key update` still lets a blind replace insert blocks (its foreign-key check takes + // `key share`), so the two cannot deadlock; a blind replace's delete surfaces below instead. + const [lockedWorkflow] = await tx + .select({ id: workflow.id }) + .from(workflow) + .where(eq(workflow.id, workflowId)) + .limit(1) + .for('no key update') + if (!lockedWorkflow) { + return + } + const allBlocks = await tx .select({ id: workflowBlocks.id, @@ -316,12 +331,14 @@ async function flushSubblockUpdate( subBlocks[subblockId] = { ...subBlocks[subblockId], value } } - await tx + // A writer that replaced the blocks without the row lock deleted this row under us. + const updated = await tx .update(workflowBlocks) .set({ subBlocks, updatedAt: new Date() }) .where(and(eq(workflowBlocks.id, blockId), eq(workflowBlocks.workflowId, workflowId))) + .returning({ id: workflowBlocks.id }) - updateSuccessful = true + updateSuccessful = updated.length > 0 }) if (updateSuccessful) { From 0eb83c0af38f3092bc686a0b3a0d94560d3b3c6b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:40:55 -0800 Subject: [PATCH 005/104] fix(realtime): a variable flush no longer writes stale variables over a source apply The variable flush read the workflow's variables without the row lock and updated them afterwards. A source apply that rewrote the variables under the lock in between was reverted by the flush's stale copy, though both reported success. The flush now takes the same workflow row lock as the subblock flush before its read. --- ...n.ts => graph-replace-race.integration.ts} | 147 ++++++++++++------ apps/realtime/src/handlers/variables.ts | 4 + 2 files changed, 106 insertions(+), 45 deletions(-) rename apps/realtime/src/handlers/{subblocks.integration.ts => graph-replace-race.integration.ts} (63%) diff --git a/apps/realtime/src/handlers/subblocks.integration.ts b/apps/realtime/src/handlers/graph-replace-race.integration.ts similarity index 63% rename from apps/realtime/src/handlers/subblocks.integration.ts rename to apps/realtime/src/handlers/graph-replace-race.integration.ts index 920ed258ef9..11028e19119 100644 --- a/apps/realtime/src/handlers/subblocks.integration.ts +++ b/apps/realtime/src/handlers/graph-replace-race.integration.ts @@ -3,25 +3,30 @@ * locks the workflow row, re-reads the graph, then deletes and re-inserts every block from what it * read; a revert to a deployed version deletes and re-inserts without the lock. A keystroke flushed * inside either window must survive the replace or be reported to its sender as failed (the client - * retries a retryable failure): it may never be confirmed and then vanish. + * retries a retryable failure): it may never be confirmed and then vanish. A variable keystroke + * racing an apply that rewrites the variables must not revert the apply's own change either. * - * Drives the real `subblock-update` handler (real permission checks and flush) with only the + * Drives the real `subblock-update` and `variable-update` handlers (real permission checks and flush) with only the * socket and the room manager stood in, and runs the replace's SQL sequence by hand at each * interleaving point. */ import { db, runOutsideTransactionContext } from '@sim/db' import { permissions, user, workflow, workflowBlocks, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' import { and, eq, isNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import { setupSubblocksHandlers } from '@/handlers/subblocks' +import { setupVariablesHandlers } from '@/handlers/variables' import type { IRoomManager } from '@/rooms' const userId = generateId() const workspaceId = generateId() const workflowId = generateId() const blockId = generateId() +const variableId = generateId() +const otherVariableId = generateId() const SOCKET_ID = 'socket-typing' const BEFORE = 'before the apply' const TYPED = 'typed during the apply' @@ -60,10 +65,9 @@ function connect() { updateUserActivity: async () => {}, io: { to: (room: string) => ({ ...emitTo(room), except: () => emitTo(room) }) }, } - setupSubblocksHandlers( - socket as unknown as Parameters[0], - roomManager as unknown as IRoomManager - ) + const connected = socket as unknown as Parameters[0] + setupSubblocksHandlers(connected, roomManager as unknown as IRoomManager) + setupVariablesHandlers(connected, roomManager as unknown as IRoomManager) return { handlers, outcome } } @@ -88,7 +92,7 @@ async function untilSettledOrBlocked(settled: Promise): Promise { where datname = current_database() and wait_event_type = 'Lock'` ) if (waiting > 0) return - await new Promise((resolve) => setTimeout(resolve, 10)) + await sleep(10) } } @@ -122,41 +126,46 @@ async function replaceGraph(writer: Writer, point: Point, interleave: () => Prom }) } -describe('subblock flush racing a whole-graph replace', () => { - beforeAll(async () => { - const now = new Date() - await db.insert(user).values({ - id: userId, - name: 'Subblock race fixture', - email: `${userId}@subblock-race.test`, - emailVerified: true, - createdAt: now, - updatedAt: now, - }) - await insertWorkspaceFixture(db, { - id: workspaceId, - name: 'Subblock race', - ownerId: userId, - billedAccountUserId: userId, - }) - await db.insert(permissions).values({ - id: generateId(), - entityType: 'workspace', - entityId: workspaceId, - userId, - permissionType: 'write', - }) - await db.insert(workflow).values({ - id: workflowId, - userId, - workspaceId, - name: 'Subblock race', - lastSynced: now, - createdAt: now, - updatedAt: now, - }) +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Subblock race fixture', + email: `${userId}@subblock-race.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Subblock race', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(permissions).values({ + id: generateId(), + entityType: 'workspace', + entityId: workspaceId, + userId, + permissionType: 'write', }) + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: 'Subblock race', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) +}) + +afterAll(async () => { + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) +}) +describe('subblock flush racing a whole-graph replace', () => { beforeEach(async () => { await db.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) await db.insert(workflowBlocks).values({ @@ -170,11 +179,6 @@ describe('subblock flush racing a whole-graph replace', () => { }) }) - afterAll(async () => { - await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) - await db.delete(user).where(eq(user.id, userId)) - }) - it.each<[Writer, Point]>([ ['locking', 'after-reread'], ['locking', 'after-delete'], @@ -198,3 +202,56 @@ describe('subblock flush racing a whole-graph replace', () => { if (reported === 'operation-confirmed') expect(stored).toBe(TYPED) }) }) + +describe('variable flush racing an apply that rewrites the variables', () => { + const variable = (id: string, value: string) => ({ id, name: id, type: 'plain', value }) + + beforeEach(async () => { + await db + .update(workflow) + .set({ + variables: { + [variableId]: variable(variableId, BEFORE), + [otherVariableId]: variable(otherVariableId, BEFORE), + }, + }) + .where(eq(workflow.id, workflowId)) + }) + + it("keeps both the keystroke and the apply's own variable change", async () => { + const { handlers, outcome } = connect() + const APPLIED = 'written by the apply' + await db.transaction(async (tx) => { + const [locked] = await tx + .select({ variables: workflow.variables }) + .from(workflow) + .where(eq(workflow.id, workflowId)) + .limit(1) + .for('update') + await runOutsideTransactionContext(async () => { + await handlers['variable-update']({ + workflowId, + variableId, + field: 'value', + value: TYPED, + timestamp: Date.now(), + operationId: generateId(), + }) + await untilSettledOrBlocked(outcome) + }) + const read = locked.variables as Record> + await tx + .update(workflow) + .set({ variables: { ...read, [otherVariableId]: variable(otherVariableId, APPLIED) } }) + .where(eq(workflow.id, workflowId)) + }) + const reported = await outcome + const [row] = await db + .select({ variables: workflow.variables }) + .from(workflow) + .where(eq(workflow.id, workflowId)) + const stored = row.variables as Record + expect(stored[otherVariableId].value).toBe(APPLIED) + if (reported === 'operation-confirmed') expect(stored[variableId].value).toBe(TYPED) + }) +}) diff --git a/apps/realtime/src/handlers/variables.ts b/apps/realtime/src/handlers/variables.ts index 0d6eaac2e3a..31903ba00c8 100644 --- a/apps/realtime/src/handlers/variables.ts +++ b/apps/realtime/src/handlers/variables.ts @@ -279,11 +279,15 @@ async function flushVariableUpdate( let updateSuccessful = false await db.transaction(async (tx) => { + // Locked for the read-modify-write, as the subblock flush is: otherwise a writer that + // rewrites the variables under the row lock (a source apply) commits between this read and + // the update below, which then writes the stale variables back over its change. const [workflowRecord] = await tx .select({ variables: workflow.variables }) .from(workflow) .where(eq(workflow.id, workflowId)) .limit(1) + .for('no key update') if (!workflowRecord) { return From 5e8471e1f7322afca9e6c9b5dd3b4ef4431a2663 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:15:12 -0800 Subject: [PATCH 006/104] fix(workspace-code): an MCP credential header accepts the auth schemes a workflow does The MCP declaration kept its own auth-scheme regex, without digest and key, so 'Digest {{TOKEN}}' was refused as a literal secret there while a workflow accepted it. Both now strip the scheme through withoutAuthScheme in secrets.ts. --- packages/workflow-code/src/index.ts | 2 +- packages/workflow-code/src/secrets.ts | 14 ++++++++++++-- packages/workspace-code/src/kinds/mcp.test.ts | 10 ++++++++++ packages/workspace-code/src/kinds/mcp.ts | 6 ++---- 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 7711c3be87e..19728c486e8 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -113,7 +113,7 @@ export { assignIdentifiers, printWorkflow } from './print' export { hasSuspiciousCharacter, printKey, quoteString } from './print/strings' export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' export { JS_RESERVED_WORDS, SDK_CORE_EXPORTS } from './sdk' -export { holdsSecret } from './secrets' +export { holdsSecret, withoutAuthScheme } from './secrets' export { mapAnchorIds, parseSourceMeta, diff --git a/packages/workflow-code/src/secrets.ts b/packages/workflow-code/src/secrets.ts index 77c6c0cdac7..d29a1114090 100644 --- a/packages/workflow-code/src/secrets.ts +++ b/packages/workflow-code/src/secrets.ts @@ -93,7 +93,17 @@ function isCredentialName(name: string): boolean { const PLACEHOLDER = /^(?:x+|\*+|\.+|-+|_+|<[^>]*>|\[[^\]]*\]|your\w*|my\w*|example\w*|placeholder\w*|changeme|redacted|secret|password|token|null|undefined|none|true|false)$/i -const AUTH_SCHEME = /^(?:bearer|basic|token|bot|digest|apikey|key)\s+/i +/** An auth scheme word that may open a credential header's value (`Bearer {{TOKEN}}`). */ +const AUTH_SCHEME = /^\s*(?:bearer|basic|token|bot|digest|apikey|key)\s+/i + +/** + * A credential header's value without its leading auth scheme word, so only what follows it + * (`{{TOKEN}}` in `Digest {{TOKEN}}`) is judged a literal secret. The one scheme list workflows and + * workspace declarations share. + */ +export function withoutAuthScheme(value: string): string { + return value.replace(AUTH_SCHEME, '') +} /** * Whether literal text in a credential slot (a credential header's value, a credential-named @@ -101,7 +111,7 @@ const AUTH_SCHEME = /^(?:bearer|basic|token|bot|digest|apikey|key)\s+/i * reference tokens are gone, and not a placeholder. */ function isCredentialText(text: string): boolean { - const literal = withoutReferences(text).trim().replace(AUTH_SCHEME, '').trim() + const literal = withoutAuthScheme(withoutReferences(text).trim()).trim() return literal.length >= 8 && !/\s/.test(literal) && !PLACEHOLDER.test(literal) } diff --git a/packages/workspace-code/src/kinds/mcp.test.ts b/packages/workspace-code/src/kinds/mcp.test.ts index d3183ee1596..8ebdcda6806 100644 --- a/packages/workspace-code/src/kinds/mcp.test.ts +++ b/packages/workspace-code/src/kinds/mcp.test.ts @@ -113,6 +113,16 @@ describe('mcpCodec', () => { ).toEqual(['E_MCP_LITERAL_SECRET']) }) + it('accepts every auth scheme a workflow credential header accepts before an env reference', () => { + for (const scheme of ['Bearer', 'Basic', 'Token', 'Bot', 'Digest', 'ApiKey', 'Key']) { + expect( + errorCodes( + `{ url: 'https://mcp.example.com', headers: { Authorization: '${scheme} {{GH_TOKEN}}' } }` + ) + ).toEqual([]) + } + }) + it('refuses a known token format in a header whose name carries no credential', () => { expect( errorCodes( diff --git a/packages/workspace-code/src/kinds/mcp.ts b/packages/workspace-code/src/kinds/mcp.ts index 935c92281dc..1186abc07d0 100644 --- a/packages/workspace-code/src/kinds/mcp.ts +++ b/packages/workspace-code/src/kinds/mcp.ts @@ -23,7 +23,7 @@ * An OAuth client secret is set in the server's settings, never in source. */ import { compareStrings } from '@sim/utils/string' -import { holdsSecret, type Json } from '@sim/workflow-code' +import { holdsSecret, type Json, withoutAuthScheme } from '@sim/workflow-code' import { asDeclared, booleanField, @@ -114,8 +114,6 @@ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** A credential-bearing header name, by its words. */ const CREDENTIAL_HEADER = /^(authorization|proxy-authorization|cookie)$|key|token|secret|auth|password|session|signature|credential/i -/** An auth scheme word that may open a credential header (`Bearer {{TOKEN}}`). */ -const AUTH_SCHEME = /^\s*(bearer|basic|token|bot|apikey)\s+/i /** `mcp/.ts`. */ export function mcpDeclarationPath(key: string): string { @@ -135,7 +133,7 @@ function isCredentialHeader(name: string): boolean { */ export function holdsLiteralSecret(name: string, value: string): boolean { const credential = isCredentialHeader(name) - return holdsSecret({ password: credential }, credential ? value.replace(AUTH_SCHEME, '') : value) + return holdsSecret({ password: credential }, credential ? withoutAuthScheme(value) : value) } /** Whether a header value is a kept stored value. */ From 29782df1c5ef0e7a6584a4ad79d07a6bad0a0276 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:39:29 -0800 Subject: [PATCH 007/104] fix(workflow-code): an iteration field read outside its container is refused lp.index after the loop, $ref.loop.index or in a block in no loop, and a block moved out of its container passed tsc, check and apply, then failed (or read nothing) at run time. Compile now reports W_REF_OUT_OF_SCOPE for every such read (handle, code file $ref, tag text); the apply refuses it as E_APPLY_REF_OUT_OF_SCOPE on a block the write adds, changes or moves, and an offline check does the same on a new block, an edited function file and a block the source moved into another container. A stored workflow that already holds one keeps the warning, so it still applies. The workflow lint reports the same reads for the operations path. The SDK keeps index/currentItem/items on a container handle: a block in a nested container reads an outer loop's index through it, and the printer emits that form. --- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 12 ++ .../apply-workflow-source.integration.ts | 108 ++++++++++++++++++ .../workflows/application/source-evaluate.ts | 56 ++++++++- .../workflows/editing/dangling-refs.test.ts | 42 ++++++- apps/sim/lib/workflows/editing/lint.ts | 73 +++++++++++- .../src/commands/protocol/source-primer.ts | 2 +- .../protocol/workflow-source-check.test.ts | 51 ++++++++- .../protocol/workflow-source-check.ts | 28 ++++- packages/sim-cli/src/generated/v2-api.ts | 12 ++ .../workflow-code/src/code-files/index.ts | 2 +- .../workflow-code/src/compile/grammar.test.ts | 88 ++++++++++++++ packages/workflow-code/src/compile/values.ts | 83 +++++++++++++- .../workflow-code/src/diagnostics/codes.ts | 13 +++ packages/workflow-code/src/index.ts | 2 + .../src/codegen/core-text.generated.ts | 2 +- packages/workflow-sdk/src/core.d.ts | 5 +- 19 files changed, 561 insertions(+), 26 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index c2b42c6fa1b..c21c8a123f4 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8640,7 +8640,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -10018,7 +10018,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 3a3a705f905..a1b788ab8fb 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1444,7 +1444,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 4be791a4c0b..cce03d4c0fb 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. 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. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 3800efe3d8a..4fc4720447d 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -18810,6 +18810,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -18920,6 +18921,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -19255,6 +19257,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19365,6 +19368,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -20217,6 +20221,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -20327,6 +20332,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -25261,6 +25267,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25370,6 +25377,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -25828,6 +25836,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25937,6 +25946,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -26238,6 +26248,7 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -26347,6 +26358,7 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", 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 de20f2c9239..1f5f95e92da 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2548,3 +2548,111 @@ describe('renames in source', () => { } ) }) + +describe('iteration references outside their container', () => { + const LOOP_SOURCE = `// @sim-sdk 1 +import { fn, js, loop, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Each item', {}, () => { + const start = trigger.start('Start', { inputFormat: { items: 'array' } }) + const each = loop.forEach('Each Item', { collection: start.items }, (item) => { + const echo = fn('Echo', { code: js\`return \${item.index}\` }) + item.to(echo) + }) + const after = fn('After', { code: 'return 1' }) + start.to(each) + each.to(after) +}) +` + + function create(source: string) { + return withPermissionGroupScope(() => + createWorkflowFromSource.execute({ + principal, + input: { + workspaceId, + name: `Source scope ${generateId()}`, + files: { 'workflow.ts': source }, + }, + }) + ) + } + + check('a new block reading a loop index from after the loop is refused', async () => { + const source = LOOP_SOURCE.replace( + "fn('After', { code: 'return 1' })", + `fn('After', { code: js\`return \${each.index}\` })` + ) + await expectRejected(create(source), 'E_APPLY_REF_OUT_OF_SCOPE') + }) + + check('moving a block that reads out of its loop is refused', async () => { + const created = await create(LOOP_SOURCE) + expect(created.applied).toBe(true) + const moved = LOOP_SOURCE.replace( + ` const echo = fn('Echo', { code: js\`return \${item.index}\` })\n item.to(echo)\n`, + '' + ).replace( + ' start.to(each)\n', + " const echo = fn('Echo', { code: 'return ' })\n after.to(echo)\n start.to(each)\n" + ) + expect(moved).not.toContain('item.to(echo)') + + const dryRun = await apply(created, { 'workflow.ts': moved }, { dryRun: true }) + + expect( + dryRun.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ code: d.code, blockKey: d.blockKey })) + ).toEqual([{ code: 'E_APPLY_REF_OUT_OF_SCOPE', blockKey: 'echo' }]) + }) + + check( + 'a stored block that already reads outside a loop stays a warning', + async () => { + const workflowId = generateId() + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: `Source scope ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const block = (name: string, type: string, code?: string): BlockState => ({ + id: generateId(), + type, + name, + position: { x: 0, y: 0 }, + subBlocks: code === undefined ? {} : { code: { id: 'code', type: 'code', value: code } }, + outputs: {}, + enabled: true, + }) + const start = block('Start', 'start_trigger') + const stray = block('Stray', 'function', 'return ') + const tail = block('Tail', 'function', 'return 1') + const saved = await saveWorkflowToNormalizedTables(workflowId, { + blocks: { [start.id]: start, [stray.id]: stray, [tail.id]: tail }, + edges: [ + { id: generateId(), source: start.id, target: stray.id }, + { id: generateId(), source: stray.id, target: tail.id }, + ], + loops: {}, + parallels: {}, + }) + if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`) + const source = await getSource(workflowId) + + const result = await apply(source, edit(source.files, "fn('Tail'", "fn('Last'")) + + expect(result.applied).toBe(true) + expect( + result.diagnostics + .filter((d) => d.code.includes('OUT_OF_SCOPE') || d.code.endsWith('_LINT')) + .map((d) => ({ code: d.code, severity: d.severity, blockKey: d.blockKey })) + ).toEqual([{ code: 'W_REF_OUT_OF_SCOPE', severity: 'warning', blockKey: 'stray' }]) + } + ) +}) diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 0d8c8cd031b..2613972b67c 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -64,10 +64,11 @@ import type { StoredSource } from '@/lib/workflows/code/print-stored' import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workflows/code/resources' import { mergeSourceMetaFromLock } from '@/lib/workflows/code/source-lock' import type { StoredCanonical } from '@/lib/workflows/code/stored-canonical' -import type { - WorkflowLintReport, - WorkflowLintTableSchema, - WorkflowLintUnresolvedReference, +import { + isIterationScopeFinding, + type WorkflowLintReport, + type WorkflowLintTableSchema, + type WorkflowLintUnresolvedReference, } from '@/lib/workflows/editing/lint' import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' import { workflowNameExistsInFolder } from '@/lib/workflows/orchestration' @@ -330,6 +331,42 @@ function withEditedCodeFileRefsRefused( }) } +/** + * The apply's handling of compile's `W_REF_OUT_OF_SCOPE`, an iteration field read from outside + * its container: refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the write adds, changes or + * moves (`changed`, by block key), which would fail at run time; a warning on a block the stored + * workflow already holds as it is, so such a workflow still applies unchanged. The lint's finding + * for the same block is dropped from `lint`, as compile's is the one located at the source line. + */ +function withOutOfScopeRefsRefused( + diagnostics: readonly LocatedDiagnostic[], + lint: WorkflowLintReport, + changed: (blockKey: string) => boolean, + keyOf: (id: string) => string | undefined +): { diagnostics: LocatedDiagnostic[]; lint: WorkflowLintReport } { + const reported = new Set() + const refused = diagnostics.map((diagnostic): LocatedDiagnostic => { + if (diagnostic.code !== 'W_REF_OUT_OF_SCOPE' || diagnostic.blockKey === undefined) { + return diagnostic + } + reported.add(diagnostic.blockKey) + return changed(diagnostic.blockKey) + ? { ...diagnostic, code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' } + : diagnostic + }) + if (reported.size === 0) return { diagnostics: refused, lint } + return { + diagnostics: refused, + lint: { + ...lint, + unresolvedReferences: lint.unresolvedReferences.filter((reference) => { + const key = keyOf(reference.blockId) + return !(isIterationScopeFinding(reference) && key !== undefined && reported.has(key)) + }), + }, + } +} + /** `{ span }` when there is one, to spread into a diagnostic. */ function withSpan(span: SourceSpan | undefined): { span?: SourceSpan } { return span ? { span } : {} @@ -918,15 +955,22 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise m.id)]) + const changedKeys = new Set([...changedIds].flatMap((id) => keyById.get(id) ?? [])) + const scoped = withOutOfScopeRefsRefused( + compileDiagnostics, + lint, + (key) => changedKeys.has(key), + (id) => keyById.get(id) + ) const diagnostics = [ - ...compileDiagnostics, + ...scoped.diagnostics, ...keptDiagnostics, ...materializeDiagnostics, ...refusals, ...normalized.diagnostics, ...lintDiagnostics( withoutCodeFileReferences( - withoutPendingReferences(lint, input.pendingResources ?? []), + withoutPendingReferences(scoped.lint, input.pendingResources ?? []), compileDiagnostics, (id) => keyById.get(id) ), diff --git a/apps/sim/lib/workflows/editing/dangling-refs.test.ts b/apps/sim/lib/workflows/editing/dangling-refs.test.ts index b7ca5986587..f193a049ffc 100644 --- a/apps/sim/lib/workflows/editing/dangling-refs.test.ts +++ b/apps/sim/lib/workflows/editing/dangling-refs.test.ts @@ -1,7 +1,10 @@ import type { Mock } from 'vitest' import { describe, expect, it, vi } from 'vitest' import { createMcpToolOutputSnapshot } from '@/lib/mcp/output-schema' -import { collectDanglingBlockOutputReferences } from '@/lib/workflows/editing/lint' +import { + collectDanglingBlockOutputReferences, + isIterationScopeFinding, +} from '@/lib/workflows/editing/lint' import { McpBlock } from '@/blocks/blocks/mcp' import { getAllBlocks, getBlock, getBlockByToolName, getBlockRegistry } from '@/blocks/registry' @@ -78,7 +81,7 @@ function graph( type?: string name?: string triggerMode?: boolean - data?: { canonicalModes?: Record } + data?: { canonicalModes?: Record; parentId?: string } subBlocks?: Record } > @@ -110,9 +113,11 @@ describe('collectDanglingBlockOutputReferences', () => { const findings = collectDanglingBlockOutputReferences( graph({ b1: { type: 'starter', name: 'Start' }, + lp: { type: 'loop', name: 'Lp' }, b2: { type: 'api', name: 'Call', + data: { parentId: 'lp' }, subBlocks: { url: { value: 'https://x.test/' }, body: { value: ' and are fine' }, @@ -123,6 +128,39 @@ describe('collectDanglingBlockOutputReferences', () => { expect(findings).toHaveLength(0) }) + it('flags iteration fields read from outside their container, by name or bare prefix', () => { + const findings = collectDanglingBlockOutputReferences( + graph({ + lp: { + type: 'loop', + name: 'Lp', + subBlocks: { whileCondition: { value: ' < 3' } }, + }, + fan: { type: 'parallel', name: 'Fan' }, + inner: { + type: 'function', + name: 'Inner', + data: { parentId: 'fan' }, + subBlocks: { + code: { value: 'return [, , ]' }, + }, + }, + after: { + type: 'function', + name: 'After', + subBlocks: { code: { value: 'return [, , ]' } }, + }, + }) + ) + expect(findings).toHaveLength(1) + expect(findings[0]).toMatchObject({ + blockId: 'after', + field: 'code', + value: ['', ''], + }) + expect(isIterationScopeFinding(findings[0])).toBe(true) + }) + it('ignores non-reference angle text (Slack links, comparisons, bare tags)', () => { const findings = collectDanglingBlockOutputReferences( graph({ diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index 3ab44ab0e1d..732de92cf7d 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -1,6 +1,6 @@ import { toRecordOrNull } from '@sim/utils/object' import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' -import { didYouMean } from '@sim/workflow-code' +import { didYouMean, LOOP_PROPERTIES, PARALLEL_PROPERTIES } from '@sim/workflow-code' import type { CanonicalModeOverrides } from '@sim/workflow-code/catalog/canonical-index' import { MCP_STRUCTURED_CONTENT_OUTPUT } from '@/lib/mcp/output-schema' import { @@ -39,7 +39,7 @@ type BlockState = { name?: string triggerMode?: boolean subBlocks?: Record - data?: { canonicalModes?: CanonicalModeOverrides } + data?: { canonicalModes?: CanonicalModeOverrides; parentId?: unknown } } type EdgeState = { @@ -857,6 +857,61 @@ function referenceTarget( return targetByKey.get(head) ?? targetByKey.get(normalizeName(head)) ?? null } +/** The iteration fields each container type exposes only to the blocks inside it. */ +const ITERATION_FIELDS: Readonly> = { + loop: LOOP_PROPERTIES, + parallel: PARALLEL_PROPERTIES, +} + +/** How an iteration-scope finding's reason starts, so a caller can tell it from the others. */ +const OUT_OF_SCOPE_REASON = 'out-of-scope:' + +/** + * The containers whose iteration fields `blockId` reads at run time: itself when it is one (a + * while condition reads ``), then each enclosing one, innermost first. + */ +function iterationScopeIds(blocks: Record, blockId: string): string[] { + const scopes: string[] = [] + const seen = new Set() + let id: string | undefined = blockId + while (id !== undefined && !seen.has(id)) { + seen.add(id) + const block: BlockState | undefined = blocks[id] + if (block?.type && Object.hasOwn(ITERATION_FIELDS, block.type)) scopes.push(id) + const parentId: unknown = block?.data?.parentId + id = typeof parentId === 'string' && parentId.length > 0 ? parentId : undefined + } + return scopes +} + +/** + * Whether a `head.path` token read from `blockId` is an iteration field (`index`, `currentItem`, + * `items`, …) of a container the block is not inside: a named loop or parallel (`targetId`), + * whose fields the executor refuses outside it, or the bare `loop`/`parallel` prefix in a block + * with no container of that kind, which resolves to nothing. + */ +function readsIterationOutOfScope( + blocks: Record, + blockId: string, + token: string, + targetId: string | undefined +): boolean { + const [head = '', field = ''] = token.split('.') + const kind = targetId === undefined ? head : blocks[targetId]?.type + const fields = + kind !== undefined && Object.hasOwn(ITERATION_FIELDS, kind) ? ITERATION_FIELDS[kind] : undefined + if (!fields?.includes(splitLeadingBracketPath(field).property)) return false + const scopes = iterationScopeIds(blocks, blockId) + return targetId === undefined + ? !scopes.some((id) => blocks[id]?.type === kind) + : !scopes.includes(targetId) +} + +/** Whether a lint reference finding is one {@link readsIterationOutOfScope} reported. */ +export function isIterationScopeFinding(reference: WorkflowLintUnresolvedReference): boolean { + return reference.kind === 'block-output' && reference.reason.startsWith(OUT_OF_SCOPE_REASON) +} + export function collectDanglingBlockOutputReferences( workflowState: Pick ): WorkflowLintUnresolvedReference[] { @@ -878,12 +933,17 @@ export function collectDanglingBlockOutputReferences( const leaves: string[] = [] collectStringLeaves((subBlock as { value?: unknown })?.value, leaves) const dangling = new Set() + const outOfScope = new Set() const unknownByTarget = new Map() const undeclaredNested = new Map() for (const leaf of leaves) { for (const token of referenceCandidates(leaf, subBlockId === 'code')) { if (!token || !REF_TOKEN_SHAPE.test(token)) continue const targetId = referenceTarget(token, targetByKey) + if (targetId !== null && readsIterationOutOfScope(blocks, blockId, token, targetId)) { + outOfScope.add(`<${token}>`) + continue + } if (targetId === undefined) continue if (targetId === null) { dangling.add(`<${token}>`) @@ -918,6 +978,15 @@ export function collectDanglingBlockOutputReferences( 'References a block that does not exist in this workflow — at run time the literal text is passed through (or the block fails), never the intended value.', }) } + if (outOfScope.size > 0) { + findings.push({ + ...blockRef(blockId, block), + field: subBlockId, + value: [...outOfScope], + kind: 'block-output', + reason: `${OUT_OF_SCOPE_REASON} reads a loop or parallel's iteration fields (index, currentItem, items) from outside that container — the run fails or reads nothing. Move the block into the container, or read the container's results after it finishes.`, + }) + } for (const [targetId, group] of unknownByTarget) { const targetName = group.target.name || targetId const plural = group.segments.size === 1 ? 'field' : 'fields' diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index fc9d577cdec..9d65ba1bf09 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -37,7 +37,7 @@ 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: the block keeps its id. Renaming the const too keeps the id when its settings, neighbours or references still tie it to the old block; otherwise the apply refuses it as a delete (\`E_APPLY_BLOCK_DELETE\`), and the dry run names it. Safest: keep the const in the same apply. -- **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 with 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\`. A rename keeps its references working: the apply rewrites every \`$ref.\` in the function files to the new key (and the files it writes back hold it), so leave them or write the new key yourself. A \`$ref\` that names no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\` in \`check\` and the dry run). +- **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 with 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\`. An index or item is read only from a block inside its container: outside it (\`lp.index\` after the loop, or a block moved out) the run fails, which the apply refuses (\`E_APPLY_REF_OUT_OF_SCOPE\`); read \`lp.results\` after the loop instead. A rename keeps its references working: the apply rewrites every \`$ref.\` in the function files to the new key (and the files it writes back hold it), so leave them or write the new key yourself. A \`$ref\` that names no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\` in \`check\` and the dry run). - **Look up a builder**: \`${PARAMS_COMMAND} \` (\`table.upsertRow\`, \`agent\`, \`trigger.schedule\`; a namespace such as \`gmail\` lists its builders), offline. - **Exit codes**: 0 ok, 1 errors (fix what it printed), ${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-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index a03bba7e97d..10f77371877 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 @@ -185,13 +185,16 @@ const STORED_SHAPES_RENAMED = STORED_SHAPES.replace( "loop.for('Retry Loop'," ).replace("api('A',", "api('Alpha',") -function writeLock(keys: readonly string[]): void { +function writeLock(keys: readonly string[], parents: Record = {}): void { writeFileSync( join(dir, '.sim/lock.json'), JSON.stringify({ version: 1, blocks: Object.fromEntries( - keys.map((key, order) => [key, { id: `id-${key}`, parent: null, ident: key, order }]) + keys.map((key, order) => [ + key, + { id: `id-${key}`, parent: parents[key] ?? null, ident: key, order }, + ]) ), variables: {}, }) @@ -478,6 +481,50 @@ describe('sim workflows source check', () => { expect(untyped()).toHaveLength(1) }) + it('fails on an iteration reference a new block reads outside its loop, and on one a move left behind', async () => { + cacheCatalog() + const source = (echo: string) => `// @sim-sdk 1 +import { fn, loop, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', {}) + const each = loop.for('Each', { count: 2 }, (p) => { + const inner = fn('Inner', { code: 'return 1' }) + p.to(inner) + }) + ${echo} + start.to(each) +}) +` + const scoped = () => + ((result().diagnostics ?? []) as Array<{ code: string; severity: string }>).filter( + (finding) => finding.code.includes('OUT_OF_SCOPE') + ) + writeFileSync( + join(dir, 'workflow.ts'), + source("const echo = fn('Echo', { code: 'return ' })") + ) + + await check() + expect(scoped()).toEqual([ + expect.objectContaining({ code: 'W_REF_OUT_OF_SCOPE', severity: 'error' }), + ]) + + writeLock(['start', 'each', 'inner', 'echo'], { inner: 'each', echo: 'each' }) + await check() + expect(scoped()).toEqual([ + expect.objectContaining({ code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' }), + ]) + + writeLock(['start', 'each', 'inner', 'echo'], { inner: 'each' }) + process.exitCode = undefined + await check() + expect(scoped()).toEqual([ + expect.objectContaining({ code: 'W_REF_OUT_OF_SCOPE', severity: 'warning' }), + ]) + expect(process.exitCode).toBeUndefined() + }) + it('fails on a dangling $ref in a new function file by default, and on any with --strict', async () => { cacheCatalog() mkdirSync(join(dir, 'functions'), { recursive: true }) 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 2b451892029..3df7852edbb 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -8,6 +8,7 @@ import { compileWorkflow, didYouMean, encodeAnchor, + getOwn, parseJsonField, parseWorkflowLock, scriptName, @@ -72,6 +73,7 @@ const STRICT_CODES: ReadonlySet = new Set([ 'W_CHILD_INPUT_UNKNOWN', 'W_BRANCH_UNWIRED', 'W_UNRESOLVED_REF', + 'W_REF_OUT_OF_SCOPE', ]) /** @@ -100,6 +102,16 @@ const EDIT_SCOPED_CODES: ReadonlySet = new Set(['W_JSON_REF_UNTYPED']) */ const EDITED_FILE_REFUSALS: ReadonlyMap = new Map([ ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], + ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], +]) + +/** + * Warnings a check refuses under the server's error code, whatever the strict mode, on a block the + * lock binds that the source moved into another container: the server refuses them on any block + * the edit changed. `W_REF_OUT_OF_SCOPE`, an iteration field the move left outside its container. + */ +const MOVED_BLOCK_REFUSALS: ReadonlyMap = new Map([ + ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], ]) /** @@ -142,9 +154,11 @@ ${[...STRICT_CODES].map((code) => ` ${code}`).join(',\n')}. lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In a function file changed since the get, ${[...EDITED_FILE_REFUSALS] .map(([warning, refusal]) => `${warning} is the error ${refusal}`) + .join(', ')} in every mode, as the server refuses it; so is ${[...MOVED_BLOCK_REFUSALS] + .map(([warning, refusal]) => `${warning} (${refusal})`) .join( ', ' - )} in every mode, as the server refuses it. ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not + )} on a block the source moved into another container. ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not bind, and with --strict on every block.` /** Adds the `--strict` / `--no-strict` pair to a check command. */ @@ -509,10 +523,18 @@ export async function checkWorkflowDir( : undefined return previousFile === undefined || written.digests[previousFile] !== textDigest } + const moved = (blockKey: string | undefined) => { + const held = blockKey === undefined || !lock ? undefined : getOwn(lock.blocks, blockKey) + const block = + blockKey === undefined || !compiled.workflow + ? undefined + : getOwn(compiled.workflow.blocks, blockKey) + return held !== undefined && block !== undefined && held.parent !== block.parent + } const editedRefusal = (code: string, file: string | undefined, blockKey: string | undefined) => - file !== undefined && file !== SOURCE_ENTRY_FILE && edited(file, blockKey) + (file !== undefined && file !== SOURCE_ENTRY_FILE && edited(file, blockKey) ? EDITED_FILE_REFUSALS.get(code) - : undefined + : undefined) ?? (moved(blockKey) ? MOVED_BLOCK_REFUSALS.get(code) : undefined) const fails = (code: string, blockKey: string | undefined) => STRICT_CODES.has(code) && !(STORED_EXEMPT_CODES.has(code) && bound(blockKey)) && diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 32de8c5040a..be1ffcd0d5d 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -844,6 +844,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -954,6 +955,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1332,6 +1334,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1441,6 +1444,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1614,6 +1618,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1723,6 +1728,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -5275,6 +5281,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -5385,6 +5392,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -10371,6 +10379,7 @@ export type GetWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -10481,6 +10490,7 @@ export type GetWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -11054,6 +11064,7 @@ export type GetWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -11163,6 +11174,7 @@ export type GetWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' diff --git a/packages/workflow-code/src/code-files/index.ts b/packages/workflow-code/src/code-files/index.ts index a89abc2f428..b1d16781a22 100644 --- a/packages/workflow-code/src/code-files/index.ts +++ b/packages/workflow-code/src/code-files/index.ts @@ -1,5 +1,5 @@ export { checkCodeFileBijection } from './bijection' export { type CodeFileRef, fromCodeFile } from './from-file' export { createJsContextScanner } from './lexer' -export { isIdentifierName } from './ref-path' +export { isIdentifierName, LOOP_PROPERTIES, PARALLEL_PROPERTIES } from './ref-path' export { type CodeFileLanguage, codeFileLanguage, toCodeFile } from './to-file' diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index ba04ecf26a6..7ab4865fb87 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1669,3 +1669,91 @@ describe('meta.retry', () => { }) }) }) + +describe('iteration references outside their container', () => { + const codes = (result: CompileResult) => + result.diagnostics.filter((d) => d.code === 'W_REF_OUT_OF_SCOPE') + + it('reports a handle read of a loop index from a block after the loop', () => { + const result = run( + source( + [ + START, + "const lp = loop.for('Lp', { count: 2 }, (p) => {", + " const inner = fn('Inner', { code: js`return ${p.index}` })", + ' p.to(inner)', + '})', + "const after = fn('After', { code: js`return ${lp.index}` })", + 'start.to(lp)', + 'lp.to(after)', + ].join('\n') + ) + ) + const [finding] = codes(result) + expect(finding?.blockKey).toBe('after') + expect(finding?.span.line).toBe(10) + expect(codes(result)).toHaveLength(1) + }) + + it('reports $ref.loop and a named $ref index in a code file of a block in no loop', () => { + const result = run( + source( + [ + START, + "const lp = parallel.count('Fan', { count: 2 }, (p) => {", + " const inner = fn('Inner', { code: codeFile('./fns/inner.js') })", + ' p.to(inner)', + '})', + "const after = fn('After', { code: codeFile('./fns/after.js') })", + 'start.to(lp)', + 'lp.to(after)', + ].join('\n') + ), + { + 'workflows/fns/inner.js': 'return [$ref.parallel.index, $ref.fan.currentItem]', + 'workflows/fns/after.js': 'return [$ref.loop.index, $ref.fan.index, $ref.fan.results]', + } + ) + expect(codes(result).map((d) => [d.blockKey, d.span.file])).toEqual([ + ['after', 'workflows/fns/after.js'], + ['after', 'workflows/fns/after.js'], + ]) + }) + + it('reports a tag in a block in no loop, and keeps a while condition quiet', () => { + const result = run( + source( + [ + START, + "const w = loop.while('W', { condition: ' < 3' }, (p) => {", + " const inner = fn('Inner', { code: 'return 1' })", + ' p.to(inner)', + '})', + "const after = api('After', { url: t`https://x/` })", + 'start.to(w)', + 'w.to(after)', + ].join('\n') + ) + ) + expect(codes(result).map((d) => d.blockKey)).toEqual(['after']) + }) + + it('accepts an outer container read from a nested body', () => { + const result = run( + source( + [ + START, + "const outer = loop.forEach('Outer', { collection: [1, 2] }, (p) => {", + " const inner = parallel.count('Inner', { count: 2 }, (q) => {", + " const leaf = fn('Leaf', { code: js`return [${outer.index}, ${p.currentItem}, ${q.index}]` })", + ' q.to(leaf)', + ' })', + ' p.to(inner)', + '})', + 'start.to(outer)', + ].join('\n') + ) + ) + expect(codes(result)).toEqual([]) + }) +}) diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 3f8a01f33c1..e327bf0b2aa 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -183,6 +183,79 @@ export function objectEntries( * normalized block key, or names no declared block. Such text is kept verbatim, so a rename in the * same apply never rewrites it; the block's ident is the reference that follows the block. */ +/** + * The containers whose iteration fields a block reads at run time: those enclosing it, and the + * block itself when it is one (a while condition reads ``). + */ +function iterationScopes(decl: BlockDecl): BlockDecl[] { + const enclosing = enclosingContainers(decl) + return containerKindOf(decl) ? [decl, ...enclosing] : enclosing +} + +/** + * Reports `W_REF_OUT_OF_SCOPE` when block `siteKey` reads iteration field `property` of a + * container it is not inside: `container` is a declared loop or parallel (`lp.index`, + * `$ref.lp.index`), or the kind whose innermost enclosing container `` names. Outside + * the container the executor refuses a named iteration field and finds no scope for a bare one. + * A container output (`results`) and a property no container has are not this check's. + */ +function checkIterationScope( + ctx: CompileContext, + at: Range, + siteKey: BlockKey, + container: BlockDecl | 'loop' | 'parallel', + property: string +): void { + const site = ctx.declsByKey.get(siteKey) + const kind = typeof container === 'string' ? container : containerKindOf(container) + if (!site || !kind) return + if (!(kind === 'loop' ? LOOP_PROPERTIES : PARALLEL_PROPERTIES).includes(property)) return + const scopes = iterationScopes(site) + if (typeof container === 'string') { + if (scopes.some((decl) => containerKindOf(decl) === kind)) return + ctx.reporter.report( + 'W_REF_OUT_OF_SCOPE', + `${site.name} reads the enclosing ${kind}'s ${property}, but it sits in no ${kind}, so the reference resolves to nothing at run time.`, + at, + { + hint: `Move ${site.name} into a ${kind}'s body, or read a ${kind}'s results after it finishes.`, + blockKey: siteKey, + } + ) + return + } + if (scopes.includes(container)) return + ctx.reporter.report( + 'W_REF_OUT_OF_SCOPE', + `${site.name} reads ${container.name}'s ${property}, but it is not inside ${container.name}; outside it a ${kind} outputs only results, so the run fails.`, + at, + { + hint: `Move ${site.name} into ${container.name}'s body, or read ${container.ident ?? container.key}.results after it finishes.`, + blockKey: siteKey, + } + ) +} + +/** + * {@link checkIterationScope} for a reference path (`` text, a code file's + * `$ref.head.property`) whose head is `loop`, `parallel` or a declared container's key. + */ +function checkIterationTag( + ctx: CompileContext, + at: Range, + siteKey: BlockKey, + segments: readonly RefSegment[] +): void { + const [head, property] = segments + if (head?.kind !== 'name' || property?.kind !== 'name') return + if (head.name === 'loop' || head.name === 'parallel') { + checkIterationScope(ctx, at, siteKey, head.name, property.name) + return + } + const target = ctx.declsByKey.get(head.name) + if (target) checkIterationScope(ctx, at, siteKey, target, property.name) +} + function checkLiteralRefs(ctx: CompileContext, node: Node, text: string, site: ValueSite): void { for (const token of findWorkflowReferenceTokens(text)) { if (token.kind !== 'workflow') continue @@ -193,8 +266,10 @@ function checkLiteralRefs(ctx: CompileContext, node: Node, text: string, site: V if ( normalized === head.name && (isReservedWorkflowBlockName(head.name) || ctx.declsByKey.has(head.name)) - ) + ) { + checkIterationTag(ctx, rangeOf(ctx, node), site.decl.key, segments) continue + } const target = ctx.declsByKey.get(normalized) ctx.reporter.report( 'W_REF_NOT_NORMALIZED', @@ -699,6 +774,7 @@ function checkOutputPath( { hint: () => didYouMean(first.name, known), blockKey } ) } + if (first.kind === 'name') checkIterationScope(ctx, at, blockKey, target, first.name) return } const block = catalogBlockOf(target) @@ -894,7 +970,10 @@ export function checkCodeFileRefs( } continue } - if (isReservedWorkflowBlockName(head.name)) continue + if (isReservedWorkflowBlockName(head.name)) { + checkIterationTag(ctx, at, blockKey, ref.segments) + continue + } const renamedTo = renamed.get(head.name) const target = ctx.declsByKey.get(head.name) ?? diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index d768acdb64e..aead134b82d 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -108,6 +108,14 @@ const COMPILE_SCOPE_CODES = [ * `[`...): the runtime would read the token as text or as another block. */ 'E_REF_UNREPRESENTABLE', + /** + * A loop or parallel iteration field (`index`, `currentItem`, `items`) read from a block outside + * that container: `lp.index` after the loop, `$ref.loop.index` or `` in a block in + * no loop. The run fails (or reads nothing) there. A warning so a stored workflow that holds one + * still round-trips; the apply refuses it on a block the edit changed as + * `E_APPLY_REF_OUT_OF_SCOPE`. + */ + 'W_REF_OUT_OF_SCOPE', ] as const /** Wiring. */ @@ -460,6 +468,11 @@ const APPLY_DIAGNOSTIC_CODES = [ * at run time; on code the stored workflow already holds it stays `W_UNRESOLVED_REF`. */ 'E_APPLY_UNRESOLVED_REF', + /** + * A `W_REF_OUT_OF_SCOPE` iteration reference on a block the edit added, changed or moved, which + * fails at run time. + */ + 'E_APPLY_REF_OUT_OF_SCOPE', /** A non-blocking workflow lint finding, mapped to a source line. */ 'W_APPLY_LINT', /** A table row write (insert, upsert, update) with a key that is not a column of its table. */ diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 19728c486e8..9e5d3cec71d 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -35,6 +35,8 @@ export { createJsContextScanner, fromCodeFile, isIdentifierName, + LOOP_PROPERTIES, + PARALLEL_PROPERTIES, } from './code-files' export { type CompileResult, compileWorkflow, type StoredEdgeRef } from './compile' export { codePointLabel, scriptName } from './compile/characters' diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index 0af41cd628b..9e69817c8db 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutput\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which is how a block\n * in a nested container reads an outer loop\u0027s index or item.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode. An object or array `body` is\n * JSON whose references keep their types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`,\n * or the block\u0027s own params (`dataMode`, `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" +export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutput\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode. An object or array `body` is\n * JSON whose references keep their types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`,\n * or the block\u0027s own params (`dataMode`, `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" diff --git a/packages/workflow-sdk/src/core.d.ts b/packages/workflow-sdk/src/core.d.ts index e421e76503a..fdf7c69ae7b 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -576,8 +576,9 @@ export interface SubflowScope extends Node { } /** - * A container's outputs, plus its iteration fields by name (`outer.index`), which is how a block - * in a nested container reads an outer loop's index or item. + * A container's outputs, plus its iteration fields by name (`outer.index`), which a block inside + * the container reads (in a nested container too: an outer loop's index or item). Outside the + * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there. */ export interface SubflowOutput { results: Json[] From ecdd05e431e6e87b74b519157cc2c76bdd4264ad Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:48:13 -0800 Subject: [PATCH 008/104] fix(workflow-code): a reference tag written in a code file is checked A tag in a JavaScript string, or in a Python or shell file, is resolved at run time and rewritten on a rename, but compile never checked it: '' or passed with no finding. Compile now finds each tag with the runtime's scanner and checks it as it checks a $ref chain (W_UNRESOLVED_REF, W_UNKNOWN_OUTPUT_PATH, W_REF_OUT_OF_SCOPE), written as the file writes it, so the apply refuses a dangling tag in code the edit changed. A token with no path ( in HTML text) is not a reference. --- .../workflow-code/src/code-files/from-file.ts | 5 +- packages/workflow-code/src/compile/blocks.ts | 30 ++++++++-- .../workflow-code/src/compile/grammar.test.ts | 55 +++++++++++++++++++ packages/workflow-code/src/compile/values.ts | 40 +++++++++----- 4 files changed, 108 insertions(+), 22 deletions(-) diff --git a/packages/workflow-code/src/code-files/from-file.ts b/packages/workflow-code/src/code-files/from-file.ts index 73822fa766f..9d81cbe57f1 100644 --- a/packages/workflow-code/src/code-files/from-file.ts +++ b/packages/workflow-code/src/code-files/from-file.ts @@ -17,10 +17,11 @@ interface CodeFileSyntaxError { /** * One `$ref` chain (`segments`) or `$env` name (`env`) read from the file, at its UTF-16 offsets - * in the file text. + * in the file text. `tag` marks a reference the file writes as stored text (``), which + * the file keeps as written and the run resolves as it does a rewritten `$ref`. */ export type CodeFileRef = { start: number; end: number } & ( - | { kind: 'ref'; segments: RefSegment[] } + | { kind: 'ref'; segments: RefSegment[]; tag?: true } | { kind: 'env'; name: string } ) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 0a3dc59abf8..deea679cd3c 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -32,8 +32,13 @@ import { } from '../catalog/surface' import type { CatalogBlock, CatalogSubBlock } from '../catalog/types' import { catalogBuildersOfType } from '../catalog/view' -import { type CodeFileLanguage, codeFileLanguage, fromCodeFile } from '../code-files' -import { isIdentifierName } from '../code-files/ref-path' +import { + type CodeFileLanguage, + type CodeFileRef, + codeFileLanguage, + fromCodeFile, +} from '../code-files' +import { isIdentifierName, parseStoredPath } from '../code-files/ref-path' import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' import { type ConfigField, type ContainerForm, loopForm, parallelForm } from '../forms/subflow' @@ -426,12 +431,27 @@ function parseCodeFile( } return null } - if (back.refs.length > 0) { - ctx.codeFiles.chains.push({ path, blockKey: decl.key, refs: back.refs }) - } + const refs = [...back.refs, ...referenceTags(text)].sort((a, b) => a.start - b.start) + if (refs.length > 0) ctx.codeFiles.chains.push({ path, blockKey: decl.key, refs }) return back.code } +/** + * The `` references a code file writes as text, found by the runtime's own scanner (a + * JavaScript string, a Python or shell line): the run resolves each one, so compile checks them as + * it checks a `$ref` chain. A token with no path (`` in HTML text) is no reference. + */ +function referenceTags(text: string): CodeFileRef[] { + const tags: CodeFileRef[] = [] + for (const token of findWorkflowReferenceTokens(text)) { + if (token.kind !== 'workflow') continue + const segments = parseStoredPath(token.value.slice(1, -1)) + if (!segments || segments.length < 2) continue + tags.push({ kind: 'ref', segments, start: token.start, end: token.end, tag: true }) + } + return tags +} + interface WrittenParam { property: ObjectProperty param: string diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 7ab4865fb87..693a0412332 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1757,3 +1757,58 @@ describe('iteration references outside their container', () => { expect(codes(result)).toEqual([]) }) }) + +describe('reference tags written in a code file', () => { + const unresolved = (result: CompileResult) => + result.diagnostics + .filter((d) => d.code === 'W_UNRESOLVED_REF') + .map((d) => ({ message: d.message, file: d.span.file, line: d.span.line })) + + it('checks tags in JavaScript strings as it checks $ref chains', () => { + const result = run( + source( + [START, "const f = fn('F', { code: codeFile('./fns/f.js') })", 'start.to(f)'].join('\n') + ), + { + 'workflows/fns/f.js': [ + "const a = ''", + 'const b = ``', + "const html = '' + a + ''", + "return [a, b, html, '', $ref.start.q]", + ].join('\n'), + } + ) + expect(unresolved(result)).toEqual([ + { + message: ' names no block, so it does not resolve at run time.', + file: 'workflows/fns/f.js', + line: 1, + }, + { + message: ': no workflow variable is keyed ghost.', + file: 'workflows/fns/f.js', + line: 2, + }, + ]) + }) + + it('checks tags in a Python file', () => { + const result = run( + source( + [ + START, + "const f = fn('F', { language: 'python', code: codeFile('./fns/f.py') })", + 'start.to(f)', + ].join('\n') + ), + { 'workflows/fns/f.py': 'q = \nr = \nreturn [q, r]' } + ) + expect(unresolved(result)).toEqual([ + { + message: ' names no block, so it does not resolve at run time.', + file: 'workflows/fns/f.py', + line: 2, + }, + ]) + }) +}) diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index e327bf0b2aa..15d3264ff77 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -953,7 +953,10 @@ export function checkCodeFileRefs( } const [head, ...rest] = ref.segments if (head?.kind !== 'name') continue - const written = formatMemberPath(REF_ROOT, ref.segments) + /** The reference as the file writes it: a `$ref` chain, or a `` tag. */ + const spell = (segments: RefSegment[]) => + ref.tag ? `<${formatStoredPath(segments)}>` : formatMemberPath(REF_ROOT, segments) + const written = spell(ref.segments) if (head.name === 'variable') { const name = rest[0]?.kind === 'name' ? rest[0].name : null if (name !== null && !ctx.variables.has(name)) { @@ -963,7 +966,9 @@ export function checkCodeFileRefs( at, { hint: () => - didYouMean(name, ctx.variables.keys(), (key) => `${REF_ROOT}.variable.${key}`), + didYouMean(name, ctx.variables.keys(), (key) => + spell([head, { kind: 'name', name: key }]) + ), blockKey, } ) @@ -985,18 +990,20 @@ export function checkCodeFileRefs( const byIdent = ctx.declsByIdent.get(head.name)?.[0] const byName = ctx.declsByKey.get(normalizeWorkflowBlockName(head.name)) const suggested = byIdent ?? byName - const rewritten = (key: BlockKey) => - formatMemberPath(REF_ROOT, [{ kind: 'name', name: key }, ...rest]) + const rewritten = (key: BlockKey) => spell([{ kind: 'name', name: key }, ...rest]) ctx.reporter.report( 'W_UNRESOLVED_REF', `${written} names no block, so it does not resolve at run time.`, at, { hint: suggested - ? `${REF_ROOT} names a block by its key: write ${rewritten(suggested.key)}.` + ? `${ref.tag ? 'A tag' : REF_ROOT} names a block by its key: write ${rewritten(suggested.key)}.` : ctx.knownKeys.has(head.name) - ? formerBlockHint(ctx, head.name, renamed, rewritten) - : () => didYouMean(head.name, ctx.declsByKey.keys(), (key) => `${REF_ROOT}.${key}`), + ? formerBlockHint(ctx, head.name, renamed, rewritten, spell) + : () => + didYouMean(head.name, ctx.declsByKey.keys(), (key) => + spell([{ kind: 'name', name: key }]) + ), blockKey, } ) @@ -1005,27 +1012,30 @@ export function checkCodeFileRefs( } /** - * The hint for a code file `$ref` head that is the key of a block the workflow had (the lock or - * the stored workflow binds it) and source no longer declares: most often a block renamed in both - * name and const, whose references an apply rewrites only when it ties the block to the stored - * one. Names the one declared block nothing binds, when there is exactly one, as the probable new - * key (`rewritten` writes the reference with it). + * The hint for a code file reference whose head is the key of a block the workflow had (the lock + * or the stored workflow binds it) and source no longer declares: most often a block renamed in + * both name and const, whose references an apply rewrites only when it ties the block to the + * stored one. Names the one declared block nothing binds, when there is exactly one, as the + * probable new key (`rewritten` writes the reference with it; `spell` writes a reference path as + * the file does). */ function formerBlockHint( ctx: CompileContext, formerKey: BlockKey, renamed: ReadonlyMap, - rewritten: (key: BlockKey) => string + rewritten: (key: BlockKey) => string, + spell: (segments: RefSegment[]) => string ): string { const renamedTo = new Set(renamed.values()) const unbound = [...ctx.declsByKey.values()].filter( (decl) => !ctx.knownKeys.has(decl.key) && !renamedTo.has(decl.key) ) - const lead = `${REF_ROOT}.${formerKey} is a block this workflow had that ${SOURCE_ENTRY_FILE} no longer declares under that key` + const lead = `${spell([{ kind: 'name', name: formerKey }])} is a block this workflow had that ${SOURCE_ENTRY_FILE} no longer declares under that key` const [only] = unbound + const placeholder = spell([{ kind: 'name', name: 'NEWKEY' }]).replace('NEWKEY', '') return unbound.length === 1 && only ? `${lead}: if ${only.name} is it renamed, write ${rewritten(only.key)}.` - : `${lead}: if you renamed it, write ${REF_ROOT}., the display name lowercased with whitespace and dots removed.` + : `${lead}: if you renamed it, write ${placeholder}, the display name lowercased with whitespace and dots removed.` } function subflowScopeRef( From 09ba45eb3f4ab08f3de3b02762ca5bee6a150a4a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:56:02 -0800 Subject: [PATCH 009/104] fix(workflow-code): $ref in a Python or shell code file is diagnosed Only JavaScript code files are rewritten, so $ref.key.path or $env.NAME in a .py or .sh file was saved as written and broke the code at run time, while the primer told agents to write $ref in any function code file. Compile now reports W_CODE_FILE_REF_SYNTAX with the form those files take (, {{NAME}}); the apply refuses it as E_APPLY_CODE_FILE_REF_SYNTAX on code the edit changed, and an offline check in a file changed since the get. The code-file refusals the server and the check apply are one shared map, EDITED_CODE_FILE_REFUSALS. The primer, the docs and SYNTAX.md state the per-language form. --- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- apps/docs/content/docs/workflows/code.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 12 ++++ .../apply-workflow-source.integration.ts | 32 +++++++++++ .../workflows/application/source-evaluate.ts | 25 +++++---- .../src/commands/protocol/source-primer.ts | 2 +- .../protocol/workflow-source-check.test.ts | 30 ++++++++++ .../protocol/workflow-source-check.ts | 19 ++----- packages/sim-cli/src/generated/v2-api.ts | 12 ++++ packages/workflow-code/src/compile/SYNTAX.md | 5 +- packages/workflow-code/src/compile/blocks.ts | 36 ++++++++++++ .../workflow-code/src/compile/grammar.test.ts | 55 +++++++++++++++++++ .../workflow-code/src/diagnostics/codes.ts | 30 ++++++++++ packages/workflow-code/src/index.ts | 1 + 16 files changed, 236 insertions(+), 33 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index c21c8a123f4..46ca1f84995 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8640,7 +8640,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -10018,7 +10018,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index a1b788ab8fb..ff8ac309aed 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1444,7 +1444,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index cce03d4c0fb..9f08d62589f 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. 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. diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index a46903e0f7a..bf84fb2c496 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -197,7 +197,7 @@ Code that does not fit a block goes in a Function block, kept in its own file: const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) ``` -In the file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is a warning, because it would not resolve when the workflow runs. Python and shell files are saved as written. +In the file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is refused in a file you edited, because it would not resolve when the workflow runs. Python and shell files are saved as written, so `$ref` and `$env` mean nothing there: read an output as `` (``) and an environment variable as `{{NAME}}`. ## Use it in CI diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 4fc4720447d..c3172cb52c2 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -18811,6 +18811,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -18922,6 +18923,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -19258,6 +19260,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19369,6 +19372,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -20222,6 +20226,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -20333,6 +20338,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -25268,6 +25274,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25378,6 +25385,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -25837,6 +25845,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25947,6 +25956,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -26249,6 +26259,7 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -26359,6 +26370,7 @@ "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", 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 1f5f95e92da..4573578a806 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2530,6 +2530,38 @@ describe('renames in source', () => { } ) + check( + 'a $ref the edit wrote into a Python function file is refused, naming the tag', + async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + const entry = source.files['workflow.ts'].replace( + /fn\('Boom', \{.*\}\)/, + "fn('Boom', { language: 'python', code: codeFile('./functions/boom.py') })" + ) + expect(entry).toContain('boom.py') + const files = { + ...omit(source.files, ['functions/boom.js']), + 'workflow.ts': entry, + 'functions/boom.py': 'return $ref.start.value\n', + } + + const dryRun = await apply(source, files, { dryRun: true }) + + expect( + dryRun.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ code: d.code, file: d.file, hint: d.hint })) + ).toEqual([ + { + code: 'E_APPLY_CODE_FILE_REF_SYNTAX', + file: 'functions/boom.py', + hint: 'Python files are saved as written: write .', + }, + ]) + } + ) + check( 'a dangling reference the stored code already holds stays a warning, whatever else the apply changes', async () => { diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 2613972b67c..25400b1c9f8 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -13,6 +13,7 @@ import { compileWorkflow, type Diagnostic, diffCanonical, + EDITED_CODE_FILE_REFUSALS, encodeAnchor, getOwn, type LocatedDiagnostic, @@ -309,32 +310,34 @@ function withoutRenameSettledFindings( } /** - * `diagnostics` with each function code file `W_UNRESOLVED_REF` on a block whose code the source - * changed (`codeChanged`, by block key) refused as `E_APPLY_UNRESOLVED_REF`: a `$ref` the edit - * wrote that names no block fails at run time. On code the stored workflow already holds it stays - * a warning, so a workflow saved with a dangling reference still applies unchanged. + * `diagnostics` with each function code file finding of {@link EDITED_CODE_FILE_REFUSALS} on a + * block whose code the source changed (`codeChanged`, by block key) refused under its error code: + * a `$ref` naming no block, a `$ref` in a Python file, fail at run time. On code the stored + * workflow already holds it stays a warning, so a workflow saved with one still applies unchanged. */ function withEditedCodeFileRefsRefused( diagnostics: CompileResult['diagnostics'], codeChanged: (blockKey: string) => boolean ): LocatedDiagnostic[] { return diagnostics.map((diagnostic): LocatedDiagnostic => { + const refusal = EDITED_CODE_FILE_REFUSALS.get(diagnostic.code) if ( - diagnostic.code !== 'W_UNRESOLVED_REF' || + refusal === undefined || diagnostic.span.file === SOURCE_ENTRY_FILE || diagnostic.blockKey === undefined || !codeChanged(diagnostic.blockKey) ) { return diagnostic } - return { ...diagnostic, code: 'E_APPLY_UNRESOLVED_REF', severity: 'error' } + return { ...diagnostic, code: refusal, severity: 'error' } }) } /** * The apply's handling of compile's `W_REF_OUT_OF_SCOPE`, an iteration field read from outside * its container: refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the write adds, changes or - * moves (`changed`, by block key), which would fail at run time; a warning on a block the stored + * moves (`changed`, by block key), which would fail at run time (a code file the edit changed + * already refused it); a warning on a block the stored * workflow already holds as it is, so such a workflow still applies unchanged. The lint's finding * for the same block is dropped from `lint`, as compile's is the one located at the source line. */ @@ -346,11 +349,11 @@ function withOutOfScopeRefsRefused( ): { diagnostics: LocatedDiagnostic[]; lint: WorkflowLintReport } { const reported = new Set() const refused = diagnostics.map((diagnostic): LocatedDiagnostic => { - if (diagnostic.code !== 'W_REF_OUT_OF_SCOPE' || diagnostic.blockKey === undefined) { - return diagnostic - } + const scoped = + diagnostic.code === 'W_REF_OUT_OF_SCOPE' || diagnostic.code === 'E_APPLY_REF_OUT_OF_SCOPE' + if (!scoped || diagnostic.blockKey === undefined) return diagnostic reported.add(diagnostic.blockKey) - return changed(diagnostic.blockKey) + return diagnostic.code === 'W_REF_OUT_OF_SCOPE' && changed(diagnostic.blockKey) ? { ...diagnostic, code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' } : diagnostic }) diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 9d65ba1bf09..81f35c9e851 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -37,7 +37,7 @@ 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: the block keeps its id. Renaming the const too keeps the id when its settings, neighbours or references still tie it to the old block; otherwise the apply refuses it as a delete (\`E_APPLY_BLOCK_DELETE\`), and the dry run names it. Safest: keep the const in the same apply. -- **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 with 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\`. An index or item is read only from a block inside its container: outside it (\`lp.index\` after the loop, or a block moved out) the run fails, which the apply refuses (\`E_APPLY_REF_OUT_OF_SCOPE\`); read \`lp.results\` after the loop instead. A rename keeps its references working: the apply rewrites every \`$ref.\` in the function files to the new key (and the files it writes back hold it), so leave them or write the new key yourself. A \`$ref\` that names no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\` in \`check\` and the dry run). +- **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 with 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\`. \`.py\`/\`.sh\` files are saved as written: write \`\` and \`{{NAME}}\` there, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`); after it, \`lp.results\`. A rename keeps its references working: the apply rewrites every \`$ref.\` in the function files to the new key (and the files it writes back hold it), so leave them or write the new key yourself. A \`$ref\` that names no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\` in \`check\` and the dry run). - **Look up a builder**: \`${PARAMS_COMMAND} \` (\`table.upsertRow\`, \`agent\`, \`trigger.schedule\`; a namespace such as \`gmail\` lists its builders), offline. - **Exit codes**: 0 ok, 1 errors (fix what it printed), ${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-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index 10f77371877..4e524912b53 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 @@ -525,6 +525,36 @@ export default workflow('W', {}, () => { expect(process.exitCode).toBeUndefined() }) + it('fails on $ref in a Python function file, naming the tag the file writes instead', async () => { + cacheCatalog() + mkdirSync(join(dir, 'functions'), { recursive: true }) + writeFileSync(join(dir, 'functions/total.py'), 'q = $ref.start.q\nreturn q\n') + writeFileSync( + join(dir, 'workflow.ts'), + `// @sim-sdk 1 +import { codeFile, fn, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', { inputFormat: { q: 'string' } }) + const total = fn('Total', { language: 'python', code: codeFile('./functions/total.py') }) + start.to(total) +}) +` + ) + + await check() + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ + code: 'E_APPLY_CODE_FILE_REF_SYNTAX', + severity: 'error', + file: 'functions/total.py', + line: 1, + hint: 'Python files are saved as written: write .', + }) + ) + expect(process.exitCode).toBe(1) + }) + it('fails on a dangling $ref in a new function file by default, and on any with --strict', async () => { cacheCatalog() mkdirSync(join(dir, 'functions'), { recursive: true }) 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 3df7852edbb..6526f18f412 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -7,6 +7,7 @@ import { codePointLabel, compileWorkflow, didYouMean, + EDITED_CODE_FILE_REFUSALS, encodeAnchor, getOwn, parseJsonField, @@ -92,19 +93,6 @@ const STORED_EXEMPT_CODES: ReadonlySet = new Set(['W_BRANCH_UNWIRED']) */ const EDIT_SCOPED_CODES: ReadonlySet = new Set(['W_JSON_REF_UNTYPED']) -/** - * Warnings in a function code file a check refuses under the server's error code, whatever the - * strict mode, when that file changed since the get wrote it (or is new; a file only moved from - * the path the lock bound its block to is unchanged while its text matches that path's digest): - * the server refuses them on code the edit changed, and keeps them as warnings only on code the - * stored workflow already holds. `W_UNRESOLVED_REF`, a `$ref` naming no block or variable, which fails at run time, is - * `E_APPLY_UNRESOLVED_REF`. - */ -const EDITED_FILE_REFUSALS: ReadonlyMap = new Map([ - ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], - ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], -]) - /** * Warnings a check refuses under the server's error code, whatever the strict mode, on a block the * lock binds that the source moved into another container: the server refuses them on any block @@ -152,7 +140,7 @@ does not bind (a block added since the get, or every block of a new workflow): ${[...STRICT_CODES].map((code) => ` ${code}`).join(',\n')}. --strict fails on them in every block, except ${[...STORED_EXEMPT_CODES].join(', ')} 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 a function file changed since the get, ${[...EDITED_FILE_REFUSALS] +on none of them. In a function file changed since the get, ${[...EDITED_CODE_FILE_REFUSALS] .map(([warning, refusal]) => `${warning} is the error ${refusal}`) .join(', ')} in every mode, as the server refuses it; so is ${[...MOVED_BLOCK_REFUSALS] .map(([warning, refusal]) => `${warning} (${refusal})`) @@ -512,6 +500,7 @@ export async function checkWorkflowDir( const bound = (blockKey: string | undefined) => lock !== undefined && blockKey !== undefined && Object.hasOwn(lock.blocks, blockKey) const written = await readFolderWritten(dir) + // A file only moved from the path the lock bound its block to is unedited while its text matches that path's digest. const edited = (file: string, blockKey: string | undefined) => { const text = files[file] if (text === undefined) return true @@ -533,7 +522,7 @@ export async function checkWorkflowDir( } const editedRefusal = (code: string, file: string | undefined, blockKey: string | undefined) => (file !== undefined && file !== SOURCE_ENTRY_FILE && edited(file, blockKey) - ? EDITED_FILE_REFUSALS.get(code) + ? EDITED_CODE_FILE_REFUSALS.get(code) : undefined) ?? (moved(blockKey) ? MOVED_BLOCK_REFUSALS.get(code) : undefined) const fails = (code: string, blockKey: string | undefined) => STRICT_CODES.has(code) && diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index be1ffcd0d5d..c231cd82084 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -845,6 +845,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -956,6 +957,7 @@ export type ApplyWorkflowSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1335,6 +1337,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1445,6 +1448,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1619,6 +1623,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1729,6 +1734,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -5282,6 +5288,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -5393,6 +5400,7 @@ export type CreateWorkflowFromSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -10380,6 +10388,7 @@ export type GetWorkflowSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -10491,6 +10500,7 @@ export type GetWorkflowSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -11065,6 +11075,7 @@ export type GetWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -11175,6 +11186,7 @@ export type GetWorkspaceSourceResponse = { | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index a2fdb95a20e..1278354bb82 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -270,7 +270,10 @@ template. `code: codeFile('./functions/x.js')`, relative to `workflow.ts`, with the extension matching `language` (default `javascript`). Otherwise `E_CODE_FILE_PATH`; a file the request did not send is `E_CODE_FILE_MISSING`. JavaScript files use `$ref.block.path` for `` and `$env.NAME` for -`{{NAME}}`, rewritten back on compile; Python and shell files are verbatim. `$ref` names a block by +`{{NAME}}`, rewritten back on compile; Python and shell files are verbatim, so they write +`` and `{{NAME}}` themselves, and a `$ref` or `$env` in one is +`W_CODE_FILE_REF_SYNTAX` (the apply refuses it in a file the edit changed). A `` tag in +any code file (a JavaScript string included) is checked like a `$ref` chain. `$ref` names a block by its key (`$ref.triageagent.content`), not its ident; a chain that names no block or variable is `W_UNRESOLVED_REF` at the file location (the hint names the key when the head is an ident or a block name), and a path no output has is `W_UNKNOWN_OUTPUT_PATH`. When the stored code diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index deea679cd3c..749a711a516 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -431,11 +431,47 @@ function parseCodeFile( } return null } + if (language !== 'javascript') reportScriptRefSyntax(ctx, path, text, language, decl.key) const refs = [...back.refs, ...referenceTags(text)].sort((a, b) => a.start - b.start) if (refs.length > 0) ctx.codeFiles.chains.push({ path, blockKey: decl.key, refs }) return back.code } +/** A `$ref` chain or `$env` name, as a JavaScript code file writes one. */ +const SCRIPT_REF = /\$(ref|env)((?:\.[A-Za-z0-9_$-]+)+)/g + +const SCRIPT_LANGUAGE_LABEL: Record, string> = { + python: 'Python', + shell: 'Shell', +} + +/** + * `W_CODE_FILE_REF_SYNTAX` on each `$ref.key.path` and `$env.NAME` in a Python or shell file: + * only JavaScript files are rewritten, so these reach the run as text and break the code. The + * hint names the form those files take, the stored `` tag or `{{NAME}}`, which the run + * resolves with the language's own quoting. + */ +function reportScriptRefSyntax( + ctx: CompileContext, + path: string, + text: string, + language: Exclude, + blockKey: BlockKey +): void { + const label = SCRIPT_LANGUAGE_LABEL[language] + for (const match of text.matchAll(SCRIPT_REF)) { + const [written, root, members] = match + const names = members.slice(1).split('.') + const form = root === 'env' ? `{{${names[0]}}}` : `<${names.join('.')}>` + ctx.reporter.report( + 'W_CODE_FILE_REF_SYNTAX', + `${written} is the JavaScript code file form; a ${label} file is saved as written, so the run reads it as text and the code breaks.`, + { file: path, start: match.index, end: match.index + written.length }, + { hint: `${label} files are saved as written: write ${form}.`, blockKey } + ) + } +} + /** * The `` references a code file writes as text, found by the runtime's own scanner (a * JavaScript string, a Python or shell line): the run resolves each one, so compile checks them as diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 693a0412332..2fa33a89744 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1812,3 +1812,58 @@ describe('reference tags written in a code file', () => { ]) }) }) + +describe('$ref and $env in a Python or shell code file', () => { + const syntax = (result: CompileResult) => + result.diagnostics + .filter((d) => d.code === 'W_CODE_FILE_REF_SYNTAX') + .map((d) => ({ hint: d.hint, file: d.span.file, line: d.span.line, column: d.span.column })) + + it('names the tag a Python file writes instead of $ref, and {{NAME}} instead of $env', () => { + const result = run( + source( + [ + START, + "const f = fn('F', { language: 'python', code: codeFile('./fns/f.py') })", + 'start.to(f)', + ].join('\n') + ), + { 'workflows/fns/f.py': "q = $ref.start.q\nkey = $env.API_KEY\nreturn '$5 ok'" } + ) + expect(syntax(result)).toEqual([ + { + hint: 'Python files are saved as written: write .', + file: 'workflows/fns/f.py', + line: 1, + column: 5, + }, + { + hint: 'Python files are saved as written: write {{API_KEY}}.', + file: 'workflows/fns/f.py', + line: 2, + column: 7, + }, + ]) + }) + + it('reports $ref in a shell file and leaves JavaScript files to the rewrite', () => { + const result = run( + source( + [ + START, + "const sh = fn('Sh', { language: 'shell', code: codeFile('./fns/s.sh') })", + "const js = fn('Js', { code: codeFile('./fns/j.js') })", + 'start.to(sh)', + 'sh.to(js)', + ].join('\n') + ), + { + 'workflows/fns/s.sh': 'echo "$ref.start.q" "$HOME"', + 'workflows/fns/j.js': 'return $ref.start.q', + } + ) + expect(syntax(result).map((d) => [d.file, d.hint])).toEqual([ + ['workflows/fns/s.sh', 'Shell files are saved as written: write .'], + ]) + }) +}) diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index aead134b82d..9c08c639400 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -116,6 +116,13 @@ const COMPILE_SCOPE_CODES = [ * `E_APPLY_REF_OUT_OF_SCOPE`. */ 'W_REF_OUT_OF_SCOPE', + /** + * `$ref.key.path` or `$env.NAME` in a Python or shell code file, which is saved as written (only + * JavaScript files are rewritten), so the run reads it as text; `hint` names the `` or + * `{{NAME}}` form those files take. A warning so stored code that holds the text still + * round-trips; refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. + */ + 'W_CODE_FILE_REF_SYNTAX', ] as const /** Wiring. */ @@ -473,6 +480,8 @@ const APPLY_DIAGNOSTIC_CODES = [ * fails at run time. */ 'E_APPLY_REF_OUT_OF_SCOPE', + /** A `W_CODE_FILE_REF_SYNTAX` in a code file the edit changed, which breaks the code at run time. */ + 'E_APPLY_CODE_FILE_REF_SYNTAX', /** A non-blocking workflow lint finding, mapped to a source line. */ 'W_APPLY_LINT', /** A table row write (insert, upsert, update) with a key that is not a column of its table. */ @@ -512,6 +521,27 @@ export const DIAGNOSTIC_CODES = [ ] as const export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number] +/** The error codes {@link EDITED_CODE_FILE_REFUSALS} refuses a code file warning under. */ +type EditedCodeFileRefusal = + | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' + +/** + * Code file warnings refused under an error code in a function code file the edit changed: the + * server refuses them on a block whose code the source changed, and an offline check in a file + * changed since the get wrote it. On code the stored workflow already holds they stay warnings, so + * a workflow saved with one still applies unchanged. + */ +export const EDITED_CODE_FILE_REFUSALS: ReadonlyMap = new Map< + CompileDiagnosticCode, + EditedCodeFileRefusal +>([ + ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], + ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], + ['W_CODE_FILE_REF_SYNTAX', 'E_APPLY_CODE_FILE_REF_SYNTAX'], +]) + /** * Whether a finding with `code` may carry a code frame. A finding about a literal secret in * source carries its span only, so the frame never echoes the secret over the API into logs or diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 9e5d3cec71d..03553c149b2 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -52,6 +52,7 @@ export { type ApplyDiagnosticCode, type DiagnosticCode, type DiagnosticSeverity, + EDITED_CODE_FILE_REFUSALS, framesSource, } from './diagnostics/codes' export { From 10a853629feb304ebfd63677c9713d0acad8e108 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:57:48 -0800 Subject: [PATCH 010/104] fix(workflow-code): the plan summary pairs swapped names and reports a retype diffCanonical dropped every rename pair whose base key the target still held, so two blocks that swapped display names fell back to pairing by key: the dry run and apply reported both as code/language changes with 3/3 edges moved where only two names changed. The same drop broke a chain rename after a name collision (Fetch Data renamed while Fetch.Data took its key), reporting a false 'both name and const changed' E_APPLY_BLOCK_DELETE. Rename pairs now win over key pairing, and an unpaired target block's edges never match a base edge. A retype mints a new id under the same key; it was reported as one modified block with one edge each way. replacedBetween names such keys from the two identities, and diffCanonical reports them as a removed plus an added block with all their edges. The delete gate still treats a retype as no delete, since W_MAT_RETYPE_RECREATED covers it. --- .../apply-workflow-source.integration.ts | 109 ++++++++++++++++++ .../workflows/application/source-evaluate.ts | 15 ++- packages/workflow-code/src/diff/index.test.ts | 70 ++++++++++- packages/workflow-code/src/diff/index.ts | 35 ++++-- packages/workflow-code/src/index.ts | 2 +- 5 files changed, 218 insertions(+), 13 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 4573578a806..d2543468168 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2339,6 +2339,115 @@ describe('renames in source', () => { expect(result.files['functions/report.js']).toBe('return $ref.bang.result + $ref.total.result') }) + check('two blocks that swap display names are two renames that move no edge', async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + const files = edit( + edit(edit(source.files, "fn('Boom'", "fn('Swap'"), "fn('Tally'", "fn('Boom'"), + "fn('Swap'", + "fn('Tally'" + ) + + const result = await apply(source, files) + + expect(result.applied).toBe(true) + expect(result.diff.blocks.added).toEqual([]) + expect(result.diff.blocks.removed).toEqual([]) + expect(result.diff.blocks.renamed).toEqual([ + { id: seeded.ids.boom, from: 'boom', to: 'tally' }, + { id: seeded.ids.tally, from: 'tally', to: 'boom' }, + ]) + expect( + result.diff.blocks.modified + .filter((block) => block.id === seeded.ids.boom || block.id === seeded.ids.tally) + .map((block) => block.fields) + ).toEqual([['name'], ['name']]) + expect(result.diff.edges).toEqual({ added: 0, removed: 0 }) + }) + + check('a retype is reported as a removed and an added block with all their edges', async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + const entry = source.files['workflow.ts'] + .replace(/import \{ /, 'import { api, ') + .replace( + / {2}const tally = fn\('Tally'.*\n/, + " const tally = api('Tally', { url: 'https://x.test' })\n" + ) + expect(entry).toContain("api('Tally'") + const files = { ...omit(source.files, ['functions/tally.js']), 'workflow.ts': entry } + + const result = await apply(source, files) + + expect(result.applied).toBe(true) + expect(codes(result.diagnostics)).toContain('W_MAT_RETYPE_RECREATED') + expect(result.diff.blocks.removed).toEqual([ + { id: seeded.ids.tally, key: 'tally', type: 'function' }, + ]) + expect(result.diff.blocks.added).toEqual([ + expect.objectContaining({ key: 'tally', type: 'api' }), + ]) + expect(result.diff.blocks.modified.map((block) => block.key)).not.toContain('tally') + expect(result.diff.edges).toEqual({ added: 2, removed: 2 }) + }) + + check( + 'after a name collision, renaming one block and dropping the other key override keeps both ids', + async () => { + const workflowId = generateId() + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: `Source collision ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const block = (name: string, type: string, code?: string): BlockState => ({ + id: generateId(), + type, + name, + position: { x: 0, y: 0 }, + subBlocks: code === undefined ? {} : { code: { id: 'code', type: 'code', value: code } }, + outputs: {}, + enabled: true, + }) + const start = block('Start', 'start_trigger') + const first = block('Fetch Data', 'function', 'return 1') + const second = block('Fetch.Data', 'function', 'return 2') + const saved = await saveWorkflowToNormalizedTables(workflowId, { + blocks: { [start.id]: start, [first.id]: first, [second.id]: second }, + edges: [ + { id: generateId(), source: start.id, target: first.id }, + { id: generateId(), source: first.id, target: second.id }, + ], + loops: {}, + parallels: {}, + }) + if (!saved.success) throw new Error(`Seeding the workflow failed: ${saved.error}`) + const source = await getSource(workflowId) + const entry = source.files['workflow.ts'] + expect(entry).toContain("key: 'fetchdata~2'") + const edited = entry + .replace("fn('Fetch Data'", "fn('Get Data'") + .replace(/,?\s*key: 'fetchdata~2',?/, '') + .replace(/, \{\s*\}\)/, ')') + + const result = await apply(source, { ...source.files, 'workflow.ts': edited }) + + expect(codes(result.diagnostics)).not.toContain('E_APPLY_BLOCK_DELETE') + expect(result.applied).toBe(true) + expect(result.diff.blocks.removed).toEqual([]) + expect(result.diff.blocks.added).toEqual([]) + expect(result.diff.blocks.renamed).toEqual([ + { id: first.id, from: 'fetchdata', to: 'getdata' }, + { id: second.id, from: 'fetchdata~2', to: 'fetchdata' }, + ]) + } + ) + check( 'a block whose name and const both change while its wiring changes keeps its id', async () => { diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 25400b1c9f8..2b7480c0a6e 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -24,6 +24,7 @@ import { type ResourceKeyResolver, type ResourceKind, renamesBetween, + replacedBetween, type SourceBase, type SourceHints, type SourceSpan, @@ -824,10 +825,12 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise [storedKey, key])) const storedKeyOf = new Map([...renamedKeys].map(([storedKey, key]) => [key, storedKey])) @@ -874,9 +877,15 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise !replacedKeys.has(key)) const removedBlocks = removedKeys.map((key) => storedCanonical.workflow.blocks[key]) - const addedBlocks = canonicalDiff.blocks.added.map((key) => materialized.workflow.blocks[key]) + const addedBlocks = canonicalDiff.blocks.added + .filter((key) => !replacedKeys.has(key)) + .map((key) => materialized.workflow.blocks[key]) if (removedKeys.length > 0 && !input.allowDelete) { sourceRefusals.push(blockDeleteRefusal(removedBlocks, addedBlocks, metaSpan())) } diff --git a/packages/workflow-code/src/diff/index.test.ts b/packages/workflow-code/src/diff/index.test.ts index 328b028cf39..838e1c6e5b4 100644 --- a/packages/workflow-code/src/diff/index.test.ts +++ b/packages/workflow-code/src/diff/index.test.ts @@ -11,7 +11,7 @@ import { } from '../materialize/fixtures.test-helpers' import type { CanonicalWorkflow, CodeComment } from '../model' import { setOwn } from '../records' -import { diffCanonical, renamesBetween } from '.' +import { diffCanonical, renamesBetween, replacedBetween } from '.' const base = canonical( workflowState( @@ -169,4 +169,72 @@ describe('diffCanonical', () => { expect([...renames]).toEqual([['load', 'fetch']]) expect(diffCanonical(base.workflow, target, renames).blocks.added).toEqual([]) }) + it('pairs two blocks that swap display names by id, so only their names change', () => { + const target = edit((draft) => { + const { fetch, report } = draft.blocks + draft.blocks.report = { ...fetch, key: 'report', name: 'Report' } + draft.blocks.fetch = { ...report, key: 'fetch', name: 'Fetch' } + const swap = (key: string) => (key === 'fetch' ? 'report' : key === 'report' ? 'fetch' : key) + draft.edges = draft.edges.map((e) => ({ ...e, from: swap(e.from), to: swap(e.to) })) + }) + const diff = diffCanonical( + base.workflow, + target, + new Map([ + ['report', 'fetch'], + ['fetch', 'report'], + ]) + ) + expect(diff.blocks.renamed).toEqual([ + { from: 'fetch', to: 'report' }, + { from: 'report', to: 'fetch' }, + ]) + expect(diff.blocks.modified.map((m) => [m.key, m.changes])).toEqual([ + ['report', [{ kind: 'attribute', attribute: 'name' }]], + ['fetch', [{ kind: 'attribute', attribute: 'name' }]], + ]) + expect(diff.blocks.added).toEqual([]) + expect(diff.edges).toEqual({ added: [], removed: [] }) + }) + + it('reports a block replaced under its key (a retype gets a new id) as removed plus added', () => { + const target = edit((draft) => { + draft.blocks.report = { ...draft.blocks.report, type: 'agent', params: {} } + }) + const identity = { + ...base.identity, + blocks: { ...base.identity.blocks, report: { ...base.identity.blocks.report, id: 'new-id' } }, + } + const replaced = replacedBetween(base.identity, identity) + expect([...replaced]).toEqual(['report']) + + const diff = diffCanonical(base.workflow, target, new Map(), replaced) + + expect(diff.blocks.added).toEqual(['report']) + expect(diff.blocks.removed).toEqual(['report']) + expect(diff.blocks.modified).toEqual([]) + expect(diff.edges.added).toHaveLength(2) + expect(diff.edges.removed).toHaveLength(2) + }) + it('pairs a chain rename, where one block takes the key another leaves, without a delete', () => { + const target = edit((draft) => { + const { fetch, report } = draft.blocks + draft.blocks.load = { ...fetch, key: 'load', name: 'Load' } + draft.blocks.fetch = { ...report, key: 'fetch', name: 'Fetch' } + draft.blocks = omit(draft.blocks, ['report']) + const moved = (key: string) => (key === 'fetch' ? 'load' : key === 'report' ? 'fetch' : key) + draft.edges = draft.edges.map((e) => ({ ...e, from: moved(e.from), to: moved(e.to) })) + }) + const diff = diffCanonical( + base.workflow, + target, + new Map([ + ['load', 'fetch'], + ['fetch', 'report'], + ]) + ) + expect(diff.blocks.removed).toEqual([]) + expect(diff.blocks.added).toEqual([]) + expect(diff.edges).toEqual({ added: [], removed: [] }) + }) }) diff --git a/packages/workflow-code/src/diff/index.ts b/packages/workflow-code/src/diff/index.ts index ab3ed83c34b..4e968fd2edf 100644 --- a/packages/workflow-code/src/diff/index.ts +++ b/packages/workflow-code/src/diff/index.ts @@ -110,16 +110,23 @@ function edgeKey(edge: CanonicalEdge, keyOf: (key: BlockKey) => BlockKey): strin return edgeTupleKey(keyOf(edge.from), portKey(edge.port), keyOf(edge.to)) } +/** Stands in for a target block no base block pairs with, so none of its edges match a base one. */ +const UNPAIRED = '\u0000added:' + /** - * Diffs base against target. `renames` (target key → base key) pairs blocks whose key changed; - * without it a rename is a remove plus an add. A rename pair whose base key is missing, or that - * names a base key a target block of the same key also claims, is ignored. Edges are compared - * after mapping target keys to base keys, so a rename alone moves no edge. + * Diffs base against target. `renames` (target key → base key) pairs blocks whose key changed, + * and it wins over a same-key pairing, so two blocks that swap names pair with the blocks they + * continue; without it a rename is a remove plus an add. A rename pair whose either key is missing, + * or whose base key another pair already claims, is ignored. Any other target block pairs with the + * base block of its key, unless `replaced` holds the key: that block took a new id (a retype), so + * it is a remove plus an add. Edges are compared after mapping target keys to the base keys they + * pair with, so a rename alone moves no edge and every edge of a replaced block is re-added. */ export function diffCanonical( base: CanonicalWorkflow, target: CanonicalWorkflow, - renames?: ReadonlyMap + renames?: ReadonlyMap, + replaced?: ReadonlySet ): CanonicalDiff { const pairs = new Map() const claimedBase = new Set() @@ -127,7 +134,6 @@ export function diffCanonical( if ( Object.hasOwn(target.blocks, targetKey) && Object.hasOwn(base.blocks, baseKey) && - !Object.hasOwn(target.blocks, baseKey) && !claimedBase.has(baseKey) ) { pairs.set(targetKey, baseKey) @@ -135,13 +141,13 @@ export function diffCanonical( } } for (const targetKey of Object.keys(target.blocks)) { - if (pairs.has(targetKey) || claimedBase.has(targetKey)) continue + if (pairs.has(targetKey) || claimedBase.has(targetKey) || replaced?.has(targetKey)) continue if (Object.hasOwn(base.blocks, targetKey)) { pairs.set(targetKey, targetKey) claimedBase.add(targetKey) } } - const baseKeyOf = (targetKey: BlockKey) => pairs.get(targetKey) ?? targetKey + const baseKeyOf = (targetKey: BlockKey) => pairs.get(targetKey) ?? `${UNPAIRED}${targetKey}` const added = Object.keys(target.blocks).filter((key) => !pairs.has(key)) const removed = Object.keys(base.blocks).filter((key) => !claimedBase.has(key)) @@ -192,6 +198,19 @@ export function diffCanonical( } } +/** + * Keys both identities of one workflow hold for different blocks (target key): a block that took + * a new id under its key, as a retype does. The `replaced` input `diffCanonical` takes. + */ +export function replacedBetween(base: LockIdentity, target: LockIdentity): Set { + const replaced = new Set() + for (const [key, block] of Object.entries(target.blocks)) { + const held = getOwn(base.blocks, key) + if (held && held.id !== block.id) replaced.add(key) + } + return replaced +} + /** * Block renames between two identities of one workflow (target key → base key): every block id * both carry under different keys. This is the `renames` input `diffCanonical` takes, from the diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 03553c149b2..b7a567196a0 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -63,7 +63,7 @@ export { type SourceSpan, splitLines, } from './diagnostics/frame' -export { type CanonicalDiff, diffCanonical, renamesBetween } from './diff' +export { type CanonicalDiff, diffCanonical, renamesBetween, replacedBetween } from './diff' export { canonicalDigests, canonicalEquals, From 0f85398250c689cc33043069a8407d6758aed82a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:02:59 -0800 Subject: [PATCH 011/104] fix(workflow-code): diagnostics name a missing import and stop flooding A loop, a template tag or env used without importing it got a wrong lead: 'loop is not an SDK namespace. Did you mean loops.*?', 'This template tag is not supported... use js``' on a js`` tag, 'env is not defined'. Any SDK core export or catalog namespace the file uses unimported is now one finding, ' is not imported from @sim/workflow-sdk', with the import to add. HTML in a note gave 99 identical ' names no block' warnings on every check, and the 100-warning cap could hide a real warning behind them. A note never resolves references, so its text is not scanned; the reporter lists a finding repeated at the same place once, and caps each warning code at 20 so a flood of one code leaves room for the rest. Errors keep their own cap. --- packages/workflow-code/src/compile/SYNTAX.md | 2 +- .../workflow-code/src/compile/checks.test.ts | 42 +++++++++++++++ packages/workflow-code/src/compile/context.ts | 34 +++++++++++++ .../workflow-code/src/compile/grammar.test.ts | 29 +++++++++++ .../workflow-code/src/compile/hostile.test.ts | 21 +++++--- packages/workflow-code/src/compile/report.ts | 35 +++++++++++-- packages/workflow-code/src/compile/scope.ts | 51 +++++++++---------- packages/workflow-code/src/compile/values.ts | 12 +++++ .../workflow-code/src/diagnostics/codes.ts | 5 +- packages/workflow-code/src/sdk.ts | 5 ++ 10 files changed, 197 insertions(+), 39 deletions(-) diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 1278354bb82..365af9c60ea 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -382,7 +382,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `E_WORKFLOW_EXPORT` | Not exactly one `export default workflow(…)`. | | `E_LIMIT_EXCEEDED` | Over the block, edge, total-byte, depth or `codeFile()` reference cap (`SOURCE_LIMITS`). Apply answers 413. | | `E_TOO_MANY_ERRORS` | The compile stopped after 100 errors; fix those and compile again to see the rest. | -| `W_TOO_MANY_WARNINGS` | 100 warnings were listed and the rest omitted. Infos are capped apart (100, the rest dropped), so they never displace a warning. | +| `W_TOO_MANY_WARNINGS` | 100 warnings, or 20 of one code, were listed and the rest omitted, so a flood of one finding never hides another. A finding repeated at the same place is listed once. Infos are capped apart (100, the rest dropped), so they never displace a warning, and errors are never displaced by either. | | `E_DUPLICATE_NAME` | Two blocks normalize to one key. | | `E_RESERVED_NAME` | A block name normalizes to `loop`, `parallel` or `variable`. | | `E_KEY_OVERRIDE` | A `meta.key` that is not a legacy key the stored workflow already has. | diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index c433b00a8c2..49674ad4882 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -482,6 +482,48 @@ describe('unknown builders', () => { }) }) +describe('an SDK export the file did not import', () => { + function compileWith(imports: string, body: string): CompileResult { + return compileWorkflow({ + entry: { + path: 'workflow.ts', + text: `// @sim-sdk 1\nimport { ${imports} } from '@sim/workflow-sdk'\n\nexport default workflow('Test', {}, () => {\n${body}\n})\n`, + }, + files: new Map(), + catalog: TEST_CATALOG, + sdkMajor: 1, + }) + } + + it('names the missing import of a container, a template tag and env, and nothing else', () => { + const result = compileWith( + 'fn, js, trigger, workflow', + [ + START, + "const lp = loop.for('Lp', { count: 2 }, (p) => {", + " const inner = fn('Inner', { code: js`return ${p.index}` })", + ' p.to(inner)', + '})', + "const after = fn('After', { code: t`${lp.results}` })", + "const last = fn('Last', { code: js`return ${env.KEY}` })", + 'start.to(lp)', + 'lp.to(after)', + 'after.to(last)', + ].join('\n') + ) + expect( + result.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ message: d.message, hint: d.hint })) + ).toEqual( + ['loop', 't', 'env'].map((name) => ({ + message: `${name} is not imported from '@sim/workflow-sdk'.`, + hint: `Add ${name} to the import from '@sim/workflow-sdk'.`, + })) + ) + }) +}) + describe('a misspelled required param', () => { it('reports the unknown param once, without a second W_REQUIRED_MISSING for its suggestion', () => { const result = run("const a = api('A', { urll: 'https://x' })") diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index e898733b931..52acc1cbc45 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -7,6 +7,7 @@ import type { } from '@babel/types' import { encodeAnchor } from '../anchors' import type { BlockCatalog, CatalogBlock, CatalogBuilder } from '../catalog/types' +import { catalogBuilderPaths } from '../catalog/view' import type { CodeFileRef } from '../code-files' import type { RefSegment } from '../code-files/ref-path' import type { SourceSpan } from '../diagnostics/frame' @@ -25,6 +26,7 @@ import type { SubBlockId, VarKey, } from '../model' +import { isSdkCoreExport, SDK_MODULE } from '../sdk' import type { AddCommentItem, CommentCollector } from './comments' import { didYouMean } from './hints' import type { CompileLimits } from './parse' @@ -255,6 +257,35 @@ function visibleNames(scope: Scope): string[] { return names } +/** + * Whether `name` is something a workflow file imports from the SDK: a core export (`loop`, `js`, + * `env`) or a block namespace of the catalog (`slack`). + */ +export function isSdkImportable(ctx: CompileContext, name: string): boolean { + return ( + isSdkCoreExport(name) || + catalogBuilderPaths(ctx.catalog).some((path) => path === name || path.startsWith(`${name}.`)) + ) +} + +/** + * Reports `code` for an SDK export the file uses but does not import: the one finding that names + * the fix, which the caller follows by compiling nothing that depends on it. + */ +export function reportNotImported( + ctx: CompileContext, + code: 'E_UNKNOWN_BUILDER' | 'E_UNKNOWN_IDENTIFIER', + name: string, + at: Located, + blockKey?: BlockKey +): null { + ctx.reporter.report(code, `${name} is not imported from '${SDK_MODULE}'.`, rangeOf(ctx, at), { + hint: `Add ${name} to the import from '${SDK_MODULE}'.`, + blockKey, + }) + return null +} + /** * Reports an identifier `scope` does not bind: `E_OUT_OF_SCOPE` when a block inside another loop or * parallel holds the name, else `E_UNKNOWN_IDENTIFIER` with a did-you-mean over the visible names. @@ -279,6 +310,9 @@ export function reportUnresolvedIdentifier( ) return null } + if (isSdkImportable(ctx, identifier.name)) { + return reportNotImported(ctx, 'E_UNKNOWN_IDENTIFIER', identifier.name, identifier, blockKey) + } ctx.reporter.report( 'E_UNKNOWN_IDENTIFIER', `${identifier.name} is not defined.`, diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 2fa33a89744..3476c278296 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1867,3 +1867,32 @@ describe('$ref and $env in a Python or shell code file', () => { ]) }) }) + +describe('reference-shaped text that floods the warnings', () => { + const notNormalized = (result: CompileResult) => + result.diagnostics.filter((d) => d.code === 'W_REF_NOT_NORMALIZED') + + it('never reads a note for references, which a note never resolves', () => { + const html = 'bold and it '.repeat(50) + const result = run(source(`note('Docs', { content: md\`${html}\` })`)) + expect(notNormalized(result)).toEqual([]) + }) + + it('lists one finding once, however often the text repeats it', () => { + const result = run(source("const a = api('A', { url: t`xyz` })")) + expect(notNormalized(result).map((d) => d.message)).toEqual([ + ' names no block; the text is kept as written.', + ]) + }) + + it('caps one code apart from the rest, so a flood of it hides no other warning', () => { + const flood = Array.from( + { length: 120 }, + (_, i) => `const a${i} = api('A${i}', { url: t\`\` })` + ) + const later = "const later = api('Later', { url: t`${start.missing}` })" + const result = run(source([START, ...flood, later].join('\n'))) + expect(result.diagnostics.filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH')).toHaveLength(1) + expect(result.diagnostics.filter((d) => d.code === 'W_TOO_MANY_WARNINGS')).toHaveLength(1) + }) +}) diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 2643fda97b5..779d825789c 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -4,7 +4,7 @@ import { TEST_CATALOG } from './catalog.test-helpers' import type { CompileResult } from './index' import { compileWorkflow } from './index' import { type CompileLimits, sourceDepthOverflow } from './parse' -import { MAX_ERRORS, MAX_INFOS, MAX_WARNINGS, Reporter } from './report' +import { MAX_ERRORS, MAX_INFOS, MAX_WARNINGS, MAX_WARNINGS_PER_CODE, Reporter } from './report' /** * Hostile sources: compile never executes anything and never throws. Each input must come @@ -195,7 +195,14 @@ describe('hostile sources produce diagnostics only', () => { const reporter = new Reporter() reporter.addFile('w.ts', `body: '${jwt}'`) const at = { file: 'w.ts', start: 7, end: 7 + jwt.length } - for (let i = 0; i < MAX_WARNINGS; i++) reporter.report('W_SUBFLOW_COUNT', 'x', at) + const fillers = [ + 'W_SUBFLOW_COUNT', + 'W_FORWARD_REF', + 'W_VALUE_KIND', + 'W_OUT_OF_RANGE', + 'W_UNKNOWN_OPTION', + ] as const + for (let i = 0; i < MAX_WARNINGS; i++) reporter.report(fillers[i % fillers.length], `x${i}`, at) reporter.report('W_LITERAL_SECRET', 'body holds a literal secret', at) const capped = reporter.diagnostics.at(-1) expect(capped?.code).toBe('W_TOO_MANY_WARNINGS') @@ -218,13 +225,13 @@ describe('hostile sources produce diagnostics only', () => { expect(frameChars).toBeLessThan(result.diagnostics.length * 1_000) }) - it('lists 100 warnings and omits the rest without failing the compile', () => { + it('lists 20 warnings of one code and omits the rest without failing the compile', () => { let body = '' for (let i = 0; i < 150; i++) body += `const a${i} = api('A${i}', { url: a${i + 1}.data })\n` body += `const a150 = api('A150', { url: 'x' })` const result = run(wrap(body)) expect(result.workflow).not.toBeNull() - expect(result.diagnostics).toHaveLength(MAX_WARNINGS + 1) + expect(result.diagnostics).toHaveLength(MAX_WARNINGS_PER_CODE + 1) expect(result.diagnostics.at(-1)?.code).toBe('W_TOO_MANY_WARNINGS') }) @@ -235,7 +242,7 @@ describe('hostile sources produce diagnostics only', () => { for (let i = 0; i < 1_000; i++) { reporter.report( 'W_UNRESOLVED_REF', - 'x', + `x${i}`, { file: 'w.ts', start: 0, end: 1 }, { hint: () => { @@ -245,7 +252,7 @@ describe('hostile sources produce diagnostics only', () => { } ) } - expect(computed).toBe(MAX_WARNINGS) + expect(computed).toBe(MAX_WARNINGS_PER_CODE) expect(reporter.diagnostics[0]?.hint).toBe('Did you mean y?') }) @@ -253,7 +260,7 @@ describe('hostile sources produce diagnostics only', () => { const reporter = new Reporter() reporter.addFile('w.ts', 'x') const at = { file: 'w.ts', start: 0, end: 1 } - for (let i = 0; i < MAX_WARNINGS + 50; i++) reporter.report('I_SCHEDULE_UTC', 'x', at) + for (let i = 0; i < MAX_WARNINGS + 50; i++) reporter.report('I_SCHEDULE_UTC', `x${i}`, at) reporter.report('W_LITERAL_SECRET', 'apiKey holds a literal secret', at) const listed = reporter.diagnostics.map((d) => d.code) expect(listed).toContain('W_LITERAL_SECRET') diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index 091242727ef..887cc6353b7 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -72,6 +72,12 @@ function severityOf(code: CompileDiagnosticCode): SeverityOfCode { export const MAX_ERRORS = 100 /** Warnings one compile lists before the rest are omitted with `W_TOO_MANY_WARNINGS`. */ export const MAX_WARNINGS = 100 +/** + * Warnings of one code one compile lists before the rest of that code are omitted with + * `W_TOO_MANY_WARNINGS`, so a flood of one finding leaves room under {@link MAX_WARNINGS} for the + * others. + */ +export const MAX_WARNINGS_PER_CODE = 20 /** Infos one compile lists before the rest are dropped; counted apart so none displaces a warning. */ export const MAX_INFOS = 100 /** Code units of a message or hint kept; longer text, which quotes the source, is cut. */ @@ -105,6 +111,9 @@ export class Reporter { private errorCount = 0 private warningCount = 0 private infoCount = 0 + private readonly warningsByCode = new Map() + /** What each recorded finding says where, so the same finding is listed once. */ + private readonly seen = new Set() addFile(path: string, text: string): void { this.indexes.set(path, new LineIndex(text)) @@ -131,12 +140,17 @@ export class Reporter { } /** - * Records a diagnostic. The error after the {@link MAX_ERRORS}th is recorded as + * Records a diagnostic, once: a finding with the same code, message and range as one already + * recorded is dropped. The error after the {@link MAX_ERRORS}th is recorded as * `E_TOO_MANY_ERRORS` and throws {@link ErrorLimitReached}; the warning after the - * {@link MAX_WARNINGS}th is recorded as `W_TOO_MANY_WARNINGS` and later ones are dropped. Infos - * have their own cap, {@link MAX_INFOS}, so they never crowd out a warning. + * {@link MAX_WARNINGS}th, or after the {@link MAX_WARNINGS_PER_CODE}th of its code, is recorded as + * `W_TOO_MANY_WARNINGS` and later ones are dropped. Each severity has its own cap, so a warning + * never crowds out an error, nor an info a warning. */ report(code: CompileDiagnosticCode, message: string, at: Range, extras: ReportExtras = {}): void { + const key = `${code}\u0000${at.file}\u0000${at.start}\u0000${at.end}\u0000${message}` + if (this.seen.has(key)) return + this.seen.add(key) const severity = severityOf(code) if (severity === 'error') { if (this.errorCount === MAX_ERRORS) { @@ -162,6 +176,21 @@ export class Reporter { ) } return + } else { + const ofCode = this.warningsByCode.get(code) ?? 0 + this.warningsByCode.set(code, ofCode + 1) + if (ofCode >= MAX_WARNINGS_PER_CODE) { + if (ofCode === MAX_WARNINGS_PER_CODE) { + this.record( + 'W_TOO_MANY_WARNINGS', + `Listed ${MAX_WARNINGS_PER_CODE} ${code} warnings; the rest of them are omitted. The next: ${message}`, + at, + {}, + framesSource(code) + ) + } + return + } } this.record(code, message, at, extras, framesSource(code)) } diff --git a/packages/workflow-code/src/compile/scope.ts b/packages/workflow-code/src/compile/scope.ts index 0e63ca11c55..3e9e95cb7f2 100644 --- a/packages/workflow-code/src/compile/scope.ts +++ b/packages/workflow-code/src/compile/scope.ts @@ -21,10 +21,12 @@ import { type BlockDecl, type CompileContext, EDGE_METHODS, + isSdkImportable, lookup, type ResolvedBuilder, rangeOf, recordSpan, + reportNotImported, type Scope, unsupported, } from './context' @@ -59,22 +61,19 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): if (!path) return { kind: 'other' } const binding = lookup(scope, path.root) if (!binding && path.rest.length > 0) { - // `discord.sendMessage(...)` with no such import: a builder namespace the SDK does not have. + // `loop.for(...)` or `slack.sendMessage(...)` with no import, or `discord.sendMessage(...)`: + // a builder namespace the SDK does not have. const dotted = [path.root, ...path.rest].join('.') - const paths = catalogBuilderPaths(ctx.catalog) - const imported = paths.some((candidate) => candidate.startsWith(`${path.root}.`)) - ctx.reporter.report( - 'E_UNKNOWN_BUILDER', - imported - ? `${dotted}: ${path.root} is not imported from '@sim/workflow-sdk'.` - : `${dotted} is not a block builder: ${path.root} is not an SDK namespace.`, - rangeOf(ctx, call.callee), - { - hint: imported - ? `Add ${path.root} to the import from '@sim/workflow-sdk'.` - : suggestBuilder(dotted, paths), - } - ) + if (isSdkImportable(ctx, path.root)) { + reportNotImported(ctx, 'E_UNKNOWN_BUILDER', path.root, call.callee) + } else { + ctx.reporter.report( + 'E_UNKNOWN_BUILDER', + `${dotted} is not a block builder: ${path.root} is not an SDK namespace.`, + rangeOf(ctx, call.callee), + { hint: suggestBuilder(dotted, catalogBuilderPaths(ctx.catalog)) } + ) + } return { kind: 'builder', path: dotted, builder: { kind: 'unknown' } } } const [firstArgument] = call.arguments @@ -87,18 +86,16 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): // `apii('Call', { ... })`: a bare, builder-shaped call nothing binds, naming a builder or close // to one (`fetch('x')` stays an unsupported call). It classifies as an unknown builder so the // const still binds and its wiring raises no E_UNKNOWN_IDENTIFIER. - ctx.reporter.report( - 'E_UNKNOWN_BUILDER', - imported - ? `${path.root} is not imported from '@sim/workflow-sdk'.` - : `${path.root} is not a block builder.`, - rangeOf(ctx, call.callee), - { - hint: imported - ? `Add ${path.root} to the import from '@sim/workflow-sdk'.` - : suggestBuilder(path.root, bareBuilderPaths), - } - ) + if (imported) { + reportNotImported(ctx, 'E_UNKNOWN_BUILDER', path.root, call.callee) + } else { + ctx.reporter.report( + 'E_UNKNOWN_BUILDER', + `${path.root} is not a block builder.`, + rangeOf(ctx, call.callee), + { hint: suggestBuilder(path.root, bareBuilderPaths) } + ) + } return { kind: 'builder', path: path.root, builder: { kind: 'unknown' } } } if (!binding || binding.kind !== 'sdk') return { kind: 'other' } diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 15d3264ff77..800501d410c 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -58,6 +58,7 @@ import { type JsonFieldEntry, lookup, rangeOf, + reportNotImported, reportUnresolvedIdentifier, type Scope, unsupported, @@ -257,6 +258,8 @@ function checkIterationTag( } function checkLiteralRefs(ctx: CompileContext, node: Node, text: string, site: ValueSite): void { + // A note never runs, so nothing in it resolves: `` in its markdown is text, not a reference. + if (catalogBlockOf(site.decl)?.graph.annotationOnly) return for (const token of findWorkflowReferenceTokens(text)) { if (token.kind !== 'workflow') continue const segments = parseStoredPath(token.value.slice(1, -1)) @@ -1323,6 +1326,15 @@ export function compileValue( } case 'TaggedTemplateExpression': { const tag = node.tag.type === 'Identifier' ? lookup(site.scope, node.tag.name) : null + if (!tag && node.tag.type === 'Identifier' && isTemplateTag(node.tag.name)) { + return reportNotImported( + ctx, + 'E_UNKNOWN_IDENTIFIER', + node.tag.name, + node.tag, + site.decl.key + ) + } if (!tag || tag.kind !== 'sdk' || !isTemplateTag(tag.name)) return rejectNode(ctx, node, site) const text = templateText(ctx, node, site) return text === null ? null : { kind: 'value', value: text, form: 'template' } diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 9c08c639400..de528a9689b 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -41,7 +41,10 @@ const COMPILE_SYNTAX_CODES = [ * Fixing the errors listed and compiling again shows the rest. */ 'E_TOO_MANY_ERRORS', - /** `MAX_WARNINGS` warnings were listed; this one sits where the next was found, and the rest are omitted. */ + /** + * `MAX_WARNINGS` warnings, or `MAX_WARNINGS_PER_CODE` of one code, were listed; this one sits + * where the next was found, and the rest (of that code) are omitted. + */ 'W_TOO_MANY_WARNINGS', ] as const diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index e2af3f24d27..04bf90f6c8f 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -155,6 +155,11 @@ const SDK_CORE_ENTRIES = Object.entries(SDK_CORE) as Array<[SdkCoreExport, SdkCo /** Every value the SDK's core module exports. */ export const SDK_CORE_EXPORTS: readonly SdkCoreExport[] = SDK_CORE_ENTRIES.map(([name]) => name) +/** Whether `name` is a value the SDK's core module exports. */ +export function isSdkCoreExport(name: string): name is SdkCoreExport { + return Object.hasOwn(SDK_CORE, name) +} + /** Core exports that are core blocks' builders; every other core export is an SDK-owned root. */ export const SDK_CORE_BLOCK_BUILDERS: ReadonlySet = new Set( SDK_CORE_ENTRIES.filter(([, traits]) => traits.blockBuilder).map(([name]) => name) From fafc8ef1b8e3db61504f8fcebd4174e332b5d499 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:03:42 -0800 Subject: [PATCH 012/104] fix(workflow-code): a do-while count beside a condition is diagnosed loop.doWhile('X', { condition, count: 7 }) passed check and the dry run with no finding while the count changed nothing: the executor ignores the count when a condition is set, and the printer never writes one. Compile now reports W_FIELD_NOT_APPLICABLE on it, from the form table's printedWhen, with the fix: remove count, or remove condition to run count times. --- packages/workflow-code/src/compile/blocks.ts | 48 ++++++++++++++++--- .../workflow-code/src/compile/grammar.test.ts | 35 ++++++++++++++ packages/workflow-code/src/forms/subflow.ts | 14 +++++- 3 files changed, 90 insertions(+), 7 deletions(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 749a711a516..5296d6a6860 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1715,11 +1715,14 @@ function compileConfig( container: 'loop' | 'parallel', form: ContainerForm, configNode: ObjectExpression | undefined -): Map, Value> { +): CompiledConfig { const { decl } = site const fields = new Map, Value>() - if (!configNode) return fields + const written = new Map, ObjectProperty>() + if (!configNode) return { fields, written } for (const [key, property] of objectEntries(ctx, configNode)) { + const known = getOwn(form, key) + if (known) written.set(known.field, property) const entry = getOwn(form, key) if (!entry) { ctx.reporter.report( @@ -1762,7 +1765,37 @@ function compileConfig( } fields.set(entry.field, compiled.value) } - return fields + return { fields, written } +} + +/** A container's compiled config values, and the property each written key came from. */ +interface CompiledConfig { + fields: Map, Value> + written: Map, ObjectProperty> +} + +/** + * `W_FIELD_NOT_APPLICABLE` on a written config key the container does not read beside the rest of + * its config (`count` on a do-while that has a condition): the executor ignores it, so writing it + * changes nothing. + */ +function reportUnreadConfig( + ctx: CompileContext, + decl: BlockDecl, + form: ContainerForm, + written: ReadonlyMap, ObjectProperty>, + spec: S +): void { + for (const [key, entry] of Object.entries(form)) { + const property = written.get(entry.field) + if (!property || !entry.unread || !entry.printedWhen || entry.printedWhen(spec)) continue + ctx.reporter.report( + 'W_FIELD_NOT_APPLICABLE', + `${key} is not read: ${entry.unread.reason}.`, + rangeOf(ctx, property), + { hint: entry.unread.hint, blockKey: decl.key } + ) + } } function numberField(value: Value | undefined): number | undefined { @@ -1805,12 +1838,13 @@ function compileContainer(ctx: CompileContext, decl: BlockDecl): CompiledBlock | let subflow: LoopSpec | ParallelSpec if (builder.container === 'loop') { - const fields = compileConfig(ctx, site, 'loop', loopForm(builder.method), config) + const form = loopForm(builder.method) + const { fields, written } = compileConfig(ctx, site, 'loop', form, config) const iterations = numberField(fields.get('iterations')) const forEachItems = jsonField(fields.get('forEachItems')) const whileCondition = textField(fields.get('whileCondition')) const doWhileCondition = textField(fields.get('doWhileCondition')) - subflow = { + const loop: LoopSpec = { kind: 'loop', loopType: builder.method, iterations: iterations ?? DEFAULT_LOOP_ITERATIONS, @@ -1818,8 +1852,10 @@ function compileContainer(ctx: CompileContext, decl: BlockDecl): CompiledBlock | ...(whileCondition !== undefined && { whileCondition }), ...(doWhileCondition !== undefined && { doWhileCondition }), } + reportUnreadConfig(ctx, decl, form, written, loop) + subflow = loop } else { - const fields = compileConfig(ctx, site, 'parallel', parallelForm(builder.method), config) + const { fields } = compileConfig(ctx, site, 'parallel', parallelForm(builder.method), config) const count = numberField(fields.get('count')) const distribution = jsonField(fields.get('distribution')) const batchSize = numberField(fields.get('batchSize')) diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 3476c278296..597f9eae0da 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1896,3 +1896,38 @@ describe('reference-shaped text that floods the warnings', () => { expect(result.diagnostics.filter((d) => d.code === 'W_TOO_MANY_WARNINGS')).toHaveLength(1) }) }) + +describe('a do-while count beside a condition', () => { + const unread = (result: CompileResult) => + result.diagnostics + .filter((d) => d.code === 'W_FIELD_NOT_APPLICABLE') + .map((d) => ({ message: d.message, hint: d.hint, blockKey: d.blockKey })) + const loopWith = (config: string) => + run( + source( + [ + START, + `const dw = loop.doWhile('Do While', ${config}, (p) => {`, + " const inner = fn('Inner', { code: 'return 1' })", + ' p.to(inner)', + '})', + 'start.to(dw)', + ].join('\n') + ) + ) + + it('reports a count the executor ignores because a condition is set', () => { + expect(unread(loopWith("{ condition: ' < 3', count: 7 }"))).toEqual([ + { + message: + 'count is not read: a do-while with a condition runs until the condition is false.', + hint: 'Remove count, or remove condition to run count times.', + blockKey: 'dowhile', + }, + ]) + }) + + it('keeps a count on a do-while with no condition quiet', () => { + expect(unread(loopWith('{ count: 7 }'))).toEqual([]) + }) +}) diff --git a/packages/workflow-code/src/forms/subflow.ts b/packages/workflow-code/src/forms/subflow.ts index b1ab42e3767..0a4219429fe 100644 --- a/packages/workflow-code/src/forms/subflow.ts +++ b/packages/workflow-code/src/forms/subflow.ts @@ -27,6 +27,11 @@ type ConfigEntry = { kind: ConfigKind> /** Whether the type prints and runs the field for this spec; always when absent. */ printedWhen?: (spec: S) => boolean + /** + * Why the executor does not read the field when `printedWhen` is false, and how to write what + * runs instead: the `W_FIELD_NOT_APPLICABLE` a source that writes it anyway gets. + */ + unread?: { reason: string; hint: string } /** The value the executor reads for the field (its fallback for an absent or falsy one). */ runs: (spec: S) => Json } @@ -60,7 +65,14 @@ const LOOP_FORMS: Record> = { }, doWhile: { // Without a condition the do-while runs as a count loop. - count: { ...LOOP_COUNT, printedWhen: (spec) => !spec.doWhileCondition }, + count: { + ...LOOP_COUNT, + printedWhen: (spec) => !spec.doWhileCondition, + unread: { + reason: 'a do-while with a condition runs until the condition is false', + hint: 'Remove count, or remove condition to run count times.', + }, + }, condition: { field: 'doWhileCondition', kind: 'text', From e96007f4c8b2259534b0954bbc41ea77f77bca34 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:05:00 -0800 Subject: [PATCH 013/104] fix(workflow-code): a const named like an unused builder namespace keeps its name const stripe = trigger.stripe.webhook(...) came back as const stripe2 from create and every later get: the printer reserved every catalog namespace as a block ident, imported or not. It now reserves only the namespaces of the builders of the block and agent tool types the workflow holds, the ones the printed file may import, so a const shadows no import it uses. --- .../__golden__/identifier-collisions.txt | 2 +- packages/workflow-code/src/print/idents.ts | 2 +- .../src/print/round-trip.test.ts | 14 ++++++++ packages/workflow-code/src/print/scope.ts | 33 +++++++++++++++---- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/packages/workflow-code/src/print/__golden__/identifier-collisions.txt b/packages/workflow-code/src/print/__golden__/identifier-collisions.txt index be602e70748..fe1a79bea77 100644 --- a/packages/workflow-code/src/print/__golden__/identifier-collisions.txt +++ b/packages/workflow-code/src/print/__golden__/identifier-collisions.txt @@ -9,7 +9,7 @@ export default workflow('Fixture', {}, () => { const myHinted = api('Hinted', { url: t`https://i.test ${default2.data}`, method: todo() }) const sendEmail = api('send-email', { url: 'https://f.test', method: todo() }) const sendEmail2 = api('Send Email', { url: 'https://e.test', method: todo() }) - const slack2 = api('Slack', { url: 'https://d.test', method: todo() }) + const slack = api('Slack', { url: 'https://d.test', method: todo() }) const table2 = api('Table', { url: 'https://b.test', method: todo() }) const workflow2 = api('Workflow', { url: 'https://c.test', method: todo() }) const block2 = api('ę—„ęœ¬čŖž', { url: 'https://h.test', method: todo() }) diff --git a/packages/workflow-code/src/print/idents.ts b/packages/workflow-code/src/print/idents.ts index caee41cbe25..3c4b800e66c 100644 --- a/packages/workflow-code/src/print/idents.ts +++ b/packages/workflow-code/src/print/idents.ts @@ -23,7 +23,7 @@ function isReservedIdentifier(name: string, extraReserved: ReadonlySet): * usable hinted ident (lock or source meta) is claimed first, so a canvas rename keeps the * identifier; the rest derive camelCase from the display name, with a * numeric suffix on collision with another block, `SDK_RESERVED_IDENTIFIERS` or a name in - * `reserved` (the catalog's builder namespaces). + * `reserved` (the builder namespaces the printed file may import). */ export function assignIdentifiers( blocks: Array<{ key: BlockKey; name: string; hint: string | undefined }>, diff --git a/packages/workflow-code/src/print/round-trip.test.ts b/packages/workflow-code/src/print/round-trip.test.ts index 97bb93880d9..7999982f425 100644 --- a/packages/workflow-code/src/print/round-trip.test.ts +++ b/packages/workflow-code/src/print/round-trip.test.ts @@ -107,4 +107,18 @@ describe('a container param holding a detected credential', () => { expect(again.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) expect(again.workflow?.blocks.l?.params).toEqual(workflow.blocks.l?.params) }) + it('names a block like a builder namespace only when the file builds with that namespace', () => { + const alone = printed(compiled(" const mail = api('Mail', { url: 'x' })")).files[0]?.text ?? '' + expect(alone).toContain("const mail = api('Mail'") + expect(compile(alone).diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + + const text = + "// @sim-sdk 1\nimport { api, mail, workflow } from '@sim/workflow-sdk'\n\n" + + "export default workflow('Test', {}, () => {\n const mail2 = api('Mail', { url: 'x' })\n const m = mail.send('M', { to: 'a@b.co' })\n})\n" + const both = compile(text).workflow + if (!both) throw new Error('expected a workflow') + const entry = printed(both).files[0]?.text ?? '' + expect(entry).toContain("const mail2 = api('Mail'") + expect(compile(entry).diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + }) }) diff --git a/packages/workflow-code/src/print/scope.ts b/packages/workflow-code/src/print/scope.ts index 39b45edbd25..a6d89bb74eb 100644 --- a/packages/workflow-code/src/print/scope.ts +++ b/packages/workflow-code/src/print/scope.ts @@ -3,7 +3,7 @@ * by name (`visibility`). Mirrors `compile/scope.ts`. */ -import { catalogBlock, catalogBuilderPaths } from '../catalog/view' +import { catalogBlock, catalogBuildersOfType } from '../catalog/view' import type { BlockKey, CanonicalBlock } from '../model' import { getOwn } from '../records' import type { PrintContext } from './context' @@ -135,18 +135,13 @@ export function orderDeclarations(ctx: PrintContext): void { } visit(null) - const reserved = new Set() - for (const path of catalogBuilderPaths(ctx.catalog)) { - const [namespace] = path.split('.') - if (namespace) reserved.add(namespace) - } ctx.idents = assignIdentifiers( ctx.preorder.map((key) => ({ key, name: ctx.blocks.get(key)?.name ?? key, hint: getOwn(ctx.hints.blocks, key)?.ident, })), - reserved + usableNamespaces(ctx) ) const taken = new Set(ctx.idents.values()) for (const key of ctx.preorder) { @@ -158,6 +153,30 @@ export function orderDeclarations(ctx: PrintContext): void { } } +/** + * The builder namespaces the printed file may import: the first segment of every builder of a + * block or agent tool type the workflow holds. A block ident must not take one, or the const would + * shadow the import; any other namespace (`const stripe` beside `trigger.stripe.webhook`) is free. + */ +function usableNamespaces(ctx: PrintContext): Set { + const types = new Set() + for (const block of ctx.blocks.values()) { + types.add(block.type) + for (const param of Object.values(block.params)) { + if (param.kind !== 'tools') continue + for (const tool of param.tools) types.add(tool.type) + } + } + const namespaces = new Set() + for (const type of types) { + for (const [path] of catalogBuildersOfType(ctx.catalog, type)) { + const [namespace] = path.split('.') + if (namespace) namespaces.add(namespace) + } + } + return namespaces +} + function blockRefHeads(block: CanonicalBlock): string[] { const heads: string[] = [] const walk = (value: unknown) => { From 9da28cf4ec37f6397e7bf040f75e5df3c494eeef Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:09:12 -0800 Subject: [PATCH 014/104] fix(workflow-code): renaming a branch key, input field or variable keeps its id Block renames keep their ids, but renaming a condition branch key (same expression), a start input field or a variable key minted a new id: the edge from the branch was removed and re-added, and anything keyed on the row, field or variable id lost continuity. Materialize now infers these renames as it does a block's: when exactly one entry's key is new and exactly one known id's key is gone, and the former entry agrees (the same branch expression, the same field or variable type), the entry keeps that id. Anything else still gets a new id. --- .../workflow-code/src/materialize/block.ts | 1 + .../workflow-code/src/materialize/branches.ts | 53 +++++++++-- .../src/materialize/index.test.ts | 92 +++++++++++++++++++ .../workflow-code/src/materialize/index.ts | 59 +++++++++--- .../src/structured/input-format.ts | 62 +++++++++++-- 5 files changed, 242 insertions(+), 25 deletions(-) diff --git a/packages/workflow-code/src/materialize/block.ts b/packages/workflow-code/src/materialize/block.ts index 6d83a75768d..c07f386f662 100644 --- a/packages/workflow-code/src/materialize/block.ts +++ b/packages/workflow-code/src/materialize/block.ts @@ -204,6 +204,7 @@ export function buildBlock(inputs: BlockInputs, context: MaterializeContext): Bu target.branches, id, [resolved.lockOwned ? inputs.lockBlock?.branches : undefined, prev?.branchIds], + before?.branches?.rows, context ) const existing = getOwn(subBlocks, subBlockId) diff --git a/packages/workflow-code/src/materialize/branches.ts b/packages/workflow-code/src/materialize/branches.ts index 9179a43feb1..940320f8c48 100644 --- a/packages/workflow-code/src/materialize/branches.ts +++ b/packages/workflow-code/src/materialize/branches.ts @@ -1,6 +1,6 @@ import { positionalKeys, positionalTitle } from '../canonicalize/branches' -import type { BranchKey, CanonicalBranches } from '../model' -import { getOwn, setOwn } from '../records' +import type { BranchKey, CanonicalBranches, CanonicalBranchRow } from '../model' +import { deepEqual, getOwn, setOwn } from '../records' import type { MaterializeContext } from './context' interface BranchWrite { @@ -13,8 +13,10 @@ interface BranchWrite { /** * Writes condition/router rows. Each row keeps the id its key * had (the lock's, then prev's, including the implicit `${blockId}-if` a never-persisted list - * answered to); a new row gets `${blockId}-${newId()}`, which keeps `remapConditionBlockIds` - * working. Titles are positional unless the row overrides one or stored + * answered to). When exactly one row's key is new and exactly one known id's key is gone, and + * `prevRows` held that key with the same expression, the row is a renamed branch and keeps the + * id, so its edges stay; any other new row gets `${blockId}-${newId()}`, which keeps + * `remapConditionBlockIds` working. Titles are positional unless the row overrides one or stored * none. The row `key` is persisted only when it differs from the positional default, so a lockless * read gets the same keys back. `rows: null` stays `null`. The list is always text: the * canvas reads it with `toString()` and a stored array breaks it (condition-input.tsx). @@ -23,18 +25,26 @@ export function writeBranches( branches: CanonicalBranches, blockId: string, knownIds: ReadonlyArray | undefined>, + prevRows: readonly CanonicalBranchRow[] | null | undefined, context: MaterializeContext ): BranchWrite { if (branches.rows === null) return { value: null, ids: {} } const rows = branches.rows const defaults = positionalKeys(branches.kind, rows.length) const used = new Set() - const ids: Record = {} - const stored = rows.map((row, index) => { + const knownRowIds = rows.map((row) => { const known = knownIds .map((source) => (source ? getOwn(source, row.key) : undefined)) .find((id): id is string => id !== undefined && !used.has(id)) - const id = known ?? `${blockId}-${context.hooks.newId()}` + if (known !== undefined) used.add(known) + return known + }) + const renamed = renamedRowId(rows, knownRowIds, knownIds, prevRows ?? [], used) + const ids: Record = {} + const stored = rows.map((row, index) => { + const id = + knownRowIds[index] ?? + (renamed?.index === index ? renamed.id : `${blockId}-${context.hooks.newId()}`) used.add(id) setOwn(ids, row.key, id) const entry: Record = { id } @@ -47,3 +57,32 @@ export function writeBranches( }) return { value: JSON.stringify(stored), ids } } + +/** + * The one row a branch rename left without a known id, with the one known id whose key no row + * holds any more, when the prev row under that key held the same expression; `null` unless there + * is exactly one of each, as a single key rename leaves. + */ +function renamedRowId( + rows: readonly CanonicalBranchRow[], + knownRowIds: ReadonlyArray, + knownIds: ReadonlyArray | undefined>, + prevRows: readonly CanonicalBranchRow[], + used: ReadonlySet +): { index: number; id: string } | null { + const unmatched = knownRowIds.flatMap((id, index) => (id === undefined ? [index] : [])) + if (unmatched.length !== 1) return null + const keys = new Set(rows.map((row) => row.key)) + const orphans = new Map() + for (const source of knownIds) { + for (const [key, id] of Object.entries(source ?? {})) { + if (!keys.has(key) && !used.has(id)) orphans.set(id, key) + } + } + const [index] = unmatched + const [orphan] = orphans + if (orphans.size !== 1 || index === undefined || orphan === undefined) return null + const [id, formerKey] = orphan + const former = prevRows.find((row) => row.key === formerKey) + return former && deepEqual(former.value, rows[index]?.value) ? { index, id } : null +} diff --git a/packages/workflow-code/src/materialize/index.test.ts b/packages/workflow-code/src/materialize/index.test.ts index 5b93ac4ca59..bfdce0dbee2 100644 --- a/packages/workflow-code/src/materialize/index.test.ts +++ b/packages/workflow-code/src/materialize/index.test.ts @@ -432,6 +432,56 @@ describe('materialize: branches', () => { expect(JSON.parse(String(raw))[0]).toEqual({ id: 'c1-if', value: 'b' }) }) + it('keeps the row id of the one branch whose key changed, and its edge with it', () => { + const prev = workflowState( + [ + blockState('c1', 'condition', 'Gate', { + conditions: JSON.stringify([ + { id: 'c1-a', key: 'one', value: 'x' }, + { id: 'c1-b', key: 'two', value: 'y' }, + { id: 'c1-else', value: '' }, + ]), + }), + blockState('n1', 'function', 'Next', { code: 'return 1' }), + ], + { edges: [{ ...edge('e1', 'c1', 'n1'), sourceHandle: 'condition-c1-a' }] } + ) + const target = edit(canonical(prev).workflow, (draft) => { + const rows = draft.blocks.gate.branches?.rows ?? [] + rows[0].key = 'single' + draft.edges = draft.edges.map((e) => + e.port.kind === 'branch' ? { ...e, port: { kind: 'branch', key: 'single' } } : e + ) + }) + const result = run(target, null, { prev }) + const stored = JSON.parse(String(subBlockValue(result.state, 'c1', 'conditions'))) + expect(stored.map((row: { id: string }) => row.id)).toEqual(['c1-a', 'c1-b', 'c1-else']) + expect(result.state.edges.map((e) => [e.id, e.sourceHandle])).toEqual([ + ['e1', 'condition-c1-a'], + ]) + }) + + it('mints new row ids when more than one branch key changed, which nothing pairs', () => { + const prev = workflowState([ + blockState('c1', 'condition', 'Gate', { + conditions: JSON.stringify([ + { id: 'c1-a', key: 'one', value: 'x' }, + { id: 'c1-b', key: 'two', value: 'y' }, + { id: 'c1-else', value: '' }, + ]), + }), + ]) + const target = edit(canonical(prev).workflow, (draft) => { + const rows = draft.blocks.gate.branches?.rows ?? [] + rows[0].key = 'uno' + rows[1].key = 'dos' + }) + const result = run(target, null, { prev }) + const stored = JSON.parse(String(subBlockValue(result.state, 'c1', 'conditions'))) + expect(stored[0].id).not.toBe('c1-a') + expect(stored[1].id).not.toBe('c1-b') + }) + it('keeps never-persisted rows null and routes edges to the implicit ids', () => { const [, prev] = QUIRK_STATES[4] const target = edit(canonical(prev).workflow, (draft) => { @@ -829,6 +879,48 @@ describe('materialize: identity', () => { }) }) + it('keeps the id of the one inputFormat field renamed to a field of the same type', () => { + const prev = workflowState([ + blockState('start', 'start_trigger', 'Start', { + inputFormat: [ + { id: 'f-n', name: 'n', type: 'number' }, + { id: 'f-q', name: 'q', type: 'string' }, + ], + }), + ]) + const renamed = (to: string, type: string) => + edit(canonical(prev).workflow, (draft) => { + const inputFormat = draft.blocks.start.params.inputFormat + if (inputFormat.kind === 'value' && Array.isArray(inputFormat.value)) { + inputFormat.value[0] = { name: to, type } + } + }) + const ids = (workflow: CanonicalWorkflow) => + ( + subBlockValue(run(workflow, null, { prev }).state, 'start', 'inputFormat') as Array<{ + id: string + }> + ).map((field) => field.id) + + expect(ids(renamed('num', 'number'))).toEqual(['f-n', 'f-q']) + expect(ids(renamed('label', 'string'))).toEqual(['new-1', 'f-q']) + }) + + it('keeps the id of the one variable renamed to a key of the same type', () => { + const pulled = base() + const renamed = (type: 'number' | 'plain') => + edit(canonical(pulled).workflow, (draft) => { + draft.variables = { + total: { key: 'total', name: 'Total', type, value: type === 'number' ? 1 : '1' }, + } + }) + const ids = (workflow: CanonicalWorkflow) => + Object.keys(run(workflow, null, { prev: pulled }).state.variables ?? {}) + + expect(ids(renamed('number'))).toEqual(['var-1']) + expect(ids(renamed('plain'))).toEqual(['new-1']) + }) + it('leaves an inputFormat id two fields share out of the identity items', () => { const prev = workflowState([ blockState('start', 'start_trigger', 'Start', { diff --git a/packages/workflow-code/src/materialize/index.ts b/packages/workflow-code/src/materialize/index.ts index 9b5a7ba48d9..335d65561a7 100644 --- a/packages/workflow-code/src/materialize/index.ts +++ b/packages/workflow-code/src/materialize/index.ts @@ -30,8 +30,10 @@ import { loopEntry, parallelEntry } from './subflows' import { rewriteRenamedReferences, rewriteStoredBlockReferences } from './values' /** - * Variables keep their ids by key: the lock's id, then prev's, else a new one. A variable - * canonical-equal to the prev variable with that id is prev's stored object unchanged. + * Variables keep their ids by key: the lock's id, then prev's, else a new one. When exactly one + * variable's key is new and exactly one prev variable's key is gone, with the same type, the + * variable is a rename and keeps that id. A variable canonical-equal to the prev variable with + * that id is prev's stored object unchanged. */ function writeVariables( workflow: CanonicalWorkflow, @@ -47,21 +49,30 @@ function writeVariables( for (const id of Object.values(lockIds)) lockIdCounts.set(id, (lockIdCounts.get(id) ?? 0) + 1) const used = new Set() - const variables: Record = {} - const idByKey = new Map() - for (const [key, variable] of Object.entries(workflow.variables)) { + const knownIds = new Map() + for (const key of Object.keys(workflow.variables)) { const fromLock = getOwn(lockIds, key) const candidates = [ fromLock !== undefined && lockIdCounts.get(fromLock) === 1 ? fromLock : undefined, prevCanonical ? getOwn(prevCanonical.identity.variables, key) : undefined, ] - const id = - candidates.find( - (candidate): candidate is string => - candidate !== undefined && - !used.has(candidate) && - (!Object.hasOwn(prevVariables, candidate) || prevKeyById.get(candidate) === key) - ) ?? hooks.newId() + const known = candidates.find( + (candidate): candidate is string => + candidate !== undefined && + !used.has(candidate) && + (!Object.hasOwn(prevVariables, candidate) || prevKeyById.get(candidate) === key) + ) + if (known === undefined) continue + used.add(known) + knownIds.set(key, known) + } + const renamed = renamedVariable(workflow, knownIds, prevCanonical, used) + if (renamed) knownIds.set(renamed.key, renamed.id) + + const variables: Record = {} + const idByKey = new Map() + for (const [key, variable] of Object.entries(workflow.variables)) { + const id = knownIds.get(key) ?? hooks.newId() used.add(id) idByKey.set(key, id) const stored = getOwn(prevVariables, id) @@ -87,6 +98,30 @@ function writeVariables( return { variables, idByKey } } +/** + * The one variable a rename left without a known id, with the one prev variable whose key the + * workflow no longer holds, when both have the same type; `null` unless there is exactly one of + * each, as a single key rename leaves. + */ +function renamedVariable( + workflow: CanonicalWorkflow, + knownIds: ReadonlyMap, + prevCanonical: CanonicalizeResult | null, + used: ReadonlySet +): { key: VarKey; id: string } | null { + if (!prevCanonical) return null + const unmatched = Object.keys(workflow.variables).filter((key) => !knownIds.has(key)) + const orphans = Object.entries(prevCanonical.identity.variables).filter( + ([key, id]) => !Object.hasOwn(workflow.variables, key) && !used.has(id) + ) + const [key] = unmatched + const [orphan] = orphans + if (unmatched.length !== 1 || orphans.length !== 1 || key === undefined || !orphan) return null + const [formerKey, id] = orphan + const former = getOwn(prevCanonical.workflow.variables, formerKey) + return former?.type === getOwn(workflow.variables, key)?.type ? { key, id } : null +} + /** * Each matched block with the preserved UI state of the stored block it continues * (`restorePreserved`): source holds what executes, and the rest comes from prev. diff --git a/packages/workflow-code/src/structured/input-format.ts b/packages/workflow-code/src/structured/input-format.ts index 53e0d3bb341..6cafc1389a2 100644 --- a/packages/workflow-code/src/structured/input-format.ts +++ b/packages/workflow-code/src/structured/input-format.ts @@ -171,8 +171,10 @@ function liftInputFormat( /** * Puts inputFormat field ids back: canonicalize moved the id of every field whose name and id are * both unique to the lock, so each such field takes the lock's id for its name, then prev's, else a - * new one. Fields that kept their id inline keep it. Every field with an id takes the editor's - * `collapsed` flag from the prev field with that id. + * new one. When exactly one field's name is new and exactly one known id's name is gone, and prev + * stored that id with the same type, the field is a rename and keeps the id. Fields that kept their + * id inline keep it. Every field with an id takes the editor's `collapsed` flag from the prev field + * with that id. */ function restoreInputFormatIds(list: unknown[], site: ParamSite, context: MaterializeContext) { const unique = uniqueFieldNames(list) @@ -186,20 +188,68 @@ function restoreInputFormatIds(list: unknown[], site: ParamSite, context: Materi return { ...item, collapsed: prevItem.collapsed } } const used = new Set() - return list.map((item) => { + const known = list.map((item) => { + if (!isRecordLike(item) || item.id !== undefined) return undefined + if (typeof item.name !== 'string' || !unique.has(item.name)) return undefined + const name = item.name + const entry = site.itemIds.find( + (candidate) => candidate.name === name && !used.has(candidate.id) + ) + if (entry) used.add(entry.id) + return entry?.id + }) + const renamed = renamedFieldId(list, known, unique, site.itemIds, prevById, used) + return list.map((item, index) => { if (!isRecordLike(item)) return item if (item.id !== undefined) { return typeof item.id === 'string' ? withPrevCollapsed(item.id, item) : item } if (typeof item.name !== 'string' || !unique.has(item.name)) return item - const name = item.name - const known = site.itemIds.find((entry) => entry.name === name && !used.has(entry.id)) - const id = known?.id ?? context.hooks.newId() + const id = known[index] ?? (renamed?.index === index ? renamed.id : context.hooks.newId()) used.add(id) return withPrevCollapsed(id, { id, ...item }) }) } +/** + * The one field a rename left without a known id, with the one known id whose name no field holds + * any more, when prev stored that id with the same type; `null` unless there is exactly one of + * each, as a single field rename leaves. + */ +function renamedFieldId( + list: readonly unknown[], + known: ReadonlyArray, + unique: ReadonlySet, + itemIds: readonly LockItem[], + prevById: ReadonlyMap>, + used: ReadonlySet +): { index: number; id: string } | null { + const unmatched = list.flatMap((item, index) => + isRecordLike(item) && + item.id === undefined && + typeof item.name === 'string' && + unique.has(item.name) && + known[index] === undefined + ? [index] + : [] + ) + if (unmatched.length !== 1) return null + const names = new Set(list.flatMap((item) => (isRecordLike(item) ? [item.name] : []))) + const orphans = new Set( + itemIds + .filter((entry) => !names.has(entry.name) && !used.has(entry.id)) + .map((entry) => entry.id) + ) + const [index] = unmatched + const [id] = orphans + if (orphans.size !== 1 || index === undefined || id === undefined) return null + const field = list[index] + const former = prevById.get(id) + return isRecordLike(field) && former !== undefined && former.type === field.type + ? { index, id } + : null +} + /** The record sugar as source: `name: 'type'`, or `name: { type, value?, description?, required? }`. */ function printRecord( values: ValuePrinter, From d089fc437db36ac40155c4ea5994193fca5c6e48 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:24:51 -0800 Subject: [PATCH 015/104] fix(workflows): deleting a workflow variable needs allowDelete, as deleting a block does An apply that dropped a variable from workflow(name, { variables }) deleted it with no --allow-delete, even when code read it, while a block delete is refused. The apply now refuses it as E_APPLY_VARIABLE_DELETE, naming the variables, unless allowDelete is passed; a variable whose key was renamed (same type) keeps its id and is no delete. The contract, the CLI help, the primer and the docs say --allow-delete covers variables. --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/workflows/code.mdx | 2 +- .../content/docs/workflows/workspace-code.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 14 ++++-- .../lib/api/contracts/v2/workflow-source.ts | 2 +- .../apply-workflow-source.integration.ts | 44 +++++++++++++++++++ .../workflows/application/source-evaluate.ts | 23 ++++++++-- .../src/commands/protocol/source-primer.ts | 4 +- .../protocol/workflow-source-apply.ts | 2 +- packages/sim-cli/src/generated/v2-api.ts | 10 ++++- .../workflow-code/src/diagnostics/codes.ts | 5 +++ 12 files changed, 95 insertions(+), 17 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 46ca1f84995..60bc460217c 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8579,7 +8579,7 @@ sim workflows source apply [workflowId] [options] | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | +| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index ff8ac309aed..2e9b7cb38de 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1395,7 +1395,7 @@ sim workflows source apply [workflowId] [options] | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | +| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index bf84fb2c496..6f501abcf1b 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -90,7 +90,7 @@ Nothing in the file runs on your machine. Sim reads it statically, checks it aga 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. - A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks. Pass `--allow-delete` when the deletion is intended. + A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks, and one that removes a workflow variable with `E_APPLY_VARIABLE_DELETE`. Pass `--allow-delete` when the deletion is intended. To create a new workflow, run `sim workflows source create --dir --workspace ` on an empty directory: without `--dry-run` or `--yes` it creates nothing and writes a starter `workflow.ts` with that workspace's type declarations, `tsconfig.json` and `.sim/AGENTS.md`, and records the workspace in `.sim/starter.json`. Edit the starter, check it, then run `sim workflows source create --dir --workspace --dry-run` and `--yes` (the starter prints both). A create goes to the starter's workspace whatever your default workspace, unless `--workspace` names another. Until the workflow is created the directory has no `.sim/base.json`, so `status`, `diff` and `apply` refuse it. The file starts with the `// @sim-sdk 1` line and default-exports one `workflow('Name', {}, () => { ... })`. The command prints the new workflow ID and writes the same type declarations, `tsconfig.json`, and `.sim/` files that `get` writes, so you can continue editing with `apply`. If another workflow already has that name, the command exits `1`; pass `--name` to choose another. diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx index f5b580f4740..17ae4599e93 100644 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ b/apps/docs/content/docs/workflows/workspace-code.mdx @@ -75,7 +75,7 @@ To apply the rest with a workspace key, such as in CI, narrow the apply to the k ## Deletes - A kind is managed only when its folder exists. A directory without `skills/` never touches a skill. -- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file or workflow block. +- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file, workflow block or workflow variable. - A resource the directory never managed is kept, and the apply names it in a warning. - Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. - Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index c3172cb52c2..4ee88ce5262 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6075,9 +6075,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -6280,9 +6280,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -18928,6 +18928,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -19377,6 +19378,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -20343,6 +20345,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -25390,6 +25393,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." @@ -25961,6 +25965,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code." @@ -26375,6 +26380,7 @@ "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 42b34189693..55864c463ed 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -32,7 +32,7 @@ const applyWorkflowSourceQuerySchema = z allowDelete: booleanQueryFlagSchema .optional() .describe( - 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.' + 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.' ), }) .strict() 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 d2543468168..3a2b291d6af 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2797,3 +2797,47 @@ export default workflow('Each item', {}, () => { } ) }) + +describe('workflow variables in source', () => { + /** `workflow.ts` with its `variables` option replaced by `variables` (source text). */ + function withVariables(files: Record, variables: string): Record { + const entry = files['workflow.ts'] + const edited = entry.replace(/variables: \{[^}]*\{[^}]*\}[^}]*\}/, `variables: ${variables}`) + expect(edited, 'the source declares its variables').not.toBe(entry) + return { ...files, 'workflow.ts': edited } + } + + check('a variable renamed to a key of the same type keeps its id', async () => { + const seeded = await seedWorkflow() + const source = await getSource(seeded.workflowId) + + const result = await apply( + source, + withVariables(source.files, "{ limit: { type: 'number', value: 3 } }") + ) + + expect(result.applied).toBe(true) + const [row] = await db + .select({ variables: workflow.variables }) + .from(workflow) + .where(eq(workflow.id, seeded.workflowId)) + expect(Object.keys(row.variables as Record)).toEqual([seeded.variableId]) + }) + + check('deleting a variable is refused without allowDelete, like deleting a block', async () => { + const seeded = await seedWorkflow() + const source = await getSource(seeded.workflowId) + const files = withVariables(source.files, '{}') + const before = await snapshot(seeded.workflowId) + + const error = await expectRejected(apply(source, files), 'E_APPLY_VARIABLE_DELETE') + + expect(error.diagnostics.find((d) => d.code === 'E_APPLY_VARIABLE_DELETE')?.message).toContain( + 'threshold' + ) + expect(await snapshot(seeded.workflowId)).toEqual(before) + const allowed = await apply(source, files, { allowDelete: true }) + expect(allowed.applied).toBe(true) + expect(allowed.diff.variables.removed).toEqual(['threshold']) + }) +}) diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 2b7480c0a6e..4ea69619fa0 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -338,9 +338,9 @@ function withEditedCodeFileRefsRefused( * The apply's handling of compile's `W_REF_OUT_OF_SCOPE`, an iteration field read from outside * its container: refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the write adds, changes or * moves (`changed`, by block key), which would fail at run time (a code file the edit changed - * already refused it); a warning on a block the stored - * workflow already holds as it is, so such a workflow still applies unchanged. The lint's finding - * for the same block is dropped from `lint`, as compile's is the one located at the source line. + * already refused it); a warning on a block the stored workflow already holds as it is, so such a + * workflow still applies unchanged. The lint's finding for the same block is dropped from `lint`, + * as compile's is the one located at the source line. */ function withOutOfScopeRefsRefused( diagnostics: readonly LocatedDiagnostic[], @@ -889,6 +889,23 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise 0 && !input.allowDelete) { sourceRefusals.push(blockDeleteRefusal(removedBlocks, addedBlocks, metaSpan())) } + const keptVariableIds = new Set(Object.values(materialized.identity.variables)) + const removedVariables = isNew + ? [] + : Object.entries(storedCanonical.identity.variables).flatMap(([key, id]) => + keptVariableIds.has(id) + ? [] + : [getOwn(storedCanonical.workflow.variables, key)?.name ?? key] + ) + if (removedVariables.length > 0 && !input.allowDelete) { + sourceRefusals.push({ + code: 'E_APPLY_VARIABLE_DELETE', + severity: 'error', + message: `This apply deletes ${removedVariables.length} variable${removedVariables.length === 1 ? '' : 's'} the source no longer declares: ${listNames(removedVariables)}.`, + hint: 'Pass --allow-delete (allowDelete=true) to delete them, or declare them again in workflow(name, { variables }) to keep them.', + ...withSpan(metaSpan()), + }) + } const renameWarnings = input.allowDelete ? probableRenames(removedBlocks, addedBlocks).map( ({ removed, added }): Diagnostic => ({ diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 81f35c9e851..4ead2b26d27 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -48,7 +48,7 @@ const WORKFLOW_PRIMER = `# Sim workflow source: primer **Edit loop**: edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`) → \`sim workflows source check --dir .\` (offline; it also adds new blocks to \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workflows source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. -- **Deletes**: removing a block's declaration deletes the block only with \`apply --allow-delete\`; without it the apply is refused (\`E_APPLY_BLOCK_DELETE\`). +- **Deletes**: removing a block's declaration deletes the block only with \`apply --allow-delete\`; without it the apply is refused (\`E_APPLY_BLOCK_DELETE\`); so does removing a variable. - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. ${sharedRules('sim workflows source')} ` @@ -59,7 +59,7 @@ This directory is a Sim workspace as files (\`tables/\`, \`workflows//workf **Edit loop**: edit the files → \`sim workspaces source check --dir .\` (offline; regenerates \`.sim/sdk/workspace.d.ts\`, adds new blocks to \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workspaces source apply --dir . --dry-run\` (the plan) → \`--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 or workflow block is deleted only with \`apply --allow-delete\`; without it the apply is refused. A kind is managed only when its folder exists. Deletes cannot be undone. +- **Deletes**: a removed file (a resource this directory managed), table column, workflow block or workflow variable is deleted only with \`apply --allow-delete\`; without it the apply is refused. A kind is managed only when its folder exists. Deletes cannot be undone. - **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. ${sharedRules('sim workspaces source')} ` 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 ee3233cefd7..9a7ee82e0c1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -474,7 +474,7 @@ export function attachWorkflowSourceApply(source: Command): void { ) .option( '--allow-delete', - 'Delete blocks the source no longer declares; without it, an apply that deletes a block is refused' + 'Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused' ) .allowExcessArguments(false) .description('Apply a workflow source directory to a workflow draft') diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index c231cd82084..586a2f6803c 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -962,6 +962,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -1453,6 +1454,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' message: string } @@ -1739,6 +1741,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -5405,6 +5408,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -10505,6 +10509,7 @@ export type GetWorkflowSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -11191,6 +11196,7 @@ export type GetWorkspaceSourceResponse = { | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -19587,7 +19593,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', }, }, body: { @@ -21244,7 +21250,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', }, }, body: { diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index de528a9689b..97ef527c90e 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -499,6 +499,11 @@ const APPLY_DIAGNOSTIC_CODES = [ * `allowDelete` (`--allow-delete`). */ 'E_APPLY_BLOCK_DELETE', + /** + * The apply removes workflow variables the source no longer declares and the caller did not pass + * `allowDelete` (`--allow-delete`), as for blocks. + */ + 'E_APPLY_VARIABLE_DELETE', /** The source renames the workflow to a name another workflow in its folder holds. */ 'E_NAME_TAKEN', /** From 3069f3d878b3155aa6dc098edd6862bd340ae723 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:22:32 -0800 Subject: [PATCH 016/104] fix(sim-cli): a source get refuses a directory of the other kind A workflow get into a workspace source directory (or a workspace get into a workflow directory) replaced its base and exited 0, so staleness could no longer be detected and unapplied edits sat in a directory neither command reads. One guard, assertSourceDirKind, now refuses the other kind in both gets, create, check and every command that reads a workflow base, --force included. --- apps/docs/content/docs/workflows/code.mdx | 2 +- .../src/commands/protocol/source-dir.ts | 40 +++++++++++++++++++ .../protocol/workflow-source-apply.ts | 3 ++ .../protocol/workflow-source-check.test.ts | 3 +- .../protocol/workflow-source-check.ts | 12 +----- .../protocol/workflow-source-get.test.ts | 19 +++++++++ .../commands/protocol/workflow-source-get.ts | 9 +++-- .../protocol/workspace-source-check.test.ts | 2 +- .../commands/protocol/workspace-source-dir.ts | 11 +---- .../protocol/workspace-source-get.test.ts | 23 +++++++++++ .../commands/protocol/workspace-source-get.ts | 5 ++- 11 files changed, 103 insertions(+), 26 deletions(-) diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index 6f501abcf1b..4aceb276fba 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -41,7 +41,7 @@ Nothing in the file runs on your machine. Sim reads it statically, checks it aga This writes `workflow.ts`, any function code under `functions/`, and type declarations for the blocks the workflow uses and for your workspace's tables, credentials, knowledge bases, and environment variable names, with `.sim/sdk/INDEX.md` listing those blocks' builders. The declarations of every block are generated once per block catalog into the CLI's cache (`~/.sim/cache/source-catalog/`) and shared by every directory. It also writes a `tsconfig.json` that resolves them and type-checks the blocks the workflow uses, and a `tsconfig.full.json` that type-checks every block through that cache, unless the directory already has files of those names, which are left as they are. For coding agents it writes `.sim/AGENTS.md`, the primer `get` prints followed by a reference, and example workflows under `.sim/examples/` with one correct example of each common block to copy from. The examples name placeholder resources, so the tsconfig files leave them out of the type-check. - `get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. + `get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace source directory is always refused, `--force` included (and `sim workspaces source get` refuses a workflow directory the same way). 2. Edit `workflow.ts`, then compile it on your machine with Sim's compiler, without a request: diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index e3d4d6400ea..06facf984a8 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -222,6 +222,46 @@ export function directoryWorkspace( ) } +/** Which source command family a directory belongs to: one workflow's, or a whole workspace's. */ +export type SourceDirKind = 'workflow' | 'workspace' + +/** + * What `dir` holds, by its `.sim/base.json` (read leniently, as an apply reads it: a base the + * parser refuses still names what it is): a workflow base names its `workflowId`, a workspace base + * only its `workspaceId`. Without a base, a `workflow.ts` or a starter record at the root is a + * workflow directory (a workspace directory keeps its workflows under `workflows//`). `null` + * for a directory that holds neither, such as a new one. + */ +export async function sourceDirKind( + dir: string +): Promise<{ kind: SourceDirKind; readFrom: string | null } | null> { + const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) + if (typeof base.workflowId === 'string') return { kind: 'workflow', readFrom: base.workflowId } + if (typeof base.workspaceId === 'string') { + return { kind: 'workspace', readFrom: base.workspaceId } + } + const starter = await readStarterWorkspace(dir) + if (starter !== null || (await readSourceText(dir, SOURCE_ENTRY_FILE)) !== null) { + return { kind: 'workflow', readFrom: null } + } + return null +} + +/** + * Refuses a `kind` command on a directory of the other kind, whatever `--force` says: a workflow + * get into a workspace directory (or the reverse) would replace its base, so staleness could no + * longer be detected and its unapplied edits would sit in a directory neither command reads. + */ +export async function assertSourceDirKind(dir: string, kind: SourceDirKind): Promise { + const held = await sourceDirKind(dir) + if (held === null || held.kind === kind) return + const message = + held.kind === 'workspace' + ? `${dir} is a workspace source directory${held.readFrom ? ` (workspace ${held.readFrom})` : ''}, so a \`sim workflows source\` command would replace its base. Edit a workflow of it in ${dir}/${KIND_DIRS.workflow}/ with \`sim workspaces source\` (check, status, apply) --dir ${dir}, or get the workflow into another directory.` + : `${dir} is a workflow source directory${held.readFrom ? ` (workflow ${held.readFrom})` : ''}, so a \`sim workspaces source\` command would replace its base. Use \`sim workflows source\` (get, check, status, apply) --dir ${dir}, or get the workspace into another directory.` + throw new SimApiError(message, 0, 'SOURCE_DIR_KIND_MISMATCH') +} + /** The workspace {@link SOURCE_STARTER_FILE} names, or `null` when the directory holds no starter. */ export async function readStarterWorkspace(dir: string): Promise { const workspaceId = toRecord(await readSourceJson(dir, SOURCE_STARTER_FILE)).workspaceId 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 9a7ee82e0c1..1b6a4453917 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -23,6 +23,7 @@ import { apiCommand, type OperationClient } from '../../runtime/called-operation import { printProtocolResult } from './result' import { absoluteDirOption, + assertSourceDirKind, FILE_CONCURRENCY, lockCodeFiles, readSourceText, @@ -185,6 +186,7 @@ export async function readBase( directory: string, workflowId: string | undefined ): Promise { + await assertSourceDirKind(directory, 'workflow') const parsed = parseSourceBase(await readJson(directory, BASE_FILE, GET_HINT)) if ('problem' in parsed) { throw new SimApiError( @@ -550,6 +552,7 @@ export function attachWorkflowSourceCreate(source: Command): void { ) .action(async (options: SourceWriteOptions & { name?: string; folder?: string }) => withWorkspaceFolderLock(options.dir, async () => { + await assertSourceDirKind(options.dir, 'workflow') if ((await readSourceText(options.dir, ENTRY_FILE)) === null) { if (options.dryRun || options.yes) { throw new SimApiError( 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 4e524912b53..54d5183fe59 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 @@ -366,8 +366,9 @@ describe('sim workflows source check', () => { const error = await check().catch((caught: unknown) => caught) + expect((error as SimApiError).message).toContain('is a workspace source directory') expect((error as SimApiError).message).toContain( - `is a workspace source directory: check it with \`sim workspaces source check --dir ${dir}\`` + `\`sim workspaces source\` (check, status, apply) --dir ${dir}` ) }) 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 6526f18f412..e3dedf1ed9d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -27,6 +27,7 @@ import { SimApiError } from '../../http/client' import { printProtocolResult } from './result' import { absoluteDirOption, + assertSourceDirKind, digest, directoryWorkspace, readFolderWritten, @@ -613,17 +614,8 @@ export function attachWorkflowSourceCheck(source: Command): void { .action( async (options: { dir: string; verbose?: boolean } & StrictOptions, command: Command) => { const profile = profileFrom(command) + await assertSourceDirKind(options.dir, 'workflow') const base = toRecord(await readSourceJson(options.dir, SOURCE_BASE_FILE)) - if ( - typeof base.workspaceId === 'string' && - base.workflowId === undefined && - (await readSourceText(options.dir, SOURCE_ENTRY_FILE)) === null - ) { - throw new SimApiError( - `${options.dir} is a workspace source directory: check it with \`sim workspaces source check --dir ${options.dir}\`.`, - 0 - ) - } await requireEntry(options.dir) const workspace = await workspaceFolderOf(options.dir) const recorded = diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 55ab1fb1b47..5b1a33c5f1f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -351,6 +351,25 @@ describe('sim workflows source get --dir', () => { expect(request).toHaveBeenCalledTimes(1) }) + it('refuses a workspace source directory, --force included, keeping its base and unapplied edits', async () => { + const base = JSON.stringify({ version: 1, workspaceId: WORKSPACE_ID, resources: {} }) + mkdirSync(join(outDir, '.sim'), { recursive: true }) + mkdirSync(join(outDir, 'tables')) + writeFileSync(join(outDir, '.sim/base.json'), base) + writeFileSync(join(outDir, 'tables/leads.ts'), '// my unapplied edit\n') + serve() + + for (const flags of [[], ['--force']]) { + await expect(get('--dir', outDir, ...flags)).rejects.toMatchObject({ + code: 'SOURCE_DIR_KIND_MISMATCH', + message: expect.stringContaining('is a workspace source directory'), + }) + } + expect(readFileSync(join(outDir, '.sim/base.json'), 'utf8')).toBe(base) + expect(existsSync(join(outDir, 'workflow.ts'))).toBe(false) + expect(request).not.toHaveBeenCalled() + }) + it('prints the response unchanged without --dir', async () => { request.mockResolvedValue(source()) 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 b4d719da980..69298277a40 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -14,6 +14,7 @@ import { buildRequest } from '../../runtime/request' import { absoluteDirOption, assertPrintedSourcePaths, + assertSourceDirKind, locallyEditedFiles, readPreviousLock, readSourceJson, @@ -289,9 +290,10 @@ async function assertNoLocalEdits(dir: string, source: PrintedSource): Promise { const force = flags[FORCE_FLAG] === true + await assertSourceDirKind(dir, 'workflow') if (!force) await assertSameWorkflow(dir, workflowId) const { client, profile } = connectGet() const request = await buildRequest( diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index d966ca640d5..bcc98d3d476 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -245,7 +245,7 @@ describe('sim workspaces source check', () => { expect(error).toMatchObject({ message: expect.stringContaining( - 'is a workflow source directory: use `sim workflows source`' + 'is a workflow source directory (workflow wf_first), so a `sim workspaces source` command' ), }) }) 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 9608a974d94..2394ecf5569 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -6,7 +6,6 @@ */ import { realpath, stat } from 'node:fs/promises' import { mapWithConcurrency } from '@sim/utils/concurrency' -import { toRecord } from '@sim/utils/object' import type { WorkflowInput } from '@sim/workflow-code' import { SOURCE_COMPILER_OPTIONS, @@ -47,11 +46,11 @@ import { SOURCE_TOO_LARGE_EXIT_CODE } from '../../exit-codes' import type { ApplyWorkspaceSourceBody } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { + assertSourceDirKind, checkedPath, digest, FILE_CONCURRENCY, listSourceFiles, - readSourceJson, readSourceText, SOURCE_DIR_LOCK, SOURCE_DOWNLOADS_DIR, @@ -519,13 +518,7 @@ export async function kindFolders( * workflow folder fails instead of passing with nothing checked or applied. */ export async function assertWorkspaceDir(dir: string): Promise { - const base = toRecord(await readSourceJson(dir, WORKSPACE_BASE_FILE)) - if (typeof base.workflowId === 'string') { - throw new SimApiError( - `${dir} is a workflow source directory: use \`sim workflows source\` (check, apply) with --dir ${dir}.`, - 0 - ) - } + await assertSourceDirKind(dir, 'workspace') const { present } = await kindFolders(dir, APPLY_ORDER) if (present.length > 0) return throw new SimApiError( diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 858451de70c..36ef0fe69d4 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -129,6 +129,29 @@ describe('workspaces source get', () => { expect(readFileSync(join(dir, 'tables/leads.ts'), 'utf8')).toBe(`${LEADS}// server\n`) }) + it('refuses a workflow source directory, --force included, keeping its base and unapplied edits', async () => { + const base = JSON.stringify({ + workflowId: 'wf-1', + workspaceId: 'ws_local', + fingerprint: 'sf1:x', + catalogHash: 'h', + }) + mkdirSync(join(dir, '.sim'), { recursive: true }) + writeFileSync(join(dir, '.sim/base.json'), base) + writeFileSync(join(dir, 'workflow.ts'), '// @sim-sdk 1\n// my unapplied edit\n') + serve({ 'tables/leads.ts': LEADS }) + + for (const flags of [[], ['--force']]) { + await expect(get(...flags)).rejects.toMatchObject({ + code: 'SOURCE_DIR_KIND_MISMATCH', + message: expect.stringContaining('is a workflow source directory (workflow wf-1)'), + }) + } + expect(readFileSync(join(dir, '.sim/base.json'), 'utf8')).toBe(base) + expect(existsSync(join(dir, 'tables'))).toBe(false) + expect(request).not.toHaveBeenCalled() + }) + it('keeps the seed rows file of a table the answer declares seed rows for, which no read prints', async () => { const seeded = (name: string) => `// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({ name: '${name}', columns: { code: column.string() }, rows: { mode: 'seed' } })\n` 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 6cd5c22d924..011ab6524c3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -23,6 +23,7 @@ import { apiCommand } from '../../runtime/called-operations' import { removeStagingOnSignal } from './files-get' import { absoluteDirOption, + assertSourceDirKind, checkedPath, directoryWorkspace, editedFiles, @@ -79,7 +80,8 @@ 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), or a downloaded +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 @@ -384,6 +386,7 @@ export function attachWorkspaceSourceGet(source: Command): void { const kinds = parseKinds(options.only) const { client, profile } = connect() await withSourceDirLock(options.dir, async () => { + await assertSourceDirKind(options.dir, 'workspace') // Read as leniently as an apply reads it: a base the parser refuses still names its workspace. const recorded = toRecord( await readSourceJson(options.dir, WORKSPACE_BASE_FILE) From 00111910e5f7c92b7433a00d5fc0bb4089420553 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:30:43 -0800 Subject: [PATCH 017/104] fix(workflow-code): one code file path rule for the compiler, printer and CLI A function file named functions/My_Sink.js (or for_body.py) passed check and the dry run, was stored, and then the CLI exited 1 "unsafe file path" without writing the base or lock, because the CLI only accepted the printer's kebab names while the compiler accepted any relative path. isCodeFilePath in @sim/workflow-code/limits is now the one rule: the compiler refuses anything else as E_CODE_FILE_PATH (so check and the server refuse it before a write), the printer only reuses a hinted path it accepts, and the CLI refuses it before sending. After a stored write the CLI never throws on an answer path: it skips one it would not write, warns, and still writes the lock and base. --- .../src/commands/protocol/source-dir.ts | 55 +++++++++---- .../protocol/workflow-source-apply.test.ts | 46 +++++++++++ .../protocol/workflow-source-apply.ts | 2 + .../workflow-source-roundtrip.test.ts | 14 ++-- .../src/code-files/bijection.test.ts | 18 +++++ packages/workflow-code/src/compile/blocks.ts | 20 ++++- .../workflow-code/src/compile/grammar.test.ts | 80 ++++++++++++------- .../workflow-code/src/compile/hostile.test.ts | 59 ++++++++------ .../workflow-code/src/diagnostics/codes.ts | 5 +- packages/workflow-code/src/limits.ts | 16 ++++ packages/workflow-code/src/print/context.ts | 7 +- packages/workflow-code/src/print/params.ts | 4 +- 12 files changed, 244 insertions(+), 82 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index 06facf984a8..983687c3d65 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -30,7 +30,7 @@ import { basename, dirname, join, posix, resolve } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' import { isRecordLike, toRecord } from '@sim/utils/object' import { - CODE_FILE_EXTENSIONS, + isCodeFilePath, SOURCE_BASE_FILE, SOURCE_ENTRY_FILE, SOURCE_CODE_DIR as SOURCE_FUNCTIONS_DIR, @@ -38,6 +38,7 @@ import { } from '@sim/workflow-code/limits' import { fingerprintOf, KIND_DIRS } from '@sim/workspace-code' import type { Command } from 'commander' +import { printError } from '#sim-cli/output/io' import type { ResolvedProfile } from '../../config/index' import { embedStore } from '../../embed-context' import { SOURCE_BUSY_EXIT_CODE } from '../../exit-codes' @@ -86,17 +87,12 @@ export const SOURCE_DOWNLOADS_DIR = '.sim/downloads' export const SOURCE_STAGING_PREFIX = '.sim-staging-' /** - * The only files a server answer may name: the entry file and function code under `functions/`, - * named as the printer names them (`functions/[-n].`). Anything else - * (`.git/hooks/*`, `conftest.py`, a dotfile) is refused, whatever base URL answered. + * Whether a server answer may write `path` into the source directory: the entry file, or a code + * file as {@link isCodeFilePath} (the rule the compiler applies to `codeFile()`) names one. + * Anything else (`.git/hooks/*`, `conftest.py`, a dotfile) is refused, whatever base URL answered. */ -const FUNCTION_FILE = new RegExp( - `^${SOURCE_FUNCTIONS_DIR}/[a-z0-9$-]+\\.(?:${Object.values(CODE_FILE_EXTENSIONS).join('|')})$` -) - -/** Whether a server answer may write `path` into the source directory. */ function isPrintedSourcePath(path: string): boolean { - return path === SOURCE_ENTRY_FILE || FUNCTION_FILE.test(path) + return path === SOURCE_ENTRY_FILE || isCodeFilePath(path) } /** Refuses a server answer naming a file the printer never writes, before anything is written. */ @@ -108,6 +104,21 @@ export function assertPrintedSourcePaths(files: Record): void { } } +/** + * Refuses, before a write is sent, a code file the server would store but the CLI could never + * write back: one rule ({@link isCodeFilePath}) for both, so an apply is never stored and then + * reported as failed. + */ +export function assertSendableCodeFiles(files: Record): void { + const refused = Object.keys(files).filter((path) => !isPrintedSourcePath(path)) + if (refused.length === 0) return + throw new SimApiError( + `${refused.join(', ')} ${refused.length === 1 ? 'is not a code file path' : 'are not code file paths'} a workflow directory holds, so nothing was sent. Move the code to ${SOURCE_FUNCTIONS_DIR}/.js (or .py, .sh: letters, digits, _, $, - and dots, not starting with a dot) and update its codeFile().`, + 0, + 'E_CODE_FILE_PATH' + ) +} + const GITATTRIBUTES_LINES = [ `${SOURCE_ENTRY_FILE} text eol=lf`, `${SOURCE_FUNCTIONS_DIR}/** text eol=lf`, @@ -789,10 +800,26 @@ interface PrintedSourceAnswer { base: unknown } +/** + * The files of a stored write's answer the CLI may write: every one {@link isPrintedSourcePath} + * accepts. The write is already stored, so a path refused here is left as it is on disk (it is + * the author's own file, which the server echoed) with a warning, never thrown: the lock and base + * are still written, so the directory matches the stored workflow. + */ +function writableFiles(files: Record): Record { + const refused = Object.keys(files).filter((path) => !isPrintedSourcePath(path)) + if (refused.length === 0) return files + printError( + `warning: the answer named ${refused.join(', ')}, which the CLI never writes; the write was saved and the lock and base were written, but ${refused.length === 1 ? 'that file was' : 'those files were'} left as ${refused.length === 1 ? 'it is' : 'they are'} on disk.` + ) + return Object.fromEntries(Object.entries(files).filter(([path]) => isPrintedSourcePath(path))) +} + /** * Writes a server answer into the source directory in one staged update: its files, lock and base, * plus `extra`, pruning the function files the previous lock named and the new one no longer does. - * Returns how many files it wrote. + * Returns how many files it wrote. A get refuses an unsafe path first + * ({@link assertPrintedSourcePaths}); after a stored write one is skipped ({@link writableFiles}). */ export async function writeBack( dir: string, @@ -800,16 +827,16 @@ export async function writeBack( previousLock: unknown, extra: SourceDirChange = { write: [] } ): Promise { - assertPrintedSourcePaths(answer.files) + const files = writableFiles(answer.files) const folder = await workspaceFolderOf(dir) const printed: Array = [ - ...Object.entries(answer.files), + ...Object.entries(files), [SOURCE_LOCK_FILE, `${JSON.stringify(answer.lock, null, 2)}\n`], [SOURCE_BASE_FILE, `${JSON.stringify(answer.base, null, 2)}\n`], ] const write = [ ...printed, - ...(folder ? [] : [[SOURCE_WRITTEN_FILE, writtenFile(writtenRecord(answer.files))] as const]), + ...(folder ? [] : [[SOURCE_WRITTEN_FILE, writtenFile(writtenRecord(files))] as const]), ...extra.write, ] const orphaned = orphanedCodeFiles(previousLock, answer.lock, Object.keys(answer.files)) 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 5a34c301403..df3bd0dc159 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 @@ -1067,6 +1067,52 @@ describe('the code files an apply sends', () => { expect(sentCodeFiles()).toEqual(['functions/used.py']) }) + /** Applies `entry` with --yes, the server answering with `files` as what it stored. */ + async function applyStored(entry: string, files: Record): Promise { + writeFileSync(join(dir, 'workflow.ts'), entry) + setTerminal(false) + const stored = outcome() + request.mockResolvedValue({ data: { ...stored.data, files } }) + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + } + + it('applies a function file named with capitals and underscores, and writes the base and lock', async () => { + writeFunctions('functions/My_Sink.js') + const entry = entryWith( + "const sink = fn('Sink', { code: codeFile('./functions/My_Sink.js') })\n" + ) + + await applyStored(entry, { 'workflow.ts': entry, 'functions/My_Sink.js': 'return 2\n' }) + + expect(sentCodeFiles()).toEqual(['functions/My_Sink.js']) + expect(readFileSync(join(dir, 'functions/My_Sink.js'), 'utf8')).toBe('return 2\n') + expect(JSON.parse(readFileSync(join(dir, '.sim/base.json'), 'utf8')).fingerprint).toBe('sf1:b') + }) + + it('refuses before sending a code file outside functions/, which no workflow directory holds', async () => { + mkdirSync(join(dir, 'lib')) + writeFileSync(join(dir, 'lib/helper.js'), 'return 1\n') + const entry = entryWith("const a = fn('A', { code: codeFile('./lib/helper.js') })\n") + + await expect(applyStored(entry, { 'workflow.ts': entry })).rejects.toMatchObject({ + code: 'E_CODE_FILE_PATH', + message: expect.stringContaining('lib/helper.js is not a code file path'), + }) + expect(request).not.toHaveBeenCalled() + }) + + it('after a stored write, skips an answer path it never writes and still writes the base and lock', async () => { + const entry = entryWith('') + + await applyStored(entry, { 'workflow.ts': entry, '.git/hooks/pre-commit.sh': 'exit 1\n' }) + + expect(existsSync(join(dir, '.git/hooks/pre-commit.sh'))).toBe(false) + expect(JSON.parse(readFileSync(join(dir, '.sim/base.json'), 'utf8')).fingerprint).toBe('sf1:b') + expect(stderrLines().join('\n')).toContain( + 'the answer named .git/hooks/pre-commit.sh, which the CLI never writes' + ) + }) + it('sends only .js, .py and .sh files, whatever the source or the lock names', async () => { writeFileSync(join(dir, '.env'), 'SECRET=1') writeFileSync(join(dir, 'notes.txt'), 'SECRET') 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 1b6a4453917..fde5ca45a64 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -23,6 +23,7 @@ import { apiCommand, type OperationClient } from '../../runtime/called-operation import { printProtocolResult } from './result' import { absoluteDirOption, + assertSendableCodeFiles, assertSourceDirKind, FILE_CONCURRENCY, lockCodeFiles, @@ -270,6 +271,7 @@ async function runSourceWrite(args: { command: string }): Promise { const { options, creating } = args + assertSendableCodeFiles(args.body.files) /** Sends the write (or its dry run); a refusal prints its diagnostics and rethrows. */ const send = async (dryRun: boolean): Promise => { try { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 358f555de29..f97ee7923cb 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -348,16 +348,16 @@ describe('the source directory never reaches outside --dir', () => { expect(applyBodies).toEqual([]) }) - it('refuses a write-back the server names outside the directory, writing nothing', async () => { + it('never writes a stored write-back path outside the directory, and still records the write', async () => { await get() server.apply = () => json(appliedResponse({ 'workflow.ts': '// changed\n', '../escape.js': 'x' })) - await expect(apply()).rejects.toThrow('unsafe file path') + await apply() expect(existsSync(join(root, 'escape.js'))).toBe(false) - expect(read('workflow.ts')).toBe(WORKFLOW_TS) - expect(JSON.parse(read('.sim/base.json')).fingerprint).toBe(FIRST) + expect(read('workflow.ts')).toBe('// changed\n') + expect(JSON.parse(read('.sim/base.json')).fingerprint).not.toBe(FIRST) }) it.each([ @@ -428,14 +428,14 @@ describe('the files a server answer may write', () => { expect(existsSync(dir)).toBe(false) }) - it('refuses an apply answer naming a file the printer never writes, keeping the directory', async () => { + it('never writes an apply answer file the printer never writes, and still records the write', async () => { await get() server.apply = () => json(appliedResponse({ ...FILES, '.git/hooks/pre-commit': 'planted' })) - await expect(apply()).rejects.toThrow('unsafe file path') + await apply() expect(existsSync(join(dir, '.git'))).toBe(false) - expect(JSON.parse(read('.sim/base.json')).fingerprint).toBe(FIRST) + expect(JSON.parse(read('.sim/base.json')).fingerprint).not.toBe(FIRST) }) }) diff --git a/packages/workflow-code/src/code-files/bijection.test.ts b/packages/workflow-code/src/code-files/bijection.test.ts index 9e8f0d31b30..a3592b54b59 100644 --- a/packages/workflow-code/src/code-files/bijection.test.ts +++ b/packages/workflow-code/src/code-files/bijection.test.ts @@ -261,4 +261,22 @@ describe('code file paths', () => { expect(print().hints.blocks.fetchdata?.codeFile).toBe(hinted) expect(print()).toEqual(print()) }) + + it.each(['lib/fetch.js', 'functions/.fetch.js', '.git/hooks/fetch.js'])( + 'prints a hinted path no workflow directory holds (%s) under functions/ instead', + (hinted) => { + const stored = canonical( + workflowState([ + blockState('f0', 'function', 'Fetch data', { language: 'javascript', code: 'return 1' }), + ]) + ).workflow + const printed = printWorkflow({ + workflow: stored, + catalog: CATALOG, + hints: { blocks: { fetchdata: { codeFile: hinted } } }, + options: { functionCode: 'files' }, + }) + expect(printed.files.slice(1).map((file) => file.path)).toEqual(['functions/fetch-data.js']) + } + ) }) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 5296d6a6860..445bdbf3c41 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -42,7 +42,7 @@ import { isIdentifierName, parseStoredPath } from '../code-files/ref-path' import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' import { type ConfigField, type ContainerForm, loopForm, parallelForm } from '../forms/subflow' -import { CODE_FILE_EXTENSIONS, utf8Bytes } from '../limits' +import { CODE_FILE_EXTENSIONS, isCodeFilePath, SOURCE_CODE_DIR, utf8Bytes } from '../limits' import { isJson } from '../lock' import { type AnchorKey, @@ -350,12 +350,26 @@ function readCodeFile( return null } const path = resolveRelative(ctx.file, compiled.path) - if (path === null || codeFileLanguage(compiled.path) !== language) { + const entryName = ctx.file.slice(ctx.file.lastIndexOf('/') + 1) + const fromEntry = resolveRelative(entryName, compiled.path) + if (path === null || fromEntry === null || !isCodeFilePath(fromEntry)) { ctx.reporter.report( 'E_CODE_FILE_PATH', path === null ? `${compiled.path} is not a relative path inside the repository.` - : `${compiled.path} does not match the block language ${language}.`, + : `${compiled.path} is not a code file path a workflow directory holds.`, + at, + { + hint: `Name it ./${SOURCE_CODE_DIR}/.js (or .py, .sh): one file directly in ${SOURCE_CODE_DIR}/ beside ${entryName}, its name letters, digits, _, $, - and dots, not starting with a dot.`, + blockKey: decl.key, + } + ) + return null + } + if (codeFileLanguage(compiled.path) !== language) { + ctx.reporter.report( + 'E_CODE_FILE_PATH', + `${compiled.path} does not match the block language ${language}.`, at, { hint: "Write codeFile('./functions/name.js') with .js, .py or .sh matching language.", diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 597f9eae0da..a539801dc5d 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -423,13 +423,13 @@ describe('accepted grammar', () => { source( [ START, - "const score = fn('Score', { language: 'javascript', code: codeFile('./fns/score.js') })", - "const py = fn('Py', { language: 'python', code: codeFile('./fns/py.py') })", + "const score = fn('Score', { language: 'javascript', code: codeFile('./functions/score.js') })", + "const py = fn('Py', { language: 'python', code: codeFile('./functions/py.py') })", ].join('\n') ), { - 'workflows/fns/score.js': 'return $ref.start.input + $env.KEY // $ref.x', - 'workflows/fns/py.py': 'print($ref.start.input)', + 'workflows/functions/score.js': 'return $ref.start.input + $env.KEY // $ref.x', + 'workflows/functions/py.py': 'print($ref.start.input)', } ) expect(errorsOf(result)).toEqual([]) @@ -440,7 +440,7 @@ describe('accepted grammar', () => { expect(result.hints.blocks.score).toEqual({ ident: 'score', order: 1, - codeFile: 'workflows/fns/score.js', + codeFile: 'workflows/functions/score.js', }) }) @@ -841,9 +841,9 @@ describe('errors, each with its code, location and hint', () => { ], [ 'codeFile() in an extra field', - "const a = api('A', { url: 'x' }, { extra: { script: codeFile('./fns/a.js') } })", + "const a = api('A', { url: 'x' }, { extra: { script: codeFile('./functions/a.js') } })", 'E_UNSUPPORTED_SYNTAX', - "codeFile('./fns/a.js') }", + "codeFile('./functions/a.js') }", "Write code: codeFile('./functions/x.js').", ], [ @@ -984,9 +984,9 @@ describe('errors, each with its code, location and hint', () => { ], [ 'a missing code file', - "const f = fn('F', { code: codeFile('./fns/missing.js') })", + "const f = fn('F', { code: codeFile('./functions/missing.js') })", 'E_CODE_FILE_MISSING', - "'./fns/missing.js'", + "'./functions/missing.js'", ], [ 'a code file outside the repo', @@ -994,21 +994,42 @@ describe('errors, each with its code, location and hint', () => { 'E_CODE_FILE_PATH', "'../../../x.js'", ], + [ + 'a code file outside functions/, which the CLI never writes back', + "const f = fn('F', { code: codeFile('./lib/a.js') })", + 'E_CODE_FILE_PATH', + "'./lib/a.js'", + ], + [ + 'a code file whose name starts with a dot', + "const f = fn('F', { code: codeFile('./functions/.a.js') })", + 'E_CODE_FILE_PATH', + "'./functions/.a.js'", + ], [ 'a code file whose extension does not match the language', - "const f = fn('F', { language: 'python', code: codeFile('./fns/a.js') })", + "const f = fn('F', { language: 'python', code: codeFile('./functions/a.js') })", 'E_CODE_FILE_PATH', - "'./fns/a.js'", + "'./functions/a.js'", ], ] as const)('reports %s', (_label, body, code, needle) => { const text = source(body) expectDiagnostic( - run(text, { 'workflows/fns/a.js': 'return 1' }), + run(text, { 'workflows/functions/a.js': 'return 1' }), code, locate(text, needle, code === 'E_DUPLICATE_EDGE' ? 2 : 1) ) }) + it('reads a code file named with capitals and underscores, as an author names a Python file', () => { + const text = source( + "const f = fn('F', { language: 'python', code: codeFile('./functions/My_Sink.py') })" + ) + const result = run(text, { 'workflows/functions/My_Sink.py': 'print(1)' }) + expect(result.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + expect(result.hints.blocks.f?.codeFile).toBe('workflows/functions/My_Sink.py') + }) + it('attributes a wiring error to the source block', () => { const text = source( "const a = api('A', { url: 'x' })\nconst b = api('B', { url: 'x' })\na.to(b)\na.to(b)" @@ -1033,7 +1054,7 @@ describe('errors, each with its code, location and hint', () => { START, "const classifier = agent('Triage Agent', { model: 'm' })", "const lookup = api('Lookup', { url: 'x' })", - "const f = fn('F', { code: codeFile('./fns/f.js') })", + "const f = fn('F', { code: codeFile('./functions/f.js') })", ].join('\n') ) const file = [ @@ -1042,22 +1063,22 @@ describe('errors, each with its code, location and hint', () => { 'const c = $ref.variable.missing', 'const d = $ref.triageagent.content + $ref.lookup.data + $ref.start.input + $ref.variable.retries', ].join('\n') - const result = run(text, { 'workflows/fns/f.js': file }) + const result = run(text, { 'workflows/functions/f.js': file }) expect(errorsOf(result)).toEqual([]) const unresolved = result.diagnostics.filter((d) => d.code === 'W_UNRESOLVED_REF') expect(unresolved).toEqual([ expect.objectContaining({ - span: expect.objectContaining({ file: 'workflows/fns/f.js', line: 1, column: 11 }), + span: expect.objectContaining({ file: 'workflows/functions/f.js', line: 1, column: 11 }), hint: expect.stringContaining('$ref.triageagent.content'), }), expect.objectContaining({ - span: expect.objectContaining({ file: 'workflows/fns/f.js', line: 3 }), + span: expect.objectContaining({ file: 'workflows/functions/f.js', line: 3 }), }), ]) const outputPath = result.diagnostics.filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH') expect(outputPath).toEqual([ expect.objectContaining({ - span: expect.objectContaining({ file: 'workflows/fns/f.js', line: 2 }), + span: expect.objectContaining({ file: 'workflows/functions/f.js', line: 2 }), }), ]) }) @@ -1067,10 +1088,10 @@ describe('errors, each with its code, location and hint', () => { [ START, "const lookup = api('Fetch Page', { url: 'x' })", - "const f = fn('F', { code: codeFile('./fns/f.js') })", + "const f = fn('F', { code: codeFile('./functions/f.js') })", ].join('\n') ) - const files = { 'workflows/fns/f.js': 'return $ref.lookup.data + $ref.lookup.nope' } + const files = { 'workflows/functions/f.js': 'return $ref.lookup.data + $ref.lookup.nope' } const lockBlock = (id: string, ident: string, order: number) => ({ id, parent: null, @@ -1096,7 +1117,7 @@ describe('errors, each with its code, location and hint', () => { }) const codes = (result: CompileResult) => result.diagnostics - .filter((d) => d.span.file === 'workflows/fns/f.js') + .filter((d) => d.span.file === 'workflows/functions/f.js') .map((d) => `${d.code} ${d.span.column}`) const expected = ['W_UNKNOWN_OUTPUT_PATH 27'] expect(codes(compile({ storedUnread }))).toEqual(expected) @@ -1109,7 +1130,7 @@ describe('errors, each with its code, location and hint', () => { [ START, "const fetcher = api('Fetch Page', { url: 'x' })", - "const f = fn('F', { code: codeFile('./fns/f.js') })", + "const f = fn('F', { code: codeFile('./functions/f.js') })", ].join('\n') ) const lockBlock = (id: string, ident: string, order: number) => ({ @@ -1129,7 +1150,7 @@ describe('errors, each with its code, location and hint', () => { } const result = compileWorkflow({ entry: { path: ENTRY, text }, - files: new Map([['workflows/fns/f.js', 'return $ref.lookup.data']]), + files: new Map([['workflows/functions/f.js', 'return $ref.lookup.data']]), catalog: TEST_CATALOG, sdkMajor: 1, knownKeys: new Set(Object.keys(storedUnread.blocks)), @@ -1143,11 +1164,11 @@ describe('errors, each with its code, location and hint', () => { }) it('reports a syntax error inside a code file at its own location', () => { - const result = run(source("const f = fn('F', { code: codeFile('./fns/bad.js') })"), { - 'workflows/fns/bad.js': 'return (', + const result = run(source("const f = fn('F', { code: codeFile('./functions/bad.js') })"), { + 'workflows/functions/bad.js': 'return (', }) const syntax = result.diagnostics.find((d) => d.code === 'E_SYNTAX') - expect(syntax?.span).toMatchObject({ file: 'workflows/fns/bad.js', line: 1 }) + expect(syntax?.span).toMatchObject({ file: 'workflows/functions/bad.js', line: 1 }) expect(result.workflow).toBeNull() }) @@ -1477,8 +1498,11 @@ describe('env names the workspace does not hold', () => { it('warns on a $env name in a code file at the file location', () => { const result = compileWorkflow({ - entry: { path: ENTRY, text: source("const f = fn('F', { code: codeFile('./fns/f.js') })") }, - files: new Map([['workflows/fns/f.js', 'return $env.API_URL + $env.MISSING_KEY']]), + entry: { + path: ENTRY, + text: source("const f = fn('F', { code: codeFile('./functions/f.js') })"), + }, + files: new Map([['workflows/functions/f.js', 'return $env.API_URL + $env.MISSING_KEY']]), catalog: TEST_CATALOG, sdkMajor: 1, envNames: new Set(['API_URL']), @@ -1487,7 +1511,7 @@ describe('env names the workspace does not hold', () => { expect(unknown).toEqual([ expect.objectContaining({ message: expect.stringContaining('MISSING_KEY'), - span: expect.objectContaining({ file: 'workflows/fns/f.js', line: 1, column: 23 }), + span: expect.objectContaining({ file: 'workflows/functions/f.js', line: 1, column: 23 }), }), ]) }) diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 779d825789c..29ed24e2043 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -296,8 +296,12 @@ describe('hostile sources produce diagnostics only', () => { }) it('never reads a code file outside the repository or past the size cap', () => { - const text = `// @sim-sdk 1\nimport { codeFile, fn, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('X', {}, () => {\n const a = fn('A', { code: codeFile('../../etc/passwd.js') })\n const b = fn('B', { code: codeFile('./big.js') })\n})\n` - const result = run(text, { maxTotalBytes: 1_000 }, { 'workflows/big.js': 'x'.repeat(5_000) }) + const text = `// @sim-sdk 1\nimport { codeFile, fn, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('X', {}, () => {\n const a = fn('A', { code: codeFile('../../etc/passwd.js') })\n const b = fn('B', { code: codeFile('./functions/big.js') })\n})\n` + const result = run( + text, + { maxTotalBytes: 1_000 }, + { 'workflows/functions/big.js': 'x'.repeat(5_000) } + ) expect(codes(result)).toEqual(expect.arrayContaining(['E_CODE_FILE_PATH', 'E_LIMIT_EXCEEDED'])) }) @@ -312,10 +316,10 @@ describe('hostile sources produce diagnostics only', () => { it('reports an unstorable code file shared by many blocks once', () => { const result = run( - fnFile(5, () => './a.js'), + fnFile(5, () => './functions/a.js'), undefined, { - 'workflows/a.js': 'return "x\u0000"\n', + 'workflows/functions/a.js': 'return "x\u0000"\n', } ) expect(errorCodes(result)).toEqual(['E_INVALID_CHARACTER']) @@ -323,10 +327,13 @@ describe('hostile sources produce diagnostics only', () => { it('caps the total bytes of distinct code files', () => { const files = Object.fromEntries( - Array.from({ length: 4 }, (_, i) => [`workflows/f${i}.js`, `return ${'1'.repeat(700)}\n`]) + Array.from({ length: 4 }, (_, i) => [ + `workflows/functions/f${i}.js`, + `return ${'1'.repeat(700)}\n`, + ]) ) const result = run( - fnFile(4, (i) => `./f${i}.js`), + fnFile(4, (i) => `./functions/f${i}.js`), { maxTotalBytes: 2_000 }, files ) @@ -336,9 +343,9 @@ describe('hostile sources produce diagnostics only', () => { it('accepts exactly the block cap', () => { const result = run( - fnFile(3, () => './a.js'), + fnFile(3, () => './functions/a.js'), { maxBlocks: 3 }, - { 'workflows/a.js': 'return 1\n' } + { 'workflows/functions/a.js': 'return 1\n' } ) expect(errorCodes(result)).toEqual([]) expect(Object.keys(result.workflow?.blocks ?? {})).toHaveLength(3) @@ -346,39 +353,39 @@ describe('hostile sources produce diagnostics only', () => { it('caps the number of blocks with one diagnostic', () => { const result = run( - fnFile(4, () => './a.js'), + fnFile(4, () => './functions/a.js'), { maxBlocks: 3 }, - { 'workflows/a.js': 'return 1\n' } + { 'workflows/functions/a.js': 'return 1\n' } ) expect(errorCodes(result)).toEqual(['E_LIMIT_EXCEEDED']) expect(result.workflow).toBeNull() }) it('counts the entry file toward the total bytes', () => { - const entry = fnFile(1, () => './a.js') + const entry = fnFile(1, () => './functions/a.js') const result = run( entry, { maxTotalBytes: entry.length + 4 }, - { 'workflows/a.js': 'return 1\n' } + { 'workflows/functions/a.js': 'return 1\n' } ) expect(errorCodes(result)).toEqual(['E_LIMIT_EXCEEDED']) }) it('caps the number of codeFile() references with one diagnostic', () => { const result = run( - fnFile(10, () => './a.js'), + fnFile(10, () => './functions/a.js'), { maxCodeFileRefs: 3 }, - { 'workflows/a.js': 'return 1\n' } + { 'workflows/functions/a.js': 'return 1\n' } ) expect(errorCodes(result)).toEqual(['E_LIMIT_EXCEEDED']) }) it('rejects a depth bomb in a code file before parsing it', () => { const result = run( - fnFile(1, () => './a.js'), + fnFile(1, () => './functions/a.js'), undefined, { - 'workflows/a.js': `return ${'['.repeat(100_000)}${']'.repeat(100_000)}\n`, + 'workflows/functions/a.js': `return ${'['.repeat(100_000)}${']'.repeat(100_000)}\n`, } ) expect(errorCodes(result)).toEqual(['E_LIMIT_EXCEEDED']) @@ -412,8 +419,8 @@ describe('one set of limits for get and compile', () => { [ 'a JavaScript code file nested in brackets', { - 'workflows/hostile.ts': `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./deep.js') })\n})\n`, - 'workflows/deep.js': `return ${'['.repeat(250)}${']'.repeat(250)}\n`, + 'workflows/hostile.ts': `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./functions/deep.js') })\n})\n`, + 'workflows/functions/deep.js': `return ${'['.repeat(250)}${']'.repeat(250)}\n`, }, ], ])('flags %s that compile refuses, so a get never prints it', (_, files) => { @@ -431,8 +438,8 @@ describe('one set of limits for get and compile', () => { ].join('\n') ) const files = { - 'workflows/hostile.ts': `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./regex.js') })\n})\n`, - 'workflows/regex.js': `${lines.join('\n')}\nreturn 1\n`, + 'workflows/hostile.ts': `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./functions/regex.js') })\n})\n`, + 'workflows/functions/regex.js': `${lines.join('\n')}\nreturn 1\n`, } const { 'workflows/hostile.ts': entry, ...codeFiles } = files expect(errorCodes(run(entry, undefined, codeFiles))).toEqual([]) @@ -442,9 +449,9 @@ describe('one set of limits for get and compile', () => { // Two linear walks of 300k nodes: ~0.5s locally, 1.8-2.4s on CI, 5.1s on one loaded runner. it('walks a node with more children than one call can take as arguments', () => { const wide = `[${'0,'.repeat(300_000)}0]` - const entry = `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./f.js') })\n const a = api('A', { url: 'x', body: raw(${wide}) })\n})\n` - expect(() => run(entry, undefined, { 'workflows/f.js': 'return 1\n' })).not.toThrow() - expect(codeFileReferences(entry)).toEqual(['./f.js']) + const entry = `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./functions/f.js') })\n const a = api('A', { url: 'x', body: raw(${wide}) })\n})\n` + expect(() => run(entry, undefined, { 'workflows/functions/f.js': 'return 1\n' })).not.toThrow() + expect(codeFileReferences(entry)).toEqual(['./functions/f.js']) }, 15_000) it('passes a source nested within the cap', () => { @@ -470,11 +477,11 @@ describe('characters a workflow cannot store', () => { }) it('refuses a NUL in a code file at its line, for the block reading it', () => { - const text = `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./f.js') })\n})\n` + const text = `${HEADER.replace('api, ', 'codeFile, fn, ')}export default workflow('Hostile', {}, () => {\n const f = fn('F', { code: codeFile('./functions/f.js') })\n})\n` const code = 'const a = 1\nreturn "x\u0000"\n' - const result = run(text, undefined, { 'workflows/f.js': code }) + const result = run(text, undefined, { 'workflows/functions/f.js': code }) const refused = result.diagnostics.find((d) => d.code === 'E_INVALID_CHARACTER') - expect(refused?.span).toMatchObject({ file: 'workflows/f.js', line: 2, column: 10 }) + expect(refused?.span).toMatchObject({ file: 'workflows/functions/f.js', line: 2, column: 10 }) expect(refused?.blockKey).toBe('f') }) diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 97ef527c90e..1b8e8d6eda0 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -251,7 +251,10 @@ const COMPILE_CATALOG_CODES = [ const CODE_FILE_CODES = [ /** `fn('./x.js')` names a file absent from `CompileInput.files`. */ 'E_CODE_FILE_MISSING', - /** Not a relative path inside the repo, or the extension does not match the block language. */ + /** + * Not `./functions/.` beside the entry file (`isCodeFilePath`), or the extension + * does not match the block language. + */ 'E_CODE_FILE_PATH', /** The printer's bijection self-check failed; the code was printed inline as `js```. */ 'W_CODE_FILE_INLINED', diff --git a/packages/workflow-code/src/limits.ts b/packages/workflow-code/src/limits.ts index 5b3d4ea8e12..dd55dc55e5a 100644 --- a/packages/workflow-code/src/limits.ts +++ b/packages/workflow-code/src/limits.ts @@ -60,6 +60,22 @@ export const CODE_FILE_EXTENSIONS = { shell: 'sh', } as const +/** + * A function code file's path in a workflow directory, from the directory root: + * `functions/.`, the name letters, digits, `_`, `$`, `-` and inner dots (never a + * leading one). The one rule the compiler (`E_CODE_FILE_PATH`), the printer and the CLI (on what + * it sends and what it writes) share, so a name one accepts the others never refuse after a + * write was stored. + */ +const CODE_FILE_PATH = new RegExp( + `^${SOURCE_CODE_DIR}/[A-Za-z0-9_$-][A-Za-z0-9_.$-]*\\.(?:${Object.values(CODE_FILE_EXTENSIONS).join('|')})$` +) + +/** Whether `path` (from the workflow directory root) is a code file path a source may name. */ +export function isCodeFilePath(path: string): boolean { + return CODE_FILE_PATH.test(path) +} + /** One size limit a source exceeds, with the measured value. */ export interface SourceLimitExcess { limit: 'maxBlocks' | 'maxEdges' | 'maxFiles' | 'maxTotalBytes' diff --git a/packages/workflow-code/src/print/context.ts b/packages/workflow-code/src/print/context.ts index 0c79f7280d8..dba17334f3a 100644 --- a/packages/workflow-code/src/print/context.ts +++ b/packages/workflow-code/src/print/context.ts @@ -8,6 +8,7 @@ import type { BlockCatalog } from '../catalog/types' import type { PrintDiagnosticCode } from '../diagnostics/codes' import type { Diagnostic } from '../diagnostics/frame' import type { RefTypeScope } from '../json-fields' +import { isCodeFilePath } from '../limits' import type { SourceHints } from '../lock' import type { BlockKey, CanonicalBlock, CanonicalEdge, CanonicalWorkflow } from '../model' import { getOwn } from '../records' @@ -123,7 +124,11 @@ export function createPrintContext(input: PrintInput): PrintContext { } for (const key of blocks.keys()) { const hinted = getOwn(ctx.hints.blocks, key)?.codeFile - if (hinted !== undefined && !ctx.codePathOwners.has(foldCodePath(hinted))) { + if ( + hinted !== undefined && + isCodeFilePath(hinted) && + !ctx.codePathOwners.has(foldCodePath(hinted)) + ) { ctx.codePathOwners.set(foldCodePath(hinted), key) } } diff --git a/packages/workflow-code/src/print/params.ts b/packages/workflow-code/src/print/params.ts index 79e65001402..598a46a2791 100644 --- a/packages/workflow-code/src/print/params.ts +++ b/packages/workflow-code/src/print/params.ts @@ -27,7 +27,7 @@ import type { CatalogBlock, CatalogSubBlock } from '../catalog/types' import { type CodeFileLanguage, checkCodeFileBijection } from '../code-files' import type { ResponseForm } from '../forms/response' import { JsonRef, type JsonTree, jsonFieldText, parseJsonField, refValueKind } from '../json-fields' -import { CODE_FILE_EXTENSIONS, SOURCE_CODE_DIR } from '../limits' +import { CODE_FILE_EXTENSIONS, isCodeFilePath, SOURCE_CODE_DIR } from '../limits' import type { AnchorKey, CanonicalBlock, ParamMode, Value } from '../model' import { getOwn, setOwn } from '../records' import type { TemplateTag } from '../sdk' @@ -236,7 +236,7 @@ function printCodeFile( return owner === undefined || owner === block.key } let path = - hinted?.endsWith(`.${extension}`) && free(hinted) + hinted?.endsWith(`.${extension}`) && isCodeFilePath(hinted) && free(hinted) ? hinted : `${SOURCE_CODE_DIR}/${kebab(ctx.idents.get(block.key) ?? block.key)}.${extension}` let suffix = 2 From 9d1858167fccc6e25cf53ee23ccdfd75bddc11a9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:43:12 -0800 Subject: [PATCH 018/104] fix(workflow-code): check refuses an output typo the server refuses, as one finding An output-reference typo in an existing block passed check with a warning, while the dry run refused it as E_APPLY_LINT, printed beside W_UNKNOWN_OUTPUT_PATH and W_JSON_REF_UNTYPED for the same reference. Now: - compile drops W_JSON_REF_UNTYPED at a reference whose path is already unknown; - the server drops the lint's block-output finding on a block compile reported a dangling entry reference for, and where the lint would refuse it (a block the apply adds or changes) refuses compile's finding as E_APPLY_UNRESOLVED_REF at the reference; - check refuses W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF in workflow.ts as E_APPLY_UNRESOLVED_REF on a block the edit added or changed, telling a changed block from the per-block digests .sim/stored-edges.json now records. --- .../apply-workflow-source.integration.ts | 45 +++++++++++ .../workflows/application/source-evaluate.ts | 75 ++++++++++++++++--- .../src/commands/protocol/stored-edges.ts | 65 ++++++++++++++-- .../protocol/workflow-source-check.test.ts | 72 +++++++++++++++++- .../protocol/workflow-source-check.ts | 60 ++++++++++++--- .../commands/protocol/workflow-source-get.ts | 2 +- .../workflow-code/src/compile/checks.test.ts | 14 ++++ packages/workflow-code/src/compile/index.ts | 33 +++++--- 8 files changed, 323 insertions(+), 43 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 3a2b291d6af..8b2c6c2ce37 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2293,6 +2293,51 @@ describe('renames in source', () => { return { workflowId: seeded.workflowId, calcId } } + check( + 'an output typo in an existing block is one refusal at the reference, as an offline check reports it', + async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + const written = await apply( + source, + { + 'workflow.ts': [ + '// @sim-sdk 1', + "import { api, response, trigger, workflow } from '@sim/workflow-sdk'", + '', + `export default workflow('Output typo ${seeded.workflowId}', {}, () => {`, + " const start = trigger.start('Start', {})", + " const fetch = api('Fetch', { url: 'https://example.com' })", + " const reply = response('Reply', { dataMode: 'json', data: { items: fetch.data } })", + ' start.to(fetch)', + ' fetch.to(reply)', + '})', + '', + ].join('\n'), + }, + { allowDelete: true } + ) + expect(written.applied).toBe(true) + const stored = await getSource(seeded.workflowId) + const typo = edit(stored.files, 'fetch.data', 'fetch.dataa') + + const replyLine = + typo['workflow.ts'].split('\n').findIndex((line) => line.includes('fetch.dataa')) + 1 + const replyId = written.lock.blocks.reply?.id + + const dryRun = await apply(stored, typo, { dryRun: true }) + + expect( + dryRun.diagnostics + .filter((d) => d.blockId === replyId || d.line === replyLine) + .map((d) => ({ code: d.code, severity: d.severity, file: d.file, line: d.line })) + ).toEqual([ + { code: 'E_APPLY_UNRESOLVED_REF', severity: 'error', file: 'workflow.ts', line: replyLine }, + ]) + await expectRejected(apply(stored, typo), 'E_APPLY_UNRESOLVED_REF') + } + ) + check( 'a rename does not report W_JSON_REF_UNTYPED on a JSON field only its reference rewrite changed', async () => { diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 4ea69619fa0..e063df0302c 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -371,6 +371,56 @@ function withOutOfScopeRefsRefused( } } +/** Compile findings of a reference in the entry file to an output or block that does not exist. */ +const ENTRY_REF_CODES: ReadonlySet = new Set(['W_UNKNOWN_OUTPUT_PATH', 'W_UNRESOLVED_REF']) + +/** + * One finding per dangling reference in the entry file, in the vocabulary an offline check uses. + * Compile reports such a reference at its line (`W_UNKNOWN_OUTPUT_PATH`, `W_UNRESOLVED_REF`), and + * the lint reports the same one again on the whole block, refusing it (`E_APPLY_LINT`) on a block + * this apply adds or changes (`changed`, by block key). So the lint's block-output finding on a + * block compile already reported one for is dropped, and where the lint would have refused it, + * compile's finding is the refusal instead: `E_APPLY_UNRESOLVED_REF`, located at the reference. + */ +function withEntryRefsDeduplicated( + diagnostics: LocatedDiagnostic[], + lint: WorkflowLintReport, + changed: ReadonlySet, + keyOf: (id: string) => string | undefined +): { diagnostics: LocatedDiagnostic[]; lint: WorkflowLintReport } { + const reported = new Set( + diagnostics.flatMap((diagnostic) => + ENTRY_REF_CODES.has(diagnostic.code) && + diagnostic.blockKey !== undefined && + diagnostic.span.file === SOURCE_ENTRY_FILE + ? [diagnostic.blockKey] + : [] + ) + ) + if (reported.size === 0) return { diagnostics, lint } + const refused = new Set() + const unresolvedReferences = lint.unresolvedReferences.filter((reference) => { + const key = keyOf(reference.blockId) + if (reference.kind !== 'block-output' || key === undefined || !reported.has(key)) return true + if (changed.has(reference.blockId)) refused.add(key) + return false + }) + return { + lint: { ...lint, unresolvedReferences }, + diagnostics: diagnostics.map((diagnostic): LocatedDiagnostic => { + if ( + !ENTRY_REF_CODES.has(diagnostic.code) || + diagnostic.span.file !== SOURCE_ENTRY_FILE || + diagnostic.blockKey === undefined || + !refused.has(diagnostic.blockKey) + ) { + return diagnostic + } + return { ...diagnostic, code: 'E_APPLY_UNRESOLVED_REF', severity: 'error' } + }), + } +} + /** `{ span }` when there is one, to spread into a diagnostic. */ function withSpan(span: SourceSpan | undefined): { span?: SourceSpan } { return span ? { span } : {} @@ -985,27 +1035,30 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise m.id)]) const changedKeys = new Set([...changedIds].flatMap((id) => keyById.get(id) ?? [])) + const keyOfId = (id: string) => keyById.get(id) const scoped = withOutOfScopeRefsRefused( compileDiagnostics, lint, (key) => changedKeys.has(key), - (id) => keyById.get(id) + keyOfId + ) + const entryRefs = withEntryRefsDeduplicated( + scoped.diagnostics, + withoutCodeFileReferences( + withoutPendingReferences(scoped.lint, input.pendingResources ?? []), + compileDiagnostics, + keyOfId + ), + changedIds, + keyOfId ) const diagnostics = [ - ...scoped.diagnostics, + ...entryRefs.diagnostics, ...keptDiagnostics, ...materializeDiagnostics, ...refusals, ...normalized.diagnostics, - ...lintDiagnostics( - withoutCodeFileReferences( - withoutPendingReferences(scoped.lint, input.pendingResources ?? []), - compileDiagnostics, - (id) => keyById.get(id) - ), - changedIds, - (id) => keyById.get(id) - ), + ...lintDiagnostics(entryRefs.lint, changedIds, keyOfId), ].map(locate) if (hasErrors(diagnostics)) { return { diff --git a/packages/sim-cli/src/commands/protocol/stored-edges.ts b/packages/sim-cli/src/commands/protocol/stored-edges.ts index 04306d11abb..aedb5cd0ceb 100644 --- a/packages/sim-cli/src/commands/protocol/stored-edges.ts +++ b/packages/sim-cli/src/commands/protocol/stored-edges.ts @@ -1,15 +1,17 @@ import { isRecordLike, toRecord } from '@sim/utils/object' import { type BlockCatalog, + type CanonicalBlock, compileWorkflow, parseWorkflowLock, type StoredEdgeRef, setOwn, + stableStringify, } from '@sim/workflow-code' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import type { OperationClient } from '../../runtime/called-operations' -import { readSourceJson, SOURCE_STORED_EDGES_FILE } from './source-dir' +import { digest, readSourceJson, SOURCE_STORED_EDGES_FILE } from './source-dir' import { cachedCatalogByHash, loadWorkflowCatalog } from './source-tree' /** A printed source as a get, apply or create answers it. */ @@ -19,11 +21,16 @@ interface PrintedAnswer { base: unknown } +/** A digest of one compiled block, to tell a block an edit changed from one it left alone. */ +export function blockDigest(block: CanonicalBlock): string { + return digest(stableStringify(block)) +} + /** - * The `.sim/stored-edges.json` write for a printed source: its edges, compiled against `catalog` - * (the one it was printed with), tagged with its base fingerprint. `null` when the answer has no - * fingerprint or entry, or nothing to compile it with; the record left on disk then names an - * older fingerprint, which a check ignores. + * The `.sim/stored-edges.json` write for a printed source: its edges and a digest of each block + * ({@link blockDigest}, by key), compiled against `catalog` (the one it was printed with), tagged + * with its base fingerprint. `null` when the answer has no fingerprint or entry, or nothing to + * compile it with; the record left on disk then names an older fingerprint, which a check ignores. */ export function storedEdgesWrite( answer: PrintedAnswer, @@ -34,7 +41,7 @@ export function storedEdgesWrite( const entry = answer.files[SOURCE_ENTRY_FILE] const { lock } = parseWorkflowLock(answer.lock) if (!catalog || typeof fingerprint !== 'string' || entry === undefined || !lock) return null - const { edges } = compileWorkflow({ + const { edges, workflow } = compileWorkflow({ entry: { path: SOURCE_ENTRY_FILE, text: entry }, files: new Map(Object.entries(answer.files).filter(([path]) => path !== SOURCE_ENTRY_FILE)), catalog, @@ -44,7 +51,22 @@ export function storedEdgesWrite( }) return [ `${folder}${SOURCE_STORED_EDGES_FILE}`, - `${JSON.stringify({ version: 1, fingerprint, edges }, null, 2)}\n`, + `${JSON.stringify( + { + version: 1, + fingerprint, + edges, + ...(workflow + ? { + blocks: Object.fromEntries( + Object.entries(workflow.blocks).map(([key, block]) => [key, blockDigest(block)]) + ), + } + : {}), + }, + null, + 2 + )}\n`, ] } @@ -170,6 +192,35 @@ export async function readStoredEdges(dir: string): Promise | undefined> { + const [record, base] = await Promise.all([ + readSourceJson(dir, SOURCE_STORED_EDGES_FILE), + readSourceJson(dir, SOURCE_BASE_FILE), + ]) + const { version, fingerprint, blocks } = toRecord(record) + if ( + version !== 1 || + typeof fingerprint !== 'string' || + fingerprint !== toRecord(base).fingerprint || + !isRecordLike(blocks) + ) { + return undefined + } + const digests = new Map() + for (const [key, value] of Object.entries(blocks)) { + if (typeof value !== 'string') return undefined + digests.set(key, value) + } + return digests +} + /** The stored-edges records of the workflow folders whose base a write removes (`paths`). */ export function removedWorkflowRecords(paths: Iterable): string[] { return [...paths].flatMap((path) => 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 54d5183fe59..33b90fc3b4d 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 @@ -7,6 +7,7 @@ import type { SimApiError } from '../../http/client' import { cacheCatalogText } from '../../test/catalog-cache' import { contextMockFns, mockedProfile } from '../../test/context-mock' import { digest } from './source-dir' +import { storedEdgesWrite } from './stored-edges' import { attachWorkflowSourceCheck } from './workflow-source-check' vi.mock('../../context', async () => (await import('../../test/context-mock')).contextMock) @@ -463,8 +464,8 @@ describe('sim workflows source check', () => { join(dir, 'workflow.ts'), CLEAN.replace( "const done = response('Done', { body: { received: start.message } })", - "const call = api('Call', { url: 'https://x', method: 'POST', body: { n: start.missing.deep } })\n const done = response('Done', { body: { received: start.message } })" - ).replace('import { response,', 'import { api, response,') + "const calc = fn('Calc', { code: 'return 1' })\n const call = api('Call', { url: 'https://x', method: 'POST', body: { n: calc.result.deep } })\n const done = response('Done', { body: { received: start.message } })" + ).replace('import { response,', 'import { api, fn, response,') ) const untyped = () => ((result().diagnostics ?? []) as Array<{ code: string }>).filter( @@ -474,7 +475,7 @@ describe('sim workflows source check', () => { await check() expect(untyped()).toHaveLength(1) - writeLock(['start', 'done', 'call']) + writeLock(['start', 'done', 'calc', 'call']) await check() expect(untyped()).toEqual([]) @@ -673,6 +674,71 @@ export default workflow('W', {}, () => { } }) + describe('a reference to an output the block lacks', () => { + /** Start → Call (an HTTP request) → Done, whose JSON body reads `call.`. */ + const reads = (output: string) => + CLEAN.replace( + "const done = response('Done', { body: { received: start.message } })", + `const call = api('Call', { url: 'https://example.com', method: 'GET' })\n const done = response('Done', { body: { items: call.${output} } })` + ) + .replace(' start.to(done)', ' start.to(call)\n call.to(done)') + .replace('import { response,', 'import { api, response,') + + /** Writes `printed` as a get leaves it: the source, its lock and its stored-edges record. */ + function writePrinted(printed: string): void { + const lock = { + version: 1, + blocks: Object.fromEntries( + ['start', 'call', 'done'].map((key, order) => [ + key, + { id: `id-${key}`, parent: null, ident: key, order }, + ]) + ), + variables: {}, + } + writeFileSync(join(dir, 'workflow.ts'), printed) + writeFileSync(join(dir, '.sim/lock.json'), JSON.stringify(lock)) + const record = storedEdgesWrite( + { files: { 'workflow.ts': printed }, lock, base: { fingerprint: 'sf1:a' } }, + JSON.parse(readFileSync(FIXTURE_CATALOG, 'utf8')) + ) + if (!record) throw new Error('no stored-edges record') + writeFileSync(join(dir, record[0]), record[1]) + } + + const findings = () => + ((result().diagnostics ?? []) as Array<{ code: string; severity: string }>).map( + ({ code, severity }) => `${severity} ${code}` + ) + + it('fails as the server refuses it once an edit types it into a block the lock binds', async () => { + cacheCatalog() + writePrinted(reads('data')) + await check() + expect(result()).toMatchObject({ errors: 0 }) + + writeFileSync(join(dir, 'workflow.ts'), reads('dataa')) + await check() + + expect(findings()).toEqual(['error E_APPLY_UNRESOLVED_REF']) + expect(process.exitCode).toBe(1) + }) + + it('stays a warning on a block the stored workflow already holds that way, and with --no-strict', async () => { + cacheCatalog() + writePrinted(reads('dataa')) + await check() + expect(findings()).toEqual(['warning W_UNKNOWN_OUTPUT_PATH']) + expect(process.exitCode).toBeUndefined() + + writePrinted(reads('data')) + writeFileSync(join(dir, 'workflow.ts'), reads('dataa')) + await checkIn(dir, '--no-strict') + expect(findings()).toEqual(['warning W_UNKNOWN_OUTPUT_PATH']) + expect(process.exitCode).toBeUndefined() + }) + }) + it('fails on a bound block with --strict and on nothing with --no-strict', async () => { cacheCatalog() writeFileSync(join(dir, 'workflow.ts'), UNKNOWN_METHOD) 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 e3dedf1ed9d..92cad8b88b7 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -44,7 +44,7 @@ import { refreshWorkspaceTypes, } from './source-tree' import { type Diagnostic, findingsOutput, verboseFlag } from './source-ui' -import { readStoredEdges } from './stored-edges' +import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' import { readSourceFiles, requireEntry } from './workflow-source-apply' import { WORKFLOW_TREE } from './workflow-source-get' import { @@ -103,6 +103,20 @@ const MOVED_BLOCK_REFUSALS: ReadonlyMap = new Map( ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], ]) +/** + * Warnings in `workflow.ts` a check refuses under the server's error code on a block the edit + * added or changed, in the default and strict modes: a reference to an output or block that does + * not exist (`E_APPLY_UNRESOLVED_REF`, at the reference), or an iteration field read outside its + * container (`E_APPLY_REF_OUT_OF_SCOPE`), which the server refuses on such a block and keeps as a warning only on a block the stored workflow already holds. A block counts as + * changed when the lock does not bind it, 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). + */ +const EDITED_ENTRY_REFUSALS: ReadonlyMap = new Map([ + ['W_UNKNOWN_OUTPUT_PATH', 'E_APPLY_UNRESOLVED_REF'], + ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], + ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], +]) + /** * Which {@link STRICT_CODES} warnings fail a check: `new` those on a block the lock does not bind * (one added since the get, or every block of a workflow that has no lock yet), `all` every one, @@ -145,9 +159,12 @@ on none of them. In a function file changed since the get, ${[...EDITED_CODE_FIL .map(([warning, refusal]) => `${warning} is the error ${refusal}`) .join(', ')} in every mode, as the server refuses it; so is ${[...MOVED_BLOCK_REFUSALS] .map(([warning, refusal]) => `${warning} (${refusal})`) - .join( - ', ' - )} on a block the source moved into another container. ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not + .join(', ')} on a block the source moved into another container. In workflow.ts, ${[ + ...EDITED_ENTRY_REFUSALS.keys(), +].join(', ')} are the error ${[...new Set(EDITED_ENTRY_REFUSALS.values())].join( + ', ' +)} on a block the edit added or changed, as the server refuses them there (not with +--no-strict). ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not bind, and with --strict on every block.` /** Adds the `--strict` / `--no-strict` pair to a check command. */ @@ -397,9 +414,10 @@ async function compileWorkflowDir( declarations?: WorkspaceDeclarations ) { const { lock } = parseWorkflowLock(await readSourceJson(dir, SOURCE_LOCK_FILE)) - const [files, storedEdges, printedWith] = await Promise.all([ + const [files, storedEdges, storedBlocks, printedWith] = await Promise.all([ readSourceFiles(dir, lock ?? null), readStoredEdges(dir), + readStoredBlockDigests(dir), cachedSourceCatalog(dir), ]) const catalog = printedWith ?? workspaceCatalog @@ -414,7 +432,7 @@ async function compileWorkflowDir( ...(storedEdges ? { storedUnreadEdges: storedEdges } : {}), ...(envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}), }) - return { lock, files, compiled } + return { lock, files, compiled, storedBlocks } } /** @@ -461,7 +479,11 @@ export async function checkWorkflowDir( catalog: BlockCatalog, options: { declarations?: WorkspaceDeclarations; strict: StrictMode; prefix?: string } ): Promise<{ findings: CheckFinding[]; entry: string }> { - const { lock, files, compiled } = await compileWorkflowDir(dir, catalog, options.declarations) + const { lock, files, compiled, storedBlocks } = await compileWorkflowDir( + dir, + catalog, + options.declarations + ) const entryText = files[SOURCE_ENTRY_FILE] const locate = (block: string, param: string, names: string | undefined) => { const prefix = encodeAnchor({ kind: 'param', block, param: '' }) @@ -521,10 +543,26 @@ export async function checkWorkflowDir( : getOwn(compiled.workflow.blocks, blockKey) return held !== undefined && block !== undefined && held.parent !== block.parent } - const editedRefusal = (code: string, file: string | undefined, blockKey: string | undefined) => - (file !== undefined && file !== SOURCE_ENTRY_FILE && edited(file, blockKey) - ? EDITED_CODE_FILE_REFUSALS.get(code) - : undefined) ?? (moved(blockKey) ? MOVED_BLOCK_REFUSALS.get(code) : undefined) + /** Whether the edit added or changed the block: see {@link EDITED_ENTRY_REFUSALS}. */ + const changed = (blockKey: string | undefined) => { + if (!bound(blockKey)) return true + const block = blockKey === undefined ? undefined : compiled.workflow?.blocks[blockKey] + const printed = blockKey === undefined ? undefined : storedBlocks?.get(blockKey) + return block !== undefined && printed !== undefined && blockDigest(block) !== printed + } + const editedRefusal = (code: string, file: string | undefined, blockKey: string | undefined) => { + const refusal = + file === undefined + ? undefined + : file !== SOURCE_ENTRY_FILE + ? edited(file, blockKey) + ? EDITED_CODE_FILE_REFUSALS.get(code) + : undefined + : options.strict !== 'off' && changed(blockKey) + ? EDITED_ENTRY_REFUSALS.get(code) + : undefined + return refusal ?? (moved(blockKey) ? MOVED_BLOCK_REFUSALS.get(code) : undefined) + } const fails = (code: string, blockKey: string | undefined) => STRICT_CODES.has(code) && !(STORED_EXEMPT_CODES.has(code) && bound(blockKey)) && 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 69298277a40..e5d6f3def7e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -129,7 +129,7 @@ The \`// @sim-sdk 1\` header must be the first line, and the file has exactly on ## Diagnostics and exit codes -Findings print as \`file:line:column severity CODE: message\`, then the code frame and a hint. \`E_*\` refuses the whole apply; \`W_*\` is saved as written and names a real problem. \`check\` prints the \`W_*\` codes it fails on as \`error\` on a block you added; the apply still saves them as warnings. Exit codes of every \`workflows source\` command: +Findings print as \`file:line:column severity CODE: message\`, then the code frame and a hint. \`E_*\` refuses the whole apply; \`W_*\` is saved as written and names a real problem. \`check\` prints the \`W_*\` codes it fails on as \`error\` on a block you added; the apply still saves them as warnings. A reference to an output or block that does not exist, in a block you added or changed, is the error \`E_APPLY_UNRESOLVED_REF\` in both. Exit codes of every \`workflows source\` command: ${sourceExitCodesTable('sim workflows source')} diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 49674ad4882..4f76c5cd78b 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -547,6 +547,20 @@ describe('typed references in JSON fields', () => { expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) }) + it('reports a reference to an output the block lacks once, not also as untyped', () => { + const result = run( + [ + START, + "const a = api('A', { url: 'https://x' })", + "const b = api('B', { url: 'https://x', body: { items: a.dataa } })", + 'start.to(a)', + 'a.to(b)', + ].join('\n') + ) + expect(findings(result, 'W_UNKNOWN_OUTPUT_PATH')).toHaveLength(1) + expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) + }) + it('tells an untyped reference to stay bare unless it holds text', () => { const result = run( `${START}\nconst a = api('A', { url: 'https://x', body: { items: start.input.list } })` diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index a005fa6ebc2..2f58b44c7b4 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -36,7 +36,7 @@ import { EdgeCollector } from './edges' import { referencedResultKind } from './function-returns' import { didYouMean, HINTS, hintForNode, nodeLabel } from './hints' import { type CompileLimits, DEFAULT_LIMITS, parseWorkflowSource, sdkHeader } from './parse' -import { ErrorLimitReached, Reporter } from './report' +import { ErrorLimitReached, type Range, Reporter } from './report' import { checkSuspiciousName, collectBody, collisionSuffix } from './scope' import { checkCodeFileRefs, @@ -688,6 +688,8 @@ function compileEntry( variable: (key) => ctx.variables.get(key), } const isString = (token: string) => refValueKind(token, refTypes) === 'string' + /** Bare references nothing types, reported once the unknown paths are known (see below). */ + const untyped: Array<{ token: string; range: Range; blockKey: BlockKey }> = [] for (const { params, id, tree, refs } of ctx.jsonFields) { const value = jsonFieldText(tree, isString) setOwn(params, id, { kind: 'value', value }) @@ -703,15 +705,7 @@ function compileEntry( ) { continue } - reporter.report( - 'W_JSON_REF_UNTYPED', - `Nothing declares the type of ${ref.token}; it is stored bare, so a string value would break the JSON.`, - ref.range, - { - hint: `Leave it bare when it holds an array, object, number or boolean (it is spliced in as JSON); only when it holds text write t\`\${${text.slice(ref.range.start, ref.range.end)}}\`.`, - blockKey: ref.blockKey, - } - ) + untyped.push({ token: ref.token, range: ref.range, blockKey: ref.blockKey }) } } @@ -745,6 +739,25 @@ function compileEntry( if (edge.port.kind === 'error') erroring.add(edge.from) } checkErrorOutputRefs(ctx, erroring) + // A reference to an output that does not exist is that one finding: whether text there would + // break the JSON is moot until the path is fixed. + const unknownAt = new Set( + reporter.diagnostics + .filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH' || d.code === 'W_UNRESOLVED_REF') + .map((d) => `${d.span.file}:${d.span.start}`) + ) + for (const ref of untyped) { + if (unknownAt.has(`${ref.range.file}:${ref.range.start}`)) continue + reporter.report( + 'W_JSON_REF_UNTYPED', + `Nothing declares the type of ${ref.token}; it is stored bare, so a string value would break the JSON.`, + ref.range, + { + hint: `Leave it bare when it holds an array, object, number or boolean (it is spliced in as JSON); only when it holds text write t\`\${${text.slice(ref.range.start, ref.range.end)}}\`.`, + blockKey: ref.blockKey, + } + ) + } ctx.comments.assign( (ast.comments ?? []).filter((comment) => (comment.start ?? 0) >= parsed.headerEnd) From 050cdc0ccf2045a962105e2c7e2c4c02aee92058 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:45:47 -0800 Subject: [PATCH 019/104] fix(sim-cli): apply and create refresh a workflow directory's workspace types workspace.d.ts in a workflow source directory was written only by get, so tsc refused a child workflow (or table, credential) created since, and the edit loop's type-check step failed until an undocumented get. Every workflow source command that already talks to the server now re-reads the resources into workspace.d.ts and the manifest beside it (apply, its dry run and plan, create; status follows when it becomes a read), rewriting only what changed and never failing the command over a listing it could not get. --- .../src/commands/protocol/source-tree.ts | 30 +++++++++++++++++++ .../protocol/workflow-source-apply.ts | 7 +++-- .../workflow-source-roundtrip.test.ts | 14 +++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index f5ba410c59f..f7874c01973 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -392,6 +392,36 @@ export async function refreshWorkspaceTypes(dir: string, local: LocalDeclaration } } +/** + * Re-reads the workspace's resources into a workflow directory's `workspace.d.ts` and the manifest + * kept beside it, so `tsc` types a resource created since the last get (a child workflow, a table, + * a credential) instead of refusing its key, and stops accepting one deleted since. The commands + * that already talk to the server (apply, its dry run and plan, create, status) call it; an offline + * check cannot. Only a directory holding types the CLI wrote is touched (a workflow folder of a + * workspace directory types its workflows at the root, which the workspace commands refresh), only + * a file whose text changes is rewritten, and a failure to list the resources (a rate limit, a + * dropped connection) leaves the files as they are: the types are a convenience, never the write. + */ +export async function refreshWorkflowWorkspaceTypes( + client: OperationClient<'getSourceResources'>, + dir: string, + workspaceId: string +): Promise { + const [types, manifest] = await Promise.all([ + readSourceText(dir, WORKSPACE_TYPES_FILE), + readSourceText(dir, WORKSPACE_MANIFEST_FILE), + ]) + if (types === null || manifest === null) return + const fresh = await loadWorkspaceTypes(client, workspaceId).catch(() => null) + if (!fresh?.stored) return + const stored = `${JSON.stringify(fresh.stored, null, 2)}\n` + const write = [ + ...(fresh.text !== types ? [[WORKSPACE_TYPES_FILE, fresh.text] as const] : []), + ...(stored !== manifest ? [[WORKSPACE_MANIFEST_FILE, stored] as const] : []), + ] + if (write.length > 0) await updateSourceDir(dir, { write }) +} + /** * Refuses a catalog for another SDK major than the bundled `core.d.ts`: its builders would be * written beside declarations that cannot type them. 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 fde5ca45a64..60527c85781 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -38,7 +38,7 @@ import { writeBack, } from './source-dir' import { SOURCE_WRITE_EXIT_CODES_HELP } from './source-exit-codes' -import { cachedCatalogByHash, printTreeResult } from './source-tree' +import { cachedCatalogByHash, printTreeResult, refreshWorkflowWorkspaceTypes } from './source-tree' import { type CreatedResource, confirm, @@ -461,6 +461,7 @@ export function attachWorkflowSourceApply(source: Command): void { const [command, connectApply] = apiCommand(source, 'apply', [ 'applyWorkflowSource', 'deployWorkflow', + 'getSourceResources', ]) absoluteDirOption(command) verboseFlag(command) @@ -494,7 +495,8 @@ export function attachWorkflowSourceApply(source: Command): void { const base = await readBase(options.dir, named) const workflowId = base.workflowId const files = await readSourceFiles(options.dir, lock) - await runSourceWrite({ + await refreshWorkflowWorkspaceTypes(client, options.dir, base.workspaceId) + await runSourceWrite<'applyWorkflowSource'>({ options, creating: false, question: `Apply these changes to workflow ${workflowId}?`, @@ -579,6 +581,7 @@ export function attachWorkflowSourceCreate(source: Command): void { profile.sources.workspaceId === 'flag' ? null : await readStarterWorkspace(options.dir) const workspaceId = client.requireWorkspace(starterWorkspace ?? undefined) const files = await readSourceFiles(options.dir, null) + await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) await runSourceWrite<'createWorkflowFromSource'>({ options, creating: true, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index f97ee7923cb..76741bf6081 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -487,6 +487,20 @@ describe('the workspace-scoped source reads', () => { }) describe('catalog and declarations', () => { + it('types a workflow created since the get once an apply or its dry run talks to the server', async () => { + await get() + expect(read('.sim/sdk/workspace.d.ts')).not.toContain("'handbook-answer'") + const child = { key: 'handbook-answer', id: 'wf-child', name: 'Handbook Answer', inputs: [] } + server.manifest = () => json({ data: { ...MANIFEST, workflows: [child] } }) + + await sim('workflows', 'source', 'apply', WORKFLOW_ID, '--dir', dir, '--dry-run') + + expect(read('.sim/sdk/workspace.d.ts')).toContain("'handbook-answer'") + expect(JSON.parse(read('.sim/sdk/workspace.manifest.json')).workflows).toHaveProperty( + 'handbook-answer' + ) + }) + it('refuses a catalog for another SDK major, telling the person to upgrade, writing nothing', async () => { server.catalog = () => json({ data: { ...CATALOG, sdkMajor: 2 } }) From 4bed33b5ade88cda8727f07245cb72a0d3fea4c1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:48:16 -0800 Subject: [PATCH 020/104] fix(sim-cli): source get prints the server's findings and names unnamed code files workflows source get dropped the diagnostics the server returns with the printed source, so a function whose literal secret became code: stored() changed with no explanation, and the old function file holding the secret stayed on disk unmentioned. Both gets now print and return the server's findings, and every write back (get, apply, create) warns with the path of a code file the entry or the previous lock named that the printed source no longer does, leaving it on disk rather than deleting a file the person may have written. --- .../src/commands/protocol/source-dir.ts | 34 +++++++++++++++++++ .../protocol/workflow-source-get.test.ts | 14 ++++++++ .../commands/protocol/workflow-source-get.ts | 4 +++ .../workflow-source-roundtrip.test.ts | 25 ++++++++++++++ .../commands/protocol/workspace-source-get.ts | 4 +++ 5 files changed, 81 insertions(+) diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index 983687c3d65..e516a53f442 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -29,6 +29,8 @@ import { hostname, tmpdir } from 'node:os' import { basename, dirname, join, posix, resolve } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' import { isRecordLike, toRecord } from '@sim/utils/object' +import { compareStrings } from '@sim/utils/string' +import { codeFileReferences } from '@sim/workflow-code/code-files/references' import { isCodeFilePath, SOURCE_BASE_FILE, @@ -840,6 +842,7 @@ export async function writeBack( ...extra.write, ] const orphaned = orphanedCodeFiles(previousLock, answer.lock, Object.keys(answer.files)) + const unnamed = await unnamedCodeFiles(dir, previousLock, answer, orphaned) await updateSourceDir(dir, { write, remove: [ @@ -850,9 +853,40 @@ export async function writeBack( ], }) if (folder) await recordFolderWrite(folder, Object.fromEntries(printed), orphaned, answer.base) + if (unnamed.length > 0) { + printError( + `warning: ${unnamed.join(', ')} ${unnamed.length === 1 ? 'is' : 'are'} no longer named by ${SOURCE_ENTRY_FILE} (the printed source names no code file there, such as code now printed as stored()), so ${unnamed.length === 1 ? 'it was' : 'they were'} left on disk as written: delete ${unnamed.length === 1 ? 'it' : 'them'}, or name ${unnamed.length === 1 ? 'it' : 'them'} again with codeFile(). Never commit one that holds a credential.` + ) + } return write.length } +/** + * The code files a write leaves on disk although the printed source no longer names them: named + * by the entry file on disk before the write or by the previous lock, neither written nor pruned + * now, and still present. A file the person added is never deleted, so the caller says where it + * is instead: one that held a literal secret now printed as `stored()` must not be committed. + */ +async function unnamedCodeFiles( + dir: string, + previousLock: unknown, + answer: PrintedSourceAnswer, + pruned: readonly string[] +): Promise { + const entry = await readSourceText(dir, SOURCE_ENTRY_FILE) + const named = lockCodeFiles(previousLock) + for (const literal of entry === null ? [] : codeFileReferences(entry)) { + const path = sourceRelativePath(literal) + if (path !== null) named.add(path) + } + const kept = new Set([...Object.keys(answer.files), ...lockCodeFiles(answer.lock), ...pruned]) + const candidates = [...named].filter((path) => isCodeFilePath(path) && !kept.has(path)) + const present = await Promise.all( + candidates.map(async (path) => (await readSourceText(dir, path)) !== null) + ) + return candidates.filter((_, index) => present[index]).sort(compareStrings) +} + /** * Held while a command reads and rewrites a source directory, so two commands on one directory * (an agent and a person, two terminals) never interleave their writes: each file moves into diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 5b1a33c5f1f..93e6c694b73 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -370,6 +370,20 @@ describe('sim workflows source get --dir', () => { expect(request).not.toHaveBeenCalled() }) + it("reports the server's findings on the printed source, such as a secret printed as stored()", async () => { + const finding = { + code: 'W_LITERAL_SECRET', + severity: 'warning', + message: 'code holds what looks like a literal credential; get prints it as stored()', + } + serve({ [SOURCE_PATH]: () => ({ data: { ...source().data, diagnostics: [finding] } }) }) + + await get('--dir', outDir) + + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed.diagnostics).toEqual([expect.objectContaining(finding)]) + }) + it('prints the response unchanged without --dir', async () => { request.mockResolvedValue(source()) 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 e5d6f3def7e..eafc0bd1d5c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -43,6 +43,7 @@ import { type WorkspaceTypes, withSourceExitCode, } from './source-tree' +import { findingsOutput } from './source-ui' import { storedEdgesWrite } from './stored-edges' const DIR_FLAG = 'dir' @@ -370,11 +371,14 @@ export function attachWorkflowSourceGet(source: Command): void { workflowSource, workflowSource.blockTypes ) + const findings = findingsOutput(profile.output) + findings.print(workflowSource.diagnostics) printTreeResult(profile.output, { workflowId: workflowSource.workflowId, dir, ...tree, fingerprint: workflowSource.base.fingerprint, + ...findings.result(workflowSource.diagnostics), }) }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 76741bf6081..2f443403952 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -588,6 +588,31 @@ describe('pruning function files', () => { expect(read('functions/mine.js')).toBe('mine') }) + it('keeps, and names, a code file the edit added that the printed source no longer names', async () => { + await get() + writeFileSync(join(dir, 'functions/leak.js'), 'const token = "ghp_secret"\nreturn token\n') + writeFileSync( + join(dir, 'workflow.ts'), + WORKFLOW_TS.replace( + '})\n})', + "})\n const leak = fn('Leak', { code: codeFile('./functions/leak.js') })\n})" + ) + ) + const stored = WORKFLOW_TS.replace( + '})\n})', + "})\n const leak = fn('Leak', { code: stored() })\n})" + ) + server.apply = () => json(appliedResponse({ ...FILES, 'workflow.ts': stored })) + + await apply() + + expect(read('functions/leak.js')).toContain('ghp_secret') + expect(stderr.join('\n')).toContain( + 'warning: functions/leak.js is no longer named by workflow.ts' + ) + expect(stderr.join('\n')).not.toContain('functions/score.js is no longer named') + }) + it('prunes, on a fresh get, a function file the previous get wrote', async () => { server.source = () => json(sourceResponse(twoFiles, twoLock)) await get() 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 011ab6524c3..8fbbdd4f0b1 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -49,6 +49,7 @@ import { sourceTreeChange, withSourceExitCode, } from './source-tree' +import { findingsOutput } from './source-ui' import { removedWorkflowRecords, unrecordedFoldersWarning, @@ -409,6 +410,8 @@ 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) + findings.print(data.diagnostics) printTreeResult(profile.output, { workspaceId: data.workspaceId, dir: options.dir, @@ -419,6 +422,7 @@ export function attachWorkspaceSourceGet(source: Command): void { skipped: data.skipped.length, guide: result.guide, primer: result.primer, + ...findings.result(data.diagnostics), }) }) }) From 6e3049e4b1f36595c50bc7318f5b0249ef1c9783 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:49:53 -0800 Subject: [PATCH 021/104] fix(workflow-code): an unknown resource hint names the command that creates it "This workspace has no credential a source can name yet." was a dead end: an agent had to search for sim credentials connect. E_MAT_UNKNOWN_RESOURCE now ends with the sim command that creates a resource of that kind (credentials connect or create, tables, knowledge, skills, custom-tools, mcp-servers create, or workflows source create) and where the keys are listed; a did-you-mean hint keeps pointing at the near key instead. --- .../src/materialize/index.test.ts | 20 +++++++++++- .../workflow-code/src/materialize/values.ts | 32 +++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/packages/workflow-code/src/materialize/index.test.ts b/packages/workflow-code/src/materialize/index.test.ts index bfdce0dbee2..c61457429ff 100644 --- a/packages/workflow-code/src/materialize/index.test.ts +++ b/packages/workflow-code/src/materialize/index.test.ts @@ -244,7 +244,25 @@ describe('materialize: params keep prev bytes unless they changed', () => { prev: state, resources: { ...RESOURCES, keysOf: () => [] }, }).diagnostics - expect(none?.hint).toBe('This workspace has no knowledge-base a source can name yet.') + expect(none?.hint).toBe( + 'This workspace has no knowledge-base a source can name yet. Create it with `sim knowledge create`; a source names it by its key, which `sim workflows source resources` lists.' + ) + }) + + it('names the command that creates a credential the workspace lacks, the dead end an agent hit', () => { + const state = workflowState([blockState('s1', 'slack', 'Notify', {})]) + const target = edit(canonical(state).workflow, (draft) => { + draft.blocks.notify.params.credential = { + kind: 'value', + value: { $sim: 'resource', kind: 'credential', key: 'team-slack' }, + } + }) + const keysOf = (kind: string) => (kind === 'credential' ? ['ops-gmail'] : []) + const [finding] = run(target, null, { + prev: state, + resources: { ...RESOURCES, keysOf }, + }).diagnostics.filter((d) => d.code === 'E_MAT_UNKNOWN_RESOURCE') + expect(finding?.hint).toContain('sim credentials connect --name ""') }) it('recomputes stored outputs when an edit changes what they derive from', () => { diff --git a/packages/workflow-code/src/materialize/values.ts b/packages/workflow-code/src/materialize/values.ts index 0a08e62cb25..6376ef50e7a 100644 --- a/packages/workflow-code/src/materialize/values.ts +++ b/packages/workflow-code/src/materialize/values.ts @@ -48,9 +48,34 @@ export function unliftValue( /** How many keys an unknown-key hint lists. */ const LISTED_KEYS = 20 +/** + * The `sim` command that creates a resource of each kind a source names by key, so an unknown-key + * hint says how to make the one the source wants, not only that it is missing. A source names a + * resource by the key its name slugs to; `sim workflows source resources` lists them. + */ +const CREATE_COMMANDS: Partial> = { + credential: + '`sim credentials connect --name ""` (OAuth; hand the link to the person who owns the account) or `sim credentials create `', + table: '`sim tables create`', + 'knowledge-base': '`sim knowledge create`', + skill: '`sim skills create`', + 'custom-tool': '`sim custom-tools create`', + 'mcp-server': '`sim mcp-servers create`', + workflow: '`sim workflows source create --dir `', +} + +/** How to create a missing resource of `kind`, as a sentence, or empty when no command does. */ +function createHint(kind: ResourceKind): string { + const command = CREATE_COMMANDS[kind] + return command + ? ` Create it with ${command}; a source names it by its key, which \`sim workflows source resources\` lists.` + : '' +} + /** * The hint of an unknown resource key: the closest available key, then the keys of that kind the - * workspace holds (or that it holds none). `undefined` when the caller loaded no keys. + * workspace holds (or that it holds none), then the command that creates one. `undefined` when the + * caller loaded no keys. */ function availableKeysHint( kind: ResourceKind, @@ -58,9 +83,10 @@ function availableKeysHint( written: string ): string | undefined { if (keys === undefined) return undefined - if (keys.length === 0) return `This workspace has no ${kind} a source can name yet.` + if (keys.length === 0) + return `This workspace has no ${kind} a source can name yet.${createHint(kind)}` const near = closest(written, keys) - return `${near !== null ? `Did you mean ${near}? ` : ''}Keys: ${listed(keys)}.` + return `${near !== null ? `Did you mean ${near}? ` : ''}Keys: ${listed(keys)}.${near !== null ? '' : createHint(kind)}` } /** The first {@link LISTED_KEYS} keys, then how many more there are. */ From 19498e2e03c89a178486b0855a01709f74b72853 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:50:41 -0800 Subject: [PATCH 022/104] fix(sim-cli): a table never clips the next command a result names With --output table the record renderer clamped every field to 160 columns, so the next: line, the one instruction a write stopped at its plan (exit 14) leaves, was cut at the very flag the person needed. Result fields holding a command are now printed whole in every display format. --- .../sim-cli/src/commands/protocol/result.ts | 10 ++++++++-- .../protocol/workflow-source-apply.test.ts | 19 +++++++++++++++++++ packages/sim-cli/src/output/render.ts | 13 ++++++++++--- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/result.ts b/packages/sim-cli/src/commands/protocol/result.ts index d7d39852fc8..e1bdc81240d 100644 --- a/packages/sim-cli/src/commands/protocol/result.ts +++ b/packages/sim-cli/src/commands/protocol/result.ts @@ -8,11 +8,17 @@ function fieldText(value: unknown): string { return text(nested ? JSON.stringify(value) : value) } +/** + * Result fields holding a command to run next: printed whole in every display format, since the + * one instruction a stopped write (exit 14) leaves is useless with its last flag clipped. + */ +const COMMAND_FIELDS: ReadonlySet = new Set(['next']) + /** * Prints a protocol command's result: the record itself in a machine format, else one line per * field, with `display` replacing the text of the fields it names (a list a person reads as a * sentence rather than as JSON). An override is built from server text (resource keys, ids), so it - * is sanitized like every other field. + * is sanitized like every other field. A {@link COMMAND_FIELDS} field is never clamped. */ export function printProtocolResult( format: OutputFormat, @@ -23,5 +29,5 @@ export function printProtocolResult( key, display[key] === undefined ? fieldText(value) : sanitize(display[key]), ]) - printRecord(format, fields, result) + printRecord(format, fields, result, COMMAND_FIELDS) } 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 df3bd0dc159..46e225ee08a 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 @@ -180,6 +180,25 @@ describe('sim workflows source apply', () => { expect(stderrLines().join('\n')).toContain('Blocks: 1 added') }) + it('prints the whole next command in a table, never clipping the flag it names', async () => { + setTerminal(false) + contextMockState.output = 'table' + const deep = join(dir, 'a-directory-name-long-enough-that-the-next-command-runs-past-any-clamp') + mkdirSync(join(deep, '.sim'), { recursive: true }) + writeFileSync(join(deep, 'workflow.ts'), ENTRY) + writeFileSync(join(deep, '.sim/lock.json'), JSON.stringify(LOCK)) + writeFileSync(join(deep, '.sim/base.json'), JSON.stringify(BASE)) + request.mockResolvedValue(outcome({ dryRun: true })) + + await apply(WORKFLOW_ID, '--dir', deep, '--allow-delete') + + const lines = vi.mocked(console.log).mock.calls.map((call) => call.join(' ')) + expect(lines.find((line) => line.includes('next:'))).toContain( + `sim workflows source apply --dir ${deep} --allow-delete --yes` + ) + expect(process.exitCode).toBe(14) + }) + it('without --yes, exits with the refusal and names no next step when the plan has errors', async () => { setTerminal(false) request.mockResolvedValue( diff --git a/packages/sim-cli/src/output/render.ts b/packages/sim-cli/src/output/render.ts index 0e630e72ff3..76216f8852f 100644 --- a/packages/sim-cli/src/output/render.ts +++ b/packages/sim-cli/src/output/render.ts @@ -300,9 +300,15 @@ export function printDocument(format: OutputFormat, raw: unknown): void { /** * Prints a single record: machine formats from the raw value, otherwise aligned - * lines. As in `printList`, only the `table` rendering is clamped. + * lines. As in `printList`, only the `table` rendering is clamped, and never a field `whole` names + * (a command to run next, which a clipped flag would make wrong). */ -export function printRecord(format: OutputFormat, fields: Array<[string, string]>, raw: unknown) { +export function printRecord( + format: OutputFormat, + fields: Array<[string, string]>, + raw: unknown, + whole: ReadonlySet = new Set() +) { const machine = renderMachine(format, raw) if (machine !== null) { printLine(machine) @@ -320,8 +326,9 @@ export function printRecord(format: OutputFormat, fields: Array<[string, string] const width = Math.max(...safeFields.map(([label]) => visibleWidth(label))) for (const [label, value] of safeFields) { + const line = oneLine(value) printLine( - `${styles().dim(pad(`${label}:`, width + 1))} ${clamp(oneLine(value), MAX_RECORD_WIDTH)}` + `${styles().dim(pad(`${label}:`, width + 1))} ${whole.has(label) ? line : clamp(line, MAX_RECORD_WIDTH)}` ) } } From c5332fb83558bd48f933fa546a9425a3416dcb8e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:56:38 -0800 Subject: [PATCH 023/104] fix(sim-cli): apply defaults --dir to the current directory like the other readers check, status, diff and params defaulted --dir to . while workflow and workspace apply required it, so apply failed when run from inside the directory the primer says to run commands from. One rule now: a command that reads an existing source directory (check, status, diff, params, apply) defaults --dir to the current directory; get and create, which write one, still require it. --- apps/docs/content/docs/workflows/code.mdx | 2 +- .../protocol/workflow-source-apply.test.ts | 15 +++++++++++++++ .../commands/protocol/workflow-source-apply.ts | 2 +- .../commands/protocol/workspace-source-apply.ts | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx index 4aceb276fba..e686757a492 100644 --- a/apps/docs/content/docs/workflows/code.mdx +++ b/apps/docs/content/docs/workflows/code.mdx @@ -66,7 +66,7 @@ Nothing in the file runs on your machine. Sim reads it statically, checks it aga sim workflows source apply --dir ./support-triage --dry-run ``` - `apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. + `apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. Every command that reads a source directory (`check`, `status`, `diff`, `params`, `apply`, and their `sim workspaces source` counterparts) defaults `--dir` to the current directory; `get` and `create`, which write one, always need `--dir`. Sim compiles the file and runs every check a save would run: unknown settings, missing required fields, broken references, permissions, and locked blocks. Each problem prints with its line, the code around it, and a hint: 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 46e225ee08a..73a6ca5ea37 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 @@ -199,6 +199,21 @@ describe('sim workflows source apply', () => { expect(process.exitCode).toBe(14) }) + it('applies the current directory when --dir is left out, as check and status do', async () => { + setTerminal(false) + request.mockResolvedValue(outcome({ dryRun: true })) + const cwd = process.cwd() + process.chdir(dir) + try { + await apply('--dry-run') + } finally { + process.chdir(cwd) + } + + expect(request.mock.calls[0][0]).toBe(APPLY_PATH) + expect(request.mock.calls[0][1].body.files['workflow.ts']).toBe(ENTRY) + }) + it('without --yes, exits with the refusal and names no next step when the plan has errors', async () => { setTerminal(false) request.mockResolvedValue( 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 60527c85781..690aed89f2e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -470,7 +470,7 @@ export function attachWorkflowSourceApply(source: Command): void { '[workflowId]', 'Workflow whose draft the source replaces (default: the workflowId in .sim/base.json)' ) - .requiredOption('--dir ', DIR_DESCRIPTION) + .option('--dir ', DIR_DESCRIPTION, '.') .option('--dry-run', 'Check the source and show the outcome without saving or writing files') .option('-y, --yes', 'Apply without asking for confirmation') .option( 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 77619db4da0..bc4d88c04f2 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -468,7 +468,7 @@ export function attachWorkspaceSourceApply(source: Command): void { absoluteDirOption(command) verboseFlag(command) command - .requiredOption('--dir ', 'Workspace source directory written by `workspaces source get`') + .option('--dir ', 'Workspace source directory written by `workspaces source get`', '.') .option('--dry-run', 'Plan and check without writing anything') .option('-y, --yes', 'Apply without asking for confirmation') .option('--allow-delete', 'Delete resources, columns and data the directory no longer declares') From c21667394153c14cafca944e51f0e2530804b1cc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:57:16 -0800 Subject: [PATCH 024/104] fix(sim-cli): the primer covers run, debug, credentials and promote; search finds them The source primer stopped at apply, so running a workflow, reading why a run failed, adding a credential and promoting a workspace each cost an agent turns of discovery, and cli search missed source for natural phrasings. The primer (still within its byte budget) now names sim workflows run, logs get --trace, credentials connect with the key a name slugs to, and apply --to in the workspace primer; a test keeps every command and flag it names real. cli search indexes the tasks a command answers (searchTasks), so "build a workflow", "change the model in every agent block" and "promote dev to prod" rank the source commands first. --- .../src/commands/protocol/source-primer.ts | 17 ++++---- .../protocol/workflow-source-apply.ts | 7 ++++ .../protocol/workflow-source-get.test.ts | 41 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 6 +++ .../commands/protocol/workspace-source-get.ts | 6 +++ packages/sim-cli/src/commands/search.test.ts | 9 ++++ packages/sim-cli/src/commands/search.ts | 22 +++++++++- 7 files changed, 99 insertions(+), 9 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 4ead2b26d27..cbc004865dd 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -36,10 +36,12 @@ 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: the block keeps its id. Renaming the const too keeps the id when its settings, neighbours or references still tie it to the old block; otherwise the apply refuses it as a delete (\`E_APPLY_BLOCK_DELETE\`), and the dry run names it. Safest: keep the const in the same apply. -- **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 with 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\`. \`.py\`/\`.sh\` files are saved as written: write \`\` and \`{{NAME}}\` there, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`); after it, \`lp.results\`. A rename keeps its references working: the apply rewrites every \`$ref.\` in the function files to the new key (and the files it writes back hold it), so leave them or write the new key yourself. A \`$ref\` that names no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\` in \`check\` and the dry run). -- **Look up a builder**: \`${PARAMS_COMMAND} \` (\`table.upsertRow\`, \`agent\`, \`trigger.schedule\`; a namespace such as \`gmail\` lists its builders), offline. -- **Exit codes**: 0 ok, 1 errors (fix what it printed), ${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}\`.` + 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: the block keeps its id. 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, \`lp.results\`. A rename rewrites every \`$ref.\` in the function files to the new key. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). +- **Look up a builder**: \`${PARAMS_COMMAND} \` (\`agent\`, \`trigger.schedule\`; a namespace like \`gmail\` lists its builders), offline. +- **Credentials**: \`sim credentials connect --name ""\`, give its link to the account owner, then name it \`credential('')\`. +- **Run and debug**: \`sim workflows run --input '{…}'\`; a failed run: \`sim logs get --trace --no-include-workflow-state\` (spans show 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}\`.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer @@ -55,12 +57,13 @@ ${sharedRules('sim workflows source')} const WORKSPACE_PRIMER = `# Sim workspace source: primer -This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); the server reads them statically and nothing runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. +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. -**Edit loop**: edit the files → \`sim workspaces source check --dir .\` (offline; regenerates \`.sim/sdk/workspace.d.ts\`, adds new blocks to \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workspaces source apply --dir . --dry-run\` (the plan) → \`--yes\`. Rerun each step until it exits 0. Apply rewrites the directory from what it stored: read a file again before the next edit. +**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\`; without it the apply is refused. A kind is managed only when its folder exists. Deletes cannot be undone. +- **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')} ` 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 690aed89f2e..1145555b2ce 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -20,6 +20,7 @@ import type { } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' +import { searchTasks } from '../search' import { printProtocolResult } from './result' import { absoluteDirOption, @@ -535,6 +536,12 @@ export function attachWorkflowSourceCreate(source: Command): void { ]) absoluteDirOption(command) verboseFlag(command) + searchTasks(command, [ + 'build a new workflow', + 'create a new workflow as code', + 'author or write a workflow in TypeScript', + 'build a workflow that answers questions with an agent over a knowledge base, table or integration', + ]) command .requiredOption( '--dir ', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 93e6c694b73..81de8c7bdeb 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -6,6 +6,7 @@ import { COOKBOOK_EXAMPLES } from '@sim/workflow-sdk/codegen' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' +import { buildProgram } from '../../program' import { buildGeneratedCommands } from '../../runtime/build' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' import { digest } from './source-dir' @@ -88,6 +89,13 @@ function tsconfigInclude(project: string): string[] { return JSON.parse(json.join('\n')).include } +/** `command`'s parents, nearest first. */ +function ancestorsOf(command: Command): Command[] { + const ancestors: Command[] = [] + for (let at = command.parent; at; at = at.parent) ancestors.push(at) + return ancestors +} + async function get(...argv: string[]): Promise { await program().parseAsync(['node', 'sim', 'workflows', 'source', 'get', WORKFLOW_ID, ...argv]) } @@ -177,6 +185,39 @@ describe('sim workflows source get --dir', () => { expect(primer).not.toContain('`slack.sendMessage`') }) + it.each(['workflow', 'workspace'] as const)( + 'names in the %s primer only commands and flags this CLI has', + (kind) => { + const program = buildProgram() + const named = [...sourcePrimer(kind).matchAll(/`(sim [^`]+)`/g)].map((match) => match[1]) + expect(named.length).toBeGreaterThan(0) + for (const line of named) { + let command: Command = program + const words = line.split(/\s+/).slice(1) + for (const word of words) { + if (word.startsWith('-') || word.startsWith('<') || /^['"{.]/.test(word)) break + const next = command.commands.find( + (child) => child.name() === word || child.aliases().includes(word) + ) + if (!next) break + command = next + } + expect(command.commands.length, `${line} names a command`).toBe(0) + const flags = new Set( + [command, ...ancestorsOf(command)].flatMap((at) => + at.options.map((option) => option.long) + ) + ) + for (const flag of line.match(/--[a-z-]+/g) ?? []) { + expect( + flags.has(flag) || flags.has(flag.replace(/^--no-/, '--')), + `${line}: ${flag}` + ).toBe(true) + } + } + } + ) + it('keeps the primer without snippets within its byte budget for both directory kinds', () => { for (const kind of ['workflow', 'workspace'] as const) { expect(Buffer.byteLength(sourcePrimer(kind))).toBeLessThanOrEqual(PRIMER_MAX_BYTES) 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 bc4d88c04f2..43d6d8c997e 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -31,6 +31,7 @@ import type { } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' +import { searchTasks } from '../search' import { printProtocolResult } from './result' import { absoluteDirOption, @@ -467,6 +468,11 @@ export function attachWorkspaceSourceApply(source: Command): void { ]) absoluteDirOption(command) verboseFlag(command) + searchTasks(command, [ + 'promote dev to prod', + 'copy every workflow from a dev workspace into a prod workspace (--to)', + 'save bulk edits to every workflow', + ]) command .option('--dir ', 'Workspace source directory written by `workspaces source get`', '.') .option('--dry-run', 'Plan and check without writing anything') 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 8fbbdd4f0b1..78dde8cb6bd 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -20,6 +20,7 @@ import { printError } from '#sim-cli/output/io' import type { GetWorkspaceSourceResponse } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand } from '../../runtime/called-operations' +import { searchTasks } from '../search' import { removeStagingOnSignal } from './files-get' import { absoluteDirOption, @@ -376,6 +377,11 @@ export function attachWorkspaceSourceGet(source: Command): void { 'downloadKnowledgeDocument', ]) absoluteDirOption(command) + searchTasks(command, [ + 'change the model in every agent block', + 'bulk edit every workflow in the workspace', + 'edit all workflows, tables and skills as code', + ]) command .requiredOption('--dir ', 'Directory to write the workspace source into') .option('--only ', `Read only these kinds (${ONLY_KINDS_HELP})`) diff --git a/packages/sim-cli/src/commands/search.test.ts b/packages/sim-cli/src/commands/search.test.ts index a86bfead085..b129ed9730a 100644 --- a/packages/sim-cli/src/commands/search.test.ts +++ b/packages/sim-cli/src/commands/search.test.ts @@ -30,6 +30,15 @@ describe('sim cli search', () => { ['switch workspace', 'sim configure'], ['edit workflow blocks', 'sim workflows operations apply'], ['how much have i spent', 'sim billing status'], + ['build a workflow', 'sim workflows source create'], + ['create a new workflow', 'sim workflows source create'], + [ + 'build a workflow that answers questions from a knowledge base', + 'sim workflows source create', + ], + ['change the model in every agent block', 'sim workspaces source get'], + ['promote dev to prod', 'sim workspaces source apply'], + ['promote a dev workspace to a prod workspace', 'sim workspaces source apply'], ])('ranks the intended command first for "%s"', (query, expected) => { expect(searchReal(query)[0]?.command).toBe(expected) }) diff --git a/packages/sim-cli/src/commands/search.ts b/packages/sim-cli/src/commands/search.ts index ab3d38e30f8..e6abfe6c502 100644 --- a/packages/sim-cli/src/commands/search.ts +++ b/packages/sim-cli/src/commands/search.ts @@ -12,7 +12,7 @@ const MAX_RESULTS = 5 * it heavily would rank every command that takes `--workflow` as a workflow * command. */ -const FIELD_BOOST = { command: 8, summary: 5, context: 0.5 } as const +const FIELD_BOOST = { command: 8, summary: 5, tasks: 4, context: 0.5 } as const /** * Filler in a plain-language query. Left in, prefix matching turns `a` or `i` @@ -46,12 +46,29 @@ const SEARCH_OPTIONS = { */ const TRAILING_PARENTHETICAL = /\s*\([^)]*\)\s*$/ +/** + * The plain-language tasks a command is the answer to, where its name and summary use other + * words: "build a workflow" for `workflows source create`, "promote dev to prod" for + * `workspaces source apply`. Set by the command's own module ({@link searchTasks}). + */ +const TASKS = new WeakMap() + +/** + * Indexes `command` for `tasks` too, so `sim cli search` finds it from how an agent or a person + * phrases the job, not only from its name. Returns the command, to chain. + */ +export function searchTasks(command: Command, tasks: readonly string[]): Command { + TASKS.set(command, tasks.join('. ')) + return command +} + interface SearchDocument { command: string /** The summary as printed, qualifier included. */ display: string /** The summary with its trailing qualifier removed, so only what the command does is ranked. */ summary: string + tasks: string context: string } @@ -93,6 +110,7 @@ function collectDocuments( command: ['sim', ...path].join(' '), display, summary: display.replace(TRAILING_PARENTHETICAL, ''), + tasks: TASKS.get(command) ?? '', context: [ ...ancestors, ...command.registeredArguments.map((argument) => @@ -114,7 +132,7 @@ function collectDocuments( /** Ranks every command in `program` against a plain-language query, best first. */ export function searchCommands(program: Command, query: string, exclude: Command): SearchResult[] { const index = new MiniSearch({ - fields: ['command', 'summary', 'context'], + fields: ['command', 'summary', 'tasks', 'context'], storeFields: ['command', 'display'], idField: 'command', }) From 2b030fd7357a6b3baf5bef5a7a1c98f1cb2638eb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:58:15 -0800 Subject: [PATCH 025/104] fix(sim-cli): say on stderr when a request waits out a rate limit The CLI resent a request answered 429 after a silent wait of up to a minute, six times, so a workspace status hitting the source budget looked like a three-minute hang. Each wait now prints how long it is and which retry. --- packages/sim-cli/src/http/client.test.ts | 21 +++++++++++++++++++++ packages/sim-cli/src/http/client.ts | 6 +++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index e8ef2101888..b3865a8c1a1 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -474,6 +474,27 @@ describe('rate limiting', () => { expect(fetch).toHaveBeenCalledTimes(2) }) + it('says on stderr how long it waits before resending a request answered 429', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const written: string[] = [] + const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + written.push(String(chunk)) + return true + }) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValueOnce(limited('7')) + .mockResolvedValueOnce(Response.json({ data: {} })) + ) + + await settle(client().request('/api/v2/tables/tbl_1')) + write.mockRestore() + + expect(written.join('')).toMatch(/Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/) + }) + it('resends a GET answered 429 even when that response body is lost', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) const lostBody = new Response( diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 5990b79db07..8f80810cb14 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -795,7 +795,11 @@ export class SimClient { RATE_LIMIT_RETRY_AFTER_MAX_MS ) const backoffMs = backoffWithJitter(rateLimitResends + 1, null, RATE_LIMIT_BACKOFF) - await interruptibleSleep(Math.max(retryAfterMs ?? 0, backoffMs), caller) + const waitMs = Math.max(retryAfterMs ?? 0, backoffMs) + writeStderr( + `${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` + ) + await interruptibleSleep(waitMs, caller) if (caller?.aborted) throw new SimApiError('Request cancelled.', 0, REQUEST_CANCELLED) return this.send(path, options, retriedAfterRefresh, rateLimitResends + 1) } From 5bc3bba5bcc93b4fb2b8428c134f7417cf61574b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:28:01 -0800 Subject: [PATCH 026/104] fix(source): status reads a plan on the read budget instead of an apply dry run workflows and workspaces source status posted an apply dry run, so every status spent the source-write budget (one unit per workflow folder for a workspace): a clean 27-workflow workspace status took 171-178 s through 429 waits, and the status, dry run, apply loop allowed about one call per two minutes. The server gains POST /api/v2/workflows/{id}/source/plan and POST /api/v2/workspaces/{id}/source/plan (workflows.source.plan and workspaces.source.plan, read role, api:read): the same pipeline as a dry run, recording no dry-run analytics, on the generic and the source-read budget (one unit whatever the directory holds). Both status commands read them, falling back to the apply dry run only on a server without the route, and the workflow status also refreshes the directory's workspace types. --- .../(generated)/workflows/meta.json | 2 + apps/docs/openapi-v2-workflows.json | 10088 ++++++++++------ .../[workflowId]/source/plan/route.ts | 33 + .../[workspaceId]/source/plan/route.ts | 39 + .../contracts/v2/openapi/workflow-source.ts | 64 + .../contracts/v2/openapi/workspace-source.ts | 55 + .../lib/api/contracts/v2/workflow-source.ts | 33 + .../lib/api/contracts/v2/workspace-source.ts | 13 + .../lib/api/mcp/generated/v2-operations.ts | 19 + .../server/routes/v2-route-table.generated.ts | 8 + .../apply-workflow-source.integration.ts | 29 + .../application/apply-workflow-source.ts | 35 + .../lib/workflows/application/operations.ts | 16 + .../application/apply-workspace-source.ts | 20 + .../application/operations.ts | 14 + .../application/status.integration.ts | 25 +- .../src/commands/protocol/source-dir.ts | 2 +- .../src/commands/protocol/source-status.ts | 14 + .../protocol/workflow-source-status.test.ts | 27 +- .../protocol/workflow-source-status.ts | 43 +- .../protocol/workspace-source-status.test.ts | 11 +- .../protocol/workspace-source-status.ts | 44 +- packages/sim-cli/src/contract/commands.ts | 4 + packages/sim-cli/src/generated/v2-api.ts | 1058 ++ packages/sim-cli/src/http/client.test.ts | 3 + 25 files changed, 7875 insertions(+), 3824 deletions(-) create mode 100644 apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts create mode 100644 apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts diff --git a/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json b/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json index 61b9b358023..e5d6fb0c217 100644 --- a/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json +++ b/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json @@ -12,10 +12,12 @@ "getWorkflowOutline", "getWorkflowSource", "applyWorkflowSource", + "planWorkflowSource", "createWorkflowFromSource", "getSourceResources", "getWorkspaceSource", "applyWorkspaceSource", + "planWorkspaceSource", "findMissingWorkspaceSourceBlobs", "stageWorkspaceSourceBlobs", "replaceWorkflowState", diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 4ee88ce5262..b160e16f5c1 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6237,6 +6237,195 @@ } } }, + "/api/v2/workflows/{workflowId}/source/plan": { + "post": { + "operationId": "planWorkflowSource", + "summary": "Plan workflow source", + "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workflows.source.plan", + "x-oauth-scope": "api:read", + "tags": ["Workflows"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:read"] + } + ], + "parameters": [ + { + "name": "workflowId", + "in": "path", + "required": true, + "description": "Unique workflow identifier.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Unique workflow identifier.", + "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] + } + }, + { + "name": "allowDelete", + "in": "query", + "required": false, + "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "schema": { + "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "type": "boolean" + } + } + ], + "requestBody": { + "required": true, + "description": "Edited source files with the lock and base they were read with.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlanWorkflowSourceBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The evaluated source.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlanWorkflowSourceResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": true, + "applied": false, + "diff": { + "noop": true, + "blocks": { + "added": [], + "removed": [], + "renamed": [], + "modified": [] + }, + "edges": { + "added": 0, + "removed": 0 + }, + "variables": { + "added": [], + "removed": [], + "modified": [] + } + }, + "diagnostics": [], + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + }, + "mintedIds": {}, + "notes": [], + "needsRedeployment": false + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v2/workspaces/{workspaceId}/workflows/source": { "post": { "operationId": "createWorkflowFromSource", @@ -8858,20 +9047,20 @@ } } }, - "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { + "/api/v2/workspaces/{workspaceId}/source/plan": { "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`.", - "x-sim-operation": "workspaces.source.blobs.missing", - "x-oauth-scope": "api:write", + "operationId": "planWorkspaceSource", + "summary": "Plan workspace source", + "description": "Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workspaces.source.plan", + "x-oauth-scope": "api:read", "tags": ["Workflows"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ @@ -8890,22 +9079,42 @@ ], "requestBody": { "required": true, - "description": "The binary files an apply will need.", + "description": "The directory files, its managed kinds and the base they were read with.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" + "$ref": "#/components/schemas/PlanWorkspaceSourceBody" }, "examples": { "example1": { "summary": "Request example 1", "value": { - "blobs": [ - { - "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", - "size": 18432 + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "kinds": ["table"], + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } } - ] + } } } } @@ -8914,7 +9123,7 @@ }, "responses": { "200": { - "description": "The binary files still to stage.", + "description": "The planned changes.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -8929,7 +9138,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" + "$ref": "#/components/schemas/PlanWorkspaceSourceResponse" }, "examples": { "example1": { @@ -8937,40 +9146,191 @@ "value": { "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "missing": [ - "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e" - ] - } - } - } - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "409": { - "$ref": "#/components/responses/Conflict" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, - "423": { - "$ref": "#/components/responses/Locked" - }, + "dryRun": true, + "plan": [ + { + "kind": "table", + "key": "leads", + "action": "noop", + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" + } + ], + "applied": [], + "needBlobs": [], + "files": {}, + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "diagnostics": [] + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { + "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`.", + "x-sim-operation": "workspaces.source.blobs.missing", + "x-oauth-scope": "api:write", + "tags": ["Workflows"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "workspaceId", + "in": "path", + "required": true, + "description": "Workspace to read or apply.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace to read or apply." + } + } + ], + "requestBody": { + "required": true, + "description": "The binary files an apply will need.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "blobs": [ + { + "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", + "size": 18432 + } + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The binary files still to stage.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "missing": [ + "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e" + ] + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "423": { + "$ref": "#/components/responses/Locked" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -19984,7 +20344,7 @@ } ] }, - "CreateWorkflowFromSourceResponse": { + "PlanWorkflowSourceResponse": { "type": "object", "properties": { "data": { @@ -20227,8 +20587,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -20339,13 +20697,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -20647,25 +21002,19 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Create workflow from source response", - "description": "The outcome, with the source re-printed from the saved workflow.", + "title": "Plan workflow source response", + "description": "What an apply would store, and every finding.", "examples": [ { "data": { "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, - "applied": true, + "dryRun": true, + "applied": false, "diff": { - "noop": false, + "noop": true, "blocks": { - "added": [ - { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "key": "start", - "type": "start_trigger" - } - ], + "added": [], "removed": [], "renamed": [], "modified": [] @@ -20703,16 +21052,14 @@ "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" }, - "mintedIds": { - "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" - }, + "mintedIds": {}, "notes": [], "needsRedeployment": false } } ] }, - "CreateWorkflowFromSourceBody": { + "PlanWorkflowSourceBody": { "type": "object", "properties": { "files": { @@ -20727,1716 +21074,1385 @@ }, "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." }, - "name": { - "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", - "type": "string", - "minLength": 1, - "maxLength": 255 - }, - "description": { - "description": "Workflow description. Defaults to the description in the source.", - "anyOf": [ - { - "type": "string", - "maxLength": 50000 - }, - { - "type": "null" - } - ] - }, - "folderPath": { - "$ref": "#/components/schemas/FolderPathInput" - }, - "provenance": { - "description": "Where the source came from, for the audit log.", + "lock": { "type": "object", "properties": { - "client": { - "type": "string", - "enum": ["cli", "copilot", "canvas", "api"], - "description": "What submitted the source." - }, - "gitSha": { - "description": "The commit the source was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" + "version": { + "type": "number", + "const": 1, + "description": "Lock format version." }, - "repo": { - "description": "The repository the source was taken from.", - "type": "string", - "minLength": 1, - "maxLength": 512 - } - }, - "required": ["client"], - "additionalProperties": false - } - }, - "required": ["files"], - "additionalProperties": false, - "title": "Create workflow from source body", - "description": "Source files and where to create the workflow." - }, - "GetSourceResourcesResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, - "tables": { - "type": "array", - "items": { + "blocks": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { "type": "object", "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, "id": { "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." + "description": "Block id." }, - "columns": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Column name, as row data names it." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "currency", - "boolean", - "date", - "json", - "select" - ], - "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." - }, - "options": { - "description": "Option names a `select` column accepts, as table blocks read and write them.", - "type": "array", - "items": { - "type": "string" - } - }, - "multiple": { - "description": "A `select` column whose cells hold several options.", - "type": "boolean" - }, - "required": { - "description": "Every row holds a value.", - "type": "boolean" - } + "parent": { + "anyOf": [ + { + "type": "string" }, - "required": ["name", "type"], - "additionalProperties": false + { + "type": "null" + } + ], + "description": "Key of the enclosing loop or parallel, or null." + }, + "branches": { + "description": "Condition or router branch key → stored branch id.", + "type": "object", + "propertyNames": { + "type": "string" }, - "description": "Columns in table order." - } - }, - "required": ["key", "id", "name", "columns"], - "additionalProperties": false, - "description": "A table: `table(key)`." - }, - "description": "Tables, oldest first." - }, - "knowledgeBases": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." + "additionalProperties": { + "type": "string" + } }, - "id": { - "type": "string", - "description": "Resource id." + "items": { + "description": "Per field, its id-bearing items (input format fields) in stored order.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Item name." + }, + "id": { + "type": "string", + "description": "Item id." + } + }, + "required": ["name", "id"], + "additionalProperties": false, + "description": "One id-bearing list item." + } + } }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A knowledge base: `knowledgeBase(key)`." - }, - "description": "Knowledge bases, oldest first." - }, - "credentials": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { + "ident": { "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." + "description": "The `const` name the block is printed as." }, - "id": { - "type": "string", - "description": "Resource id." + "order": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Declaration-order tie-break." }, - "name": { - "type": "string", - "description": "Current display name." + "layout": { + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "Canvas x position." + }, + "y": { + "type": "number", + "description": "Canvas y position." + }, + "w": { + "description": "Container width.", + "type": "number" + }, + "h": { + "description": "Container height.", + "type": "number" + }, + "height": { + "description": "Stored block height.", + "type": "number" + }, + "horizontalHandles": { + "description": "Handles on the left and right.", + "type": "boolean" + } + }, + "required": ["x", "y"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Stored canvas geometry; applied only to new blocks." }, - "provider": { - "type": "string", - "description": "The provider the credential is for, e.g. `slack` or `google-email`." + "codeFile": { + "description": "Path of the block’s function-code file.", + "type": "string" } }, - "required": ["key", "id", "name", "provider"], - "additionalProperties": false, - "description": "A saved credential: `credential(key)`." + "required": ["id", "parent", "ident", "order"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "One block’s identity." }, - "description": "Saved credentials, oldest first. Secrets are listed under `env`." + "description": "Block key → identity." }, - "workflows": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "inputs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Input field name." - }, - "type": { - "type": "string", - "description": "Input field type, e.g. `string` or `number`." - } - }, - "required": ["name", "type"], - "additionalProperties": false - }, - "description": "Inputs the workflow start block declares." - } - }, - "required": ["key", "id", "name", "inputs"], - "additionalProperties": false, - "description": "A workflow: `childWorkflow(key)`." + "variables": { + "type": "object", + "propertyNames": { + "type": "string" }, - "description": "Workflows, oldest first." - }, - "skills": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace skill: `skill(key)`." + "additionalProperties": { + "type": "string" }, - "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." + "description": "Variable key → variable id." + } + }, + "required": ["version", "blocks", "variables"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." + }, + "base": { + "type": "object", + "properties": { + "version": { + "default": 1, + "description": "Base format version; a base written before it existed reads as 1.", + "type": "number", + "const": 1 }, - "customTools": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace custom tool, by its title: `customTool(key)`." - }, - "description": "Workspace custom tools, oldest first." + "workflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow the source was read from; an apply to another workflow is refused." }, - "mcpServers": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "tools": { - "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "An MCP server the workspace consumes: `mcp(key)`." - }, - "description": "MCP servers, oldest first." + "workspaceId": { + "type": "string", + "description": "Workspace the workflow belongs to." }, - "env": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." + "fingerprint": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." }, - "truncated": { - "type": "boolean", - "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." + "catalogHash": { + "type": "string", + "description": "Hash of the block catalog the source was printed against." } }, - "required": [ - "workspaceId", - "tables", - "knowledgeBases", - "credentials", - "workflows", - "skills", - "customTools", - "mcpServers", - "env", - "truncated" - ], - "additionalProperties": false, - "description": "Response data." + "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`." } }, - "required": ["data"], + "required": ["files", "lock", "base"], "additionalProperties": false, - "title": "Get source resources response", - "description": "The workspace resources workflow source can name.", + "title": "Plan workflow source body", + "description": "Edited source files with the lock and base they were read with.", "examples": [ { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "tables": [ - { - "key": "tickets", - "id": "tbl_4f1c2a9e", - "name": "Tickets", - "columns": [ - { - "name": "subject", - "type": "string" - }, - { - "name": "status", - "type": "select", - "options": ["open", "closed"] - } - ] - } - ], - "knowledgeBases": [ - { - "key": "docs", - "id": "kb_93a1e7c2", - "name": "Docs" - } - ], - "credentials": [ - { - "key": "support-slack", - "id": "cred_51d0b8f4", - "name": "Support Slack", - "provider": "slack" - } - ], - "workflows": [ - { - "key": "assign-owner", - "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "name": "Assign owner", - "inputs": [ - { - "name": "leads", - "type": "array" - } - ] - } - ], - "skills": [ - { - "key": "triage", - "id": "skl_7e2a4c19", - "name": "Triage" - } - ], - "customTools": [ - { - "key": "lookup-order", - "id": "ctl_2b8d6f03", - "name": "lookup_order" - } - ], - "mcpServers": [ - { - "key": "github", - "id": "mcp-1a2b3c4d", - "name": "GitHub", - "tools": ["create_issue", "list_issues"] + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 } - ], - "env": ["CRM_KEY"], - "truncated": false + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" } } ] }, - "WorkspaceForkPreview": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." - }, - "sourceWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace the workflows and resources are copied from." - }, - "workflows": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - } - }, - "required": ["sourceWorkflowId", "name"], - "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." - }, - "selectedResourceCount": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources explicitly selected for copying." - }, - "draftOnly": { - "type": "boolean", - "const": true, - "description": "True because fork creation produces undeployed drafts." - } - }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "workflows", - "selectedResourceCount", - "draftOnly" - ], - "additionalProperties": false, - "title": "Workspace fork preview", - "description": "Read-only fork plan and fingerprint." - }, - "PreviewWorkspaceForkResponse": { + "CreateWorkflowFromSourceResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceForkPreview" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Preview workspace fork response", - "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", - "examples": [ - { - "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "workflows": [], - "selectedResourceCount": 0, - "draftOnly": true - } - } - ] - }, - "PreviewWorkspaceForkBody": { - "type": "object", - "properties": { - "name": { - "description": "Display name of the workflow or workspace.", - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "files": { - "description": "Workspace file IDs to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "workflowId": { + "type": "string", + "description": "Workflow id." }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "workspaceId": { + "type": "string", + "description": "Workspace id." }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "dryRun": { + "type": "boolean", + "description": "True when nothing was written because `dryRun` was set." }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false, - "title": "Preview workspace fork request", - "description": "Optional child name and explicitly selected resource copies." - }, - "WorkspaceOperationReport": { - "type": "object", - "properties": { - "operationId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Durable operation identifier to use for polling." - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." - }, - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." - }, - "kind": { - "type": "string", - "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], - "description": "Type of committed workspace operation." - }, - "applied": { - "type": "boolean", - "const": true, - "description": "The business transaction committed, including when follow-up work fails." - }, - "status": { - "type": "string", - "enum": [ - "processing", - "completed", - "completed_with_warnings", - "requires_configuration", - "failed" - ], - "description": "Operation status; failed follow-up work does not undo the committed transaction." - }, - "resourceIds": { - "maxItems": 5000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - "description": "Identifiers of resources created or changed by the committed operation." - }, - "issues": { - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "code": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable machine-readable issue code." - }, - "message": { - "type": "string", - "maxLength": 2048, - "description": "Human-readable explanation of the issue." - }, - "workflowId": { - "description": "Workflow affected by this issue or deployment attempt.", - "type": "string", - "maxLength": 256 - }, - "blockId": { - "description": "Source block identifier before graph ID regeneration.", - "type": "string", - "maxLength": 256 - }, - "subBlockKey": { - "description": "Registered source field key, including the tool index for nested Agent fields.", - "type": "string", - "maxLength": 256 - } + "applied": { + "type": "boolean", + "description": "True when the draft was written or the workflow renamed or redescribed; false on a dry run and on a no-op." }, - "required": ["code", "message"], - "additionalProperties": false - }, - "description": "Structured warnings, missing configuration, and follow-up failures." - }, - "idMap": { - "description": "Source graph identifiers mapped to the imported identifiers.", - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 256 - } - }, - "deploymentOperationIds": { - "description": "Exact deployment attempts admitted by the workspace operation.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "maxLength": 256 - } - }, - "deployments": { - "description": "Readiness of the exact admitted deployment attempts.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "operationId": { - "type": "string", - "maxLength": 256, - "description": "Durable operation identifier to use for polling." - }, - "workflowId": { - "type": "string", - "maxLength": 256, - "description": "Workflow affected by this issue or deployment attempt." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 9007199254740991, - "description": "Deployment version number for this admitted attempt." - }, - "status": { - "type": "string", - "enum": ["preparing", "activating", "active", "failed", "superseded"], - "description": "Status of this exact admitted deployment attempt." - }, - "ready": { - "type": "boolean", - "description": "Whether this exact deployment attempt is active and all required components are ready." - }, - "pendingComponents": { - "maxItems": 32, - "type": "array", - "items": { - "type": "string", - "maxLength": 128 + "diff": { + "type": "object", + "properties": { + "noop": { + "type": "boolean", + "description": "True when the source matches the saved draft." }, - "description": "Deployment components that have not finished becoming ready." - } - }, - "required": [ - "operationId", - "workflowId", - "version", - "status", - "ready", - "pendingComponents" - ], - "additionalProperties": false - } - }, - "triggerUrlChanges": { - "description": "Public trigger paths changed by this sync, with the affected workflow names.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Name of the workflow whose public trigger path stops serving." + "meta": { + "description": "The workflow name and description fields the source changes.", + "type": "array", + "items": { + "type": "string", + "enum": ["name", "description"] + } + }, + "blocks": { + "type": "object", + "properties": { + "added": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "type": { + "type": "string", + "description": "Block type." + } + }, + "required": ["id", "key", "type"], + "additionalProperties": false, + "description": "An added or removed block by id, source key and type." + }, + "description": "New blocks." + }, + "removed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "type": { + "type": "string", + "description": "Block type." + } + }, + "required": ["id", "key", "type"], + "additionalProperties": false, + "description": "An added or removed block by id, source key and type." + }, + "description": "Deleted blocks." + }, + "renamed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id; unchanged by the rename." + }, + "from": { + "type": "string", + "description": "Previous key." + }, + "to": { + "type": "string", + "description": "New key." + } + }, + "required": ["id", "from", "to"], + "additionalProperties": false, + "description": "A renamed block." + }, + "description": "Renamed blocks; each keeps its id." + }, + "modified": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Changed fields, modes (`modes.`) and attributes." + }, + "reparented": { + "description": "Moved into or out of a container.", + "type": "boolean" + } + }, + "required": ["id", "key", "fields"], + "additionalProperties": false, + "description": "A changed block." + }, + "description": "Changed blocks." + } + }, + "required": ["added", "removed", "renamed", "modified"], + "additionalProperties": false, + "description": "Block changes." + }, + "edges": { + "type": "object", + "properties": { + "added": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Connections added." + }, + "removed": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Connections removed." + } + }, + "required": ["added", "removed"], + "additionalProperties": false, + "description": "Connection changes." + }, + "variables": { + "type": "object", + "properties": { + "added": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys added." + }, + "removed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys removed." + }, + "modified": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys changed." + } + }, + "required": ["added", "removed", "modified"], + "additionalProperties": false, + "description": "Variable changes." + } }, - "path": { - "type": "string", - "maxLength": 4096, - "description": "Public trigger path that stops serving after this sync." - } + "required": ["noop", "blocks", "edges", "variables"], + "additionalProperties": false, + "description": "What the apply changed, or would change on a dry run." }, - "required": ["workflowName", "path"], - "additionalProperties": false - } - }, - "backgroundWorkId": { - "description": "Workspace activity identifier for resource-copy progress.", - "type": "string", - "maxLength": 256 - }, - "copyProgress": { - "description": "Completion status and counts for explicitly selected resource copies.", - "type": "object", - "properties": { - "status": { - "type": "string", - "enum": ["pending", "completed", "failed"], - "description": "Background resource-copy status." - }, - "copied": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources copied successfully." - }, - "failed": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources that failed to copy." - } - }, - "required": ["status", "copied", "failed"], - "additionalProperties": false - } - }, - "required": [ - "operationId", - "requestId", - "workspaceId", - "kind", - "applied", - "status", - "resourceIds", - "issues" - ], - "additionalProperties": false, - "title": "Workspace operation receipt", - "description": "Committed operation receipt, resource copies, and exact deployment readiness." - }, - "ForkWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Fork workspace response", - "description": "Committed fork receipt and resource-copy progress.", - "examples": [ - { - "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "fork-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_fork", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] - } - } - ] - }, - "ForkWorkspaceBody": { - "type": "object", - "properties": { - "name": { - "description": "Display name of the workflow or workspace.", - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", - "type": "object", - "properties": { - "files": { - "description": "Workspace file IDs to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", - "maxItems": 2000, + "diagnostics": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - } - }, - "required": ["requestId", "previewFingerprint"], - "additionalProperties": false, - "title": "Fork workspace request", - "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", - "examples": [ - { - "name": "Support sandbox", - "requestId": "fork-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" - } - ] - }, - "WorkspaceSyncPreview": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." - }, - "sourceWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace the workflows and resources are copied from." - }, - "targetWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace receiving the changes." - }, - "ready": { - "type": "boolean", - "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." - }, - "workflows": { - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "action": { - "type": "string", - "enum": ["create", "replace", "archive"], - "description": "Planned workflow creation, replacement, or archival." - }, - "sourceWorkflowId": { - "description": "Workflow identifier in the source workspace.", - "type": "string", - "minLength": 1 - }, - "targetWorkflowId": { - "description": "Existing target workflow identifier; absent when apply will create a new target.", - "type": "string", - "minLength": 1 - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "comparison": { - "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", - "oneOf": [ - { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "available", - "description": "Both exact source snapshots are available." - }, - "base": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Source deployment last successfully synced to this destination." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "base", "target"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "unavailable", - "description": "The source baseline cannot be compared." - }, - "reason": { - "type": "string", - "enum": ["new_workflow", "no_baseline", "missing_baseline"], - "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "reason", "target"], - "additionalProperties": false - } - ] - } - }, - "required": ["action", "name"], - "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." - }, - "unresolvedBindings": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "maxLength": 256, - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "blockName": { - "description": "Display name of the affected source block.", - "type": "string", - "maxLength": 1024 - }, - "reason": { - "description": "Structured explanation of the unresolved binding.", - "type": "string", - "maxLength": 256 - } - }, - "required": ["kind", "sourceId"], - "additionalProperties": false - }, - "description": "Source references that still require destination mappings or explicit copy choices." - }, - "configuration": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "currentValue": { - "type": "string", - "maxLength": 65536, - "description": "Persisted sync override or proposed override; empty when neither is configured." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s options.", - "type": "string", - "maxLength": 256 - }, - "discoveryWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." - }, - "context": { "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 4096 - }, - "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." - }, - "parentKind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource kind that owns this dependent configuration." - }, - "parentSourceId": { - "type": "string", - "maxLength": 4096, - "description": "Source identifier of the parent resource being mapped." - }, - "parentContextKey": { - "description": "Selector context key supplied by the mapped parent resource.", - "type": "string", - "maxLength": 256 - } - }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "subBlockKey", - "title", - "required", - "currentValue", - "discoveryWorkspaceId", - "context", - "parentKind", - "parentSourceId" - ], - "additionalProperties": false - }, - "description": "Dependent fields that may need destination-specific values." - }, - "excludedTargets": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - } - }, - "required": ["id", "name"], - "additionalProperties": false - }, - "description": "Target workflows explicitly excluded from sync." - }, - "triggerSlots": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Stable source trigger block identifier to use in trigger mappings." - }, - "blockName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source trigger block." - }, - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source workflow." - }, - "ownPath": { - "anyOf": [ - { + "properties": { + "code": { "type": "string", - "maxLength": 4096 + "enum": [ + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_LIMIT_EXCEEDED", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_STALE", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_NAME_TAKEN", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, - { - "type": "null" - } - ], - "description": "Existing target trigger path, preserved automatically and not configurable." - }, - "adoptablePaths": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - "description": "Retiring paths in the same target workflow with a compatible trigger provider." - }, - "defaultAdoptPath": { - "anyOf": [ - { + "severity": { "type": "string", - "maxLength": 4096 + "enum": ["error", "warning", "info"], + "description": "Diagnostic severity." }, - { - "type": "null" + "message": { + "type": "string", + "description": "What was found." + }, + "hint": { + "description": "How to address it.", + "type": "string" + }, + "blockKey": { + "description": "Block the finding is about.", + "type": "string" + }, + "param": { + "description": "Field the finding is about.", + "type": "string" + }, + "file": { + "description": "Submitted file the finding is in.", + "type": "string" + }, + "line": { + "description": "1-based line in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "column": { + "description": "1-based column in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endLine": { + "description": "1-based line the finding ends on.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endColumn": { + "description": "1-based column the finding ends at.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "frame": { + "description": "The source lines around the finding, with a caret row.", + "type": "string" + }, + "blockId": { + "description": "Stored id of the block the finding is about.", + "type": "string" + }, + "path": { + "description": "JSON Pointer into the lock, for a lock finding.", + "type": "string" } - ], - "description": "Default adoption when ownPath is null; null then allocates a new path." - } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding from applying workflow source, pinned to the submitted files." + }, + "description": "Warnings, and on a dry run every error a commit would refuse." }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "blockName", - "workflowName", - "ownPath", - "adoptablePaths", - "defaultAdoptPath" - ], - "additionalProperties": false - }, - "description": "Source triggers and the target paths available for explicit adoption choices." - }, - "triggerUrlChanges": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Name of the affected workflow." + "files": { + "type": "object", + "propertyNames": { + "type": "string" }, - "path": { - "type": "string", - "maxLength": 4096, - "description": "Public trigger path that stops serving after this sync." - } + "additionalProperties": { + "type": "string" + }, + "description": "The source re-printed from what was saved, including any normalized values." }, - "required": ["workflowName", "path"], - "additionalProperties": false + "lock": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Lock format version." + }, + "blocks": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Block id." + }, + "parent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Key of the enclosing loop or parallel, or null." + }, + "branches": { + "description": "Condition or router branch key → stored branch id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + }, + "items": { + "description": "Per field, its id-bearing items (input format fields) in stored order.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Item name." + }, + "id": { + "type": "string", + "description": "Item id." + } + }, + "required": ["name", "id"], + "additionalProperties": false, + "description": "One id-bearing list item." + } + } + }, + "ident": { + "type": "string", + "description": "The `const` name the block is printed as." + }, + "order": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Declaration-order tie-break." + }, + "layout": { + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "Canvas x position." + }, + "y": { + "type": "number", + "description": "Canvas y position." + }, + "w": { + "description": "Container width.", + "type": "number" + }, + "h": { + "description": "Container height.", + "type": "number" + }, + "height": { + "description": "Stored block height.", + "type": "number" + }, + "horizontalHandles": { + "description": "Handles on the left and right.", + "type": "boolean" + } + }, + "required": ["x", "y"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Stored canvas geometry; applied only to new blocks." + }, + "codeFile": { + "description": "Path of the block’s function-code file.", + "type": "string" + } + }, + "required": ["id", "parent", "ident", "order"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "One block’s identity." + }, + "description": "Block key → identity." + }, + "variables": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Variable key → variable id." + } + }, + "required": ["version", "blocks", "variables"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." + }, + "base": { + "type": "object", + "properties": { + "version": { + "default": 1, + "description": "Base format version; a base written before it existed reads as 1.", + "type": "number", + "const": 1 + }, + "workflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow the source was read from; an apply to another workflow is refused." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the workflow belongs to." + }, + "fingerprint": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." + }, + "catalogHash": { + "type": "string", + "description": "Hash of the block catalog the source was printed against." + } + }, + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Where the saved (or, on a dry run, would-be) draft was read: the next apply’s `base`." + }, + "mintedIds": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Block key → id for new blocks whose id was minted rather than taken from the lock." + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Non-fatal notes about the write." + }, + "needsRedeployment": { + "type": "boolean", + "description": "Whether the draft now differs from the live deployment; apply never deploys." + } }, - "description": "Retiring target trigger URLs no arriving trigger adopts." - } - }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "targetWorkspaceId", - "ready", - "workflows", - "unresolvedBindings", - "configuration", - "excludedTargets", - "triggerSlots", - "triggerUrlChanges" - ], - "additionalProperties": false, - "title": "Workspace sync preview", - "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." - }, - "PreviewWorkspacePushResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceSyncPreview" + "required": [ + "workflowId", + "workspaceId", + "dryRun", + "applied", + "diff", + "diagnostics", + "files", + "lock", + "base", + "mintedIds", + "notes", + "needsRedeployment" + ], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workspace push response", - "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", + "title": "Create workflow from source response", + "description": "The outcome, with the source re-printed from the saved workflow.", "examples": [ { "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "ready": true, - "workflows": [], - "unresolvedBindings": [], - "configuration": [], - "excludedTargets": [], - "triggerSlots": [], - "triggerUrlChanges": [] + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": false, + "applied": true, + "diff": { + "noop": false, + "blocks": { + "added": [ + { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "key": "start", + "type": "start_trigger" + } + ], + "removed": [], + "renamed": [], + "modified": [] + }, + "edges": { + "added": 0, + "removed": 0 + }, + "variables": { + "added": [], + "removed": [], + "modified": [] + } + }, + "diagnostics": [], + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + }, + "mintedIds": { + "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" + }, + "notes": [], + "needsRedeployment": false } } ] }, - "PreviewWorkspacePushBody": { + "CreateWorkflowFromSourceBody": { "type": "object", "properties": { - "otherWorkspaceId": { + "files": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "additionalProperties": { + "type": "string" + }, + "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." + }, + "name": { + "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "maxLength": 255 }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } + "description": { + "description": "Workflow description. Defaults to the description in the source.", + "anyOf": [ + { + "type": "string", + "maxLength": 50000 }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + { + "type": "null" + } + ] }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "folderPath": { + "$ref": "#/components/schemas/FolderPathInput" }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "provenance": { + "description": "Where the source came from, for the audit log.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "client": { + "type": "string", + "enum": ["cli", "copilot", "canvas", "api"], + "description": "What submitted the source." }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "gitSha": { + "description": "The commit the source was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, + "repo": { + "description": "The repository the source was taken from.", + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "required": ["client"], + "additionalProperties": false + } + }, + "required": ["files"], + "additionalProperties": false, + "title": "Create workflow from source body", + "description": "Source files and where to create the workflow." + }, + "GetSourceResourcesResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "tables": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "columns": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Column name, as row data names it." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "currency", + "boolean", + "date", + "json", + "select" + ], + "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." + }, + "options": { + "description": "Option names a `select` column accepts, as table blocks read and write them.", + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "description": "A `select` column whose cells hold several options.", + "type": "boolean" + }, + "required": { + "description": "Every row holds a value.", + "type": "boolean" + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Columns in table order." + } + }, + "required": ["key", "id", "name", "columns"], + "additionalProperties": false, + "description": "A table: `table(key)`." + }, + "description": "Tables, oldest first." }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, + "knowledgeBases": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A knowledge base: `knowledgeBase(key)`." + }, + "description": "Knowledge bases, oldest first." }, - "files": { - "description": "Workspace file storage keys to copy.", - "maxItems": 2000, + "credentials": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "provider": { + "type": "string", + "description": "The provider the credential is for, e.g. `slack` or `google-email`." + } + }, + "required": ["key", "id", "name", "provider"], + "additionalProperties": false, + "description": "A saved credential: `credential(key)`." + }, + "description": "Saved credentials, oldest first. Secrets are listed under `env`." }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, + "workflows": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Input field name." + }, + "type": { + "type": "string", + "description": "Input field type, e.g. `string` or `number`." + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Inputs the workflow start block declares." + } + }, + "required": ["key", "id", "name", "inputs"], + "additionalProperties": false, + "description": "A workflow: `childWorkflow(key)`." }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - } + "description": "Workflows, oldest first." }, - "required": ["kind", "sourceId"], - "additionalProperties": false - } - }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." - }, - "adoptPath": { - "anyOf": [ - { + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { "type": "string", - "minLength": 1, - "maxLength": 4096 + "description": "The key workflow source names this resource by; it never changes once assigned." }, - { - "type": "null" + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace skill: `skill(key)`." + }, + "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Preview workspace push request", - "description": "Other workspace and proposed source-to-target sync choices." - }, - "PushWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + "customTools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace custom tool, by its title: `customTool(key)`." + }, + "description": "Workspace custom tools, oldest first." + }, + "mcpServers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "tools": { + "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "An MCP server the workspace consumes: `mcp(key)`." + }, + "description": "MCP servers, oldest first." + }, + "env": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." + }, + "truncated": { + "type": "boolean", + "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." + } + }, + "required": [ + "workspaceId", + "tables", + "knowledgeBases", + "credentials", + "workflows", + "skills", + "customTools", + "mcpServers", + "env", + "truncated" + ], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Push workspace response", - "description": "Committed push receipt with copy and deployment readiness.", + "title": "Get source resources response", + "description": "The workspace resources workflow source can name.", "examples": [ { "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "push-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_push", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "tables": [ + { + "key": "tickets", + "id": "tbl_4f1c2a9e", + "name": "Tickets", + "columns": [ + { + "name": "subject", + "type": "string" + }, + { + "name": "status", + "type": "select", + "options": ["open", "closed"] + } + ] + } + ], + "knowledgeBases": [ + { + "key": "docs", + "id": "kb_93a1e7c2", + "name": "Docs" + } + ], + "credentials": [ + { + "key": "support-slack", + "id": "cred_51d0b8f4", + "name": "Support Slack", + "provider": "slack" + } + ], + "workflows": [ + { + "key": "assign-owner", + "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "name": "Assign owner", + "inputs": [ + { + "name": "leads", + "type": "array" + } + ] + } + ], + "skills": [ + { + "key": "triage", + "id": "skl_7e2a4c19", + "name": "Triage" + } + ], + "customTools": [ + { + "key": "lookup-order", + "id": "ctl_2b8d6f03", + "name": "lookup_order" + } + ], + "mcpServers": [ + { + "key": "github", + "id": "mcp-1a2b3c4d", + "name": "GitHub", + "tools": ["create_issue", "list_issues"] + } + ], + "env": ["CRM_KEY"], + "truncated": false } } ] }, - "PushWorkspaceBody": { + "WorkspaceForkPreview": { "type": "object", "properties": { - "otherWorkspaceId": { + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." + }, + "sourceWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + "description": "Canonical workspace the workflows and resources are copied from." }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, + "workflows": { + "maxItems": 1000, "type": "array", "items": { "type": "object", @@ -22446,34 +22462,79 @@ "minLength": 1, "description": "Workflow identifier in the source workspace." }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { + "name": { "type": "string", - "minLength": 1, "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." + "description": "Display name of the workflow or workspace." } }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "required": ["sourceWorkflowId", "name"], "additionalProperties": false + }, + "description": "Eligible workflows and their planned actions." + }, + "selectedResourceCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources explicitly selected for copying." + }, + "draftOnly": { + "type": "boolean", + "const": true, + "description": "True because fork creation produces undeployed drafts." + } + }, + "required": [ + "previewFingerprint", + "sourceWorkspaceId", + "workflows", + "selectedResourceCount", + "draftOnly" + ], + "additionalProperties": false, + "title": "Workspace fork preview", + "description": "Read-only fork plan and fingerprint." + }, + "PreviewWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceForkPreview" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workspace fork response", + "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "workflows": [], + "selectedResourceCount": 0, + "draftOnly": true } + } + ] + }, + "PreviewWorkspaceForkBody": { + "type": "object", + "properties": { + "name": { + "description": "Display name of the workflow or workspace.", + "type": "string", + "minLength": 1, + "maxLength": 100 }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", + "files": { + "description": "Workspace file IDs to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22490,6 +22551,15 @@ "minLength": 1 } }, + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, "customTools": { "description": "Source custom tool identifiers to copy.", "maxItems": 2000, @@ -22508,8 +22578,8 @@ "minLength": 1 } }, - "files": { - "description": "Workspace file storage keys to copy.", + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", "maxItems": 2000, "type": "array", "items": { @@ -22517,8 +22587,8 @@ "minLength": 1 } }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", "maxItems": 2000, "type": "array", "items": { @@ -22528,236 +22598,285 @@ } }, "additionalProperties": false + } + }, + "additionalProperties": false, + "title": "Preview workspace fork request", + "description": "Optional child name and explicitly selected resource copies." + }, + "WorkspaceOperationReport": { + "type": "object", + "properties": { + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Durable operation identifier to use for polling." }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "kind": { + "type": "string", + "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], + "description": "Type of committed workspace operation." + }, + "applied": { + "type": "boolean", + "const": true, + "description": "The business transaction committed, including when follow-up work fails." + }, + "status": { + "type": "string", + "enum": [ + "processing", + "completed", + "completed_with_warnings", + "requires_configuration", + "failed" + ], + "description": "Operation status; failed follow-up work does not undo the committed transaction." + }, + "resourceIds": { + "maxItems": 5000, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "description": "Identifiers of resources created or changed by the committed operation." + }, + "issues": { "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "code": { "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." + "minLength": 1, + "maxLength": 128, + "description": "Stable machine-readable issue code." }, - "sourceId": { + "message": { "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." + "maxLength": 2048, + "description": "Human-readable explanation of the issue." + }, + "workflowId": { + "description": "Workflow affected by this issue or deployment attempt.", + "type": "string", + "maxLength": 256 + }, + "blockId": { + "description": "Source block identifier before graph ID regeneration.", + "type": "string", + "maxLength": 256 + }, + "subBlockKey": { + "description": "Registered source field key, including the tool index for nested Agent fields.", + "type": "string", + "maxLength": 256 } }, - "required": ["kind", "sourceId"], + "required": ["code", "message"], "additionalProperties": false + }, + "description": "Structured warnings, missing configuration, and follow-up failures." + }, + "idMap": { + "description": "Source graph identifiers mapped to the imported identifiers.", + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 256 } }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, + "deploymentOperationIds": { + "description": "Exact deployment attempts admitted by the workspace operation.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + } + }, + "deployments": { + "description": "Readiness of the exact admitted deployment attempts.", + "maxItems": 1000, "type": "array", "items": { "type": "object", "properties": { - "sourceWorkflowId": { + "operationId": { "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." + "maxLength": 256, + "description": "Durable operation identifier to use for polling." }, - "sourceBlockId": { + "workflowId": { "type": "string", - "minLength": 1, "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." + "description": "Workflow affected by this issue or deployment attempt." }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + "version": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "Deployment version number for this admitted attempt." + }, + "status": { + "type": "string", + "enum": ["preparing", "activating", "active", "failed", "superseded"], + "description": "Status of this exact admitted deployment attempt." + }, + "ready": { + "type": "boolean", + "description": "Whether this exact deployment attempt is active and all required components are ready." + }, + "pendingComponents": { + "maxItems": 32, + "type": "array", + "items": { + "type": "string", + "maxLength": 128 + }, + "description": "Deployment components that have not finished becoming ready." + } + }, + "required": [ + "operationId", + "workflowId", + "version", + "status", + "ready", + "pendingComponents" + ], + "additionalProperties": false + } }, - "confirm": { - "type": "boolean", - "const": true, - "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." + "triggerUrlChanges": { + "description": "Public trigger paths changed by this sync, with the affected workflow names.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Name of the workflow whose public trigger path stops serving." + }, + "path": { + "type": "string", + "maxLength": 4096, + "description": "Public trigger path that stops serving after this sync." + } + }, + "required": ["workflowName", "path"], + "additionalProperties": false + } + }, + "backgroundWorkId": { + "description": "Workspace activity identifier for resource-copy progress.", + "type": "string", + "maxLength": 256 + }, + "copyProgress": { + "description": "Completion status and counts for explicitly selected resource copies.", + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": ["pending", "completed", "failed"], + "description": "Background resource-copy status." + }, + "copied": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources copied successfully." + }, + "failed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources that failed to copy." + } + }, + "required": ["status", "copied", "failed"], + "additionalProperties": false } }, - "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], + "required": [ + "operationId", + "requestId", + "workspaceId", + "kind", + "applied", + "status", + "resourceIds", + "issues" + ], "additionalProperties": false, - "title": "Push workspace request", - "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", - "examples": [ - { - "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "push-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "confirm": true - } - ] + "title": "Workspace operation receipt", + "description": "Committed operation receipt, resource copies, and exact deployment readiness." }, - "PreviewWorkspacePullResponse": { + "ForkWorkspaceResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceSyncPreview" + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workspace pull response", - "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", + "title": "Fork workspace response", + "description": "Committed fork receipt and resource-copy progress.", "examples": [ { "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "ready": true, - "workflows": [], - "unresolvedBindings": [], - "configuration": [], - "excludedTargets": [], - "triggerSlots": [], - "triggerUrlChanges": [] + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "fork-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_fork", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] } } ] }, - "PreviewWorkspacePullBody": { + "ForkWorkspaceBody": { "type": "object", "properties": { - "otherWorkspaceId": { + "name": { + "description": "Display name of the workflow or workspace.", "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } - }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "maxLength": 100 }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", + "files": { + "description": "Workspace file IDs to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22774,8 +22893,8 @@ "minLength": 1 } }, - "customTools": { - "description": "Source custom tool identifiers to copy.", + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", "maxItems": 2000, "type": "array", "items": { @@ -22783,8 +22902,8 @@ "minLength": 1 } }, - "skills": { - "description": "Source skill identifiers to copy.", + "customTools": { + "description": "Source custom tool identifiers to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22792,8 +22911,8 @@ "minLength": 1 } }, - "files": { - "description": "Workspace file storage keys to copy.", + "skills": { + "description": "Source skill identifiers to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22809,276 +22928,285 @@ "type": "string", "minLength": 1 } - } - }, - "additionalProperties": false - }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - } }, - "required": ["kind", "sourceId"], - "additionalProperties": false - } - }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." - }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." + "minLength": 1 } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Preview workspace pull request", - "description": "Other workspace and proposed source-to-target sync choices." - }, - "PullWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "additionalProperties": false + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." } }, - "required": ["data"], + "required": ["requestId", "previewFingerprint"], "additionalProperties": false, - "title": "Pull workspace response", - "description": "Committed pull receipt with copy and deployment readiness.", + "title": "Fork workspace request", + "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", "examples": [ { - "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "pull-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_pull", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] - } + "name": "Support sandbox", + "requestId": "fork-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" } ] }, - "PullWorkspaceBody": { + "WorkspaceSyncPreview": { "type": "object", "properties": { - "otherWorkspaceId": { + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." + }, + "sourceWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "description": "Canonical workspace the workflows and resources are copied from." }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + "targetWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Canonical workspace receiving the changes." }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "ready": { + "type": "boolean", + "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." + }, + "workflows": { "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { + "action": { + "type": "string", + "enum": ["create", "replace", "archive"], + "description": "Planned workflow creation, replacement, or archival." + }, "sourceWorkflowId": { + "description": "Workflow identifier in the source workspace.", "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." + "minLength": 1 }, - "sourceBlockId": { + "targetWorkflowId": { + "description": "Existing target workflow identifier; absent when apply will create a new target.", "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." + "minLength": 1 }, - "subBlockKey": { + "name": { "type": "string", - "minLength": 1, "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." + "description": "Display name of the workflow or workspace." }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } - }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", - "type": "object", - "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 + "comparison": { + "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "available", + "description": "Both exact source snapshots are available." + }, + "base": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Source deployment last successfully synced to this destination." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "base", "target"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "unavailable", + "description": "The source baseline cannot be compared." + }, + "reason": { + "type": "string", + "enum": ["new_workflow", "no_baseline", "missing_baseline"], + "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "reason", "target"], + "additionalProperties": false + } + ] } }, - "files": { - "description": "Workspace file storage keys to copy.", - "maxItems": 2000, - "type": "array", - "items": { + "required": ["action", "name"], + "additionalProperties": false + }, + "description": "Eligible workflows and their planned actions." + }, + "unresolvedBindings": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { "type": "string", - "minLength": 1 - } - }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { + "maxLength": 256, + "description": "Resource or operation kind." + }, + "sourceId": { "type": "string", - "minLength": 1 + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "blockName": { + "description": "Display name of the affected source block.", + "type": "string", + "maxLength": 1024 + }, + "reason": { + "description": "Structured explanation of the unresolved binding.", + "type": "string", + "maxLength": 256 } - } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false }, - "additionalProperties": false + "description": "Source references that still require destination mappings or explicit copy choices." }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, + "configuration": { + "maxItems": 10000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "currentValue": { + "type": "string", + "maxLength": 65536, + "description": "Persisted sync override or proposed override; empty when neither is configured." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s options.", + "type": "string", + "maxLength": 256 + }, + "discoveryWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 4096 + }, + "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." + }, + "parentKind": { "type": "string", "enum": [ "credential", @@ -23094,439 +23222,201 @@ "skill", "sandbox" ], - "description": "Resource or operation kind." + "description": "Resource kind that owns this dependent configuration." }, - "sourceId": { + "parentSourceId": { "type": "string", - "minLength": 1, "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." + "description": "Source identifier of the parent resource being mapped." + }, + "parentContextKey": { + "description": "Selector context key supplied by the mapped parent resource.", + "type": "string", + "maxLength": 256 } }, - "required": ["kind", "sourceId"], + "required": [ + "sourceWorkflowId", + "sourceBlockId", + "subBlockKey", + "title", + "required", + "currentValue", + "discoveryWorkspaceId", + "context", + "parentKind", + "parentSourceId" + ], "additionalProperties": false - } + }, + "description": "Dependent fields that may need destination-specific values." }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, + "excludedTargets": { + "maxItems": 1000, "type": "array", "items": { "type": "object", "properties": { - "sourceWorkflowId": { + "id": { "type": "string", "minLength": 1, - "description": "Workflow identifier in the source workspace." + "description": "Resource identifier." }, - "sourceBlockId": { + "name": { "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." - }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + } + }, + "required": ["id", "name"], + "additionalProperties": false + }, + "description": "Target workflows explicitly excluded from sync." + }, + "triggerSlots": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Stable source trigger block identifier to use in trigger mappings." + }, + "blockName": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the source trigger block." + }, + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the source workflow." + }, + "ownPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { "type": "null" } ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." + "description": "Existing target trigger path, preserved automatically and not configurable." + }, + "adoptablePaths": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + "description": "Retiring paths in the same target workflow with a compatible trigger provider." + }, + "defaultAdoptPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Default adoption when ownPath is null; null then allocates a new path." } }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "required": [ + "sourceWorkflowId", + "sourceBlockId", + "blockName", + "workflowName", + "ownPath", + "adoptablePaths", + "defaultAdoptPath" + ], "additionalProperties": false - } - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "description": "Source triggers and the target paths available for explicit adoption choices." }, - "confirm": { - "type": "boolean", - "const": true, - "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." - } - }, - "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], - "additionalProperties": false, - "title": "Pull workspace request", - "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", - "examples": [ - { - "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "pull-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "confirm": true - } - ] - }, - "GetWorkspaceForkAvailabilityResult": { - "type": "object", - "properties": { - "available": { - "type": "boolean", - "description": "Whether this deployment and workspace plan enable forking." + "triggerUrlChanges": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Name of the affected workflow." + }, + "path": { + "type": "string", + "maxLength": 4096, + "description": "Public trigger path that stops serving after this sync." + } + }, + "required": ["workflowName", "path"], + "additionalProperties": false + }, + "description": "Retiring target trigger URLs no arriving trigger adopts." } }, - "required": ["available"], + "required": [ + "previewFingerprint", + "sourceWorkspaceId", + "targetWorkspaceId", + "ready", + "workflows", + "unresolvedBindings", + "configuration", + "excludedTargets", + "triggerSlots", + "triggerUrlChanges" + ], "additionalProperties": false, - "title": "Get workspace fork availability result", - "description": "Fork feature availability for this workspace." + "title": "Workspace sync preview", + "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." }, - "GetWorkspaceForkAvailabilityResponse": { + "PreviewWorkspacePushResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" + "$ref": "#/components/schemas/WorkspaceSyncPreview" } }, "required": ["data"], "additionalProperties": false, - "title": "Get workspace fork availability response", - "description": "Whether forking is enabled for this deployment and workspace plan." - }, - "GetWorkspaceForkLineageResult": { - "type": "object", - "properties": { - "current": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false, - "description": "The current workspace lineage node." - }, - "parent": { - "anyOf": [ - { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false - }, - { - "type": "null" - } - ], - "description": "The live parent workspace, or null when this workspace is not a fork." + "title": "Preview workspace push response", + "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "ready": true, + "workflows": [], + "unresolvedBindings": [], + "configuration": [], + "excludedTargets": [], + "triggerSlots": [], + "triggerUrlChanges": [] + } } - }, - "required": ["current", "parent"], - "additionalProperties": false, - "title": "Get workspace fork lineage result", - "description": "Current workspace and its active parent." + ] }, - "GetWorkspaceForkLineageResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get workspace fork lineage response", - "description": "Current workspace and its active direct parent, when present." - }, - "ListWorkspaceForkChildrenResult": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - }, - "createdAt": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "ISO 8601 creation timestamp." - } - }, - "required": ["id", "name", "organizationId", "createdAt"], - "additionalProperties": false, - "title": "List workspace fork children result", - "description": "An active direct child workspace." - }, - "ListWorkspaceForkChildrenResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace fork children response", - "description": "A page of active direct child workspaces." - }, - "ListWorkspaceForkResourcesResult": { - "type": "object", - "properties": { - "id": { - "type": "string", - "maxLength": 4096, - "description": "Resource identifier." - }, - "label": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable resource label." - }, - "folderId": { - "description": "Containing folder identifier, or null at the workspace root.", - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "folderName": { - "description": "Containing folder name, or null at the workspace root.", - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - } - }, - "required": ["id", "label"], - "additionalProperties": false, - "title": "List workspace fork resources result", - "description": "A copyable resource candidate." - }, - "ListWorkspaceForkResourcesResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace fork resources response", - "description": "A page of copyable resource candidates." - }, - "GetWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - }, - "id": { - "type": "string", - "maxLength": 256, - "description": "Resource identifier." - } - }, - "required": ["resourceType", "sourceId", "targetId", "id"], - "additionalProperties": false, - "title": "Get workspace fork mappings result", - "description": "A saved directional mapping entry." - }, - "GetWorkspaceForkMappingsResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "Get workspace fork mappings response", - "description": "A page of persisted source-to-target mapping entries." - }, - "UpdateWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork mappings result", - "description": "Count of changed mapping records." - }, - "UpdateWorkspaceForkMappingsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Update workspace fork mappings response", - "description": "Number of mapping records changed." - }, - "UpdateWorkspaceForkMappingsBody": { + "PreviewWorkspacePushBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23535,12 +23425,8 @@ "maxLength": 128, "description": "Workspace on the other side of the direct fork edge." }, - "direction": { - "type": "string", - "enum": ["push", "pull"], - "description": "Push means current to other; pull means other to current, independent of parent/child orientation." - }, "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", "maxItems": 5000, "type": "array", "items": { @@ -23586,71 +23472,209 @@ }, "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false - }, - "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." - } - }, - "required": ["otherWorkspaceId", "direction", "mappings"], - "additionalProperties": false, - "title": "Update workspace fork mappings request", - "description": "Other workspace, direction, and mapping entries to update." - }, - "RollbackWorkspaceForkResult": { - "type": "object", - "properties": { - "restored": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows restored to their prior deployed version." + } }, - "archived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows created by the sync and now archived." + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } }, - "unarchived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Previously archived workflows restored by rollback." + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false }, - "skipped": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Snapshot workflows no longer available to restore." + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false + } }, - "pendingActivations": { - "maxItems": 1000, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, "type": "array", "items": { - "type": "string", - "maxLength": 256 - }, - "description": "Workflows whose restored deployment is still activating." + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." + }, + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "additionalProperties": false + } } }, - "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], + "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "Rollback workspace fork result", - "description": "Workflow restoration and pending-activation counts." + "title": "Preview workspace push request", + "description": "Other workspace and proposed source-to-target sync choices." }, - "RollbackWorkspaceForkResponse": { + "PushWorkspaceResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/RollbackWorkspaceForkResult" + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, "required": ["data"], "additionalProperties": false, - "title": "Rollback workspace fork response", - "description": "Restored, archived, skipped, and still-activating workflow counts." + "title": "Push workspace response", + "description": "Committed push receipt with copy and deployment readiness.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "push-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_push", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } + } + ] }, - "RollbackWorkspaceForkBody": { + "PushWorkspaceBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23658,152 +23682,43 @@ "minLength": 1, "maxLength": 128, "description": "Workspace on the other side of the direct fork edge." - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Rollback workspace fork request", - "description": "Other workspace whose latest inbound sync should be undone." - }, - "UnlinkWorkspaceForkResult": { - "type": "object", - "properties": { - "unlinked": { - "type": "boolean", - "description": "Whether the fork edge was removed." - } - }, - "required": ["unlinked"], - "additionalProperties": false, - "title": "Unlink workspace fork result", - "description": "Fork-edge removal acknowledgment." - }, - "UnlinkWorkspaceForkResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Unlink workspace fork response", - "description": "Confirmation that the relationship was removed." - }, - "UnlinkWorkspaceForkBody": { - "type": "object", - "properties": { - "otherWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Unlink workspace fork request", - "description": "Other workspace on the direct fork edge to remove." - }, - "UpdateWorkspaceForkExclusionsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork exclusions result", - "description": "Count of changed workflow exclusion flags." - }, - "UpdateWorkspaceForkExclusionsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Update workspace fork exclusions response", - "description": "Number of workflow exclusion flags changed." - }, - "UpdateWorkspaceForkExclusionsBody": { - "type": "object", - "properties": { - "workflowIds": { - "minItems": 1, - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "description": "Workflow identifiers in the current workspace." - }, - "forkSyncExcluded": { - "type": "boolean", - "description": "Whether the named workflows should be skipped as sync sources and targets." - } - }, - "required": ["workflowIds", "forkSyncExcluded"], - "additionalProperties": false, - "title": "Update workspace fork exclusions request", - "description": "Workflow IDs and whether to exclude them from sync." - }, - "PreviewWorkflowImportResult": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "minLength": 64, - "maxLength": 64, - "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." }, - "ready": { - "type": "boolean", - "description": "Whether every required destination binding and configuration field is resolved for import." - }, - "bindings": { - "maxItems": 10000, + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "resourceType": { "type": "string", "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", + "oauth_credential", + "service_account_credential", + "env_var", "table", + "knowledge_base", "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", "skill", - "sandbox", - "workflow" + "sandbox" ], - "description": "Resource or operation kind." + "description": "Resource type stored on the canonical parent/child edge." }, "sourceId": { "type": "string", + "minLength": 1, "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + "description": "Source resource identifier in the canonical source workspace." }, "targetId": { "anyOf": [ { "type": "string", + "minLength": 1, "maxLength": 4096 }, { @@ -23811,453 +23726,277 @@ } ], "description": "Authorized destination identifier, or null to clear the mapping." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "occurrence": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "maxItems": 8, - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - }, - "encoding": { - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - } - }, - "required": ["blockId", "subBlockKey", "valuePath", "encoding"], - "additionalProperties": false, - "description": "Registered source field occurrence addressed by this binding." } }, - "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false - }, - "description": "Resolved and unresolved source occurrences with their destination selections." + } }, - "unresolvedBindings": { - "maxItems": 10000, + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "sourceWorkflowId": { "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox", - "workflow" - ], - "description": "Resource or operation kind." + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - "sourceId": { + "sourceBlockId": { "type": "string", - "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." }, - "occurrence": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "maxItems": 8, - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - }, - "encoding": { - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - } - }, - "required": ["blockId", "subBlockKey", "valuePath", "encoding"], - "additionalProperties": false, - "description": "Registered source field occurrence addressed by this binding." + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." } }, - "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], "additionalProperties": false - }, - "description": "Source references that still require destination mappings or explicit copy choices." + } }, - "configuration": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "blockId": { + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "configured": { - "type": "boolean", - "description": "Whether this destination field currently has a nonempty value." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s destination options.", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "maxLength": 256 - }, - "context": { - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - }, - "description": "Allowlisted selector dependencies scoped to the destination workspace." - }, - "requiresAuthentication": { - "type": "boolean", - "description": "Whether a human must connect the provider before choices can be discovered." + "minLength": 1 } }, - "required": [ - "blockId", - "subBlockKey", - "title", - "required", - "configured", - "context", - "requiresAuthentication" - ], - "additionalProperties": false + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } }, - "description": "Dependent fields that may need destination-specific values." + "additionalProperties": false }, - "unresolvedConfiguration": { - "maxItems": 10000, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "blockId": { + "kind": { "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." }, - "subBlockKey": { + "sourceId": { "type": "string", "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "configured": { - "type": "boolean", - "description": "Whether this destination field currently has a nonempty value." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s destination options.", - "type": "string", - "maxLength": 256 - }, - "context": { - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - }, - "description": "Allowlisted selector dependencies scoped to the destination workspace." - }, - "requiresAuthentication": { - "type": "boolean", - "description": "Whether a human must connect the provider before choices can be discovered." + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." } }, - "required": [ - "blockId", - "subBlockKey", - "title", - "required", - "configured", - "context", - "requiresAuthentication" - ], + "required": ["kind", "sourceId"], "additionalProperties": false - }, - "description": "Required destination configuration that remains empty." + } }, - "discovery": { - "maxItems": 32, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "sourceWorkflowId": { "type": "string", - "maxLength": 256, - "description": "Resource or operation kind." + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - "command": { + "sourceBlockId": { "type": "string", - "maxLength": 1024, - "description": "CLI command to enumerate destination candidates." + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." }, - "humanAuthorizationMayBeRequired": { - "type": "boolean", - "description": "Whether discovery may require a human OAuth authorization step." - } + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." + } }, - "required": ["kind", "command", "humanAuthorizationMayBeRequired"], + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], "additionalProperties": false - }, - "description": "CLI operations for discovering suitable destination resources." + } + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "confirm": { + "type": "boolean", + "const": true, + "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." } }, - "required": [ - "previewFingerprint", - "ready", - "bindings", - "unresolvedBindings", - "configuration", - "unresolvedConfiguration", - "discovery" - ], + "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], "additionalProperties": false, - "title": "Workflow import preview", - "description": "Import readiness, unresolved bindings, and destination discovery instructions." + "title": "Push workspace request", + "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", + "examples": [ + { + "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "requestId": "push-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "confirm": true + } + ] }, - "PreviewWorkflowImportResponse": { + "PreviewWorkspacePullResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/PreviewWorkflowImportResult" + "$ref": "#/components/schemas/WorkspaceSyncPreview" } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workflow import response", - "description": "Import readiness, unresolved bindings, and destination discovery instructions.", + "title": "Preview workspace pull response", + "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", "examples": [ { "data": { "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", "ready": true, - "bindings": [], + "workflows": [], "unresolvedBindings": [], "configuration": [], - "unresolvedConfiguration": [], - "discovery": [] + "excludedTargets": [], + "triggerSlots": [], + "triggerUrlChanges": [] } } ] }, - "ImportWorkflowRequest": { + "PreviewWorkspacePullBody": { "type": "object", "properties": { - "workspaceId": { + "otherWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Workspace in which to import the workflow." - }, - "workflow": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "description": "JSON string containing a workflow export object or bare workflow state." - }, - { - "type": "object", - "additionalProperties": true, - "description": "Workflow export object or bare workflow state." - } - ], - "description": "Workflow export object, bare workflow state, or JSON string containing either form." - }, - "folderPath": { - "description": "Destination folder path; omit for the workspace root.", - "$ref": "#/components/schemas/FolderPathInput" - }, - "name": { - "description": "Override for the imported workflow name.", - "type": "string", - "minLength": 1, - "maxLength": 200 - }, - "description": { - "description": "Override for the imported workflow description.", - "type": "string", - "maxLength": 2000 + "description": "Workspace on the other side of the direct fork edge." }, "mappings": { - "description": "Mapping entries addressed by resource kind and source identifier.", + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", "maxItems": 5000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "resourceType": { "type": "string", "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", + "oauth_credential", + "service_account_credential", + "env_var", "table", + "knowledge_base", "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", "skill", - "sandbox", - "workflow" + "sandbox" ], - "description": "Resource or operation kind." + "description": "Resource type stored on the canonical parent/child edge." }, "sourceId": { "type": "string", "minLength": 1, "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + "description": "Source resource identifier in the canonical source workspace." }, "targetId": { "anyOf": [ @@ -24273,659 +24012,3280 @@ "description": "Authorized destination identifier, or null to clear the mapping." } }, - "required": ["kind", "sourceId", "targetId"], + "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false } }, - "bindings": { - "description": "Resolved and unresolved source occurrences with their destination selections.", - "maxItems": 5000, + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { + "sourceWorkflowId": { "type": "string", "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "default": [], - "maxItems": 8, - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - }, - "encoding": { - "default": "scalar", - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - }, - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox", - "workflow" - ], - "description": "Resource or operation kind." + "description": "Workflow identifier in the source workspace." }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["blockId", "subBlockKey", "kind", "targetId"], - "additionalProperties": false - } - }, - "dependentValues": { - "description": "Destination-specific values addressed by the source block ID and field key, before imported IDs are regenerated.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "blockId": { + "sourceBlockId": { "type": "string", "minLength": 1, "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." + "description": "Block identifier in the source workflow." }, "subBlockKey": { "type": "string", "minLength": 1, - "maxLength": 256, + "maxLength": 1024, "description": "Registered source field key, including the tool index for nested Agent fields." }, "value": { "type": "string", - "maxLength": 16384, + "maxLength": 65536, "description": "Destination value for the registered dependent field." } }, - "required": ["blockId", "subBlockKey", "value"], + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], "additionalProperties": false } - } - }, - "required": ["workspaceId", "workflow"], - "additionalProperties": false, - "title": "Import workflow request", - "description": "Portable workflow data and destination metadata for an import." - }, - "SelectorOption": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Provider resource identifier." - }, - "label": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Human-readable provider resource name." }, - "meta": { - "description": "Safe scalar metadata for presenting or configuring this choice.", + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 128 + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } }, - "additionalProperties": { - "anyOf": [ - { + "additionalProperties": false + }, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { "type": "string", - "maxLength": 16384 + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." }, - { - "type": "number" + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false + } + }, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - { - "type": "boolean" + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." }, - { - "type": "null" + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." } - ] + }, + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "additionalProperties": false } } }, - "required": ["id", "label"], + "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "SelectorOption", - "description": "The SelectorOption result." + "title": "Preview workspace pull request", + "description": "Other workspace and proposed source-to-target sync choices." }, - "ListSelectorResponse": { + "PullWorkspaceResponse": { "type": "object", "properties": { "data": { - "maxItems": 100, - "type": "array", - "items": { - "$ref": "#/components/schemas/SelectorOption" - }, - "description": "Authorized provider options in this page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string", - "maxLength": 32768 - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; null means there is nothing further to fetch. Never construct one yourself." - }, - "truncated": { - "type": "boolean", - "description": "Whether provider limits left the result incomplete. A null `nextCursor` with `truncated: true` does not establish that all options were searched." + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, - "required": ["data", "nextCursor", "truncated"], + "required": ["data"], "additionalProperties": false, - "title": "List selector response", - "description": "A page of authorized options, continuation cursor, and truncation status." + "title": "Pull workspace response", + "description": "Committed pull receipt with copy and deployment readiness.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "pull-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_pull", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } + } + ] }, - "ListSelectorBody": { + "PullWorkspaceBody": { "type": "object", "properties": { - "workspaceId": { + "otherWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Explicit current workspace scope." + "description": "Workspace on the other side of the direct fork edge." }, - "selectorKey": { - "type": "string", - "enum": [ - "airtable.bases", - "airtable.tables", - "asana.workspaces", - "attio.lists", - "attio.objects", - "bigquery.datasets", - "bigquery.tables", - "bitbucket.workspaces", - "bitbucket.repositories", - "calcom.eventTypes", - "calcom.schedules", - "clickup.workspaces", - "clickup.spaces", - "clickup.folders", - "clickup.lists", - "coda.docs", - "coda.pages", - "coda.tables", - "coda.columns", - "coda.rows", - "coda.formulas", - "coda.controls", - "coda.folders", - "coda.permissions", - "confluence.spaces", - "confluence.spacesById", - "confluence.pages", - "google.tasks.lists", - "gauge.organizations", - "gauge.categories", - "gauge.topics", - "gauge.prompts", - "gauge.tags", - "gauge.answers", - "fivetran.groups", - "fivetran.connections", - "gmail.labels", - "google.calendar", - "google.drive", - "google.sheets", - "harmonic.savedSearches", - "jama.projects", - "jama.itemTypes", - "flow.projects", - "flow.categories", - "flow.branches", - "helpscout.mailboxes", - "helpscout.assignees", - "hubspot.lists", - "hubspot.owners", - "hubspot.pipelines", - "hubspot.pipelineStages", - "hubspot.properties", - "jsm.requestTypes", - "jsm.serviceDesks", - "microsoft.planner.plans", - "notion.databases", - "notion.pages", - "netsuite.recordTypes", - "netsuite.asyncTasks", - "pipedrive.pipelines", - "sharepoint.lists", - "trello.boards", - "zoho_desk.organizations", - "zoho_desk.departments", - "zoho_desk.agents", - "zoom.meetings", - "slack.channels", - "snowflake.databases", - "snowflake.schemas", - "snowflake.tables", - "snowflake.warehouses", - "snowflake.roles", - "snowflake.fileFormats", - "snowflake.procedures", - "slack.users", - "outlook.folders", - "outlook.calendars", - "microsoft.teams", - "microsoft.chats", - "microsoft.channels", - "microsoft.planner", - "onedrive.files", - "onedrive.folders", - "sharepoint.sites", - "microsoft.excel", - "microsoft.excel.drives", - "microsoft.excel.sheets", - "microsoft.word", - "wealthbox.contacts", - "jira.issues", - "jira.projects", - "jira.projectKeys", - "linear.projects", - "linear.teams", - "monday.boards", - "monday.groups", - "webflow.sites", - "webflow.collections", - "webflow.items", - "planetscale.databases", - "powerbi.workspaces", - "powerbi.datasets", - "powerbi.reports", - "planetscale.branches", - "planetscale.backups", - "planetscale.deployRequests", - "planetscale.savedDatabases", - "planetscale.savedBranches", - "planetscale.savedBackups", - "planetscale.savedDeployRequests", - "cloudwatch.logGroups", - "cloudwatch.logStreams", - "cloudwatch.savedLogGroups", - "cloudwatch.savedLogStreams", - "imap.mailboxes", - "mcp.tools", - "managedAgent.agents", - "managedAgent.environments", - "managedAgent.vaults", - "managedAgent.memoryStores", - "knowledge.documents", - "sim.workflows", - "table.columns", - "table.outputColumns", - "workspace.secretNames", - "workspace.sandboxes", - "providers.ollamaEmbeddingModels", - "providers.openrouterEmbeddingModels" - ], - "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." - }, - "context": { - "default": {}, - "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false } }, - "search": { - "description": "Provider option search text.", - "type": "string", - "minLength": 1, - "maxLength": 1024 - }, - "cursor": { - "description": "Cursor returned by the preceding page. Keep `workspaceId`, `selectorKey`, `context`, and `search` unchanged; only `limit` may change. Restart without a cursor after a changed-page 409.", - "type": "string", - "minLength": 1, - "maxLength": 32768 - }, - "limit": { - "default": 50, - "description": "Maximum options per page, from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 - } - }, - "required": ["workspaceId", "selectorKey"], - "additionalProperties": false, - "title": "List selector request", - "description": "Workspace, registered selector key, context, and optional search/cursor." - }, - "GetSelectorResponse": { - "type": "object", - "properties": { - "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/SelectorOption" + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." + } }, - { - "type": "null" - } - ], - "description": "Response data." - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get selector response", - "description": "The authorized option, or data:null when absent from complete results." - }, - "GetSelectorBody": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } }, - "selectorKey": { - "type": "string", - "enum": [ - "airtable.bases", - "airtable.tables", - "asana.workspaces", - "attio.lists", - "attio.objects", - "bigquery.datasets", - "bigquery.tables", - "bitbucket.workspaces", - "bitbucket.repositories", - "calcom.eventTypes", - "calcom.schedules", - "clickup.workspaces", - "clickup.spaces", - "clickup.folders", - "clickup.lists", - "coda.docs", - "coda.pages", - "coda.tables", - "coda.columns", - "coda.rows", - "coda.formulas", - "coda.controls", - "coda.folders", - "coda.permissions", - "confluence.spaces", - "confluence.spacesById", - "confluence.pages", - "google.tasks.lists", - "gauge.organizations", - "gauge.categories", - "gauge.topics", - "gauge.prompts", - "gauge.tags", - "gauge.answers", - "fivetran.groups", - "fivetran.connections", - "gmail.labels", - "google.calendar", - "google.drive", - "google.sheets", - "harmonic.savedSearches", - "jama.projects", - "jama.itemTypes", - "flow.projects", - "flow.categories", - "flow.branches", - "helpscout.mailboxes", - "helpscout.assignees", - "hubspot.lists", - "hubspot.owners", - "hubspot.pipelines", - "hubspot.pipelineStages", - "hubspot.properties", - "jsm.requestTypes", - "jsm.serviceDesks", - "microsoft.planner.plans", - "notion.databases", - "notion.pages", - "netsuite.recordTypes", - "netsuite.asyncTasks", - "pipedrive.pipelines", - "sharepoint.lists", - "trello.boards", - "zoho_desk.organizations", - "zoho_desk.departments", - "zoho_desk.agents", - "zoom.meetings", - "slack.channels", - "snowflake.databases", - "snowflake.schemas", - "snowflake.tables", - "snowflake.warehouses", - "snowflake.roles", - "snowflake.fileFormats", - "snowflake.procedures", - "slack.users", - "outlook.folders", - "outlook.calendars", - "microsoft.teams", - "microsoft.chats", - "microsoft.channels", - "microsoft.planner", - "onedrive.files", - "onedrive.folders", - "sharepoint.sites", - "microsoft.excel", - "microsoft.excel.drives", - "microsoft.excel.sheets", - "microsoft.word", - "wealthbox.contacts", - "jira.issues", - "jira.projects", - "jira.projectKeys", - "linear.projects", - "linear.teams", - "monday.boards", - "monday.groups", - "webflow.sites", - "webflow.collections", - "webflow.items", - "planetscale.databases", - "powerbi.workspaces", - "powerbi.datasets", - "powerbi.reports", - "planetscale.branches", - "planetscale.backups", - "planetscale.deployRequests", - "planetscale.savedDatabases", - "planetscale.savedBranches", - "planetscale.savedBackups", - "planetscale.savedDeployRequests", - "cloudwatch.logGroups", - "cloudwatch.logStreams", - "cloudwatch.savedLogGroups", - "cloudwatch.savedLogStreams", - "imap.mailboxes", - "mcp.tools", - "managedAgent.agents", - "managedAgent.environments", - "managedAgent.vaults", - "managedAgent.memoryStores", - "knowledge.documents", - "sim.workflows", - "table.columns", - "table.outputColumns", - "workspace.secretNames", - "workspace.sandboxes", - "providers.ollamaEmbeddingModels", - "providers.openrouterEmbeddingModels" - ], - "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." - }, - "context": { - "default": {}, - "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - } - }, - "id": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Provider option ID to resolve with the same selector and declared context." - } - }, - "required": ["workspaceId", "selectorKey", "id"], - "additionalProperties": false, - "title": "Get selector request", - "description": "Workspace, registered selector key, context, and provider option ID." - }, - "GetWorkspaceOperationResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get workspace operation response", - "description": "Refreshed commit, copy progress, and exact deployment readiness." - }, - "ListWorkspaceOperationsResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/WorkspaceOperationReport" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace operations response", - "description": "A page of stored operation receipts." - }, - "GetWorkspaceSourceResponse": { - "type": "object", - "properties": { - "data": { + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", "type": "object", "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "kinds": { + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, "type": "array", "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false + }, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": [ - "secret", "credential", - "custom-tool", - "skill", - "mcp-server", - "table", + "env-var", "knowledge-base", + "knowledge-document", + "table", "file", - "workflow", - "deployment" + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false + } + }, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." + }, + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "additionalProperties": false + } + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "confirm": { + "type": "boolean", + "const": true, + "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." + } + }, + "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], + "additionalProperties": false, + "title": "Pull workspace request", + "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", + "examples": [ + { + "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "requestId": "pull-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "confirm": true + } + ] + }, + "GetWorkspaceForkAvailabilityResult": { + "type": "object", + "properties": { + "available": { + "type": "boolean", + "description": "Whether this deployment and workspace plan enable forking." + } + }, + "required": ["available"], + "additionalProperties": false, + "title": "Get workspace fork availability result", + "description": "Fork feature availability for this workspace." + }, + "GetWorkspaceForkAvailabilityResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace fork availability response", + "description": "Whether forking is enabled for this deployment and workspace plan." + }, + "GetWorkspaceForkLineageResult": { + "type": "object", + "properties": { + "current": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." + } + }, + "required": ["id", "name", "organizationId"], + "additionalProperties": false, + "description": "The current workspace lineage node." + }, + "parent": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." + } + }, + "required": ["id", "name", "organizationId"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "The live parent workspace, or null when this workspace is not a fork." + } + }, + "required": ["current", "parent"], + "additionalProperties": false, + "title": "Get workspace fork lineage result", + "description": "Current workspace and its active parent." + }, + "GetWorkspaceForkLineageResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace fork lineage response", + "description": "Current workspace and its active direct parent, when present." + }, + "ListWorkspaceForkChildrenResult": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "ISO 8601 creation timestamp." + } + }, + "required": ["id", "name", "organizationId", "createdAt"], + "additionalProperties": false, + "title": "List workspace fork children result", + "description": "An active direct child workspace." + }, + "ListWorkspaceForkChildrenResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace fork children response", + "description": "A page of active direct child workspaces." + }, + "ListWorkspaceForkResourcesResult": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 4096, + "description": "Resource identifier." + }, + "label": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable resource label." + }, + "folderId": { + "description": "Containing folder identifier, or null at the workspace root.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "folderName": { + "description": "Containing folder name, or null at the workspace root.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": ["id", "label"], + "additionalProperties": false, + "title": "List workspace fork resources result", + "description": "A copyable resource candidate." + }, + "ListWorkspaceForkResourcesResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace fork resources response", + "description": "A page of copyable resource candidates." + }, + "GetWorkspaceForkMappingsResult": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "id": { + "type": "string", + "maxLength": 256, + "description": "Resource identifier." + } + }, + "required": ["resourceType", "sourceId", "targetId", "id"], + "additionalProperties": false, + "title": "Get workspace fork mappings result", + "description": "A saved directional mapping entry." + }, + "GetWorkspaceForkMappingsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "Get workspace fork mappings response", + "description": "A page of persisted source-to-target mapping entries." + }, + "UpdateWorkspaceForkMappingsResult": { + "type": "object", + "properties": { + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." + } + }, + "required": ["updated"], + "additionalProperties": false, + "title": "Update workspace fork mappings result", + "description": "Count of changed mapping records." + }, + "UpdateWorkspaceForkMappingsResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Update workspace fork mappings response", + "description": "Number of mapping records changed." + }, + "UpdateWorkspaceForkMappingsBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + }, + "direction": { + "type": "string", + "enum": ["push", "pull"], + "description": "Push means current to other; pull means other to current, independent of parent/child orientation." + }, + "mappings": { + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false + }, + "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." + } + }, + "required": ["otherWorkspaceId", "direction", "mappings"], + "additionalProperties": false, + "title": "Update workspace fork mappings request", + "description": "Other workspace, direction, and mapping entries to update." + }, + "RollbackWorkspaceForkResult": { + "type": "object", + "properties": { + "restored": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows restored to their prior deployed version." + }, + "archived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows created by the sync and now archived." + }, + "unarchived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Previously archived workflows restored by rollback." + }, + "skipped": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Snapshot workflows no longer available to restore." + }, + "pendingActivations": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + }, + "description": "Workflows whose restored deployment is still activating." + } + }, + "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], + "additionalProperties": false, + "title": "Rollback workspace fork result", + "description": "Workflow restoration and pending-activation counts." + }, + "RollbackWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/RollbackWorkspaceForkResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Rollback workspace fork response", + "description": "Restored, archived, skipped, and still-activating workflow counts." + }, + "RollbackWorkspaceForkBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + } + }, + "required": ["otherWorkspaceId"], + "additionalProperties": false, + "title": "Rollback workspace fork request", + "description": "Other workspace whose latest inbound sync should be undone." + }, + "UnlinkWorkspaceForkResult": { + "type": "object", + "properties": { + "unlinked": { + "type": "boolean", + "description": "Whether the fork edge was removed." + } + }, + "required": ["unlinked"], + "additionalProperties": false, + "title": "Unlink workspace fork result", + "description": "Fork-edge removal acknowledgment." + }, + "UnlinkWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Unlink workspace fork response", + "description": "Confirmation that the relationship was removed." + }, + "UnlinkWorkspaceForkBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + } + }, + "required": ["otherWorkspaceId"], + "additionalProperties": false, + "title": "Unlink workspace fork request", + "description": "Other workspace on the direct fork edge to remove." + }, + "UpdateWorkspaceForkExclusionsResult": { + "type": "object", + "properties": { + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." + } + }, + "required": ["updated"], + "additionalProperties": false, + "title": "Update workspace fork exclusions result", + "description": "Count of changed workflow exclusion flags." + }, + "UpdateWorkspaceForkExclusionsResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Update workspace fork exclusions response", + "description": "Number of workflow exclusion flags changed." + }, + "UpdateWorkspaceForkExclusionsBody": { + "type": "object", + "properties": { + "workflowIds": { + "minItems": 1, + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "Workflow identifiers in the current workspace." + }, + "forkSyncExcluded": { + "type": "boolean", + "description": "Whether the named workflows should be skipped as sync sources and targets." + } + }, + "required": ["workflowIds", "forkSyncExcluded"], + "additionalProperties": false, + "title": "Update workspace fork exclusions request", + "description": "Workflow IDs and whether to exclude them from sync." + }, + "PreviewWorkflowImportResult": { + "type": "object", + "properties": { + "previewFingerprint": { + "type": "string", + "minLength": 64, + "maxLength": 64, + "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." + }, + "ready": { + "type": "boolean", + "description": "Whether every required destination binding and configuration field is resolved for import." + }, + "bindings": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "occurrence": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + } + }, + "required": ["blockId", "subBlockKey", "valuePath", "encoding"], + "additionalProperties": false, + "description": "Registered source field occurrence addressed by this binding." + } + }, + "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "additionalProperties": false + }, + "description": "Resolved and unresolved source occurrences with their destination selections." + }, + "unresolvedBindings": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "occurrence": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + } + }, + "required": ["blockId", "subBlockKey", "valuePath", "encoding"], + "additionalProperties": false, + "description": "Registered source field occurrence addressed by this binding." + } + }, + "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "additionalProperties": false + }, + "description": "Source references that still require destination mappings or explicit copy choices." + }, + "configuration": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "configured": { + "type": "boolean", + "description": "Whether this destination field currently has a nonempty value." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s destination options.", + "type": "string", + "maxLength": 256 + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + }, + "description": "Allowlisted selector dependencies scoped to the destination workspace." + }, + "requiresAuthentication": { + "type": "boolean", + "description": "Whether a human must connect the provider before choices can be discovered." + } + }, + "required": [ + "blockId", + "subBlockKey", + "title", + "required", + "configured", + "context", + "requiresAuthentication" + ], + "additionalProperties": false + }, + "description": "Dependent fields that may need destination-specific values." + }, + "unresolvedConfiguration": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "configured": { + "type": "boolean", + "description": "Whether this destination field currently has a nonempty value." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s destination options.", + "type": "string", + "maxLength": 256 + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + }, + "description": "Allowlisted selector dependencies scoped to the destination workspace." + }, + "requiresAuthentication": { + "type": "boolean", + "description": "Whether a human must connect the provider before choices can be discovered." + } + }, + "required": [ + "blockId", + "subBlockKey", + "title", + "required", + "configured", + "context", + "requiresAuthentication" + ], + "additionalProperties": false + }, + "description": "Required destination configuration that remains empty." + }, + "discovery": { + "maxItems": 32, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "maxLength": 256, + "description": "Resource or operation kind." + }, + "command": { + "type": "string", + "maxLength": 1024, + "description": "CLI command to enumerate destination candidates." + }, + "humanAuthorizationMayBeRequired": { + "type": "boolean", + "description": "Whether discovery may require a human OAuth authorization step." + } + }, + "required": ["kind", "command", "humanAuthorizationMayBeRequired"], + "additionalProperties": false + }, + "description": "CLI operations for discovering suitable destination resources." + } + }, + "required": [ + "previewFingerprint", + "ready", + "bindings", + "unresolvedBindings", + "configuration", + "unresolvedConfiguration", + "discovery" + ], + "additionalProperties": false, + "title": "Workflow import preview", + "description": "Import readiness, unresolved bindings, and destination discovery instructions." + }, + "PreviewWorkflowImportResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/PreviewWorkflowImportResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workflow import response", + "description": "Import readiness, unresolved bindings, and destination discovery instructions.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "ready": true, + "bindings": [], + "unresolvedBindings": [], + "configuration": [], + "unresolvedConfiguration": [], + "discovery": [] + } + } + ] + }, + "ImportWorkflowRequest": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace in which to import the workflow." + }, + "workflow": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "description": "JSON string containing a workflow export object or bare workflow state." + }, + { + "type": "object", + "additionalProperties": true, + "description": "Workflow export object or bare workflow state." + } + ], + "description": "Workflow export object, bare workflow state, or JSON string containing either form." + }, + "folderPath": { + "description": "Destination folder path; omit for the workspace root.", + "$ref": "#/components/schemas/FolderPathInput" + }, + "name": { + "description": "Override for the imported workflow name.", + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "description": { + "description": "Override for the imported workflow description.", + "type": "string", + "maxLength": 2000 + }, + "mappings": { + "description": "Mapping entries addressed by resource kind and source identifier.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["kind", "sourceId", "targetId"], + "additionalProperties": false + } + }, + "bindings": { + "description": "Resolved and unresolved source occurrences with their destination selections.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "default": [], + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "default": "scalar", + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + }, + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["blockId", "subBlockKey", "kind", "targetId"], + "additionalProperties": false + } + }, + "dependentValues": { + "description": "Destination-specific values addressed by the source block ID and field key, before imported IDs are regenerated.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 16384, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["blockId", "subBlockKey", "value"], + "additionalProperties": false + } + } + }, + "required": ["workspaceId", "workflow"], + "additionalProperties": false, + "title": "Import workflow request", + "description": "Portable workflow data and destination metadata for an import." + }, + "SelectorOption": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Provider resource identifier." + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Human-readable provider resource name." + }, + "meta": { + "description": "Safe scalar metadata for presenting or configuring this choice.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "maxLength": 16384 + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + } + }, + "required": ["id", "label"], + "additionalProperties": false, + "title": "SelectorOption", + "description": "The SelectorOption result." + }, + "ListSelectorResponse": { + "type": "object", + "properties": { + "data": { + "maxItems": 100, + "type": "array", + "items": { + "$ref": "#/components/schemas/SelectorOption" + }, + "description": "Authorized provider options in this page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string", + "maxLength": 32768 + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; null means there is nothing further to fetch. Never construct one yourself." + }, + "truncated": { + "type": "boolean", + "description": "Whether provider limits left the result incomplete. A null `nextCursor` with `truncated: true` does not establish that all options were searched." + } + }, + "required": ["data", "nextCursor", "truncated"], + "additionalProperties": false, + "title": "List selector response", + "description": "A page of authorized options, continuation cursor, and truncation status." + }, + "ListSelectorBody": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "selectorKey": { + "type": "string", + "enum": [ + "airtable.bases", + "airtable.tables", + "asana.workspaces", + "attio.lists", + "attio.objects", + "bigquery.datasets", + "bigquery.tables", + "bitbucket.workspaces", + "bitbucket.repositories", + "calcom.eventTypes", + "calcom.schedules", + "clickup.workspaces", + "clickup.spaces", + "clickup.folders", + "clickup.lists", + "coda.docs", + "coda.pages", + "coda.tables", + "coda.columns", + "coda.rows", + "coda.formulas", + "coda.controls", + "coda.folders", + "coda.permissions", + "confluence.spaces", + "confluence.spacesById", + "confluence.pages", + "google.tasks.lists", + "gauge.organizations", + "gauge.categories", + "gauge.topics", + "gauge.prompts", + "gauge.tags", + "gauge.answers", + "fivetran.groups", + "fivetran.connections", + "gmail.labels", + "google.calendar", + "google.drive", + "google.sheets", + "harmonic.savedSearches", + "jama.projects", + "jama.itemTypes", + "flow.projects", + "flow.categories", + "flow.branches", + "helpscout.mailboxes", + "helpscout.assignees", + "hubspot.lists", + "hubspot.owners", + "hubspot.pipelines", + "hubspot.pipelineStages", + "hubspot.properties", + "jsm.requestTypes", + "jsm.serviceDesks", + "microsoft.planner.plans", + "notion.databases", + "notion.pages", + "netsuite.recordTypes", + "netsuite.asyncTasks", + "pipedrive.pipelines", + "sharepoint.lists", + "trello.boards", + "zoho_desk.organizations", + "zoho_desk.departments", + "zoho_desk.agents", + "zoom.meetings", + "slack.channels", + "snowflake.databases", + "snowflake.schemas", + "snowflake.tables", + "snowflake.warehouses", + "snowflake.roles", + "snowflake.fileFormats", + "snowflake.procedures", + "slack.users", + "outlook.folders", + "outlook.calendars", + "microsoft.teams", + "microsoft.chats", + "microsoft.channels", + "microsoft.planner", + "onedrive.files", + "onedrive.folders", + "sharepoint.sites", + "microsoft.excel", + "microsoft.excel.drives", + "microsoft.excel.sheets", + "microsoft.word", + "wealthbox.contacts", + "jira.issues", + "jira.projects", + "jira.projectKeys", + "linear.projects", + "linear.teams", + "monday.boards", + "monday.groups", + "webflow.sites", + "webflow.collections", + "webflow.items", + "planetscale.databases", + "powerbi.workspaces", + "powerbi.datasets", + "powerbi.reports", + "planetscale.branches", + "planetscale.backups", + "planetscale.deployRequests", + "planetscale.savedDatabases", + "planetscale.savedBranches", + "planetscale.savedBackups", + "planetscale.savedDeployRequests", + "cloudwatch.logGroups", + "cloudwatch.logStreams", + "cloudwatch.savedLogGroups", + "cloudwatch.savedLogStreams", + "imap.mailboxes", + "mcp.tools", + "managedAgent.agents", + "managedAgent.environments", + "managedAgent.vaults", + "managedAgent.memoryStores", + "knowledge.documents", + "sim.workflows", + "table.columns", + "table.outputColumns", + "workspace.secretNames", + "workspace.sandboxes", + "providers.ollamaEmbeddingModels", + "providers.openrouterEmbeddingModels" + ], + "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + }, + "context": { + "default": {}, + "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + } + }, + "search": { + "description": "Provider option search text.", + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "cursor": { + "description": "Cursor returned by the preceding page. Keep `workspaceId`, `selectorKey`, `context`, and `search` unchanged; only `limit` may change. Restart without a cursor after a changed-page 409.", + "type": "string", + "minLength": 1, + "maxLength": 32768 + }, + "limit": { + "default": 50, + "description": "Maximum options per page, from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": ["workspaceId", "selectorKey"], + "additionalProperties": false, + "title": "List selector request", + "description": "Workspace, registered selector key, context, and optional search/cursor." + }, + "GetSelectorResponse": { + "type": "object", + "properties": { + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/SelectorOption" + }, + { + "type": "null" + } + ], + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get selector response", + "description": "The authorized option, or data:null when absent from complete results." + }, + "GetSelectorBody": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "selectorKey": { + "type": "string", + "enum": [ + "airtable.bases", + "airtable.tables", + "asana.workspaces", + "attio.lists", + "attio.objects", + "bigquery.datasets", + "bigquery.tables", + "bitbucket.workspaces", + "bitbucket.repositories", + "calcom.eventTypes", + "calcom.schedules", + "clickup.workspaces", + "clickup.spaces", + "clickup.folders", + "clickup.lists", + "coda.docs", + "coda.pages", + "coda.tables", + "coda.columns", + "coda.rows", + "coda.formulas", + "coda.controls", + "coda.folders", + "coda.permissions", + "confluence.spaces", + "confluence.spacesById", + "confluence.pages", + "google.tasks.lists", + "gauge.organizations", + "gauge.categories", + "gauge.topics", + "gauge.prompts", + "gauge.tags", + "gauge.answers", + "fivetran.groups", + "fivetran.connections", + "gmail.labels", + "google.calendar", + "google.drive", + "google.sheets", + "harmonic.savedSearches", + "jama.projects", + "jama.itemTypes", + "flow.projects", + "flow.categories", + "flow.branches", + "helpscout.mailboxes", + "helpscout.assignees", + "hubspot.lists", + "hubspot.owners", + "hubspot.pipelines", + "hubspot.pipelineStages", + "hubspot.properties", + "jsm.requestTypes", + "jsm.serviceDesks", + "microsoft.planner.plans", + "notion.databases", + "notion.pages", + "netsuite.recordTypes", + "netsuite.asyncTasks", + "pipedrive.pipelines", + "sharepoint.lists", + "trello.boards", + "zoho_desk.organizations", + "zoho_desk.departments", + "zoho_desk.agents", + "zoom.meetings", + "slack.channels", + "snowflake.databases", + "snowflake.schemas", + "snowflake.tables", + "snowflake.warehouses", + "snowflake.roles", + "snowflake.fileFormats", + "snowflake.procedures", + "slack.users", + "outlook.folders", + "outlook.calendars", + "microsoft.teams", + "microsoft.chats", + "microsoft.channels", + "microsoft.planner", + "onedrive.files", + "onedrive.folders", + "sharepoint.sites", + "microsoft.excel", + "microsoft.excel.drives", + "microsoft.excel.sheets", + "microsoft.word", + "wealthbox.contacts", + "jira.issues", + "jira.projects", + "jira.projectKeys", + "linear.projects", + "linear.teams", + "monday.boards", + "monday.groups", + "webflow.sites", + "webflow.collections", + "webflow.items", + "planetscale.databases", + "powerbi.workspaces", + "powerbi.datasets", + "powerbi.reports", + "planetscale.branches", + "planetscale.backups", + "planetscale.deployRequests", + "planetscale.savedDatabases", + "planetscale.savedBranches", + "planetscale.savedBackups", + "planetscale.savedDeployRequests", + "cloudwatch.logGroups", + "cloudwatch.logStreams", + "cloudwatch.savedLogGroups", + "cloudwatch.savedLogStreams", + "imap.mailboxes", + "mcp.tools", + "managedAgent.agents", + "managedAgent.environments", + "managedAgent.vaults", + "managedAgent.memoryStores", + "knowledge.documents", + "sim.workflows", + "table.columns", + "table.outputColumns", + "workspace.secretNames", + "workspace.sandboxes", + "providers.ollamaEmbeddingModels", + "providers.openrouterEmbeddingModels" + ], + "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + }, + "context": { + "default": {}, + "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + } + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Provider option ID to resolve with the same selector and declared context." + } + }, + "required": ["workspaceId", "selectorKey", "id"], + "additionalProperties": false, + "title": "Get selector request", + "description": "Workspace, registered selector key, context, and provider option ID." + }, + "GetWorkspaceOperationResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace operation response", + "description": "Refreshed commit, copy progress, and exact deployment readiness." + }, + "ListWorkspaceOperationsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkspaceOperationReport" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace operations response", + "description": "A page of stored operation receipts." + }, + "GetWorkspaceSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "kinds": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "description": "The kinds read; the directory manages exactly these." + }, + "files": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Directory path → file text." + }, + "blobs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Directory path of the binary file." + }, + "sha256": { + "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 0, + "maximum": 10000000, + "description": "Bytes." + }, + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "href": { + "type": "string", + "description": "Where to download its bytes." + }, + "rev": { + "description": "Content revision, present when `sha256` is absent.", + "type": "string" + } + }, + "required": ["path", "size", "id", "href"], + "additionalProperties": false + }, + "description": "Binary files, downloaded separately by `href`." + }, + "base": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Base format version." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the directory was read from." + }, + "resources": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id the key is bound to." + }, + "fingerprint": { + "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", + "type": "string" + }, + "columns": { + "description": "Table column key → stored column.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored column id." + }, + "options": { + "description": "Select option name → option id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["id"], + "additionalProperties": false + } + }, + "blobs": { + "description": "Binary file name → its stored id, revision and hash as last read.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "rev": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "string" + } + ], + "description": "Content revision as last read." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + } + }, + "required": ["id", "rev", "sha256"], + "additionalProperties": false + } + }, + "rows": { + "description": "A table’s managed rows, as last read.", + "type": "object", + "properties": { + "fingerprint": { + "type": "string", + "description": "`rf1:` fingerprint of the managed rows as last read." + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "The table’s row version as last read; it moves on every row write." + } + }, + "required": ["fingerprint", "version"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + } + } + }, + "required": ["id"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "One resource in the base." + }, + "description": "`kind:key` → the stored resource and its fingerprint." + } + }, + "required": ["version", "workspaceId", "resources"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." + }, + "skipped": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "reason": { + "type": "string", + "description": "Why it was left out." + } + }, + "required": ["kind", "key", "reason"], + "additionalProperties": false + }, + "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "E_DECL_SYNTAX", + "E_DECL_HEADER", + "E_DECL_IMPORT", + "E_DECL_EXPORT", + "E_DECL_UNSUPPORTED", + "E_DECL_DUPLICATE_KEY", + "E_DECL_SHAPE", + "E_DECL_UNKNOWN_FIELD", + "E_DECL_UNKNOWN_FILE", + "W_PATH_NOT_SENT", + "E_BLOB_MANIFEST", + "E_BLOB_MISSING", + "E_LIMIT_EXCEEDED", + "E_KEY_INVALID", + "W_DECL_SUSPICIOUS_CHARACTER", + "E_BASE_JSON", + "E_BASE_VERSION", + "E_BASE_SHAPE", + "E_BASE_UNKNOWN_FIELD", + "E_SECRET_NAME", + "E_SECRET_MISSING", + "W_SECRET_MISSING", + "E_CREDENTIAL_MISSING", + "E_CREDENTIAL_AMBIGUOUS", + "W_CREDENTIAL_MISSING", + "W_CREDENTIAL_AMBIGUOUS", + "E_TABLE_COLUMN_NAME", + "E_TABLE_DUPLICATE_COLUMN", + "E_TABLE_TOO_MANY_COLUMNS", + "E_TABLE_OPTIONS", + "E_TABLE_TYPE_CONVERSION", + "E_TABLE_FOLDER", + "E_TABLE_ROWS", + "I_TABLE_SEED_SKIPPED", + "I_TABLE_ROWS_UNKEYED", + "W_LIKELY_RENAME", + "E_TOOL_SCHEMA", + "E_TOOL_CODE", + "E_TOOL_STORED_MISSING", + "W_TOOL_LITERAL_SECRET", + "E_SKILL_FRONTMATTER", + "E_MCP_LITERAL_SECRET", + "E_MCP_STORED_MISSING", + "E_MCP_TOOL_UNKNOWN", + "W_MCP_REPLACE", + "W_MCP_TOOLS_UNCHECKED", + "E_FILE_PATH", + "E_FILE_PATH_COLLISION", + "E_FILE_NAME", + "E_FILE_TOO_LARGE", + "E_FILE_CONTENT", + "E_KB_EMBEDDING_IMMUTABLE", + "E_KB_EMBEDDING_MODEL", + "E_KB_DOC_AMBIGUOUS", + "E_KB_DOC_NAME", + "E_KB_DOC_EMPTY", + "E_KB_CHUNKING", + "E_KB_FOLDER", + "W_KB_DOC_UNCHECKED", + "W_KB_DOC_FAILED", + "I_KB_REEMBED", + "I_KB_CHUNKING", + "I_KB_PROCESSING", + "I_KB_DOCS_UNHASHED", + "I_KB_UNMANAGED_DOCS", + "I_KB_REPLACE_UNFINISHED", + "E_DEPLOY_WORKFLOW", + "E_DEPLOY_SECRET", + "E_DEPLOY_CHAT_OUTPUT", + "E_DEPLOY_CHAT_IDENTIFIER", + "E_DEPLOY_PINNED_CHAT", + "W_DEPLOYED_DRAFT_CHANGED", + "I_DEPLOY_DRAFT_NOT_LIVE", + "E_APPLY_STALE", + "E_APPLY_NO_BASE", + "E_APPLY_FORBIDDEN", + "E_APPLY_DELETE_NOT_ALLOWED", + "E_APPLY_LOCKED", + "E_APPLY_REFUSED", + "E_APPLY_FAILED", + "E_PLAN_TOO_LARGE", + "E_PLAN_REF_DELETED", + "E_PLAN_REF_HELD", + "W_RESOURCE_IN_USE", + "W_TABLE_COLUMN_RENAMED_IN_USE", + "E_NAME_TAKEN", + "E_WORKFLOW_FILES_MISSING", + "E_WORKFLOW_FOLDER_COPIED", + "W_UNDECLARED", + "W_BASE_OTHER_WORKSPACE", + "I_SERVER_CHANGED", + "I_SERVER_DELETED", + "I_SERVER_MOVED", + "I_KEY_REBOUND", + "E_KEY_RENAMED", + "I_FINDINGS_TRUNCATED", + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." + }, + "severity": { + "type": "string", + "enum": ["error", "warning", "info"], + "description": "Diagnostic severity." + }, + "message": { + "type": "string", + "description": "What was found." + }, + "hint": { + "description": "How to address it.", + "type": "string" + }, + "file": { + "description": "Directory file the finding is in.", + "type": "string" + }, + "line": { + "description": "1-based line in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "column": { + "description": "1-based column in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endLine": { + "description": "1-based line the finding ends on.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endColumn": { + "description": "1-based column the finding ends at.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "frame": { + "description": "The source lines around the finding, with a caret row.", + "type": "string" + }, + "path": { + "description": "JSON Pointer into a JSON file, such as the base.", + "type": "string" + }, + "kind": { + "description": "Kind of the resource the finding is about.", + "type": "string" + }, + "key": { + "description": "Key of the resource the finding is about.", + "type": "string" + }, + "blockKey": { + "description": "Workflow block the finding is about.", + "type": "string" + }, + "param": { + "description": "Block field the finding is about.", + "type": "string" + } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding about the directory, pinned to its file when it has one." + }, + "description": "Findings from reading." + } + }, + "required": [ + "workspaceId", + "kinds", + "files", + "blobs", + "base", + "skipped", + "diagnostics" + ], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace source response", + "description": "The workspace as a source directory.", + "examples": [ + { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "kinds": ["table", "workflow"], + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "blobs": [], + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "skipped": [], + "diagnostics": [] + } + } + ] + }, + "ApplyWorkspaceSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "dryRun": { + "type": "boolean", + "description": "True when nothing was written because `dryRun` was set." + }, + "plan": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "action": { + "type": "string", + "enum": ["create", "update", "adopt", "delete", "noop"], + "description": "`adopt` binds the key to an existing resource of the same name, then updates it." + }, + "fields": { + "description": "What changes.", + "type": "array", + "items": { + "type": "string" + } + }, + "destructive": { + "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", + "type": "object", + "properties": { + "what": { + "type": "string", + "description": "What is lost." + }, + "counts": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "description": "How much is lost." + } + }, + "required": ["what", "counts"], + "additionalProperties": false + }, + "id": { + "description": "Stored id, once known.", + "type": "string" + }, + "held": { + "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", + "type": "boolean", + "const": true + } + }, + "required": ["kind", "key", "action"], + "additionalProperties": false, + "description": "One planned or applied change." + }, + "description": "Every planned change, no-ops included, in apply order." + }, + "applied": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "action": { + "type": "string", + "enum": ["create", "update", "adopt", "delete", "noop"], + "description": "`adopt` binds the key to an existing resource of the same name, then updates it." + }, + "fields": { + "description": "What changes.", + "type": "array", + "items": { + "type": "string" + } + }, + "destructive": { + "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", + "type": "object", + "properties": { + "what": { + "type": "string", + "description": "What is lost." + }, + "counts": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "description": "How much is lost." + } + }, + "required": ["what", "counts"], + "additionalProperties": false + }, + "id": { + "description": "Stored id, once known.", + "type": "string" + }, + "held": { + "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", + "type": "boolean", + "const": true + } + }, + "required": ["kind", "key", "action"], + "additionalProperties": false, + "description": "One planned or applied change." + }, + "description": "The changes written, in order." + }, + "failed": { + "description": "The change that failed mid-apply. The changes before it are written (`applied`); the rest were not attempted. Applying the same directory again continues.", + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "code": { + "type": "string", + "enum": [ + "E_DECL_SYNTAX", + "E_DECL_HEADER", + "E_DECL_IMPORT", + "E_DECL_EXPORT", + "E_DECL_UNSUPPORTED", + "E_DECL_DUPLICATE_KEY", + "E_DECL_SHAPE", + "E_DECL_UNKNOWN_FIELD", + "E_DECL_UNKNOWN_FILE", + "W_PATH_NOT_SENT", + "E_BLOB_MANIFEST", + "E_BLOB_MISSING", + "E_LIMIT_EXCEEDED", + "E_KEY_INVALID", + "W_DECL_SUSPICIOUS_CHARACTER", + "E_BASE_JSON", + "E_BASE_VERSION", + "E_BASE_SHAPE", + "E_BASE_UNKNOWN_FIELD", + "E_SECRET_NAME", + "E_SECRET_MISSING", + "W_SECRET_MISSING", + "E_CREDENTIAL_MISSING", + "E_CREDENTIAL_AMBIGUOUS", + "W_CREDENTIAL_MISSING", + "W_CREDENTIAL_AMBIGUOUS", + "E_TABLE_COLUMN_NAME", + "E_TABLE_DUPLICATE_COLUMN", + "E_TABLE_TOO_MANY_COLUMNS", + "E_TABLE_OPTIONS", + "E_TABLE_TYPE_CONVERSION", + "E_TABLE_FOLDER", + "E_TABLE_ROWS", + "I_TABLE_SEED_SKIPPED", + "I_TABLE_ROWS_UNKEYED", + "W_LIKELY_RENAME", + "E_TOOL_SCHEMA", + "E_TOOL_CODE", + "E_TOOL_STORED_MISSING", + "W_TOOL_LITERAL_SECRET", + "E_SKILL_FRONTMATTER", + "E_MCP_LITERAL_SECRET", + "E_MCP_STORED_MISSING", + "E_MCP_TOOL_UNKNOWN", + "W_MCP_REPLACE", + "W_MCP_TOOLS_UNCHECKED", + "E_FILE_PATH", + "E_FILE_PATH_COLLISION", + "E_FILE_NAME", + "E_FILE_TOO_LARGE", + "E_FILE_CONTENT", + "E_KB_EMBEDDING_IMMUTABLE", + "E_KB_EMBEDDING_MODEL", + "E_KB_DOC_AMBIGUOUS", + "E_KB_DOC_NAME", + "E_KB_DOC_EMPTY", + "E_KB_CHUNKING", + "E_KB_FOLDER", + "W_KB_DOC_UNCHECKED", + "W_KB_DOC_FAILED", + "I_KB_REEMBED", + "I_KB_CHUNKING", + "I_KB_PROCESSING", + "I_KB_DOCS_UNHASHED", + "I_KB_UNMANAGED_DOCS", + "I_KB_REPLACE_UNFINISHED", + "E_DEPLOY_WORKFLOW", + "E_DEPLOY_SECRET", + "E_DEPLOY_CHAT_OUTPUT", + "E_DEPLOY_CHAT_IDENTIFIER", + "E_DEPLOY_PINNED_CHAT", + "W_DEPLOYED_DRAFT_CHANGED", + "I_DEPLOY_DRAFT_NOT_LIVE", + "E_APPLY_STALE", + "E_APPLY_NO_BASE", + "E_APPLY_FORBIDDEN", + "E_APPLY_DELETE_NOT_ALLOWED", + "E_APPLY_LOCKED", + "E_APPLY_REFUSED", + "E_APPLY_FAILED", + "E_PLAN_TOO_LARGE", + "E_PLAN_REF_DELETED", + "E_PLAN_REF_HELD", + "W_RESOURCE_IN_USE", + "W_TABLE_COLUMN_RENAMED_IN_USE", + "E_NAME_TAKEN", + "E_WORKFLOW_FILES_MISSING", + "E_WORKFLOW_FOLDER_COPIED", + "W_UNDECLARED", + "W_BASE_OTHER_WORKSPACE", + "I_SERVER_CHANGED", + "I_SERVER_DELETED", + "I_SERVER_MOVED", + "I_KEY_REBOUND", + "E_KEY_RENAMED", + "I_FINDINGS_TRUNCATED", + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code." + }, + "message": { + "type": "string", + "description": "What failed." + } }, - "description": "The kinds read; the directory manages exactly these." + "required": ["kind", "key", "code", "message"], + "additionalProperties": false + }, + "needBlobs": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Binary paths a write needs whose bytes are not staged: on a dry run, exactly what to stage before applying." + }, + "applyId": { + "description": "The id of an apply that wrote: every audit log entry its writes recorded carries it as `metadata.correlationId`. Absent on a dry run.", + "type": "string" }, "files": { "type": "object", @@ -24935,47 +27295,7 @@ "additionalProperties": { "type": "string" }, - "description": "Directory path → file text." - }, - "blobs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Directory path of the binary file." - }, - "sha256": { - "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", - "type": "string", - "pattern": "^[0-9a-f]{64}$" - }, - "size": { - "type": "integer", - "minimum": 0, - "maximum": 10000000, - "description": "Bytes." - }, - "id": { - "type": "string", - "description": "Stored id of the binary file." - }, - "href": { - "type": "string", - "description": "Where to download its bytes." - }, - "rev": { - "description": "Content revision, present when `sha256` is absent.", - "type": "string" - } - }, - "required": ["path", "size", "id", "href"], - "additionalProperties": false - }, - "description": "Binary files, downloaded separately by `href`." + "description": "Files re-printed from what was saved, for every resource written." }, "base": { "type": "object", @@ -25103,42 +27423,7 @@ "additionalProperties": { "description": "An `x-` extension field, kept as written." }, - "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." - }, - "skipped": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "reason": { - "type": "string", - "description": "Why it was left out." - } - }, - "required": ["kind", "key", "reason"], - "additionalProperties": false - }, - "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." + "description": "The base after this apply: the next apply’s `base`." }, "diagnostics": { "type": "array", @@ -25455,77 +27740,360 @@ "description": "Key of the resource the finding is about.", "type": "string" }, - "blockKey": { - "description": "Workflow block the finding is about.", - "type": "string" + "blockKey": { + "description": "Workflow block the finding is about.", + "type": "string" + }, + "param": { + "description": "Block field the finding is about.", + "type": "string" + } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding about the directory, pinned to its file when it has one." + }, + "description": "Warnings, and on a dry run every error." + } + }, + "required": [ + "workspaceId", + "dryRun", + "plan", + "applied", + "needBlobs", + "files", + "base", + "diagnostics" + ], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Apply workspace source response", + "description": "The plan, what was written, and the files re-printed from it.", + "examples": [ + { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": false, + "plan": [ + { + "kind": "table", + "key": "leads", + "action": "noop", + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" + } + ], + "applied": [], + "needBlobs": [], + "files": {}, + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "diagnostics": [] + } + } + ] + }, + "ApplyWorkspaceSourceBody": { + "type": "object", + "properties": { + "files": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "additionalProperties": { + "type": "string" + }, + "description": "Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged." + }, + "blobs": { + "description": "Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.", + "maxItems": 20000, + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Directory path of the binary file." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + }, + "size": { + "type": "integer", + "minimum": 0, + "maximum": 10000000, + "description": "Bytes." + } + }, + "required": ["path", "sha256", "size"], + "additionalProperties": false + } + }, + "base": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Base format version." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the directory was read from." + }, + "resources": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id the key is bound to." + }, + "fingerprint": { + "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", + "type": "string" + }, + "columns": { + "description": "Table column key → stored column.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored column id." + }, + "options": { + "description": "Select option name → option id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["id"] + } + }, + "blobs": { + "description": "Binary file name → its stored id, revision and hash as last read.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "rev": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "string" + } + ], + "description": "Content revision as last read." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + } + }, + "required": ["id", "rev", "sha256"] + } }, - "param": { - "description": "Block field the finding is about.", - "type": "string" + "rows": { + "description": "A table’s managed rows, as last read.", + "type": "object", + "properties": { + "fingerprint": { + "type": "string", + "description": "`rf1:` fingerprint of the managed rows as last read." + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "The table’s row version as last read; it moves on every row write." + } + }, + "required": ["fingerprint", "version"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + } } }, - "required": ["code", "severity", "message"], - "additionalProperties": false, - "description": "A finding about the directory, pinned to its file when it has one." + "required": ["id"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "One resource in the base." }, - "description": "Findings from reading." + "description": "`kind:key` → the stored resource and its fingerprint." } }, - "required": [ - "workspaceId", - "kinds", - "files", - "blobs", - "base", - "skipped", - "diagnostics" - ], - "additionalProperties": false, - "description": "Response data." + "required": ["version", "workspaceId", "resources"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." + }, + "kinds": { + "maxItems": 10, + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "description": "The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent." + }, + "options": { + "description": "How far the apply may go.", + "type": "object", + "properties": { + "allowDelete": { + "description": "Delete resources, columns and data the directory no longer declares.", + "type": "boolean" + }, + "only": { + "description": "Apply only these kinds.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + } + } + }, + "additionalProperties": false + }, + "provenance": { + "description": "Where the directory came from, for the audit log.", + "type": "object", + "properties": { + "client": { + "type": "string", + "enum": ["cli", "api"], + "description": "What submitted the directory." + }, + "gitSha": { + "description": "The commit the directory was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" + } + }, + "required": ["client"], + "additionalProperties": false } }, - "required": ["data"], + "required": ["files", "kinds"], "additionalProperties": false, - "title": "Get workspace source response", - "description": "The workspace as a source directory.", + "title": "Apply workspace source body", + "description": "The directory files, its managed kinds and the base they were read with.", "examples": [ { - "data": { + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "kinds": ["table"], + "base": { + "version": 1, "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "kinds": ["table", "workflow"], - "files": { - "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" - }, - "blobs": [], - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" } } } } - }, - "skipped": [], - "diagnostics": [] + } } } ] }, - "ApplyWorkspaceSourceResponse": { + "PlanWorkspaceSourceResponse": { "type": "object", "properties": { "data": { @@ -25848,8 +28416,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25959,13 +28525,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code." @@ -26263,8 +28826,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -26374,13 +28935,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." @@ -26474,13 +29032,13 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Apply workspace source response", - "description": "The plan, what was written, and the files re-printed from it.", + "title": "Plan workspace source response", + "description": "The plan an apply would carry out.", "examples": [ { "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, + "dryRun": true, "plan": [ { "kind": "table", @@ -26519,7 +29077,7 @@ } ] }, - "ApplyWorkspaceSourceBody": { + "PlanWorkspaceSourceBody": { "type": "object", "properties": { "files": { @@ -26740,29 +29298,11 @@ } }, "additionalProperties": false - }, - "provenance": { - "description": "Where the directory came from, for the audit log.", - "type": "object", - "properties": { - "client": { - "type": "string", - "enum": ["cli", "api"], - "description": "What submitted the directory." - }, - "gitSha": { - "description": "The commit the directory was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" - } - }, - "required": ["client"], - "additionalProperties": false } }, "required": ["files", "kinds"], "additionalProperties": false, - "title": "Apply workspace source body", + "title": "Plan workspace source body", "description": "The directory files, its managed kinds and the base they were read with.", "examples": [ { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts new file mode 100644 index 00000000000..47f5b083a4e --- /dev/null +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts @@ -0,0 +1,33 @@ +import { SOURCE_REQUEST_MAX_BYTES } from '@sim/workflow-code/limits' +import { v2PlanWorkflowSourceContract } from '@/lib/api/contracts/v2/workflow-source' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { planWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' +import { workflowOperations } from '@/lib/workflows/application/operations' + +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +/** + * POST /api/v2/workflows/[workflowId]/source/plan — what applying the submitted source would do, + * without writing: the dry run `sim workflows source status` reads. A read at the `read` role on + * the generic budget, so asking for a status never spends the source-write budget an apply + * needs. Answers 403 while the `workflow-code` flag is off. + */ +export const POST = defineV2JsonRoute({ + contract: v2PlanWorkflowSourceContract, + auth: v2ApiKeyAuth, + operation: workflowOperations.planSource, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2WorkflowErrorPolicies.concealWorkflowGraphAuthorization, + parseOptions: { maxBodyBytes: SOURCE_REQUEST_MAX_BYTES }, + mapInput: ({ params, query, body }) => ({ + workflowId: params.workflowId, + files: body.files, + lock: body.lock, + base: body.base, + ...(query.allowDelete !== undefined ? { allowDelete: query.allowDelete } : {}), + }), + useCase: planWorkflowSource, + present: (result) => ({ data: result }), +}) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts new file mode 100644 index 00000000000..1c41c1a9026 --- /dev/null +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts @@ -0,0 +1,39 @@ +import { WORKSPACE_SOURCE_REQUEST_MAX_BYTES } from '@sim/workspace-code/limits' +import { v2PlanWorkspaceSourceContract } from '@/lib/api/contracts/v2/workspace-source' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { + v2WorkspaceSourceErrorPolicy, + withSourceSlot, +} from '@/lib/workspace-source/api/route-policies' +import { readWorkspaceSourcePlan } from '@/lib/workspace-source/application/apply-workspace-source' +import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' + +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +/** + * POST /api/v2/workspaces/[workspaceId]/source/plan — what applying the submitted directory would + * do, without writing: the dry run `sim workspaces source status` reads. One unit of the + * source-read budget whatever the directory holds, so a status never spends the source-write + * budget an apply needs. A server already running as many applies as it allows answers 429. + * Answers 403 while the `workflow-code` flag is off. + */ +export const POST = defineV2JsonRoute({ + contract: v2PlanWorkspaceSourceContract, + auth: v2ApiKeyAuth, + operation: workspaceSourceOperations.plan, + rateLimit: v2RateLimits.sourceRead, + errorPolicy: v2WorkspaceSourceErrorPolicy, + parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES }, + mapInput: ({ params, body }) => ({ + workspaceId: params.workspaceId, + files: body.files, + kinds: body.kinds, + ...(body.blobs ? { blobs: body.blobs } : {}), + ...(body.base ? { base: body.base } : {}), + ...(body.options?.only ? { only: body.options.only } : {}), + ...(body.options?.allowDelete !== undefined ? { allowDelete: body.options.allowDelete } : {}), + }), + useCase: withSourceSlot(readWorkspaceSourcePlan, 'apply'), + present: (result) => ({ data: result }), +}) diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts index 6a25d2449a0..fe285191073 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts @@ -10,6 +10,7 @@ import { v2ApplyWorkflowSourceContract, v2CreateWorkflowFromSourceContract, v2GetWorkflowSourceContract, + v2PlanWorkflowSourceContract, } from '@/lib/api/contracts/v2/workflow-source' import { defineOpenApiRoute } from '@/lib/api/openapi/types' import { workflowOperations } from '@/lib/workflows/application/operations' @@ -135,6 +136,69 @@ export const workflowSourceOpenApiRoutes = [ ), } ), + defineOpenApiRoute( + v2PlanWorkflowSourceContract, + { + applicationOperation: workflowOperations.planSource, + operationId: 'planWorkflowSource', + summary: 'Plan workflow source', + description: `Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since \`base\` (\`E_APPLY_STALE\`), the diff, and every finding, exactly as \`dryRun=true\` reports them, with \`200\`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so \`sim workflows source status\` never spends what an apply needs. \`allowDelete=true\` plans block deletes instead of reporting \`E_APPLY_BLOCK_DELETE\`. Returns \`403\` while workflows as code is not enabled. ${WORKSPACE_API_KEY_DENIED}`, + tags: ['Workflows'], + errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'], + success: { description: 'The evaluated source.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: v2PlanWorkflowSourceContract.params, + query: documentedSchema( + v2PlanWorkflowSourceContract.query, + 'PlanWorkflowSourceQuery', + 'Plan workflow source query', + 'Whether to plan block deletes.' + ), + body: documentedSchema( + v2PlanWorkflowSourceContract.body, + 'PlanWorkflowSourceBody', + 'Plan workflow source body', + 'Edited source files with the lock and base they were read with.', + [ + { + files: WORKFLOW_SOURCE_EXAMPLE.files, + lock: WORKFLOW_SOURCE_EXAMPLE.lock, + base: WORKFLOW_SOURCE_EXAMPLE.base, + }, + ] + ), + response: documentedSchema( + v2PlanWorkflowSourceContract.response.schema, + 'PlanWorkflowSourceResponse', + 'Plan workflow source response', + 'What an apply would store, and every finding.', + [ + { + data: { + workflowId: WORKFLOW_SOURCE_EXAMPLE.workflowId, + workspaceId: WORKFLOW_SOURCE_EXAMPLE.workspaceId, + dryRun: true, + applied: false, + diff: { + noop: true, + blocks: { added: [], removed: [], renamed: [], modified: [] }, + edges: { added: 0, removed: 0 }, + variables: { added: [], removed: [], modified: [] }, + }, + diagnostics: [], + files: WORKFLOW_SOURCE_EXAMPLE.files, + lock: WORKFLOW_SOURCE_EXAMPLE.lock, + base: WORKFLOW_SOURCE_EXAMPLE.base, + mintedIds: {}, + notes: [], + needsRedeployment: false, + }, + }, + ] + ), + } + ), defineOpenApiRoute( v2CreateWorkflowFromSourceContract, { 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 ad5182a0343..d40dc84fca5 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts @@ -12,6 +12,7 @@ import { v2ApplyWorkspaceSourceContract, v2FindMissingWorkspaceSourceBlobsContract, v2GetWorkspaceSourceContract, + v2PlanWorkspaceSourceContract, v2StageWorkspaceSourceBlobsContract, v2StageWorkspaceSourceBlobsFormSchema, } from '@/lib/api/contracts/v2/workspace-source' @@ -149,6 +150,60 @@ export const workspaceSourceOpenApiRoutes = [ ), } ), + defineOpenApiRoute( + v2PlanWorkspaceSourceContract, + { + applicationOperation: workspaceSourceOperations.plan, + operationId: 'planWorkspaceSource', + summary: 'Plan workspace source', + description: + 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.', + tags: ['Workflows'], + errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'], + success: { description: 'The planned changes.', headers: RATE_LIMIT_HEADERS }, + }, + { + params: documentedSchema( + v2PlanWorkspaceSourceContract.params, + 'PlanWorkspaceSourceParams', + 'Plan workspace source path parameters', + 'Workspace the plan is for.' + ), + query: documentedSchema( + v2PlanWorkspaceSourceContract.query, + 'PlanWorkspaceSourceQuery', + 'Plan workspace source query', + 'No query parameters.' + ), + body: documentedSchema( + v2PlanWorkspaceSourceContract.body, + 'PlanWorkspaceSourceBody', + 'Plan workspace source body', + 'The directory files, its managed kinds and the base they were read with.', + [{ files: { 'tables/leads.ts': LEADS_TS }, kinds: ['table'], base: BASE_EXAMPLE }] + ), + response: documentedSchema( + v2PlanWorkspaceSourceContract.response.schema, + 'PlanWorkspaceSourceResponse', + 'Plan workspace source response', + 'The plan an apply would carry out.', + [ + { + data: { + workspaceId: WORKSPACE_ID, + dryRun: true, + plan: [{ kind: 'table', key: 'leads', action: 'noop', id: TABLE_ID }], + applied: [], + needBlobs: [], + files: {}, + base: BASE_EXAMPLE, + diagnostics: [], + }, + }, + ] + ), + } + ), defineOpenApiRoute( v2FindMissingWorkspaceSourceBlobsContract, { diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 55864c463ed..3f307bead6e 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -222,6 +222,39 @@ export const v2ApplyWorkflowSourceContract = defineRouteContract({ response: { mode: 'json', schema: v2DataResponse(applyWorkflowSourceDataSchema) }, }) +const planWorkflowSourceQuerySchema = z + .object({ + allowDelete: booleanQueryFlagSchema + .optional() + .describe( + 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.' + ), + }) + .strict() + +const planWorkflowSourceBodySchema = z + .object({ + files: sourceFilesSchema, + lock: workflowLockSchema, + base: sourceBaseSchema.describe( + 'Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`.' + ), + }) + .strict() + +/** + * `POST /api/v2/workflows/{workflowId}/source/plan`: what applying the source would do, as a read. + * The response is an apply dry run's. + */ +export const v2PlanWorkflowSourceContract = defineRouteContract({ + method: 'POST', + path: '/api/v2/workflows/[workflowId]/source/plan', + params: v2WorkflowIdParamsSchema, + query: planWorkflowSourceQuerySchema, + body: planWorkflowSourceBodySchema, + response: { mode: 'json', schema: v2DataResponse(applyWorkflowSourceDataSchema) }, +}) + const createWorkflowFromSourceParamsSchema = z .object({ workspaceId: workspaceIdSchema.describe('Workspace in which to create the workflow.'), diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index 4a6199e535a..608076e804d 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -339,6 +339,19 @@ export const v2ApplyWorkspaceSourceContract = defineRouteContract({ response: { mode: 'json', schema: v2DataResponse(applyDataSchema) }, }) +/** + * `POST /api/v2/workspaces/{workspaceId}/source/plan`: what applying the directory would do, as a + * read. The body is an apply's without `provenance`; the response is an apply dry run's. + */ +export const v2PlanWorkspaceSourceContract = defineRouteContract({ + method: 'POST', + path: '/api/v2/workspaces/[workspaceId]/source/plan', + params: paramsSchema, + query: noInputSchema, + body: applyBodySchema.omit({ provenance: true }), + response: { mode: 'json', schema: v2DataResponse(applyDataSchema) }, +}) + const stagedBlobSchema = z .object({ sha256: sha256Schema, size: blobSchema.shape.size }) .strict() diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 07272f541a6..430638b669d 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -313,6 +313,7 @@ import { v2ApplyWorkflowSourceContract, v2CreateWorkflowFromSourceContract, v2GetWorkflowSourceContract, + v2PlanWorkflowSourceContract, } from '@/lib/api/contracts/v2/workflow-source' import { v2ActivateWorkflowVersionContract, @@ -383,6 +384,7 @@ import { v2ApplyWorkspaceSourceContract, v2FindMissingWorkspaceSourceBlobsContract, v2GetWorkspaceSourceContract, + v2PlanWorkspaceSourceContract, } from '@/lib/api/contracts/v2/workspace-source' import { v2GetWorkspaceContract, @@ -2479,6 +2481,23 @@ export const V2_MCP_OPERATIONS = { 'Move up to 100 workflows to one folder with workspace write access. Each move succeeds or fails independently; missing, archived, or locked workflows appear in `failed`. Duplicate IDs are ignored. Workspace folder trees exceeding 10,000 folders return `413`.\n\nOAuth scope: `api:write`.', handler: () => import('@/app/api/v2/workflows/move/route').then((route) => route.POST), }, + planWorkflowSource: { + contract: v2PlanWorkflowSourceContract, + summary: 'Plan workflow source', + description: + 'Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', + workspaceKeyUnsupported: true, + handler: () => + import('@/app/api/v2/workflows/[workflowId]/source/plan/route').then((route) => route.POST), + }, + planWorkspaceSource: { + contract: v2PlanWorkspaceSourceContract, + summary: 'Plan workspace source', + description: + 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.', + handler: () => + import('@/app/api/v2/workspaces/[workspaceId]/source/plan/route').then((route) => route.POST), + }, prepareSearchSources: { contract: v2PrepareSearchSourcesContract, summary: 'Prepare Search sources', diff --git a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts index a4b05a28b39..e162ed71405 100644 --- a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts +++ b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts @@ -892,6 +892,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ pattern: '/api/v2/workflows/{workflowId}/source', load: () => import('@/app/api/v2/workflows/[workflowId]/source/route'), }, + { + pattern: '/api/v2/workflows/{workflowId}/source/plan', + load: () => import('@/app/api/v2/workflows/[workflowId]/source/plan/route'), + }, { pattern: '/api/v2/workflows/{workflowId}/state', load: () => import('@/app/api/v2/workflows/[workflowId]/state/route'), @@ -1061,6 +1065,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ pattern: '/api/v2/workspaces/{workspaceId}/source/blobs/missing', load: () => import('@/app/api/v2/workspaces/[workspaceId]/source/blobs/missing/route'), }, + { + pattern: '/api/v2/workspaces/{workspaceId}/source/plan', + load: () => import('@/app/api/v2/workspaces/[workspaceId]/source/plan/route'), + }, { pattern: '/api/v2/workspaces/{workspaceId}/workflows/source', load: () => import('@/app/api/v2/workspaces/[workspaceId]/workflows/source/route'), 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 8b2c6c2ce37..4fcb163a9ab 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -52,6 +52,7 @@ import { type ApplyWorkflowSourceInput, applyWorkflowSource, createWorkflowFromSource, + planWorkflowSource, } from '@/lib/workflows/application/apply-workflow-source' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { WorkflowSourceRejectedError } from '@/lib/workflows/application/source-error' @@ -2029,6 +2030,34 @@ export default workflow('', {}, () => { expect(await snapshot(seeded.workflowId)).toEqual(before) }) + check( + 'a plan is the dry run as a read: a reader gets it, it reports staleness, and it writes nothing', + async () => { + const seeded = await seedWorkflow() + const source = await getSource(seeded.workflowId) + const before = await snapshot(seeded.workflowId) + const files = edit(source.files, SCORE_CODE, 'return 71') + const plan = (base = source.base) => + withPermissionGroupScope(() => + planWorkflowSource.execute({ + principal: reader, + input: { workflowId: seeded.workflowId, files, lock: source.lock, base }, + }) + ) + + const planned = await plan() + const dryRun = await apply(source, files, { dryRun: true }) + + expect(planned).toMatchObject({ dryRun: true, applied: false }) + expect(planned.diff).toEqual(dryRun.diff) + expect(planned.diagnostics).toEqual(dryRun.diagnostics) + expect(planned.diff.blocks.modified.map((block) => block.id)).toEqual([seeded.scoreId]) + const stale = await plan({ ...source.base, fingerprint: `sf1:${'0'.repeat(64)}` }) + expect(stale.diagnostics.map((d) => d.code)).toContain('E_APPLY_STALE') + expect(await snapshot(seeded.workflowId)).toEqual(before) + } + ) + check( 'a schedule edited in source changes only the draft and reports needsRedeployment', async () => { diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 0851776197c..c86179fb9ad 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -296,6 +296,41 @@ export const applyWorkflowSource = defineAuthorizedWorkflowUseCase({ }, }) +/** What {@link planWorkflowSource} reads: a submission as an apply sends it, without its knobs. */ +export interface PlanWorkflowSourceInput { + workflowId: string + assertedWorkspaceId?: string + files: Record + lock: WorkflowLockV1 + base: SourceBase + /** Plan block deletes as allowed, so the plan names them instead of refusing. */ + allowDelete?: boolean +} + +/** + * What an apply of this source would do, without writing: whether the draft moved since `base` + * (`E_APPLY_STALE`), the diff and every finding, exactly as a dry run reports them. A read, so + * `sim workflows source status` costs no write budget, needs only the `read` role, and records + * no dry-run analytics; it audits and notifies nothing, like a dry run. + */ +export const planWorkflowSource = defineAuthorizedWorkflowUseCase({ + operation: workflowOperations.planSource, + resolveContext: resolvePrincipalWorkflowContext, + async execute({ principal, input, context }): Promise { + await requireWorkflowCodeEnabled(principal, context) + return runSourceApply( + principal, + { files: input.files, lock: input.lock, dryRun: true }, + { + kind: 'existing', + context, + base: input.base, + allowDelete: input.allowDelete === true, + } + ) + }, +}) + /** * Creates a workflow from source: the same pipeline as {@link applyWorkflowSource} with an empty * graph as the stored draft, so every block is new, every id is minted and no fingerprint is diff --git a/apps/sim/lib/workflows/application/operations.ts b/apps/sim/lib/workflows/application/operations.ts index 73ac154c7a6..eb8c42efba9 100644 --- a/apps/sim/lib/workflows/application/operations.ts +++ b/apps/sim/lib/workflows/application/operations.ts @@ -252,6 +252,22 @@ export const workflowOperations = { contentDelivery: 'none', ...HUMAN_WORKFLOW_PRINCIPAL_POLICY, }), + /** + * What an apply of submitted workflow source would do, without writing: the read behind + * `sim workflows source status`. The apply pipeline as a dry run, so a member who may read the + * source may ask it (`read`, `api:read`). Denied to workspace API keys like `applySource`: the + * source gates it reports take a human subject and would fail open without one. + */ + // permission-group-exempt: a plan stores nothing; the block and value gates it reports are judged per block against the principal's human subject, as for applySource + planSource: defineWorkspaceOperation({ + id: 'workflows.source.plan', + oauthScope: 'api:read', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'none', + contentDelivery: 'none', + ...HUMAN_WORKFLOW_PRINCIPAL_POLICY, + }), /** Creating a workflow from source runs the apply pipeline with no stored draft: same policy. */ // permission-group-exempt: creating a workflow from source is governed by workspace role and the same block gates as apply createFromSource: defineWorkspaceOperation({ 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 d52a56207a3..707cef09d05 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -229,6 +229,26 @@ function planned( } } +/** What {@link readWorkspaceSourcePlan} reads: a directory as an apply sends it, without its knobs. */ +export type PlanWorkspaceSourceInput = Omit + +/** + * What an apply of this directory would do, without writing: every planned change and finding, + * exactly as a dry run reports them. A read, so `sim workspaces source status` costs no write + * budget; like a dry run it takes no lease and records, audits and notifies nothing. + */ +export const readWorkspaceSourcePlan = defineAuthorizedWorkspaceUseCase({ + operation: workspaceSourceOperations.plan, + resolveContext: ({ input }: { input: PlanWorkspaceSourceInput }) => + resolveActiveWorkspaceApplicationContext(input.workspaceId), + authorizationOptions: {}, + async execute({ principal, input, context }): Promise { + await requireWorkflowCodeEnabled(principal, context) + const plan = await planWorkspaceSource(input, sourceContext(principal, context)) + return planned(plan, context.workspaceId, true) + }, +}) + /** * Applies a workspace source directory: plans every managed kind, refuses the whole apply when * any change has an error (nothing written) apart from the changes held back for a reference the diff --git a/apps/sim/lib/workspace-source/application/operations.ts b/apps/sim/lib/workspace-source/application/operations.ts index 2d5690bb88f..34c9d100a0b 100644 --- a/apps/sim/lib/workspace-source/application/operations.ts +++ b/apps/sim/lib/workspace-source/application/operations.ts @@ -25,6 +25,20 @@ export const workspaceSourceOperations = { capability: 'none', ...SOURCE_OPERATION_POLICY, }), + /** + * What an apply of a submitted directory would do, without writing: the read behind + * `sim workspaces source status`. Each change is still checked by the use case that owns it, so a + * member who may not write a kind sees that change refused in the plan. + */ + // permission-group-exempt: a plan stores nothing; each change is checked by the use case that owns it, which applies that kind's capability + plan: defineWorkspaceOperation({ + id: 'workspaces.source.plan', + oauthScope: 'api:read', + minimumRole: 'read', + workspaceApiKey: 'allow', + capability: 'none', + ...SOURCE_PRINCIPAL_POLICY, + }), // permission-group-exempt: each change runs through the use case that owns it, which applies that kind's capability apply: defineWorkspaceOperation({ id: 'workspaces.source.apply', diff --git a/apps/sim/lib/workspace-source/application/status.integration.ts b/apps/sim/lib/workspace-source/application/status.integration.ts index 85fe35a5790..55046e68aaa 100644 --- a/apps/sim/lib/workspace-source/application/status.integration.ts +++ b/apps/sim/lib/workspace-source/application/status.integration.ts @@ -1,6 +1,7 @@ /** - * `status` against Postgres: a directory read by a get, edited on either side, dry-run the way - * `sim workspaces source status` sends it (every workflow folder whole, deletes allowed), and read + * `status` against Postgres: a directory read by a get, edited on either side, planned the way + * `sim workspaces source status` sends it (the plan read, every workflow folder whole, deletes + * allowed), and read * through the status module the CLI prints. Proves that what the server's plan reports is the * drift and the conflicts a status names, a UI edit of a workflow included. */ @@ -24,6 +25,7 @@ import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope. import * as tableUseCases from '@/lib/table/application/tables' import { applyWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' +import { readWorkspaceSourcePlan } from '@/lib/workspace-source/application/apply-workspace-source' import { sourceChecks, sourceRunner, @@ -111,12 +113,19 @@ async function statusOf(read: ReadDirectory, local: Record, whol ) ) ) - const plan = await runner.apply(read.workspaceId, { - files, - base: read.base, - dryRun: true, - allowDelete: true, - }) + const plan = await withPermissionGroupScope(() => + readWorkspaceSourcePlan.execute({ + principal: owner, + input: { + workspaceId: read.workspaceId, + kinds: ['table', 'workflow'], + files, + base: read.base, + allowDelete: true, + }, + }) + ) + expect(plan.dryRun).toBe(true) const changed = changedFiles(local, read.files, () => true) return { plan, diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index e516a53f442..b04d1380eb9 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -245,7 +245,7 @@ export type SourceDirKind = 'workflow' | 'workspace' * workflow directory (a workspace directory keeps its workflows under `workflows//`). `null` * for a directory that holds neither, such as a new one. */ -export async function sourceDirKind( +async function sourceDirKind( dir: string ): Promise<{ kind: SourceDirKind; readFrom: string | null } | null> { const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index ed4ab27d1ce..85e6aa13f1a 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -466,3 +466,17 @@ export function nextStep(status: SourceStatus, input: NextStepInput): NextStep | : 'Applies your changes.', } } + +/** + * A status's plan: the plan read, or, from a server that predates it (its route answers `404`), + * the apply dry run it replaced, which spends the source-write budget. A `404` the dry run also + * answers is the resource's own, and is thrown. + */ +export async function readPlan(plan: () => Promise, dryRun: () => Promise): Promise { + try { + return await plan() + } catch (error) { + if (!(error instanceof SimApiError) || error.status !== 404) throw error + return dryRun() + } +} diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index 0248985e201..6c3f9f79f4e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -153,10 +153,14 @@ describe('workflows source status', () => { }, next: null, }) - expect(mockRequest.mock.calls[0]).toMatchObject([ - `/api/v2/workflows/${WORKFLOW_ID}/source`, - { query: { dryRun: true, allowDelete: true }, body: { files: GOT, lock: LOCK, base: BASE } }, - ]) + const [path, request] = mockRequest.mock.calls[0] + expect(path).toBe(`/api/v2/workflows/${WORKFLOW_ID}/source/plan`) + expect(request).toMatchObject({ + query: { allowDelete: true }, + body: { files: GOT, lock: LOCK, base: BASE }, + }) + expect(request.query).not.toHaveProperty('dryRun') + expect(request.body).not.toHaveProperty('provenance') expect(process.exitCode ?? 0).toBe(0) }) @@ -265,6 +269,21 @@ describe('workflows source status', () => { expect(process.exitCode).toBe(12) }) + it('falls back to the apply dry run on a server without the plan read', async () => { + mockRequest + .mockRejectedValueOnce(new SimApiError('Not found', 404, 'NOT_FOUND')) + .mockResolvedValueOnce(dryRun()) + + await run(root, 'status') + + expect(mockRequest.mock.calls.map(([path]) => path)).toEqual([ + `/api/v2/workflows/${WORKFLOW_ID}/source/plan`, + `/api/v2/workflows/${WORKFLOW_ID}/source`, + ]) + expect(mockRequest.mock.calls[1][1].query).toEqual({ dryRun: true, allowDelete: true }) + expect(printed()).toMatchObject({ state: 'clean', server: 'checked' }) + }) + it('reports a workflow the server no longer has as deleted there', async () => { mockRequest.mockRejectedValue(new SimApiError('Workflow not found', 404, 'NOT_FOUND')) 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 cfcf68d860c..a7550314650 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -2,8 +2,9 @@ * `sim workflows source status` and `sim workflows source diff`: what changed in one workflow's * 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 a dry run of the - * directory, whose `E_APPLY_STALE` says the workflow changed since the base. + * 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 + * `E_APPLY_STALE` says the workflow changed since the base. */ import { compareStrings } from '@sim/utils/string' import { SOURCE_CODE_DIR, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' @@ -18,7 +19,7 @@ import { import type { Command } from 'commander' import { profileFrom } from '../../context' import { setSoftExitCode } from '../../embed-context' -import type { ApplyWorkflowSourceResponse, GetWorkflowSourceResponse } from '../../generated/v2-api' +import type { GetWorkflowSourceResponse, PlanWorkflowSourceResponse } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand } from '../../runtime/called-operations' import { @@ -40,6 +41,7 @@ import { planFindings, printDiffReport, printStatusReport, + readPlan, type ServerCheck, STATUS_EXIT_CODES_HELP, type StatusReport, @@ -47,11 +49,11 @@ import { textDiff, unreachableReason, } from './source-status' -import { withSourceExitCode } from './source-tree' +import { refreshWorkflowWorkspaceTypes, withSourceExitCode } from './source-tree' import type { Diagnostic } from './source-ui' import { readBase, readLock, readSourceFiles } from './workflow-source-apply' -type ApplyData = ApplyWorkflowSourceResponse['data'] +type ApplyData = PlanWorkflowSourceResponse['data'] const PREFIX = 'sim workflows source' @@ -140,7 +142,11 @@ interface StatusOptions { * the server since, from a dry run. Ends with the next command. */ export function attachWorkflowSourceStatus(source: Command): void { - const [command, connect] = apiCommand(source, 'status', ['applyWorkflowSource']) + const [command, connect] = apiCommand(source, 'status', [ + 'planWorkflowSource', + 'applyWorkflowSource', + 'getSourceResources', + ]) absoluteDirOption(command) command .option('--dir ', 'Source directory: workflow.ts, functions/* and .sim/', '.') @@ -174,16 +180,25 @@ export function attachWorkflowSourceStatus(source: Command): void { const lock = await readLock(options.dir) const files = await readSourceFiles(options.dir, lock) try { - const response = await client.request( - 'applyWorkflowSource', - { - params: { workflowId }, - query: { dryRun: true, allowDelete: true }, - body: { files, lock, base: local.base, provenance: { client: 'cli' } }, - retryRateLimited: true, - } + const body = { files, lock, base: local.base } + const response = await readPlan( + () => + client.request('planWorkflowSource', { + params: { workflowId }, + query: { allowDelete: true }, + body, + retryRateLimited: true, + }), + () => + client.request('applyWorkflowSource', { + params: { workflowId }, + query: { dryRun: true, allowDelete: true }, + body: { ...body, provenance: { client: 'cli' } }, + retryRateLimited: true, + }) ) data = response.data + await refreshWorkflowWorkspaceTypes(client, options.dir, local.base.workspaceId) if (data.diagnostics.some((finding) => finding.code === 'E_APPLY_STALE')) { serverChanges = [{ kind: 'workflow', key: workflowId, server: 'changed' }] } 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 c88872ebf49..878bdfb9733 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 @@ -302,7 +302,7 @@ describe('workspaces source status', () => { await run('status') - expect(mockRequest.mock.calls[0][0]).toBe(`/api/v2/workspaces/${WORKSPACE_ID}/source`) + expect(mockRequest.mock.calls[0][0]).toBe(`/api/v2/workspaces/${WORKSPACE_ID}/source/plan`) expect(printed().next).toMatchObject({ command: `sim workspaces source apply --dir ${dir} --yes`, }) @@ -390,16 +390,15 @@ describe('workspaces source status', () => { }) }) - it('sends every workflow folder whole, so the dry run compares it with the stored workflow', async () => { + it('sends every workflow folder whole to the plan read, so it compares each with the stored workflow', async () => { mockRequest.mockResolvedValue(dryRun()) await run('status') expect(sentFiles()[0]['workflows/ingest/workflow.ts']).toBe(INGEST) - expect(mockRequest.mock.calls[0][1]).toMatchObject({ - query: { dryRun: true }, - body: { options: { allowDelete: true } }, - }) + expect(mockRequest.mock.calls[0][0]).toBe('/api/v2/workspaces/ws_local/source/plan') + expect(mockRequest.mock.calls[0][1]).toMatchObject({ body: { options: { allowDelete: true } } }) + expect(mockRequest.mock.calls[0][1].query).toBeUndefined() }) it('past one dry run, sends an unchanged workflow folder by its base and an edited one whole', async () => { 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 58ea1ddd7cd..56e91ecfaa1 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -1,8 +1,9 @@ /** * `sim workspaces source status` and `sim workspaces source diff`: what changed in a workspace * source directory since it was read, on either side, without applying anything. Local changes - * come from the file digests `.sim/written.json` records; the server's come from a dry run of - * the directory (its findings name every resource changed since the base), and the base text a + * come from the file digests `.sim/written.json` records; the server's come from the plan read + * (`planWorkspaceSource`: a dry run on the source-read budget, one unit whatever the directory + * holds) of the directory (its findings name every resource changed since the base), and the base text a * diff shows from the server's current source where it still prints what the directory was read * at. */ @@ -26,9 +27,9 @@ import type { Command } from 'commander' import { profileFrom } from '../../context' import { setSoftExitCode } from '../../embed-context' import type { - ApplyWorkspaceSourceBody, - ApplyWorkspaceSourceResponse, GetWorkspaceSourceResponse, + PlanWorkspaceSourceBody, + PlanWorkspaceSourceResponse, } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type Connection } from '../../runtime/called-operations' @@ -56,6 +57,7 @@ import { planFindings, printDiffReport, printStatusReport, + readPlan, type ServerCheck, STATUS_EXIT_CODES_HELP, type StatusReport, @@ -74,7 +76,7 @@ import { } from './workspace-source-dir' import { ONLY_KINDS_HELP, parseKinds } from './workspace-source-get' -type ApplyData = ApplyWorkspaceSourceResponse['data'] +type ApplyData = PlanWorkspaceSourceResponse['data'] type ServerSource = GetWorkspaceSourceResponse['data'] const PREFIX = 'sim workspaces source' @@ -154,7 +156,7 @@ function localPaths(local: LocalWorkspace): string[] { * naming another is refused), else the profile's. */ function targetWorkspace( - connection: Connection<'applyWorkspaceSource' | 'getWorkspaceSource'>, + connection: Connection<'planWorkspaceSource' | 'applyWorkspaceSource' | 'getWorkspaceSource'>, dir: string, readFrom: string | null ): string { @@ -299,7 +301,10 @@ interface StatusOptions { * the server since: drift, and conflicts where both sides changed. Ends with the next command. */ export function attachWorkspaceSourceStatus(source: Command): void { - const [command, connect] = apiCommand(source, 'status', ['applyWorkspaceSource']) + const [command, connect] = apiCommand(source, 'status', [ + 'planWorkspaceSource', + 'applyWorkspaceSource', + ]) absoluteDirOption(command) command .option('--dir ', 'Workspace source directory written by `workspaces source get`', '.') @@ -342,23 +347,28 @@ export function attachWorkspaceSourceStatus(source: Command): void { submission = withUnchangedWorkflowsPruned(submission, local.written, target) note = `More workflow folders than one dry run compares: an unchanged folder's server edits are not checked (\`${PREFIX} get\` shows them).` } - const body: ApplyWorkspaceSourceBody = { + const body: PlanWorkspaceSourceBody = { files: submission.files, kinds: submission.kinds, blobs: submission.blobs, ...(submission.base ? { base: submission.base } : {}), options: { allowDelete: true, ...(only ? { only } : {}) }, - provenance: { client: 'cli' }, } try { - const response = await connection.client.request( - 'applyWorkspaceSource', - { - params: { workspaceId: target }, - query: { dryRun: true }, - body, - retryRateLimited: true, - } + const response = await readPlan( + () => + connection.client.request('planWorkspaceSource', { + params: { workspaceId: target }, + body, + retryRateLimited: true, + }), + () => + connection.client.request('applyWorkspaceSource', { + params: { workspaceId: target }, + query: { dryRun: true }, + body: { ...body, provenance: { client: 'cli' } }, + retryRateLimited: true, + }) ) data = response.data applyPlan = planAsApplied(data.plan, local, target) diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 1d03f234e2c..7113d0a2b8f 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -645,6 +645,8 @@ export const CLI_CONTRACT: CliContract = { }, /** `workflows source apply --dir ` reads and writes a source directory by hand. */ applyWorkflowSource: { hidden: true }, + /** `workflows source status --dir ` reads a plan of a source directory by hand. */ + planWorkflowSource: { hidden: true }, // The ETag revalidation header is for a client that caches the catalog, as `workflows source // get --dir` does by hand; a one-off read has no cached hash to send. getSourceCatalog: { @@ -658,6 +660,8 @@ export const CLI_CONTRACT: CliContract = { /** `workspaces source get|apply --dir ` read and write a workspace directory by hand. */ getWorkspaceSource: { hidden: true }, applyWorkspaceSource: { hidden: true }, + /** `workspaces source status --dir ` reads a plan of a workspace directory by hand. */ + planWorkspaceSource: { hidden: true }, /** The staging `workspaces source apply` runs before its one apply. */ findMissingWorkspaceSourceBlobs: { hidden: true }, stageWorkspaceSourceBlobs: { hidden: true }, diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 586a2f6803c..727aa95c083 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -14270,6 +14270,995 @@ export type MoveWorkflowsResponse = { data: MoveWorkflowsResponseRef0 } +/** `POST /api/v2/workflows/[workflowId]/source/plan` */ +export type PlanWorkflowSourceParams = { + workflowId: string +} + +export type PlanWorkflowSourceQuery = { + allowDelete?: boolean +} + +export type PlanWorkflowSourceBody = { + files: Record + lock: { + version: 1 + blocks: Record< + string, + { + id: string + parent: string | null + branches?: Record + items?: Record< + string, + Array<{ + name: string + id: string + }> + > + ident: string + order: number + layout?: { + x: number + y: number + w?: number + h?: number + height?: number + horizontalHandles?: boolean + [key: string]: unknown + } + codeFile?: string + [key: string]: unknown + } + > + variables: Record + [key: string]: unknown + } + base: { + version?: 1 + workflowId: string + workspaceId: string + fingerprint: string + catalogHash: string + [key: string]: unknown + } +} + +export type PlanWorkflowSourceResponse = { + data: { + workflowId: string + workspaceId: string + dryRun: boolean + applied: boolean + diff: { + noop: boolean + meta?: Array<'name' | 'description'> + blocks: { + added: Array<{ + id: string + key: string + type: string + }> + removed: Array<{ + id: string + key: string + type: string + }> + renamed: Array<{ + id: string + from: string + to: string + }> + modified: Array<{ + id: string + key: string + fields: Array + reparented?: boolean + }> + } + edges: { + added: number + removed: number + } + variables: { + added: Array + removed: Array + modified: Array + } + } + diagnostics: Array<{ + code: + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_LIMIT_EXCEEDED' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_STALE' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_META_INVALID' + severity: 'error' | 'warning' | 'info' + message: string + hint?: string + blockKey?: string + param?: string + file?: string + line?: number + column?: number + endLine?: number + endColumn?: number + frame?: string + blockId?: string + path?: string + }> + files: Record + lock: { + version: 1 + blocks: Record< + string, + { + id: string + parent: string | null + branches?: Record + items?: Record< + string, + Array<{ + name: string + id: string + }> + > + ident: string + order: number + layout?: { + x: number + y: number + w?: number + h?: number + height?: number + horizontalHandles?: boolean + [key: string]: unknown + } + codeFile?: string + [key: string]: unknown + } + > + variables: Record + [key: string]: unknown + } + base: { + version: 1 + workflowId: string + workspaceId: string + fingerprint: string + catalogHash: string + [key: string]: unknown + } + mintedIds: Record + notes: Array + needsRedeployment: boolean + } +} + +/** `POST /api/v2/workspaces/[workspaceId]/source/plan` */ +export type PlanWorkspaceSourceParams = { + workspaceId: string +} + +export type PlanWorkspaceSourceQuery = Record + +export type PlanWorkspaceSourceBody = { + files: Record + blobs?: Array<{ + path: string + sha256: string + size: number + }> + base?: { + version: 1 + workspaceId: string + resources: Record< + string, + { + id: string + fingerprint?: string + columns?: Record< + string, + { + id: string + options?: Record + } + > + blobs?: Record< + string, + { + id: string + rev: number | string + sha256: string + } + > + rows?: { + fingerprint: string + version: number + [key: string]: unknown + } + [key: string]: unknown + } + > + [key: string]: unknown + } + kinds: Array< + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + > + options?: { + allowDelete?: boolean + only?: Array< + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + > + } +} + +export type PlanWorkspaceSourceResponse = { + data: { + workspaceId: string + dryRun: boolean + plan: Array<{ + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' + fields?: Array + destructive?: { + what: string + counts: Record + } + id?: string + held?: true + }> + applied: Array<{ + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' + fields?: Array + destructive?: { + what: string + counts: Record + } + id?: string + held?: true + }> + failed?: { + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + code: + | 'E_DECL_SYNTAX' + | 'E_DECL_HEADER' + | 'E_DECL_IMPORT' + | 'E_DECL_EXPORT' + | 'E_DECL_UNSUPPORTED' + | 'E_DECL_DUPLICATE_KEY' + | 'E_DECL_SHAPE' + | 'E_DECL_UNKNOWN_FIELD' + | 'E_DECL_UNKNOWN_FILE' + | 'W_PATH_NOT_SENT' + | 'E_BLOB_MANIFEST' + | 'E_BLOB_MISSING' + | 'E_LIMIT_EXCEEDED' + | 'E_KEY_INVALID' + | 'W_DECL_SUSPICIOUS_CHARACTER' + | 'E_BASE_JSON' + | 'E_BASE_VERSION' + | 'E_BASE_SHAPE' + | 'E_BASE_UNKNOWN_FIELD' + | 'E_SECRET_NAME' + | 'E_SECRET_MISSING' + | 'W_SECRET_MISSING' + | 'E_CREDENTIAL_MISSING' + | 'E_CREDENTIAL_AMBIGUOUS' + | 'W_CREDENTIAL_MISSING' + | 'W_CREDENTIAL_AMBIGUOUS' + | 'E_TABLE_COLUMN_NAME' + | 'E_TABLE_DUPLICATE_COLUMN' + | 'E_TABLE_TOO_MANY_COLUMNS' + | 'E_TABLE_OPTIONS' + | 'E_TABLE_TYPE_CONVERSION' + | 'E_TABLE_FOLDER' + | 'E_TABLE_ROWS' + | 'I_TABLE_SEED_SKIPPED' + | 'I_TABLE_ROWS_UNKEYED' + | 'W_LIKELY_RENAME' + | 'E_TOOL_SCHEMA' + | 'E_TOOL_CODE' + | 'E_TOOL_STORED_MISSING' + | 'W_TOOL_LITERAL_SECRET' + | 'E_SKILL_FRONTMATTER' + | 'E_MCP_LITERAL_SECRET' + | 'E_MCP_STORED_MISSING' + | 'E_MCP_TOOL_UNKNOWN' + | 'W_MCP_REPLACE' + | 'W_MCP_TOOLS_UNCHECKED' + | 'E_FILE_PATH' + | 'E_FILE_PATH_COLLISION' + | 'E_FILE_NAME' + | 'E_FILE_TOO_LARGE' + | 'E_FILE_CONTENT' + | 'E_KB_EMBEDDING_IMMUTABLE' + | 'E_KB_EMBEDDING_MODEL' + | 'E_KB_DOC_AMBIGUOUS' + | 'E_KB_DOC_NAME' + | 'E_KB_DOC_EMPTY' + | 'E_KB_CHUNKING' + | 'E_KB_FOLDER' + | 'W_KB_DOC_UNCHECKED' + | 'W_KB_DOC_FAILED' + | 'I_KB_REEMBED' + | 'I_KB_CHUNKING' + | 'I_KB_PROCESSING' + | 'I_KB_DOCS_UNHASHED' + | 'I_KB_UNMANAGED_DOCS' + | 'I_KB_REPLACE_UNFINISHED' + | 'E_DEPLOY_WORKFLOW' + | 'E_DEPLOY_SECRET' + | 'E_DEPLOY_CHAT_OUTPUT' + | 'E_DEPLOY_CHAT_IDENTIFIER' + | 'E_DEPLOY_PINNED_CHAT' + | 'W_DEPLOYED_DRAFT_CHANGED' + | 'I_DEPLOY_DRAFT_NOT_LIVE' + | 'E_APPLY_STALE' + | 'E_APPLY_NO_BASE' + | 'E_APPLY_FORBIDDEN' + | 'E_APPLY_DELETE_NOT_ALLOWED' + | 'E_APPLY_LOCKED' + | 'E_APPLY_REFUSED' + | 'E_APPLY_FAILED' + | 'E_PLAN_TOO_LARGE' + | 'E_PLAN_REF_DELETED' + | 'E_PLAN_REF_HELD' + | 'W_RESOURCE_IN_USE' + | 'W_TABLE_COLUMN_RENAMED_IN_USE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_FILES_MISSING' + | 'E_WORKFLOW_FOLDER_COPIED' + | 'W_UNDECLARED' + | 'W_BASE_OTHER_WORKSPACE' + | 'I_SERVER_CHANGED' + | 'I_SERVER_DELETED' + | 'I_SERVER_MOVED' + | 'I_KEY_REBOUND' + | 'E_KEY_RENAMED' + | 'I_FINDINGS_TRUNCATED' + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_WORKFLOW_META_INVALID' + message: string + } + needBlobs: Array + applyId?: string + files: Record + base: { + version: 1 + workspaceId: string + resources: Record< + string, + { + id: string + fingerprint?: string + columns?: Record< + string, + { + id: string + options?: Record + } + > + blobs?: Record< + string, + { + id: string + rev: number | string + sha256: string + } + > + rows?: { + fingerprint: string + version: number + [key: string]: unknown + } + [key: string]: unknown + } + > + [key: string]: unknown + } + diagnostics: Array<{ + code: + | 'E_DECL_SYNTAX' + | 'E_DECL_HEADER' + | 'E_DECL_IMPORT' + | 'E_DECL_EXPORT' + | 'E_DECL_UNSUPPORTED' + | 'E_DECL_DUPLICATE_KEY' + | 'E_DECL_SHAPE' + | 'E_DECL_UNKNOWN_FIELD' + | 'E_DECL_UNKNOWN_FILE' + | 'W_PATH_NOT_SENT' + | 'E_BLOB_MANIFEST' + | 'E_BLOB_MISSING' + | 'E_LIMIT_EXCEEDED' + | 'E_KEY_INVALID' + | 'W_DECL_SUSPICIOUS_CHARACTER' + | 'E_BASE_JSON' + | 'E_BASE_VERSION' + | 'E_BASE_SHAPE' + | 'E_BASE_UNKNOWN_FIELD' + | 'E_SECRET_NAME' + | 'E_SECRET_MISSING' + | 'W_SECRET_MISSING' + | 'E_CREDENTIAL_MISSING' + | 'E_CREDENTIAL_AMBIGUOUS' + | 'W_CREDENTIAL_MISSING' + | 'W_CREDENTIAL_AMBIGUOUS' + | 'E_TABLE_COLUMN_NAME' + | 'E_TABLE_DUPLICATE_COLUMN' + | 'E_TABLE_TOO_MANY_COLUMNS' + | 'E_TABLE_OPTIONS' + | 'E_TABLE_TYPE_CONVERSION' + | 'E_TABLE_FOLDER' + | 'E_TABLE_ROWS' + | 'I_TABLE_SEED_SKIPPED' + | 'I_TABLE_ROWS_UNKEYED' + | 'W_LIKELY_RENAME' + | 'E_TOOL_SCHEMA' + | 'E_TOOL_CODE' + | 'E_TOOL_STORED_MISSING' + | 'W_TOOL_LITERAL_SECRET' + | 'E_SKILL_FRONTMATTER' + | 'E_MCP_LITERAL_SECRET' + | 'E_MCP_STORED_MISSING' + | 'E_MCP_TOOL_UNKNOWN' + | 'W_MCP_REPLACE' + | 'W_MCP_TOOLS_UNCHECKED' + | 'E_FILE_PATH' + | 'E_FILE_PATH_COLLISION' + | 'E_FILE_NAME' + | 'E_FILE_TOO_LARGE' + | 'E_FILE_CONTENT' + | 'E_KB_EMBEDDING_IMMUTABLE' + | 'E_KB_EMBEDDING_MODEL' + | 'E_KB_DOC_AMBIGUOUS' + | 'E_KB_DOC_NAME' + | 'E_KB_DOC_EMPTY' + | 'E_KB_CHUNKING' + | 'E_KB_FOLDER' + | 'W_KB_DOC_UNCHECKED' + | 'W_KB_DOC_FAILED' + | 'I_KB_REEMBED' + | 'I_KB_CHUNKING' + | 'I_KB_PROCESSING' + | 'I_KB_DOCS_UNHASHED' + | 'I_KB_UNMANAGED_DOCS' + | 'I_KB_REPLACE_UNFINISHED' + | 'E_DEPLOY_WORKFLOW' + | 'E_DEPLOY_SECRET' + | 'E_DEPLOY_CHAT_OUTPUT' + | 'E_DEPLOY_CHAT_IDENTIFIER' + | 'E_DEPLOY_PINNED_CHAT' + | 'W_DEPLOYED_DRAFT_CHANGED' + | 'I_DEPLOY_DRAFT_NOT_LIVE' + | 'E_APPLY_STALE' + | 'E_APPLY_NO_BASE' + | 'E_APPLY_FORBIDDEN' + | 'E_APPLY_DELETE_NOT_ALLOWED' + | 'E_APPLY_LOCKED' + | 'E_APPLY_REFUSED' + | 'E_APPLY_FAILED' + | 'E_PLAN_TOO_LARGE' + | 'E_PLAN_REF_DELETED' + | 'E_PLAN_REF_HELD' + | 'W_RESOURCE_IN_USE' + | 'W_TABLE_COLUMN_RENAMED_IN_USE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_FILES_MISSING' + | 'E_WORKFLOW_FOLDER_COPIED' + | 'W_UNDECLARED' + | 'W_BASE_OTHER_WORKSPACE' + | 'I_SERVER_CHANGED' + | 'I_SERVER_DELETED' + | 'I_SERVER_MOVED' + | 'I_KEY_REBOUND' + | 'E_KEY_RENAMED' + | 'I_FINDINGS_TRUNCATED' + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_WORKFLOW_META_INVALID' + severity: 'error' | 'warning' | 'info' + message: string + hint?: string + file?: string + line?: number + column?: number + endLine?: number + endColumn?: number + frame?: string + path?: string + kind?: string + key?: string + blockKey?: string + param?: string + }> + } +} + /** `POST /api/v2/organizations/[organizationId]/search/sources/prepare` */ export type PrepareSearchSourcesParams = { organizationId: string @@ -26513,6 +27502,75 @@ export const V2_OPERATIONS = { }, }, }, + planWorkflowSource: { + method: 'POST', + path: '/api/v2/workflows/[workflowId]/source/plan', + pathParams: ['workflowId'] as const, + pathParamDocs: { workflowId: 'Unique workflow identifier.' }, + responseMode: 'json', + summary: 'Plan workflow source', + workspaceKeyUnsupported: true, + query: { + allowDelete: { + kind: 'boolean', + describe: + 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.', + }, + }, + body: { + files: { + kind: 'object', + required: true, + describe: + 'Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks.', + }, + lock: { + kind: 'object', + required: true, + describe: + 'Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids.', + }, + base: { + kind: 'object', + required: true, + describe: + 'Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`.', + }, + }, + }, + planWorkspaceSource: { + method: 'POST', + path: '/api/v2/workspaces/[workspaceId]/source/plan', + pathParams: ['workspaceId'] as const, + pathParamDocs: { workspaceId: 'Workspace to read or apply.' }, + responseMode: 'json', + summary: 'Plan workspace source', + body: { + files: { + kind: 'object', + required: true, + describe: + 'Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged.', + }, + blobs: { + kind: 'array', + describe: + 'Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.', + }, + base: { + kind: 'object', + describe: + '`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change.', + }, + kinds: { + kind: 'array', + required: true, + describe: + 'The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent.', + }, + options: { kind: 'object', describe: 'How far the apply may go.' }, + }, + }, prepareSearchSources: { method: 'POST', path: '/api/v2/organizations/[organizationId]/search/sources/prepare', diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index b3865a8c1a1..cd84dc5496f 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -707,6 +707,9 @@ describe('destructive operations are gated', () => { /** Staging blob bytes for a workspace source apply writes nothing a user sees. */ 'findMissingWorkspaceSourceBlobs', 'stageWorkspaceSourceBlobs', + /** A source plan is a read sent as a POST: it writes nothing. */ + 'planWorkflowSource', + 'planWorkspaceSource', 'completeProjectFileUpload', 'copyFileItems', 'createProjectFile', From a7cc0ec864d832af35e0878d788fd1a67a0326a6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:28:07 -0800 Subject: [PATCH 027/104] docs(cli): regenerate the CLI reference for the source command help changes --- apps/docs/content/docs/cli/reference.mdx | 20 ++++++++++---------- apps/docs/content/docs/cli/workflows.mdx | 12 ++++++------ apps/docs/content/docs/cli/workspaces.mdx | 8 ++++---- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 60bc460217c..312a636ccc0 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8546,7 +8546,7 @@ sim workflows source get [options] -Exit codes with --dir: 0 written; 1 the command failed, or the directory 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); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again. Exit 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit codes with --dir: 0 written; 1 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); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again. Exit 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getWorkflowSource](/api-reference/workflows/getWorkflowSource). @@ -8575,17 +8575,17 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | -| `--dir ` | Yes | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. | +| `--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. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | +| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 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 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. 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: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow). +API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getSourceResources](/api-reference/workflows/getSourceResources). ### sim workflows source create @@ -8640,7 +8640,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -8664,7 +8664,7 @@ sim workflows 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). -API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### sim workflows source diff @@ -9959,7 +9959,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), 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. +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. 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. @@ -9980,7 +9980,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | -| `--dir ` | Yes | Workspace source directory written by `workspaces source get`. | +| `--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. | | `--allow-delete` | No | Delete resources, columns and data the directory no longer declares. | @@ -10018,7 +10018,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). 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. @@ -10049,7 +10049,7 @@ Exit codes: 0 clean (nothing to apply, and the server changed nothing since the 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. -API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). ### sim workspaces source diff diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 2e9b7cb38de..b24f0b68149 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1316,7 +1316,7 @@ sim workflows source get [options] -Exit codes with --dir: 0 written; 1 the command failed, or the directory 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); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again. Exit 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit codes with --dir: 0 written; 1 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); 7 the workflow is too large to print as source; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again. Exit 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. API request and response schemas: [getWorkflowSource](/api-reference/workflows/getWorkflowSource). @@ -1340,7 +1340,7 @@ sim workflows 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). -API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### Create a workflow from a workflow source directory @@ -1391,17 +1391,17 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | -| `--dir ` | Yes | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. | +| `--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. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | +| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 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 10 (busy, retry): --dir is a workflow folder of a workspace directory another sim command is using (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. 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: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow). +API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getSourceResources](/api-reference/workflows/getSourceResources). ### Show the block catalog workflow source is checked against @@ -1444,7 +1444,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 9f08d62589f..e7a6ba6c4c7 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), 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. +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. 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. @@ -737,7 +737,7 @@ Exit codes: 0 clean (nothing to apply, and the server changed nothing since the 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. -API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). ### Apply a workspace source directory @@ -752,7 +752,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | With --output json, also list info findings (such as blocks placed by autolayout). | -| `--dir ` | Yes | Workspace source directory written by `workspaces source get`. | +| `--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. | | `--allow-delete` | No | Delete resources, columns and data the directory no longer declares. | @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). 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. From 5764c4a4899720a3d70ff60ff5fe84e6de687fec Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:38:35 -0800 Subject: [PATCH 028/104] fix(workspace-source): an adopt never changes or removes what the directory never read A declaration naming an unbound resource of the same name adopted it and planned the full diff against it with no base: a skill or tool was overwritten, and a table lost its columns and rows under --allow-delete. An adopt may now only add to the resource (bind its key when the declaration matches, add a column, rows into an empty table, a knowledge base document), which keeps a stopped create converging; any other adopt is E_APPLY_NO_BASE naming what it would change, for tables, skills, custom tools, knowledge bases and MCP servers. --- .../content/docs/workflows/workspace-code.mdx | 2 + .../application/apply.integration.ts | 11 +- .../workspace-source/application/findings.ts | 23 +++ .../application/kinds/knowledge/adapter.ts | 15 +- .../application/kinds/mcp/adapter.ts | 14 +- .../application/kinds/named.ts | 16 +- .../application/kinds/table/adapter.ts | 37 +++- .../application/knowledge.integration.ts | 34 ++++ .../application/rows.integration.ts | 40 +++++ .../workspace-source/application/three-way.ts | 30 +++- .../application/tools-skills.integration.ts | 163 +++++++++++------- packages/workspace-code/DESIGN.md | 14 +- 12 files changed, 314 insertions(+), 85 deletions(-) diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx index 17ae4599e93..502ea417c9f 100644 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ b/apps/docs/content/docs/workflows/workspace-code.mdx @@ -64,6 +64,8 @@ sim workspaces source apply --dir ./my-workspace --yes The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. +An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. + `status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the editor included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). ## Workspace API keys [#workspace-api-keys] diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index 5da8cd14002..34f121f9790 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -595,7 +595,7 @@ describe('workspace source apply', () => { input: { workspaceId, name: 'contacts', - schema: { columns: [{ name: 'email', type: 'string' }] }, + schema: { columns: [{ name: 'email', type: 'string', required: true }] }, }, }) const adopted = await apply( @@ -1230,7 +1230,6 @@ export default workflow('Notes', {}, () => { expect(failed.failed).toMatchObject({ kind: 'table', key: 'leads', code: 'E_APPLY_FAILED' }) expect(adds).toBe(1) expect(await tableSnapshot(workspaceId)).toEqual(before) - expect((await storedTable(workspaceId)).description ?? null).toBeNull() expect( await db.select().from(userTableRows).where(eq(userTableRows.workspaceId, workspaceId)) ).toEqual(rows) @@ -1427,12 +1426,7 @@ export default workflow('Notes', {}, () => { schema: { columns: [{ name: 'email', type: 'string', required: true }] }, }, }) - const files = { - 'tables/leads.ts': LEADS.replace( - "name: 'leads',", - "name: 'leads',\n description: 'Inbound leads'," - ), - } + const files = { 'tables/leads.ts': LEADS } const before = await tableSnapshot(workspaceId) const failing = vi .spyOn(columnService, 'addTableColumn') @@ -1446,7 +1440,6 @@ export default workflow('Notes', {}, () => { expect(failed.failed).toMatchObject({ kind: 'table', key: 'leads' }) expect(failed.base.resources['table:leads']).toBeUndefined() expect(await tableSnapshot(workspaceId)).toEqual(before) - expect((await storedTable(workspaceId)).description ?? null).toBeNull() const rerun = await apply(workspaceId, files, { base: failed.base, diff --git a/apps/sim/lib/workspace-source/application/findings.ts b/apps/sim/lib/workspace-source/application/findings.ts index dda12873ddb..95e50564369 100644 --- a/apps/sim/lib/workspace-source/application/findings.ts +++ b/apps/sim/lib/workspace-source/application/findings.ts @@ -86,6 +86,29 @@ export function noBaseFinding(kind: WorkspaceKind, key: string): WorkspaceSource ) } +/** + * `E_APPLY_NO_BASE` for an adopt: the server holds a resource of the declared name that no source + * has named and this directory never read, and adopting it would change or remove `changes` of + * what it holds. + */ +export function unreadAdoptFinding( + kind: WorkspaceKind, + key: string, + name: string, + changes: readonly string[] +): WorkspaceSourceDiagnostic { + const noun = WORKSPACE_KIND_SPECS[kind].noun + return kindFinding( + kind, + key, + 'E_APPLY_NO_BASE', + `${where(kind, key)} declares the ${noun} "${name}", which already exists and this directory never read; adopting it would change ${changes.join(', ')}. An apply never changes or removes what the directory has not read.`, + { + hint: `Run \`sim workspaces source get\` into a fresh directory to read the ${noun}, then make your edit there; or give the declaration another name to create a new ${noun}.`, + } + ) +} + /** `I_SERVER_CHANGED`: the server drifted; the directory leaves the resource as it is. */ export function serverChangedFinding(kind: WorkspaceKind, key: string): WorkspaceSourceDiagnostic { return kindFinding( 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 b59d2b86d78..36c40d06f83 100644 --- a/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts @@ -72,7 +72,12 @@ import { type StoredKnowledgeState, sourceDocs, } from '@/lib/workspace-source/application/kinds/knowledge/stored' -import { holdsIn, resolveDeclared, settle } from '@/lib/workspace-source/application/three-way' +import { + holdsIn, + refuseUnreadAdopt, + resolveDeclared, + settle, +} from '@/lib/workspace-source/application/three-way' import type { AppliedResource, ApplyContext, @@ -302,6 +307,14 @@ async function planKnowledgeBase( ...(planned.action === 'update' ? { base: planned.base } : {}), ctx, }) + if (planned.action === 'adopt') { + const refused = refuseUnreadAdopt( + change, + resource, + changes.fields.filter((field) => !field.endsWith(' (add)')) + ) + if (refused) return refused + } if (changes.settings.name !== undefined) { change.diagnostics.push(...nameTaken(key, changes.settings.name, stored, resource.id)) } diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index 2ae18d1be15..3817e111df7 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -4,7 +4,8 @@ * allowlist and SSRF checks included), audit and cache invalidation apply unchanged. * * A server's id derives from its URL (`generateMcpServerId`), so the URL is its identity: an - * unbound server at the declared URL is adopted, two declarations of one URL refuse, and a URL + * unbound server at the declared URL is adopted when the declaration matches it (any other adopt is + * refused, see `refuseUnreadAdopt`), two declarations of one URL refuse, and a URL * that keeps the id (only its query string differs) is set in place through the reconfigure use * case, which validates the URL before it writes anything. A URL with a new id replaces the server * (created at the new URL, then the old one deleted). A replace breaks stored workflows that still @@ -72,7 +73,12 @@ import { resolveStoredHeaders, storedFingerprint, } from '@/lib/workspace-source/application/kinds/mcp/stored' -import { holdsIn, resolveDeclared, settle } from '@/lib/workspace-source/application/three-way' +import { + holdsIn, + refuseUnreadAdopt, + resolveDeclared, + settle, +} from '@/lib/workspace-source/application/three-way' import type { AppliedResource, KindAdapter, @@ -218,6 +224,10 @@ async function planServer( } const record = planned.stored const changed = changedFields(declOf(record.state), decl) + if (planned.action === 'adopt' && !resumed) { + const refused = refuseUnreadAdopt(change, record, changed) + if (refused) return refused + } const update: McpChange = { ...change, action: planned.action, diff --git a/apps/sim/lib/workspace-source/application/kinds/named.ts b/apps/sim/lib/workspace-source/application/kinds/named.ts index abf797b1bbb..5acca3c1489 100644 --- a/apps/sim/lib/workspace-source/application/kinds/named.ts +++ b/apps/sim/lib/workspace-source/application/kinds/named.ts @@ -1,8 +1,9 @@ /** * The plan and write rules of a kind whose resource is one record under a unique display name * (custom tools by title, skills by name): keys bind to stored ids, the three-way rule decides - * each declared resource, an unbound record of the same name is adopted, and a name another - * resource holds is `E_NAME_TAKEN` naming that resource's key. + * each declared resource, an unbound record of the same name is adopted only when the declaration + * matches it (see `refuseUnreadAdopt`), and a name another resource holds is `E_NAME_TAKEN` naming + * that resource's key. */ import { isRecordLike } from '@sim/utils/object' import type { Json } from '@sim/workflow-code' @@ -24,7 +25,12 @@ import { refuseDeclaredTwice, } from '@/lib/workspace-source/application/findings' import { pendingOf } from '@/lib/workspace-source/application/keys' -import { holdsIn, resolveDeclared, settle } from '@/lib/workspace-source/application/three-way' +import { + holdsIn, + refuseUnreadAdopt, + resolveDeclared, + settle, +} from '@/lib/workspace-source/application/three-way' import type { AppliedResource, DeclOf, @@ -144,6 +150,10 @@ export function planNamed( named.codec.canonical(named.declOf(state)), named.codec.canonical(decl) ) + if (planned.action === 'adopt') { + const refused = refuseUnreadAdopt(change, planned.stored, changed) + if (refused) return refused + } if (named.nameOf(named.declOf(state)) !== name) holderOf(id) return { ...change, diff --git a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts index 8a7944b076b..cc4f497d78f 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts @@ -12,7 +12,9 @@ * refuses a row version that moved since the plan. The reshape writes only the rows that differ, * matched by the key column (`writeKeyedRowsWithTx`): an unchanged row keeps its id and run state * and fires no trigger. Removing a stored row needs `--allow-delete`. Seed rows are inserted into - * a table the apply creates, or adopts while it holds no rows. + * a table the apply creates, or adopts while it holds no rows. A table adopted by name (one the + * directory never read) may only gain columns and rows into an empty table; any other change to + * it is refused (`refuseUnreadAdopt`). */ import { setOwn } from '@sim/workflow-code' import { @@ -86,7 +88,12 @@ import { storedFingerprint, tableAsDecl, } from '@/lib/workspace-source/application/kinds/table/stored' -import { holdsIn, resolveDeclared, settle } from '@/lib/workspace-source/application/three-way' +import { + holdsIn, + refuseUnreadAdopt, + resolveDeclared, + settle, +} from '@/lib/workspace-source/application/three-way' import type { AppliedResource, KindAdapter, @@ -496,6 +503,24 @@ function columnsRenamedOnServer( }) } +/** + * What adopting a table would change or remove of what it holds (see `refuseUnreadAdopt`): every + * table and column change but an added column, and the rows when it writes over stored ones or + * stops managing them. Rows written into an empty table only add to it. + */ +function changedOnAdopt( + changes: TableChanges, + rows: RowsOutcome, + state: StoredTableState +): string[] { + const fields = changes.fields.filter((field) => !field.endsWith(' (add)')) + const rowsChanged = + rows.plan !== undefined && + state.table.rowCount > 0 && + (rows.plan.write !== undefined || rows.plan.mark === null) + return rowsChanged ? [...fields, ...rows.fields] : fields +} + async function planTable( key: string, decl: TableDecl, @@ -584,6 +609,14 @@ async function planTable( ctx ) const changes = await diffTable(key, decl, state, bindings, rows.kept) + if (planned.action === 'adopt') { + const refused = refuseUnreadAdopt( + change, + planned.stored, + changedOnAdopt(changes, rows, state) + ) + if (refused) return refused + } change.diagnostics.push(...changes.diagnostics, ...rows.diagnostics) const changed = changes.columns.length > 0 || changes.fields.length > 0 || rows.plan !== undefined diff --git a/apps/sim/lib/workspace-source/application/knowledge.integration.ts b/apps/sim/lib/workspace-source/application/knowledge.integration.ts index 6161edc554c..436c51b0d8e 100644 --- a/apps/sim/lib/workspace-source/application/knowledge.integration.ts +++ b/apps/sim/lib/workspace-source/application/knowledge.integration.ts @@ -1379,6 +1379,40 @@ describe('knowledge bases as workspace source', () => { } ) + check( + 'refuses adopting a knowledge base the directory never read when it would replace a document or change a setting', + async () => { + const workspaceId = await newWorkspace() + const { knowledgeBase: unbound } = await createKnowledgeBase.execute({ + principal: owner, + input: { workspaceId, name: 'Policies', description: 'A teammate keeps this one' }, + }) + const teammate = Buffer.from('# Refunds\nA teammate wrote this.\n') + await uploadKnowledgeDocument.execute({ + principal: owner, + input: { + knowledgeBaseId: unbound.id, + file: { + buffer: teammate, + filename: 'refunds.md', + fileSize: teammate.byteLength, + mimeType: 'text/markdown', + }, + }, + }) + await indexed(workspaceId) + const before = await snapshot(workspaceId) + + const refused = await refusal(apply(workspaceId, POLICIES)) + + expect(codes(refused.diagnostics)).toEqual(['E_APPLY_NO_BASE']) + expect(refused.diagnostics.find((d) => d.code === 'E_APPLY_NO_BASE')?.message).toContain( + 'description, docs/refunds.md (replace)' + ) + expect(await snapshot(workspaceId)).toEqual(before) + } + ) + check( 'an adopt that fails partway leaves the key free, so the next apply adopts again', async () => { diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index 9dce9850bac..1cc30a40837 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -21,6 +21,7 @@ import { and, eq, inArray, isNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, vi } from 'vitest' import { updateTableColumnUseCase } from '@/lib/table/application/columns' import { createTableRows } from '@/lib/table/application/rows' +import { createTableUseCase } from '@/lib/table/application/tables' import { readCurrentRowsVersion } from '@/lib/table/row-changes' import { getTableById } from '@/lib/table/service' import type { ApplyWorkspaceSourceInput } from '@/lib/workspace-source/application/apply-workspace-source' @@ -730,6 +731,45 @@ export default defineTable({ ]) }) + check( + 'refuses adopting a table the directory never read when it would drop its columns or rows, even with --allow-delete', + async () => { + const workspaceId = await newWorkspace() + await createTableUseCase.execute({ + principal: owner, + input: { + workspaceId, + name: 'plans', + schema: { + columns: [ + { name: 'code', type: 'string', required: true, unique: true }, + { name: 'seats', type: 'number' }, + { name: 'notes', type: 'string' }, + ], + }, + }, + }) + for (const code of ['solo', 'team', 'ent']) await addUiRow(workspaceId, { code, notes: code }) + const columnsBefore = (await storedTable(workspaceId)).schema.columns + const rowsBefore = await storedRows(workspaceId) + + const refused = await refusal( + apply( + workspaceId, + { 'tables/plans.ts': MANAGED, 'tables/plans.rows.jsonl': ROWS }, + { allowDelete: true } + ) + ) + + expect(codes(refused.diagnostics)).toEqual(['E_APPLY_NO_BASE']) + expect( + refused.diagnostics.find((finding) => finding.code === 'E_APPLY_NO_BASE')?.message + ).toContain('columns.notes (drop)') + expect((await storedTable(workspaceId)).schema.columns).toEqual(columnsBefore) + expect(await storedRows(workspaceId)).toEqual(rowsBefore) + } + ) + check('seeds a new table once, and only a new or empty one', async () => { const workspaceId = await newWorkspace() const files = { 'tables/plans.ts': SEED, 'tables/plans.rows.jsonl': ROWS } diff --git a/apps/sim/lib/workspace-source/application/three-way.ts b/apps/sim/lib/workspace-source/application/three-way.ts index 5db3f203778..c25f604f3b3 100644 --- a/apps/sim/lib/workspace-source/application/three-way.ts +++ b/apps/sim/lib/workspace-source/application/three-way.ts @@ -4,6 +4,7 @@ import { serverChangedFinding, serverGoneFinding, staleFinding, + unreadAdoptFinding, } from '@/lib/workspace-source/application/findings' import type { KindChange, @@ -90,7 +91,8 @@ export function holdsIn(set: StoredSet): (id: string) => boolean { * base (an earlier apply created it but never wrote its base back), and any other is * `no-base` (get it first). With nothing stored under the key, a resource the base records but * the server no longer holds was deleted there and stays deleted (`deleted`); otherwise an - * unbound resource of the same name is adopted, else the resource is created. + * unbound resource of the same name is adopted (which may only add to it, see + * {@link refuseUnreadAdopt}), else the resource is created. */ export function resolveDeclared(input: { local: string @@ -180,3 +182,29 @@ export function settle>( return resolution } } + +/** + * Refuses an adopt that would change or remove anything the stored resource holds: the directory + * never read that resource (no source named it), so like a bound resource without a base + * (`no-base`) it cannot tell its declaration from someone else's work. An adopt may still add + * what the resource lacks, so an apply that stopped after creating a resource (a knowledge base + * before its documents, a table before its rows) finishes it, and a declaration that matches the + * resource binds its key. `changes` names what the adopt would change or remove (the plan's + * field labels); empty lets the adopt go ahead and returns `undefined`. + */ +export function refuseUnreadAdopt>( + change: C, + stored: Pick, 'id' | 'name'>, + changes: readonly string[] +): C | undefined { + if (changes.length === 0) return undefined + return { + ...change, + action: 'noop', + storedId: stored.id, + diagnostics: [ + ...change.diagnostics, + unreadAdoptFinding(change.kind, change.key, stored.name, changes), + ], + } +} diff --git a/apps/sim/lib/workspace-source/application/tools-skills.integration.ts b/apps/sim/lib/workspace-source/application/tools-skills.integration.ts index c37401875b8..dbbabf5bb18 100644 --- a/apps/sim/lib/workspace-source/application/tools-skills.integration.ts +++ b/apps/sim/lib/workspace-source/application/tools-skills.integration.ts @@ -12,7 +12,6 @@ import { generateId } from '@sim/utils/id' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { eq, inArray, sql } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, vi } from 'vitest' -import { OrchestrationError } from '@/lib/core/orchestration/types' import { createWorkspaceCustomToolUseCase, deleteWorkspaceCustomToolUseCase, @@ -23,6 +22,7 @@ import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/ut import type { ApplyWorkspaceSourceInput } from '@/lib/workspace-source/application/apply-workspace-source' import { codes, + failKeyClaims, refusal, sourceChecks, sourceRunner, @@ -105,6 +105,36 @@ const LEGACY_SCHEMA = { const TOOLS: Record = { 'tools/lookup.ts': LOOKUP, 'tools/lookup.js': LOOKUP_CODE } const SKILLS: Record = { 'skills/tone.md': TONE } +/** The schema {@link LOOKUP} declares, as a tool made outside source stores it. */ +const LOOKUP_SCHEMA = { + type: 'function', + function: { + name: 'lookup_order', + parameters: { type: 'object', properties: { orderId: { type: 'string' } } }, + }, +} + +/** + * A tool and a skill made outside source that hold exactly what {@link LOOKUP} (with `code`) and + * {@link TONE} declare, so an apply may adopt them by name. + */ +async function createMatching(workspaceId: string, code: string) { + const { tool } = await createWorkspaceCustomToolUseCase.execute({ + principal: owner, + input: { workspaceId, title: 'Lookup order', schema: LOOKUP_SCHEMA, code }, + }) + const { skill: matching } = await createSkillUseCase.execute({ + principal: owner, + input: { + workspaceId, + name: 'tone', + description: 'Voice: short and warm', + content: 'Write like a person.\n', + }, + }) + return { tool, skill: matching } +} + async function newWorkspace(): Promise { return workspaces.create({ name: 'Workspace source tools', @@ -563,10 +593,27 @@ describe('workspace source: custom tools and skills', () => { expect(second.id).not.toBe(first.id) const fresh = await newWorkspace() - const { tool } = await createWorkspaceCustomToolUseCase.execute({ + const { tool, skill: unbound } = await createMatching(fresh, 'return 0\n') + const adopted = await apply(fresh, { + 'tools/orders.ts': LOOKUP.replace('./lookup.js', './orders.js'), + 'tools/orders.js': 'return 0\n', + 'skills/style.md': TONE, + }) + expect(adopted.applied).toMatchObject([ + { action: 'adopt', kind: 'custom-tool', key: 'orders', id: tool.id }, + { action: 'adopt', kind: 'skill', key: 'style', id: unbound.id }, + ]) + } + ) + + check( + 'refuses adopting a tool or skill the directory never read whose content differs, and adopts one that matches', + async () => { + const workspaceId = await newWorkspace() + await createWorkspaceCustomToolUseCase.execute({ principal: owner, input: { - workspaceId: fresh, + workspaceId, title: 'Lookup order', schema: { type: 'function', @@ -575,41 +622,54 @@ describe('workspace source: custom tools and skills', () => { code: 'return 1', }, }) - const { skill: unbound } = await createSkillUseCase.execute({ + await createSkillUseCase.execute({ principal: owner, - input: { workspaceId: fresh, name: 'tone', description: 'Old', content: 'Old' }, + input: { + workspaceId, + name: 'tone', + description: 'Hand-written', + content: 'A teammate wrote this.', + }, }) - const adopted = await apply(fresh, { - 'tools/orders.ts': LOOKUP.replace('./lookup.js', './orders.js'), - 'tools/orders.js': 'return 0\n', - 'skills/style.md': TONE, + const before = await snapshot(workspaceId) + + const refused = await refusal(apply(workspaceId, { ...TOOLS, ...SKILLS })) + + expect( + refused.diagnostics + .filter((finding) => finding.severity === 'error') + .map(({ code, kind, key }) => `${code} ${kind}:${key}`) + ).toEqual(['E_APPLY_NO_BASE custom-tool:lookup', 'E_APPLY_NO_BASE skill:tone']) + expect(refused.diagnostics.find((finding) => finding.kind === 'skill')?.message).toContain( + 'description, content' + ) + expect(await snapshot(workspaceId)).toEqual(before) + + const matching = await newWorkspace() + const { skill: same } = await createSkillUseCase.execute({ + principal: owner, + input: { + workspaceId: matching, + name: 'tone', + description: 'Voice: short and warm', + content: 'Write like a person.\n', + }, }) - expect(adopted.applied).toMatchObject([ - { action: 'adopt', kind: 'custom-tool', key: 'orders', id: tool.id }, - { action: 'adopt', kind: 'skill', key: 'style', id: unbound.id }, - ]) + const adopted = await apply(matching, SKILLS) + expect(adopted.failed).toBeUndefined() + expect(adopted.applied).toMatchObject([{ action: 'adopt', key: 'tone', id: same.id }]) } ) check('applies a workflow using a tool and a skill the same apply adopts', async () => { const workspaceId = await newWorkspace() - const { tool } = await createWorkspaceCustomToolUseCase.execute({ - principal: owner, - input: { - workspaceId, - title: 'Lookup order', - schema: { - type: 'function', - function: { name: 'old', parameters: { type: 'object', properties: {} } }, - }, - code: 'return 1', - }, - }) - const { skill: adoptedSkill } = await createSkillUseCase.execute({ - principal: owner, - input: { workspaceId, name: 'tone', description: 'Old', content: 'Old' }, - }) - const files = { ...TOOLS, ...SKILLS, 'workflows/support/workflow.ts': SUPPORT_WITH_SKILL } + const { tool, skill: adoptedSkill } = await createMatching(workspaceId, 'return 0\n') + const files = { + ...TOOLS, + 'tools/lookup.js': 'return 0\n', + ...SKILLS, + 'workflows/support/workflow.ts': SUPPORT_WITH_SKILL, + } const kinds: ApplyWorkspaceSourceInput['kinds'] = ['custom-tool', 'skill', 'workflow'] const dryRun = await apply(workspaceId, files, { kinds, dryRun: true }) @@ -733,45 +793,24 @@ describe('workspace source: custom tools and skills', () => { expect((await snapshot(workspaceId)).tools).toHaveLength(extra) }) - check('binds an adopted key only once its write succeeds', async () => { - const workspaceId = await newWorkspace() - await createWorkspaceCustomToolUseCase.execute({ - principal: owner, - input: { - workspaceId, - title: 'Lookup order', - schema: { - type: 'function', - function: { name: 'old', parameters: { type: 'object', properties: {} } }, - }, - code: 'return 1', - }, - }) - await createSkillUseCase.execute({ - principal: owner, - input: { workspaceId, name: 'tone', description: 'Old', content: 'Old' }, - }) - const raced = new OrchestrationError('conflict', 'Another write took this name.') - const toolWrite = vi - .spyOn(updateWorkspaceCustomToolUseCase, 'execute') - .mockRejectedValueOnce(raced) - const skillWrite = vi.spyOn(updateSkillUseCase, 'execute').mockRejectedValueOnce(raced) - - try { - for (const files of [TOOLS, SKILLS]) { - const failed = await apply(workspaceId, files) + check( + 'a create whose key claim failed leaves a record matching the declaration, which the next apply adopts', + async () => { + const workspaceId = await newWorkspace() + for (const [key, files] of [ + ['lookup', TOOLS], + ['tone', SKILLS], + ] as const) { + const restore = await failKeyClaims(key) + const failed = await apply(workspaceId, files).finally(restore) expect(failed.failed).toBeDefined() - expect(failed.applied).toEqual([]) const retried = await apply(workspaceId, files) expect(retried.failed).toBeUndefined() expect(retried.applied.map(({ action }) => action)).toEqual(['adopt']) } - } finally { - toolWrite.mockRestore() - skillWrite.mockRestore() } - }) + ) check('a tool delete refuses a tool edited after the plan read it', async () => { const workspaceId = await newWorkspace() diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 2b1a173b773..92a80f798de 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -63,9 +63,13 @@ resource's fingerprint as the last get or apply saw it. Workflows keep their own fingerprint that guards a delete). A get binds a key to every stored resource (`allocate`). An apply never allocates, so a resource -no source has named yet can be **adopted** by a declaration of the same name. A write claims its key -only after it succeeds (`claimKey`), so a failed write leaves the key free and the next apply -adopts the resource. +no source has named yet can be **adopted** by a declaration of the same name. The directory never +read that resource, so an adopt may only add to it (`refuseUnreadAdopt`): it binds the key when +the declaration matches, and adds what the resource lacks (a column, rows into an empty table, a +knowledge base document); one that would change or remove anything the resource holds is +`E_APPLY_NO_BASE` (get it first), even with `--allow-delete`. A write claims its key only after it +succeeds (`claimKey`), so a failed write leaves the key free and the next apply adopts the +resource, finishing what the write left. A key never changes: a declaration whose file was renamed (the base read the same resource under the old key, which the directory no longer declares) is `E_KEY_RENAMED`, and the resource is not @@ -94,8 +98,8 @@ and on the server now: | differs | differs | `noop` if local equals server (base refreshed), else `stale` | With no stored resource under the key: a resource the base records but the server no longer holds -was deleted there and stays deleted; otherwise an unbound resource of the same name is adopted, -else one is created. A stored resource with no base entry is a no-op when it matches exactly and +was deleted there and stays deleted; otherwise an unbound resource of the same name is adopted +(adding to it only, see above), else one is created. A stored resource with no base entry is a no-op when it matches exactly and `no-base` (get first) otherwise. Undeclared resources (`planUndeclared`, `application/findings.ts`): only one the base records is From 3dc790f20a9ebbfac5ea214e072a9d66f271e224 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:38:50 -0800 Subject: [PATCH 029/104] fix(table): insert a large row batch in statements Postgres accepts Creating a managed table with 10,000 rows (the documented maximum) inserted every row in one statement, 9 parameters a row, past Postgres's 65,535-parameter limit, and the apply stopped with an opaque E_APPLY_FAILED. Batch inserts now write 1,000 rows a statement. An unexpected write failure now names its cause by database error code (a timeout, a deadlock, a statement too large) and the apply id to report, never the error text. --- apps/sim/lib/table/rows/service.ts | 13 ++++- .../application/apply-workspace-source.ts | 49 ++++++++++++++++--- .../application/rows.integration.ts | 21 ++++++++ 3 files changed, 75 insertions(+), 8 deletions(-) diff --git a/apps/sim/lib/table/rows/service.ts b/apps/sim/lib/table/rows/service.ts index d0e1d6a42ca..5ac6149f62a 100644 --- a/apps/sim/lib/table/rows/service.ts +++ b/apps/sim/lib/table/rows/service.ts @@ -13,6 +13,7 @@ import { db } from '@sim/db' import { userTableRows } from '@sim/db/schema' import { createLogger } from '@sim/logger' +import { chunkArray } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' import { escapeLikePattern } from '@sim/utils/string' import { and, asc, count, eq, getTableColumns, inArray, isNull, type SQL, sql } from 'drizzle-orm' @@ -342,6 +343,13 @@ export interface BatchInsertOptions extends TxRowWriteOptions { uniqueColumnsLocked?: boolean } +/** + * Rows one insert statement writes: each row binds nine parameters, and Postgres accepts at most + * 65,535 in one statement, so a batch larger than this (workspace source writes up to 10,000 + * rows in one transaction) is inserted in several statements. + */ +const INSERT_CHUNK_ROWS = 1_000 + /** * Transaction-bound variant of `batchInsertRows`. Validates rows and unique * constraints, then performs INSERTs inside the provided transaction. Caller @@ -438,7 +446,10 @@ export async function batchInsertRowsWithTx( rowState: 'new', mode: 'replace', mutate: async () => { - const rows = await trx.insert(userTableRows).values(rowsToInsert).returning() + const rows: (typeof userTableRows.$inferSelect)[] = [] + for (const chunk of chunkArray(rowsToInsert, INSERT_CHUNK_ROWS)) { + rows.push(...(await trx.insert(userTableRows).values(chunk).returning())) + } return { value: rows, affectedRowIds: rows.map((row) => row.id) } }, }) 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 707cef09d05..3bf4752caf3 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -1,6 +1,6 @@ import { AuditAction, AuditResourceType, withAuditCorrelation } from '@sim/audit' import { createLogger } from '@sim/logger' -import { getErrorMessage } from '@sim/utils/errors' +import { getErrorMessage, getPostgresErrorCode } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { APPLY_ORDER, @@ -124,14 +124,39 @@ function writeOrder(changes: PlannedChange[]): PlannedChange[] { } /** - * A mid-apply failure as the result reports it; an unexpected one is logged, not echoed. A resource + * What an unexpected write failure says about its cause, by the database's error code (SQLSTATE, + * or the driver's own): never the error's text, which can quote what was written. + */ +const WRITE_FAILURE_CAUSES: Readonly> = { + '57014': 'a database statement timed out', + '55P03': 'another write held a lock it needed for too long', + '40P01': 'it deadlocked with another write', + '40001': 'it conflicted with a concurrent write', + '53300': 'the database had no free connection', + '54000': 'a database statement was larger than the database accepts', + MAX_PARAMETERS_EXCEEDED: 'a database statement was larger than the database accepts', +} + +/** The cause an unexpected write failure names, from its database error code. */ +function writeFailureCause(error: unknown): string { + const code = getPostgresErrorCode(error) + if (code === undefined) return 'an unexpected server error' + if (Object.hasOwn(WRITE_FAILURE_CAUSES, code)) return WRITE_FAILURE_CAUSES[code] + if (code.startsWith('08')) return 'the database connection dropped' + return `database error ${code}` +} + +/** + * A mid-apply failure as the result reports it; an unexpected one is logged, and named by its + * cause (see {@link writeFailureCause}) and the apply's id, never echoed. A resource * the change found when planning that is gone by its write (deleted since) is stale, like one that * changed: getting the directory again shows what the server holds now. A lease another apply took * over is a failure applying again continues (`E_APPLY_FAILED`), not a refusal of the change. */ function failureOf( error: unknown, - change: PlannedChange + change: PlannedChange, + applyId: string | undefined ): { failed: NonNullable diagnostics: WorkspaceSourceDiagnostic[] @@ -164,11 +189,21 @@ function failureOf( diagnostics: [refusal], } } - logger.error('Workspace source write failed', { ...resource, error: getErrorMessage(error) }) - const message = `Writing ${change.kind} ${change.key} failed; the changes before it were applied.` + logger.error('Workspace source write failed', { + ...resource, + applyId, + code: getPostgresErrorCode(error), + error: getErrorMessage(error), + }) + const message = `Writing ${change.kind} ${change.key} failed (${writeFailureCause(error)}); the changes before it were applied.` return { failed: { ...resource, code: 'E_APPLY_FAILED', message }, - diagnostics: [finding('E_APPLY_FAILED', message, resource)], + diagnostics: [ + finding('E_APPLY_FAILED', message, { + hint: `Apply again: it continues from here. If it fails the same way, report apply ${applyId ?? 'id'} to support.`, + ...resource, + }), + ], } } @@ -379,7 +414,7 @@ async function writeAll( if (written.base) base.resources[address] = written.base else delete base.resources[address] } catch (error) { - const failure = failureOf(error, change) + const failure = failureOf(error, change, result.applyId) result.failed = failure.failed result.diagnostics.push(...failure.diagnostics) break diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index 1cc30a40837..cf488fa126e 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -17,6 +17,7 @@ import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' import { tableTriggerMock, tableTriggerMockFns } from '@sim/testing/mocks/table-trigger.mock' import { generateId } from '@sim/utils/id' import { compareStrings } from '@sim/utils/string' +import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { and, eq, inArray, isNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, vi } from 'vitest' import { updateTableColumnUseCase } from '@/lib/table/application/columns' @@ -770,6 +771,26 @@ export default defineTable({ } ) + check( + 'creates a managed table holding the most rows a directory may declare, in one apply', + async () => { + const workspaceId = await newWorkspace() + const count = WORKSPACE_SOURCE_LIMITS.maxTableRows + const rows = Array.from( + { length: count }, + (_, index) => `{"code":"c${index}","seats":${index},"tier":"basic"}\n` + ).join('') + + const created = await apply(workspaceId, { + 'tables/plans.ts': MANAGED, + 'tables/plans.rows.jsonl': rows, + }) + + expect(created.failed).toBeUndefined() + expect((await storedTable(workspaceId)).rowCount).toBe(count) + } + ) + check('seeds a new table once, and only a new or empty one', async () => { const workspaceId = await newWorkspace() const files = { 'tables/plans.ts': SEED, 'tables/plans.rows.jsonl': ROWS } From 8405ff5181f9218f22a981642674c3c52d9d30dd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:39:19 -0800 Subject: [PATCH 030/104] fix(workspace-source): a clean dry run no longer stops part-way on an MCP URL The dry run checked an MCP server's URL only by role, so a host that does not resolve (or one the egress policy refuses) passed and then stopped the real apply after earlier resources were written. The plan now checks every URL a create, replace or URL change writes the way the write does (allowlist, egress policy, DNS), refusing before anything is written. After any part-way stop the CLI reprints the plan with each change marked written, failed or not written, and the JSON result lists notWritten. --- .../content/docs/workflows/workspace-code.mdx | 2 +- apps/sim/lib/mcp/application/use-cases.ts | 12 +++++ apps/sim/lib/mcp/orchestration/index.ts | 1 + .../lib/mcp/orchestration/server-lifecycle.ts | 7 ++- .../application/kinds/mcp/adapter.ts | 13 ++++-- .../application/mcp.integration.ts | 23 ++++++++++ .../protocol/workspace-source-apply.test.ts | 27 +++++++++++ .../protocol/workspace-source-apply.ts | 46 +++++++++++++++++-- 8 files changed, 120 insertions(+), 11 deletions(-) diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx index 502ea417c9f..1acb9b9e101 100644 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ b/apps/docs/content/docs/workflows/workspace-code.mdx @@ -115,7 +115,7 @@ Commit the whole directory, including `.sim/`: its base files are what an apply - A document or file over 10 MB, or whose name a directory cannot hold, is left out of `get` and listed in `.sim/skipped.json`. An apply never writes or deletes it. - Hidden files (a name starting with a dot, such as `files/.env`) and names with a character no workspace path holds (such as `:` or `?`) are never sent. An apply names each one in a `W_PATH_NOT_SENT` warning. - A knowledge base's `embeddingModel` is fixed when it is created. An apply that changes it is refused. -- An apply that stops part-way exits `8` and saves what it wrote into the directory. Run the same apply again until it exits `0`. +- An apply that stops part-way exits `8`, prints the plan again with each change marked written or not written (`notWritten` in JSON), and saves what it wrote into the directory. Run the same apply again until it exits `0`. The dry run checks an MCP server's URL as the write does, so an unresolvable host is refused before anything is written. - An apply exits `5` when a resource changed in Sim after you read it. Run `get` into a new directory and reapply your edit. See [CLI workspace commands](/cli/workspaces) for every flag. diff --git a/apps/sim/lib/mcp/application/use-cases.ts b/apps/sim/lib/mcp/application/use-cases.ts index fa85d70fb51..c52a9f2574a 100644 --- a/apps/sim/lib/mcp/application/use-cases.ts +++ b/apps/sim/lib/mcp/application/use-cases.ts @@ -31,6 +31,7 @@ import { deleteMcpServer, type PerformMcpServerResult, updateMcpServer as updateMcpServerRecord, + validateMcpServerUrl, } from '@/lib/mcp/orchestration' import { getMcpServerIdState, @@ -67,6 +68,17 @@ function requireSuccessfulResult( } } +/** + * Refuses an MCP server URL that creating a server at it, or moving one to it, would refuse, + * without writing: off the domain allowlist or resolving where egress forbids (forbidden), or a + * hostname that does not resolve (validation). A caller that writes several resources in one + * operation checks every URL up front, so it never stops after the first writes on one of these. + */ +export async function assertMcpServerUrlAccepted(url: string): Promise { + const validation = await validateMcpServerUrl(url) + if (!validation.ok) requireSuccessfulResult(validation.result, 'The MCP server URL is refused') +} + const authorizationOptions = { delegation: mcpServerDelegationPolicy } export interface ListMcpServersInput { diff --git a/apps/sim/lib/mcp/orchestration/index.ts b/apps/sim/lib/mcp/orchestration/index.ts index dc2297c6a73..b08de928ac6 100644 --- a/apps/sim/lib/mcp/orchestration/index.ts +++ b/apps/sim/lib/mcp/orchestration/index.ts @@ -12,6 +12,7 @@ export { performDeleteMcpServer, performUpdateMcpServer, updateMcpServer, + validateMcpServerUrl, } from './server-lifecycle' export { type PerformCreateWorkflowMcpServerParams, diff --git a/apps/sim/lib/mcp/orchestration/server-lifecycle.ts b/apps/sim/lib/mcp/orchestration/server-lifecycle.ts index b3d24fed276..8bf612225ed 100644 --- a/apps/sim/lib/mcp/orchestration/server-lifecycle.ts +++ b/apps/sim/lib/mcp/orchestration/server-lifecycle.ts @@ -120,7 +120,12 @@ type ValidateMcpServerUrlResult = | { ok: true; resolvedIP: string | null } | { ok: false; result: PerformMcpServerResult } -async function validateMcpServerUrl(url: string): Promise { +/** + * Checks an MCP server URL the way a create or URL change does before it writes: the domain + * allowlist and egress policy (`forbidden`) and DNS (`bad_gateway`), as the result a refused write + * returns. A URL whose hostname holds an env reference passes, checked again once resolved. + */ +export async function validateMcpServerUrl(url: string): Promise { try { validateMcpDomain(url) const resolvedIP = await validateMcpServerSsrf(url) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index 3817e111df7..1da05bb6174 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -44,6 +44,7 @@ import { authorizeWorkspaceOperation, ForbiddenOperationError } from '@/lib/core import { OrchestrationError } from '@/lib/core/orchestration/types' import { mcpServerOperations } from '@/lib/mcp/application/operations' import { + assertMcpServerUrlAccepted, createMcpServerUseCase, deleteMcpServerUseCase, discoverMcpServerToolsUseCase, @@ -525,15 +526,19 @@ export const mcpAdapter: KindAdapter<'mcp-server', McpServerRow> = { const { principal } = ctx const workspaceId = ctx.workspace.workspaceId const decl = change.decl - if ( - (change.action === 'create' || (change.detail?.replace && !change.detail.replacement)) && - decl - ) { + const createsServer = + change.action === 'create' || (change.detail?.replace && !change.detail.replacement) + if (createsServer && decl) { await createMcpServerUseCase.authorize({ principal, input: { workspaceId, name: decl.name, url: decl.url }, }) } + // The URL is checked as the write checks it (allowlist, egress policy, DNS), so a URL the + // write would refuse refuses the plan, not the apply after other resources were written. + if (decl && (createsServer || change.detail?.changed.includes('url'))) { + await assertMcpServerUrlAccepted(decl.url) + } await authorizeCarriedHeaders(change, ctx) if (!change.storedId) return if (change.action === 'delete' || change.detail?.replace) { diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index cdbd3876195..15d0fa58ec9 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -220,6 +220,29 @@ afterAll(async () => { }) describe('MCP servers as workspace source', () => { + check( + 'refuses in the dry run a server URL whose host does not resolve, so the apply writes nothing', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'mcp/github.ts': github(), + 'mcp/bad.ts': serverFile( + `{ name: 'Bad', url: 'https://nonexistent-host-wac-e2e.invalid/mcp' }` + ), + } + + const dryRun = await apply(workspaceId, files, { dryRun: true }) + expect(findings(dryRun.diagnostics, 'error')).toEqual(['E_APPLY_REFUSED mcp-server:bad']) + expect(dryRun.diagnostics.find((finding) => finding.key === 'bad')?.message).toContain( + 'could not be resolved' + ) + + const refused = await refusal(apply(workspaceId, files)) + expect(findings(refused.diagnostics, 'error')).toEqual(['E_APPLY_REFUSED mcp-server:bad']) + expect(await liveServers(workspaceId)).toEqual([]) + } + ) + check( 'creates a server and the workflow calling its tool in one apply, storing the env reference', async () => { 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 1cbc484917f..fa7e75b8f3c 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 @@ -609,6 +609,33 @@ describe('workspaces source apply', () => { }) }) + it('after a part-way stop, reprints the plan marking each change written or not', async () => { + request.mockResolvedValue( + answer({ + plan: [ + { kind: 'skill', key: 'second', action: 'create' }, + { kind: 'mcp-server', key: 'bad', action: 'create' }, + { kind: 'file', key: 'partial.txt', action: 'create' }, + { kind: 'table', key: 'leads', action: 'noop' }, + ], + applied: [{ kind: 'skill', key: 'second', action: 'create', id: 'sk_1' }], + failed: { kind: 'mcp-server', key: 'bad', code: 'E_APPLY_FAILED', message: 'failed' }, + }) + ) + + await apply('--yes') + + const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + expect(stderr).toContain('+ second — written') + expect(stderr).toContain('+ bad — failed, not written') + expect(stderr).toContain('+ partial.txt — not written') + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed).toMatchObject({ + failed: 'mcp-server:bad', + notWritten: ['mcp-server:bad', 'file:partial.txt'], + }) + }) + it.each([ ['E_APPLY_STALE', 5], ['E_APPLY_LOCKED', 6], 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 43d6d8c997e..e4dd00f6d29 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -153,8 +153,38 @@ function refusesApply(data: ApplyData): boolean { ) } -/** The plan as a person reads it: per kind, the counts, then each change with what it touches. */ -function printPlan(plan: Change[]): void { +/** What an apply that wrote did, for the plan reprinted after it stopped part-way. */ +type PlanOutcome = Pick + +const sameChange = (a: Pick, b: Pick) => + a.kind === b.kind && a.key === b.key + +/** Whether `change`, which the plan writes, was written: not held back, and in `applied`. */ +function wasWritten(change: Change, outcome: PlanOutcome): boolean { + return outcome.applied.some((written) => sameChange(written, change)) +} + +/** The changes a stopped apply planned to write and did not, as `kind:key`. */ +function notWritten(data: ApplyData): string[] { + return data.plan + .filter((change) => change.action !== 'noop' && !change.held && !wasWritten(change, data)) + .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' + return outcome.failed && sameChange(outcome.failed, change) + ? ' — failed, not written' + : ' — not written' +} + +/** + * The plan as a person reads it: per kind, the counts, then each change with what it touches. + * With `outcome` (an apply that stopped part-way), each change says whether it was written. + */ +function printPlan(plan: Change[], outcome?: PlanOutcome): void { for (const kind of APPLY_ORDER) { const changes = plan.filter((change) => change.kind === kind) if (changes.length === 0) continue @@ -173,7 +203,8 @@ function printPlan(plan: Change[]): void { ? ` — deletes ${lost.map(([what, count]) => `${count} ${what}`).join(', ')}` : '' const held = change.held ? ' — held back (see its error)' : '' - printError(` ${SYMBOLS[change.action]} ${change.key}${fields}${loses}${held}`) + const status = outcome ? outcomeText(change, outcome) : '' + printError(` ${SYMBOLS[change.action]} ${change.key}${fields}${loses}${held}${status}`) } } const destructive = destructiveChanges(plan) @@ -639,7 +670,10 @@ export function attachWorkspaceSourceApply(source: Command): void { abandoned: `Stopped before the apply answered. ${answerLostHint(options.dir)}`, } ) - if (mode === 'write') printPlan(data.plan) + if (data.failed) { + printError('The apply stopped part-way; each planned change:') + printPlan(data.plan, data) + } else if (mode === 'write') printPlan(data.plan) const held = data.plan.filter((change) => change.held) if (held.length > 0) { printError( @@ -710,7 +744,9 @@ function summarize(data: ApplyData) { destructive: destructiveChanges(changes), unchanged: data.plan.filter((change) => change.action === 'noop').length, held: data.plan.filter((change) => change.held).length, - ...(data.failed ? { failed: `${data.failed.kind}:${data.failed.key}` } : {}), + ...(data.failed + ? { failed: `${data.failed.kind}:${data.failed.key}`, notWritten: notWritten(data) } + : {}), ...(data.applyId ? { applyId: data.applyId } : {}), errors: data.diagnostics.filter((finding) => finding.severity === 'error').length, warnings: data.diagnostics.filter((finding) => finding.severity === 'warning').length, From 5526a918548966af3cff8885d4e112bc1670bece Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:39:31 -0800 Subject: [PATCH 031/104] fix(workspace-source): a promotion reports what the target deleted and every target-only delete A promotion kept a resource the target deleted since the last promotion with only a hidden info worded for a plain apply, gave a stale refusal the plain apply's 'get into a fresh directory' hint, and listed --allow-delete's deletes of target-only resources as ordinary deletes. It now warns W_PROMOTE_TARGET_DELETED for each resource it keeps deleted (and how to recreate it), W_PROMOTE_DELETES_TARGET_ONLY for each target-only delete with a loud summary under the plan, and gives stale and no-base refusals a promotion hint naming the target and its record. --- .../content/docs/workflows/workspace-code.mdx | 3 +- apps/docs/openapi-v2-workflows.json | 6 + .../protocol/workspace-source-apply.test.ts | 81 +++++++++++ .../protocol/workspace-source-apply.ts | 129 +++++++++++++++++- packages/sim-cli/src/generated/v2-api.ts | 6 + .../workspace-code/src/diagnostics/codes.ts | 10 ++ packages/workspace-code/src/promote.ts | 20 ++- 7 files changed, 246 insertions(+), 9 deletions(-) diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx index 1acb9b9e101..bfe38d33471 100644 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ b/apps/docs/content/docs/workflows/workspace-code.mdx @@ -93,12 +93,13 @@ sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --dry sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --yes ``` -Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. Resources only the target holds are kept unless you pass `--allow-delete`. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. +Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. Resources only the target holds are kept unless you pass `--allow-delete`, which deletes every one of them: the plan names each with a `W_PROMOTE_DELETES_TARGET_ONLY` warning. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. Each promotion records what it left in the target in `.sim/targets/.json`, and the next promotion compares with that record: - A resource changed in the target since the last promotion, such as a hotfix made in Sim, is kept when the directory left it alone. - When the directory changed it too, the promotion is refused as stale and exits `5`. Carry the target's change into the source workspace, or undo it in the target, then promote again. +- A resource deleted in the target since the last promotion stays deleted, with a `W_PROMOTE_TARGET_DELETED` warning. Remove its entry from the record to create it again. - The first promotion, and any resource the record does not hold (one created in the target since), updates the target to match the directory. Review the dry run first. Commit the record with the rest of the directory, so a promotion from CI or another clone compares with it. Deleting it makes the next promotion take the target as it stands. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index b160e16f5c1..c61bba2f962 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -26536,6 +26536,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "I_SERVER_CHANGED", "I_SERVER_DELETED", "I_SERVER_MOVED", @@ -27108,6 +27110,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "I_SERVER_CHANGED", "I_SERVER_DELETED", "I_SERVER_MOVED", @@ -28788,6 +28792,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "I_SERVER_CHANGED", "I_SERVER_DELETED", "I_SERVER_MOVED", 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 fa7e75b8f3c..e9398915942 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 @@ -436,6 +436,87 @@ describe('workspaces source apply', () => { }) }) + it('a --to dry run warns of what the target deleted since the last promotion, gives stale findings a promotion hint, and names each target-only delete', async () => { + const leads = { id: 'tbl_prod', fingerprint: `rf1:${'a'.repeat(64)}` } + write( + '.sim/targets/ws_prod.json', + JSON.stringify({ + version: 1, + workspaceId: 'ws_prod', + resources: { + 'table:leads': leads, + 'table:gone': { id: 'tbl_gone', fingerprint: `rf1:${'c'.repeat(64)}` }, + }, + workflows: {}, + }) + ) + write('tables/gone.ts', LEADS.replace("'leads'", "'gone'")) + request.mockImplementation(async (path: string, options: { body?: unknown }) => { + if (path === '/api/v2/workspaces/ws_prod/source' && options.body === undefined) { + return { + data: { + workspaceId: 'ws_prod', + kinds: ['table'], + files: { 'tables/leads.ts': LEADS, 'tables/prod-only.ts': LEADS }, + blobs: [], + base: { + version: 1, + workspaceId: 'ws_prod', + resources: { 'table:leads': leads, 'table:prod-only': { id: 'tbl_only' } }, + }, + skipped: [], + diagnostics: [], + }, + } + } + return answer({ + workspaceId: 'ws_prod', + dryRun: true, + plan: [ + { kind: 'table', key: 'gone', action: 'noop' }, + { kind: 'table', key: 'leads', action: 'noop' }, + { kind: 'table', key: 'prod-only', action: 'delete' }, + ], + diagnostics: [ + { + code: 'I_SERVER_DELETED', + severity: 'info', + message: 'tables/gone was deleted on the server; the next get shows that.', + kind: 'table', + key: 'gone', + }, + { + code: 'E_APPLY_STALE', + severity: 'error', + message: 'tables/leads changed on the server since this directory was read.', + hint: 'Run `sim workspaces source get` into a fresh directory, reapply your edit there, and apply again.', + kind: 'table', + key: 'leads', + }, + ], + }) + }) + + await apply('--to', 'ws_prod', '--only', 'tables', '--allow-delete', '--dry-run') + + const summary = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + const byCode = (code: string) => + summary.diagnostics.filter((finding: { code: string }) => finding.code === code) + expect(byCode('W_PROMOTE_TARGET_DELETED')).toEqual([ + expect.objectContaining({ kind: 'table', key: 'gone' }), + ]) + expect(byCode('I_SERVER_DELETED')).toEqual([]) + expect(byCode('W_PROMOTE_DELETES_TARGET_ONLY')).toEqual([ + expect.objectContaining({ kind: 'table', key: 'prod-only' }), + ]) + const [stale] = byCode('E_APPLY_STALE') + expect(stale.hint).toContain('.sim/targets/ws_prod.json') + expect(stale.hint).not.toContain('fresh directory') + expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toContain( + 'deletes 1 resource(s) that only workspace ws_prod holds' + ) + }) + it('refuses --to naming the workspace the directory was read from', async () => { await expect(apply('--to', 'ws_local', '--yes')).rejects.toThrow(/apply it without --to/) expect(request).not.toHaveBeenCalled() 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 e4dd00f6d29..6ecd17463e3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -215,6 +215,19 @@ function printPlan(plan: Change[], outcome?: PlanOutcome): void { } } +/** + * Says loudly, below a promotion's plan, how many resources `--allow-delete` deletes that only the + * target holds: a promotion deletes everything the directory does not declare. + */ +function printTargetOnlyDeletes(promotion: Promotion | null, plan: readonly Change[]): void { + if (!promotion) return + const deletes = plan.filter((change) => change.action === 'delete') + if (deletes.length === 0) return + printError( + `--allow-delete with --to: this promotion deletes ${deletes.length} resource(s) that only workspace ${promotion.target} holds: ${deletes.map((change) => resourceWhere(change.kind, change.key)).join(', ')}.` + ) +} + /** The changes that delete something (a resource, rows, documents, columns, a deployment). */ export function destructiveChanges(changes: readonly Change[]): number { return changes.filter((change) => change.action === 'delete' || change.destructive !== undefined) @@ -405,6 +418,10 @@ interface Promotion { files: Record /** The record the last promotion to this target left, if any. */ record: PromotionRecord | undefined + /** The target workspace. */ + target: string + /** What the target deleted since the last promotion that the directory declares (addresses). */ + deletedInTarget: string[] } /** @@ -452,6 +469,8 @@ async function promoted( submission: { ...submission, files: composed.files, base: composed.base }, files: submission.files, record, + target, + deletedInTarget: composed.deletedInTarget, } } @@ -482,6 +501,92 @@ async function savePromotion( await updateSourceDir(dir, { write: [[path, `${JSON.stringify(record, null, 2)}\n`]] }) } +type Finding = ApplyData['diagnostics'][number] + +/** `tables/leads`, or `secrets.ts KEY` for a root file's entry: how a promotion finding names one. */ +function resourceWhere(kind: WorkspaceKind, key: string): string { + return isFileKind(kind) ? `${KIND_DIRS[kind]} ${key}` : `${KIND_DIRS[kind]}/${key}` +} + +/** + * The hint a promotion to `target` gives a refusal the server words for an apply to the + * directory's own workspace ("get it into a fresh directory"), which a promotion cannot follow. + */ +function promotionHint(code: string, target: string): string | undefined { + const record = promotionRecordPath(target) ?? '.sim/targets/.json' + if (code === 'E_APPLY_STALE') { + return `Workspace ${target} changed this resource since the last promotion from this directory. Carry that change into the directory, or undo it in ${target}, then promote again; to take ${target} as it stands now, delete ${record} first.` + } + if (code === 'E_APPLY_NO_BASE') { + return `Workspace ${target} holds this resource, but no promotion from this directory recorded it. Rename the declaration, or rename or delete the resource in ${target}, then promote again.` + } + return undefined +} + +/** + * The server's findings as a promotion reports them: refusals carry the promotion's hint, and the + * server's `I_SERVER_DELETED` for a resource the promotion warns about itself + * (`W_PROMOTE_TARGET_DELETED`) is left out. + */ +function promotionDiagnostics(diagnostics: readonly Finding[], promotion: Promotion): Finding[] { + const warned = new Set(promotion.deletedInTarget) + return diagnostics.flatMap((finding) => { + if (finding.code === 'I_SERVER_DELETED' && warned.has(`${finding.kind}:${finding.key}`)) { + return [] + } + const hint = promotionHint(finding.code, promotion.target) + return [hint === undefined ? finding : { ...finding, hint }] + }) +} + +/** + * The warnings only a promotion knows to give: each declared resource the target deleted since the + * last promotion (kept deleted), and each resource only the target holds that `--allow-delete` + * deletes there. + */ +function promotionWarnings(promotion: Promotion, plan: readonly Change[]): Finding[] { + const { target } = promotion + const deleted = promotion.deletedInTarget.flatMap((address): Finding[] => { + const parsed = parseResourceAddress(address) + if (!parsed) return [] + return [ + { + code: 'W_PROMOTE_TARGET_DELETED', + severity: 'warning', + message: `${resourceWhere(parsed.kind, parsed.key)} was deleted in workspace ${target} since the last promotion; this promotion keeps it deleted there.`, + hint: `To create it in ${target} again, remove its entry from ${promotionRecordPath(target) ?? 'the promotion record'}, then promote again.`, + kind: parsed.kind, + key: parsed.key, + }, + ] + }) + const targetOnly = plan + .filter((change) => change.action === 'delete') + .map( + (change): Finding => ({ + code: 'W_PROMOTE_DELETES_TARGET_ONLY', + severity: 'warning', + message: `${resourceWhere(change.kind, change.key)} is only in workspace ${target}, not in this directory, so --allow-delete deletes it there.`, + hint: 'Promote without --allow-delete to keep it, or declare it in this directory.', + kind: change.kind, + key: change.key, + }) + ) + return [...deleted, ...targetOnly] +} + +/** A refusal's findings as a promotion reports them (see {@link promotionDiagnostics}). */ +function rehintRefusal(refusal: unknown, promotion: Promotion): void { + if (!(refusal instanceof SimApiError) || !isRecordLike(refusal.details)) return + const { diagnostics } = refusal.details + if (!Array.isArray(diagnostics)) return + refusal.details.diagnostics = diagnostics.map((finding) => { + if (!isRecordLike(finding) || typeof finding.code !== 'string') return finding + const hint = promotionHint(finding.code, promotion.target) + return hint === undefined ? finding : { ...finding, hint } + }) +} + /** * `sim workspaces source apply --dir `: applies a directory `workspaces source get` wrote. * On a terminal it shows the plan and asks; anywhere else it needs `--yes`. Binary files are @@ -572,6 +677,7 @@ export function attachWorkspaceSourceApply(source: Command): void { * Sends the directory. A commit the server refuses only for blobs that are not staged (the * CLI's guess from the base missed one) stages those and is sent once more. */ + let promotion: Promotion | null = null const send = async (submission: WorkspaceSubmission, dryRun: boolean): Promise => { let refusal: unknown try { @@ -588,6 +694,7 @@ export function attachWorkspaceSourceApply(source: Command): void { refusal = error } } + if (promotion) rehintRefusal(refusal, promotion) return printRefusal(refusal, profile.output, { ...(dryRun ? {} : { ifAnswerLost: answerLostHint(options.dir) }), verbose: options.verbose === true, @@ -605,10 +712,21 @@ export function attachWorkspaceSourceApply(source: Command): void { await assertWorkspaceDir(options.dir) } assertBlobsFetched(options.dir, read, written.digests) - const promotion = options.to + promotion = options.to ? await promoted(client, options.dir, read, options.to, options.allowDelete === true) : null const submission = promotion?.submission ?? read + /** `data` as this apply reports it: a promotion's own wording and warnings added. */ + const reported = (data: ApplyData): ApplyData => + promotion + ? { + ...data, + diagnostics: [ + ...promotionWarnings(promotion, data.plan), + ...promotionDiagnostics(data.diagnostics, promotion), + ], + } + : data // The apply repeats findings the preview already showed: each is printed once. const findings = findingsOutput(profile.output, options.verbose) const notSent = notSentFindings(submission.ignored) @@ -625,8 +743,9 @@ export function attachWorkspaceSourceApply(source: Command): void { } let preview: ApplyData | null = null if (mode !== 'write') { - preview = await send(submission, true) + preview = reported(await send(submission, true)) printPlan(preview.plan) + printTargetOnlyDeletes(promotion, preview.plan) findings.print(preview.diagnostics) const errors = preview.diagnostics.some((finding) => finding.severity === 'error') if (errors) setSoftExitCode(refusedExitCode(preview.diagnostics)) @@ -648,12 +767,12 @@ export function attachWorkspaceSourceApply(source: Command): void { await stage(submission, preview ? new Set(preview.needBlobs) : blobsToStage(submission)) const data = await deferInterrupts( async () => { - const answer = await send(submission, false) + const answer = reported(await send(submission, false)) findings.print(answer.diagnostics) // A promotion leaves the directory bound to the workspace it was read from, and // records what it left in the target for the next promotion to compare with. - if (promotion && options.to) { - await savePromotion(options.dir, options.to, promotion, answer) + if (promotion) { + await savePromotion(options.dir, promotion.target, promotion, answer) } else { const workspaceCatalog = cachedCatalog(workspaceId) const { records, unrecorded } = workspaceCatalog diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 727aa95c083..a6664d9ee99 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1299,6 +1299,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'I_SERVER_CHANGED' | 'I_SERVER_DELETED' | 'I_SERVER_MOVED' @@ -1586,6 +1588,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'I_SERVER_CHANGED' | 'I_SERVER_DELETED' | 'I_SERVER_MOVED' @@ -11041,6 +11045,8 @@ export type GetWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'I_SERVER_CHANGED' | 'I_SERVER_DELETED' | 'I_SERVER_MOVED' diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index 647ae6b209a..810e0b7d9ee 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -263,6 +263,16 @@ const PLAN_CODES = [ 'W_UNDECLARED', /** The directory's base was read from another workspace: every resource is created anew. */ 'W_BASE_OTHER_WORKSPACE', + /** + * A promotion (`apply --to`) keeps deleted a resource the directory declares that the target + * deleted since the last promotion: the target no longer holds it. + */ + 'W_PROMOTE_TARGET_DELETED', + /** + * A promotion with `--allow-delete` deletes a resource only the target holds (the directory does + * not declare it). + */ + 'W_PROMOTE_DELETES_TARGET_ONLY', /** The server changed a resource the directory leaves as it was; the next get shows it. */ 'I_SERVER_CHANGED', /** The server deleted a resource the directory leaves as it was; it is not created again. */ diff --git a/packages/workspace-code/src/promote.ts b/packages/workspace-code/src/promote.ts index a66370cff73..a122ee238df 100644 --- a/packages/workspace-code/src/promote.ts +++ b/packages/workspace-code/src/promote.ts @@ -38,6 +38,11 @@ export interface PromotionSubmission { files: Record /** The target's base, narrowed to what the directory declares unless deletes are allowed. */ base: WorkspaceBaseV1 + /** + * The resources (by address) the last promotion left in the target that the target deleted + * since and the directory still declares: the apply keeps them deleted, so the promotion warns. + */ + deletedInTarget: string[] } export interface PromotionInput { @@ -205,6 +210,7 @@ export function parsePromotionRecord( */ export function promotionSubmission(input: PromotionInput): PromotionSubmission { const files: Record = {} + const deletedInTarget: string[] = [] for (const [path, text] of Object.entries(input.files)) { if (!isWorkflowRecord(path)) files[path] = text } @@ -229,6 +235,7 @@ export function promotionSubmission(input: PromotionInput): PromotionSubmission } } files[basePath] = recordedFolderBase(promoted, input.target.base.workspaceId) + deletedInTarget.push(resourceAddress('workflow', key)) continue } if (targetBase === undefined || !live || promoted?.workflowId !== live.workflowId) { @@ -266,9 +273,16 @@ export function promotionSubmission(input: PromotionInput): PromotionSubmission for (const [address, recorded] of Object.entries(input.record?.resources ?? {})) { if (Object.hasOwn(input.target.base.resources, address)) continue const parsed = parseResourceAddress(address) - if (parsed && declared.get(parsed.kind)?.has(parsed.key)) resources[address] = recorded + if (parsed && declared.get(parsed.kind)?.has(parsed.key)) { + resources[address] = recorded + if (parsed.kind !== 'workflow') deletedInTarget.push(address) + } + } + return { + files, + base: { ...input.target.base, resources }, + deletedInTarget: [...new Set(deletedInTarget)].sort(compareStrings), } - return { files, base: { ...input.target.base, resources } } } /** @@ -285,7 +299,7 @@ export function promotionRecord(input: { kinds: readonly WorkspaceKind[] /** The directory's text files, as {@link PromotionInput} took them. */ files: Readonly> - submission: PromotionSubmission + submission: Pick applied: { base: WorkspaceBaseV1 files: Readonly> From 5502c50596468e65b85d5a443701f4043835ef38 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:39:47 -0800 Subject: [PATCH 032/104] fix(workflows): refuse at apply a table, workflow or knowledge base id of another workspace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A raw resource id copied from another workspace (tableId: 'tbl_…', a child workflowId) passed apply with no finding and failed only at run time, the child workflow with 'Delegated workspace access is no longer valid'. An apply now checks every table, workflow and knowledge base id a block it adds, or a field it changes, writes verbatim against the workflow's own workspace and refuses one it does not hold (E_MAT_UNKNOWN_RESOURCE); ids an enclosing apply creates count as held. A child workflow the run's delegation cannot read now says it is not in this workspace. --- .../handlers/workflow/handler.test.ts | 13 ++ .../sim/executor/handlers/workflow/handler.ts | 20 +- .../workflows/application/source-evaluate.ts | 9 + .../application/source-resource-scope.ts | 179 ++++++++++++++++++ .../application/apply.integration.ts | 58 ++++++ 5 files changed, 277 insertions(+), 2 deletions(-) create mode 100644 apps/sim/lib/workflows/application/source-resource-scope.ts diff --git a/apps/sim/executor/handlers/workflow/handler.test.ts b/apps/sim/executor/handlers/workflow/handler.test.ts index 140bad47f89..58a1034a4df 100644 --- a/apps/sim/executor/handlers/workflow/handler.test.ts +++ b/apps/sim/executor/handlers/workflow/handler.test.ts @@ -19,6 +19,7 @@ import { import { permissionsMock } from '@sim/testing/mocks/permissions.mock' import { usersQueriesMock, usersQueriesMockFns } from '@sim/testing/mocks/users-queries.mock' import { afterAll, beforeAll, beforeEach, describe, expect, it, type Mock, vi } from 'vitest' +import { DelegatedWorkspaceAuthorizationError } from '@/lib/core/application' import { classifyFailure, logFailureOnce } from '@/lib/core/errors/failure-log' import { createTimeoutAbortController, getExecutionDeadlineAt } from '@/lib/core/execution-limits' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -372,6 +373,18 @@ describe('WorkflowBlockHandler', () => { ) }) + it('names a child the run cannot read through its delegation as a workflow of another workspace', async () => { + const ctx = { ...mockContext, workspaceId: 'workspace-parent' } + mockReadWorkflowDefinitionAsExecutor.mockRejectedValueOnce( + new DelegatedWorkspaceAuthorizationError() + ) + + await expect(handler.execute(ctx, mockBlock, inputs)).rejects.toThrow( + 'Child workflow child-workflow-id is not in this workspace' + ) + expect(mockExecutorExecute).not.toHaveBeenCalled() + }) + it('leaves an internal child load fault for the block executor to log with the run identity', async () => { mockReadWorkflowDefinitionAsExecutor.mockRejectedValueOnce( new TypeError('definition is undefined') diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index bb357961de4..361c4afbc15 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -4,6 +4,7 @@ import { generateId } from '@sim/utils/id' import { isRecordLike } from '@sim/utils/object' import type { Variable, WorkflowState } from '@sim/workflow-types/workflow' import { resolveBillingAttribution } from '@/lib/billing/core/attribution' +import { DelegatedWorkspaceAuthorizationError } from '@/lib/core/application' import { inheritFailureMarks, markFailureKind, @@ -193,6 +194,18 @@ type WorkflowTraceSpan = TraceSpan & { * Handler for workflow blocks that execute other workflows inline. * Creates sub-execution contexts and manages data flow between parent and child workflows. */ +/** + * A child workflow read refused because the run's delegation does not reach it, named for what + * that almost always means: the workflow block names a workflow of another workspace (a raw id + * copied across workspaces). Any other error is returned as it is. + */ +function childReadError(error: unknown, workflowId: string): unknown { + if (!(error instanceof DelegatedWorkspaceAuthorizationError)) return error + return new Error( + `Child workflow ${workflowId} is not in this workspace, or this run may no longer read it: a workflow block runs only workflows of its own workspace.` + ) +} + export class WorkflowBlockHandler implements BlockHandler { private serializer = new Serializer() @@ -1307,7 +1320,7 @@ export class WorkflowBlockHandler implements BlockHandler { logger.warn(`Child workflow ${workflowId} not found`) return null } - throw error + throw childReadError(error, workflowId) } const workflowData = definition.workflow @@ -1365,6 +1378,9 @@ export class WorkflowBlockHandler implements BlockHandler { }) return definition.state !== null } catch (error) { + if (error instanceof DelegatedWorkspaceAuthorizationError) { + throw childReadError(error, workflowId) + } logger.error('Failed to check child deployment', { errorName: toError(error).name, hasWorkflowId: workflowId.length > 0, @@ -1385,7 +1401,7 @@ export class WorkflowBlockHandler implements BlockHandler { if (asOrchestrationError(error)?.code === 'not_found') { return null } - throw error + throw childReadError(error, workflowId) } const deployedState = definition.state diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index e063df0302c..9b735317d0b 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -53,6 +53,7 @@ import { lintDiagnostics, normalizeChangedValues, } from '@/lib/workflows/application/source-locate' +import { foreignResourceRefusals } from '@/lib/workflows/application/source-resource-scope' import { normalizeWorkflowVariables } from '@/lib/workflows/application/workflow-variables' import { gateSourceDiff } from '@/lib/workflows/code/apply/gates' import { diffGraphs, type SourceGraph } from '@/lib/workflows/code/apply/graph-diff' @@ -1052,12 +1053,20 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise entry.id)), + keyOf: keyOfId, + }) const diagnostics = [ ...entryRefs.diagnostics, ...keptDiagnostics, ...materializeDiagnostics, ...refusals, ...normalized.diagnostics, + ...foreignIds, ...lintDiagnostics(entryRefs.lint, changedIds, keyOfId), ].map(locate) if (hasErrors(diagnostics)) { diff --git a/apps/sim/lib/workflows/application/source-resource-scope.ts b/apps/sim/lib/workflows/application/source-resource-scope.ts new file mode 100644 index 00000000000..0b4841517a2 --- /dev/null +++ b/apps/sim/lib/workflows/application/source-resource-scope.ts @@ -0,0 +1,179 @@ +/** + * Resource ids a workflow source writes verbatim (`tableId: 'tbl_…'` rather than + * `table('leads')`) are not resolved through the workspace's resource keys, so an id copied from + * another workspace would be saved as is and fail only when the block runs. An apply checks the + * ids the edit itself writes against the workflow's own workspace and refuses one it does not + * hold, the way materialize refuses a key with no resource (`E_MAT_UNKNOWN_RESOURCE`). + */ +import { db } from '@sim/db' +import { knowledgeBase, userTableDefinitions, workflow } from '@sim/db/schema' +import type { Diagnostic } from '@sim/workflow-code' +import type { BlockState } from '@sim/workflow-types/workflow' +import { and, eq, inArray, isNull } from 'drizzle-orm' +import type { GraphDiff } from '@/lib/workflows/code/apply/graph-diff' +import { getBlock } from '@/blocks/registry' + +/** The workspace-owned resources a block names by id, by the picker type that names them. */ +const SCOPED_SELECTORS = { + 'table-selector': { noun: 'table', plural: 'tables', example: "table('leads')" }, + 'workflow-selector': { + noun: 'workflow', + plural: 'workflows', + example: "childWorkflow('report')", + }, + 'knowledge-base-selector': { + noun: 'knowledge base', + plural: 'knowledge bases', + example: "knowledgeBase('docs')", + }, +} as const + +type ScopedSelector = keyof typeof SCOPED_SELECTORS + +function isScopedSelector(type: string): type is ScopedSelector { + return Object.hasOwn(SCOPED_SELECTORS, type) +} + +/** One verbatim id a changed field writes. */ +interface NamedId { + selector: ScopedSelector + id: string + blockId: string + /** The param the source writes it under (the field's canonical param, else its id). */ + param: string +} + +/** + * The fields of a block type that hold a scoped resource id, by subblock id: each picker, and + * the free-text twin sharing its canonical param (a manual table id). + */ +function scopedFields(blockType: string): Map { + const fields = new Map() + const subBlocks = getBlock(blockType)?.subBlocks ?? [] + const byParam = new Map() + for (const subBlock of subBlocks) { + if (!isScopedSelector(subBlock.type)) continue + fields.set(subBlock.id, { + selector: subBlock.type, + param: subBlock.canonicalParamId ?? subBlock.id, + }) + if (subBlock.canonicalParamId) byParam.set(subBlock.canonicalParamId, subBlock.type) + } + for (const subBlock of subBlocks) { + const selector = subBlock.canonicalParamId ? byParam.get(subBlock.canonicalParamId) : undefined + if (selector && !fields.has(subBlock.id)) { + fields.set(subBlock.id, { selector, param: subBlock.canonicalParamId ?? subBlock.id }) + } + } + return fields +} + +/** The verbatim ids a stored field value holds: none for a reference, an env token or empty. */ +function idsOf(value: unknown): string[] { + const items = Array.isArray(value) + ? value + : typeof value === 'string' + ? value.split(',').map((item) => item.trim()) + : [] + return items.filter( + (item): item is string => + typeof item === 'string' && item !== '' && !item.includes('<') && !item.includes('{{') + ) +} + +/** The ids among `ids` that the workspace holds as live resources of `selector`'s kind. */ +async function heldIds( + selector: ScopedSelector, + ids: string[], + workspaceId: string +): Promise> { + if (ids.length === 0) return new Set() + const rows = + selector === 'table-selector' + ? await db + .select({ id: userTableDefinitions.id }) + .from(userTableDefinitions) + .where( + and( + inArray(userTableDefinitions.id, ids), + eq(userTableDefinitions.workspaceId, workspaceId), + isNull(userTableDefinitions.archivedAt) + ) + ) + : selector === 'workflow-selector' + ? await db + .select({ id: workflow.id }) + .from(workflow) + .where( + and( + inArray(workflow.id, ids), + eq(workflow.workspaceId, workspaceId), + isNull(workflow.archivedAt) + ) + ) + : await db + .select({ id: knowledgeBase.id }) + .from(knowledgeBase) + .where( + and( + inArray(knowledgeBase.id, ids), + eq(knowledgeBase.workspaceId, workspaceId), + isNull(knowledgeBase.deletedAt) + ) + ) + return new Set(rows.map((row) => row.id)) +} + +/** + * `E_MAT_UNKNOWN_RESOURCE` for each table, workflow or knowledge base id a block this apply adds, + * or a field it changes, writes verbatim that is not a live resource of `workspaceId`. An id an + * enclosing apply creates first (`pendingIds`) counts as held; a field the apply leaves alone is + * not checked, so a stored dangling id only refuses the edit that writes it. + */ +export async function foreignResourceRefusals(input: { + blocks: Readonly> + diff: GraphDiff + workspaceId: string + pendingIds: ReadonlySet + keyOf: (blockId: string) => string | undefined +}): Promise { + const changedFields = new Map | 'all'>([ + ...input.diff.added.map((id) => [id, 'all'] as const), + ...input.diff.modified.map((change) => [change.id, new Set(change.subBlocks)] as const), + ]) + const named: NamedId[] = [] + for (const [blockId, changed] of changedFields) { + const block = input.blocks[blockId] + if (!block) continue + for (const [fieldId, field] of scopedFields(block.type)) { + if (changed !== 'all' && !changed.has(fieldId)) continue + for (const id of idsOf(block.subBlocks?.[fieldId]?.value)) { + if (!input.pendingIds.has(id)) named.push({ ...field, id, blockId }) + } + } + } + if (named.length === 0) return [] + const held = new Map>() + for (const selector of Object.keys(SCOPED_SELECTORS) as ScopedSelector[]) { + const ids = [ + ...new Set(named.flatMap((entry) => (entry.selector === selector ? [entry.id] : []))), + ] + held.set(selector, await heldIds(selector, ids, input.workspaceId)) + } + return named.flatMap(({ selector, id, blockId, param }): Diagnostic[] => { + if (held.get(selector)?.has(id)) return [] + const { noun, plural, example } = SCOPED_SELECTORS[selector] + const blockKey = input.keyOf(blockId) + return [ + { + code: 'E_MAT_UNKNOWN_RESOURCE', + severity: 'error', + message: `No ${noun} "${id}" in this workspace: ${input.blocks[blockId]?.name ?? 'the block'} names it by id, and a run can only use this workspace's ${plural}.`, + hint: `Name the ${noun} by its key (${example}), or write the id of a ${noun} in this workspace.`, + blockId, + ...(blockKey !== undefined ? { blockKey } : {}), + param, + }, + ] + }) +} diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index 34f121f9790..c2c72dc1bce 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -1604,6 +1604,64 @@ export default workflow('Notes', {}, () => { } ) + check( + 'refuses a workflow naming by id a table or child workflow of another workspace, and accepts its own', + async () => { + const other = await newWorkspace() + const theirs = await apply(other, STARTER) + expect(theirs.failed).toBeUndefined() + const workspaceId = await newWorkspace() + const ours = await apply(workspaceId, STARTER) + expect(ours.failed).toBeUndefined() + const probe = (tableId: string, workflowId: string) => ({ + 'workflows/probe/workflow.ts': `// @sim-sdk 1 +import { runWorkflow, table, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Probe', {}, () => { + const start = trigger.start('Start', { inputFormat: { email: 'string' } }) + const save = table.insertRow('Save Lead', { + tableId: '${tableId}', + data: { email: start.email }, + }) + const child = runWorkflow('Child', { workflowId: '${workflowId}' }) + + start.to(save) + save.to(child) +}) +`, + }) + const idOf = (result: typeof ours, address: keyof typeof ours.base.resources) => + result.base.resources[address]?.id ?? '' + + const refused = await refusal( + apply(workspaceId, probe(idOf(theirs, 'table:leads'), idOf(theirs, 'workflow:ingest')), { + base: ours.base, + }) + ) + + const foreign = refused.diagnostics.filter( + (finding) => finding.code === 'E_MAT_UNKNOWN_RESOURCE' + ) + expect(foreign.map((finding) => finding.message).sort()).toEqual([ + expect.stringContaining(`No table "${idOf(theirs, 'table:leads')}" in this workspace`), + expect.stringContaining( + `No workflow "${idOf(theirs, 'workflow:ingest')}" in this workspace` + ), + ]) + expect(foreign.map((finding) => finding.file)).toEqual([ + 'workflows/probe/workflow.ts', + 'workflows/probe/workflow.ts', + ]) + + const own = await apply( + workspaceId, + probe(idOf(ours, 'table:leads'), idOf(ours, 'workflow:ingest')), + { kinds: ['workflow'], only: ['workflow'], dryRun: true } + ) + expect(codes(own.diagnostics)).toEqual([]) + } + ) + check('a workflow may use a table the same apply adopts', async () => { const workspaceId = await newWorkspace() const { table: unbound } = await tableUseCases.createTableUseCase.execute({ From a88984461e0bda82ec4d1d5aa025721f3f487454 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:28:08 -0800 Subject: [PATCH 033/104] fix(workflow-code): a deploy can name the draft it expects, and apply --deploy does The deploy use case takes expectedDraftFingerprint (v2 deploy body): it fingerprints the snapshot it is about to publish and refuses with 409, deploying nothing, when the draft no longer prints with it. sim workflows source apply --deploy sends the fingerprint its write answered with, so a canvas edit made between the write and the deploy never goes live. --- apps/docs/content/docs/cli/reference.mdx | 1 + apps/docs/content/docs/cli/workflows.mdx | 1 + apps/docs/openapi-v2-workflows.json | 5 ++ .../v2/workflows/[workflowId]/deploy/route.ts | 3 ++ apps/sim/lib/api/contracts/v2/workflows.ts | 10 ++++ .../lib/workflows/application/deployments.ts | 27 ++++++++++ .../application/read-workflow-source.ts | 42 +++++++++++++++ .../sim/lib/workflows/orchestration/deploy.ts | 8 +++ .../application/deployments.integration.ts | 53 +++++++++++++++++++ .../protocol/workflow-source-apply.test.ts | 4 ++ .../protocol/workflow-source-apply.ts | 3 +- packages/sim-cli/src/generated/v2-api.ts | 6 +++ 12 files changed, 162 insertions(+), 1 deletion(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 312a636ccc0..ece8e7a24dd 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8368,6 +8368,7 @@ sim workflows deploy [options] | --- | --- | --- | | `--name ` | No | Optional label for the deployment version. | | `--description ` | No | Optional release note for the deployment version. | +| `--expected-draft-fingerprint ` | No | Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing. | | `-y, --yes` | No | Accepted and ignored: this command needs no confirmation. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index b24f0b68149..67ee2371941 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -396,6 +396,7 @@ sim workflows deploy [options] | --- | --- | --- | | `--name ` | No | Optional label for the deployment version. | | `--description ` | No | Optional release note for the deployment version. | +| `--expected-draft-fingerprint ` | No | Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing. | | `-y, --yes` | No | Accepted and ignored: this command needs no confirmation. | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index c61bba2f962..583dcd29aff 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -15646,6 +15646,11 @@ "type": "null" } ] + }, + "expectedDraftFingerprint": { + "description": "Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing.", + "type": "string", + "pattern": "^sf1:[0-9a-f]{64}$" } }, "additionalProperties": false diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/deploy/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/deploy/route.ts index eda6637efa3..016cd660f00 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/deploy/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/deploy/route.ts @@ -28,6 +28,9 @@ export const POST = defineV2JsonRoute({ workflowId: params.workflowId, name: body.name, description: body.description ?? undefined, + ...(body.expectedDraftFingerprint + ? { expectedDraftFingerprint: body.expectedDraftFingerprint } + : {}), requestId: generateRequestId(), lintDeployedVersion: true, }), diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 1fca08bda37..a4c7f272a36 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1078,6 +1078,16 @@ export const v2DeployWorkflowContract = defineRouteContract({ description: v1DeployWorkflowBodySchema.shape.description.describe( 'Optional release note for the deployment version.' ), + expectedDraftFingerprint: z + .string() + .regex( + /^sf1:[0-9a-f]{64}$/, + 'expectedDraftFingerprint must be a source fingerprint (sf1: and 64 hex digits)' + ) + .optional() + .describe( + 'Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing.' + ), }) .strict() .optional() diff --git a/apps/sim/lib/workflows/application/deployments.ts b/apps/sim/lib/workflows/application/deployments.ts index 0455473b80b..de76678eba9 100644 --- a/apps/sim/lib/workflows/application/deployments.ts +++ b/apps/sim/lib/workflows/application/deployments.ts @@ -1,5 +1,6 @@ import { AuditAction, AuditResourceType } from '@sim/audit' import { + type Principal, resolvePrincipalAttribution, resolvePrincipalSubjectUserId, toPrincipalActor, @@ -18,6 +19,7 @@ import type { ActiveWorkflowApplicationContext } from '@/lib/workflows/applicati import { requireMutableWorkflow } from '@/lib/workflows/application/mutability' import { workflowOperations } from '@/lib/workflows/application/operations' import { resolvePrincipalWorkflowContext } from '@/lib/workflows/application/principal-scope' +import { draftSourceFingerprint } from '@/lib/workflows/application/read-workflow-source' import { checkNeedsRedeployment } from '@/lib/workflows/deployment-status' import type { WorkflowLintReport } from '@/lib/workflows/editing/lint' import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' @@ -33,6 +35,7 @@ import { loadWorkflowDeploymentVersionState, updateDeploymentVersionMetadata, } from '@/lib/workflows/persistence/utils' +import type { WorkflowState } from '@/stores/workflows/workflow/types' const logger = createLogger('WorkflowDeployments') @@ -49,6 +52,12 @@ export interface DeployWorkflowInput { * surface that presents the findings should pay for them. */ lintDeployedVersion?: boolean + /** + * The `sf1:` fingerprint of the draft the caller means to publish (what a source apply answered + * with as `base.fingerprint`): a draft that no longer has it is refused with `conflict`, nothing + * deployed, so an edit made since the caller looked never goes live in its name. + */ + expectedDraftFingerprint?: string } export interface UndeployWorkflowInput { @@ -144,6 +153,21 @@ async function lintDeployedVersion( } } +/** + * A deploy's draft check: the snapshot it publishes must print with `expected`, the fingerprint of + * the draft the caller reviewed or wrote. + */ +function expectedDraft( + principal: Principal, + context: ActiveWorkflowApplicationContext, + expected: string +): (draft: WorkflowState) => Promise { + return async (draft) => + (await draftSourceFingerprint(principal, context, draft)) === expected + ? null + : 'The workflow draft changed since it was applied, so it was not deployed. Read it again to review the change, then deploy.' +} + export const deployWorkflow = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.deploy, resolveContext: resolvePrincipalWorkflowContext, @@ -162,6 +186,9 @@ export const deployWorkflow = defineAuthorizedWorkflowUseCase({ versionDescription: input.description, requestId: input.requestId, idempotencyKey: input.idempotencyKey, + ...(input.expectedDraftFingerprint !== undefined + ? { admitDraft: expectedDraft(principal, context, input.expectedDraftFingerprint) } + : {}), }) if (!result.success) throwDeploymentFailure(result, 'Failed to deploy workflow') const lint = diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index 8ffd3670c30..8b884b198c4 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -6,6 +6,7 @@ import { type CanonicalWorkflow, type Diagnostic, type SourceBase, + type SourceFingerprint, sourceDepthOverflow, type WorkflowLockV1, type WorkflowSourceMetaV1, @@ -19,6 +20,7 @@ import { readWorkflowSourceMeta, readWorkflowSourceMetas, } from '@sim/workflow-persistence/source-meta' +import type { WorkflowState } from '@sim/workflow-types/workflow' import { type CatalogGate, resolveCatalogGate, @@ -41,6 +43,7 @@ import { printStoredSource, type StoredSource, storedCanonicalHash, + storedSourceFingerprint, } from '@/lib/workflows/code/print-stored' import { canonicalizeStored, @@ -48,6 +51,7 @@ import { prefetchStoredResources, prefetchStoredResourcesFor, } from '@/lib/workflows/code/stored-canonical' +import { parseWorkflowVariables } from '@/lib/workflows/variables/parse' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' interface GetWorkflowSourceInput { @@ -150,6 +154,44 @@ export async function loadStoredSource( } } +/** + * The `sf1:` fingerprint a source read of `draft` would report as `base.fingerprint`: `draft` is a + * graph of the workflow in `context` as the normalized tables load it (a deploy's snapshot), read + * under the workflow's current name and description. A caller holding the fingerprint an apply + * answered with tells from it whether `draft` is still the draft that apply wrote. + */ +export async function draftSourceFingerprint( + principal: Principal, + context: ActiveWorkflowApplicationContext, + draft: Pick +): Promise { + const [gate, prefetched] = await Promise.all([ + resolveCatalogGate(principal, context, { customBlockInputs: true }), + prefetchStoredResources({ + workflowId: context.workflowId, + workspaceId: context.workspaceId, + createdBy: resolvePrincipalSubjectUserId(principal) ?? null, + }), + ]) + const state = { + blocks: draft.blocks, + edges: draft.edges, + loops: draft.loops, + parallels: draft.parallels, + variables: parseWorkflowVariables(draft.variables) ?? {}, + } + const meta = { name: context.workflow.name, description: context.workflow.description ?? null } + return withCatalogBlockScope(gate, async () => { + const catalog = buildSourceCatalog({ + gate, + organizationId: context.workspaceOrganizationId, + storedTypes: storedCatalogTypes(Object.values(state.blocks)), + }) + const { canonical, resources } = await canonicalizeStored({ prefetched, state, meta, catalog }) + return storedSourceFingerprint(canonical, resources) + }) +} + /** Everything one workflow's source read prints from, loaded by a single or a batched read. */ interface LoadedSource { scope: { workflowId: string; workspaceId: string; workspaceOrganizationId: string | null } diff --git a/apps/sim/lib/workflows/orchestration/deploy.ts b/apps/sim/lib/workflows/orchestration/deploy.ts index d430cb8c23f..f599b5baf5e 100644 --- a/apps/sim/lib/workflows/orchestration/deploy.ts +++ b/apps/sim/lib/workflows/orchestration/deploy.ts @@ -107,6 +107,12 @@ export interface PerformFullDeployParams { actorId?: string actor?: PrincipalActor captureAnalytics?: false + /** + * Checks the draft snapshot this deploy is about to publish, before anything is admitted: a + * refusal message refuses the deploy (`conflict`), so a caller publishes exactly the draft it + * expects and never one edited since it looked. + */ + admitDraft?: (draft: WorkflowState) => Promise } /** @@ -259,6 +265,8 @@ async function performStableFullDeploy(params: { errorCode: 'validation', } } + const refusal = await params.params.admitDraft?.(workflowState) + if (refusal) return { success: false, error: refusal, errorCode: 'conflict' } const prepared = await prepareWorkflowSnapshotDeployment({ ...params, workflowState }) if (!prepared.success) return prepared diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index 592d012ead2..e90f14e72b6 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -27,8 +27,11 @@ vi.mock('@/lib/realtime/notify', () => realtimeNotifyMock) vi.mock('@/lib/posthog/server', () => posthogServerMock) import { replaceWorkflowChatDeployment } from '@/lib/chat-deployments/application/workflow-chat-deployment' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { encryptSecret } from '@/lib/core/security/encryption' import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' +import { deployWorkflow } from '@/lib/workflows/application/deployments' +import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { listWorkflowTriggers } from '@/lib/workflows/application/triggers' import { updateWorkflowPublicApi } from '@/lib/workflows/application/update-workflow-deployment-settings' import { deploymentAdapter } from '@/lib/workspace-source/application/kinds/deployment/adapter' @@ -251,6 +254,26 @@ async function serveChat(id: string, identifier: string) { }) } +/** + * Edits the Answer agent's prompt in the stored draft directly, as the editor's realtime save + * does: no source apply sees it. + */ +async function editDraftOutOfBand(id: string, text: string) { + const [row] = await db + .select({ id: workflowBlocks.id, subBlocks: workflowBlocks.subBlocks }) + .from(workflowBlocks) + .where(and(eq(workflowBlocks.workflowId, id), eq(workflowBlocks.name, 'Answer'))) + if (!row) throw new Error('No Answer block') + const subBlocks = JSON.parse(JSON.stringify(row.subBlocks).replace('Question: ', text)) + await db.update(workflowBlocks).set({ subBlocks }).where(eq(workflowBlocks.id, row.id)) +} + +/** The `sf1:` fingerprint a source read of workflow `id` reports now. */ +async function draftFingerprint(id: string): Promise { + const read = await readWorkflowSource.execute({ principal: owner, input: { workflowId: id } }) + return read.base.fingerprint +} + function edited(files: Files): Files { return { ...files, [WORKFLOW]: files[WORKFLOW].replace('Question: ', 'Asked: ') } } @@ -1115,4 +1138,34 @@ describe('workspace source: deployments', () => { const refused = await refusal(apply(workspaceId, { 'deployments/missing.ts': DRAFT })) expect(codes(refused.diagnostics)).toEqual(['E_DEPLOY_WORKFLOW']) }) + + check( + 'a deploy carrying the draft fingerprint it expects refuses a draft edited since, deploying nothing', + async () => { + const { id } = await deployedWorkspace(PINNED) + const reviewed = await draftFingerprint(id) + await editDraftOutOfBand(id, 'Edited in the editor: ') + + const refused = await deployWorkflow + .execute({ + principal: owner, + input: { workflowId: id, requestId: generateId(), expectedDraftFingerprint: reviewed }, + }) + .then( + () => null, + (error: unknown) => error + ) + expect(refused).toBeInstanceOf(OrchestrationError) + expect((refused as OrchestrationError).code).toBe('conflict') + expect((await deployState(id)).versions).toBe(1) + + const current = await draftFingerprint(id) + expect(current).not.toBe(reviewed) + await deployWorkflow.execute({ + principal: owner, + input: { workflowId: id, requestId: generateId(), expectedDraftFingerprint: current }, + }) + expect((await deployState(id)).versions).toBe(2) + } + ) }) 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 73a6ca5ea37..5fb19ca9ec2 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 @@ -854,6 +854,10 @@ describe('sim workflows source apply', () => { await apply(WORKFLOW_ID, '--dir', dir, '--yes', '--deploy') expect(request.mock.calls.map((call) => call[0])).toEqual([APPLY_PATH, DEPLOY_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, + }) expect(readFileSync(join(dir, 'workflow.ts'), 'utf8')).toBe(`${ENTRY}// stored\n`) expect(stdoutJson()).toMatchObject({ applied: true, 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 1145555b2ce..ef4d4f446b4 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -397,7 +397,8 @@ async function deployStep( const deployed = await client .request('deployWorkflow', { params: { workflowId: data.workflowId }, - body: {}, + // The draft this write stored: an edit made since is refused, never deployed in its name. + body: { expectedDraftFingerprint: data.base.fingerprint }, }) .then( (response) => response.data, diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index a6664d9ee99..c5f696a0f81 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -6479,6 +6479,7 @@ export type DeployWorkflowQuery = Record export type DeployWorkflowBody = { name?: string description?: string | null + expectedDraftFingerprint?: string } type DeployWorkflowResponseRef0 = { @@ -22876,6 +22877,11 @@ export const V2_OPERATIONS = { kind: 'string', describe: 'Optional release note for the deployment version.', }, + expectedDraftFingerprint: { + kind: 'string', + describe: + 'Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing.', + }, }, }, deployWorkflowMcpTool: { From 7919fd7ea8b50d9775d2e68665defac83c44d643 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 21:40:33 -0800 Subject: [PATCH 034/104] fix(workspace-source): live: 'draft' publishes only a draft the directory vouches for A deployment with live: 'draft' redeployed whenever the draft differed from the live version, so an apply of any unrelated change published editor edits nobody reviewed while git kept the old workflow. It now deploys only the draft this apply's workflow write stored, or a draft that still prints as the workflow folder's base. A draft holding edits made outside source is not deployed and warns W_DEPLOY_DRAFT_NOT_SOURCE naming the workflow; a chat write, which would deploy it, refuses with E_DEPLOY_DRAFT_NOT_SOURCE_CHAT. Every deploy names the vouched draft's fingerprint, so a draft edited between the plan and the deploy is refused as stale. --- apps/docs/openapi-v2-workflows.json | 6 + .../application/apply-workspace-source.ts | 1 + .../application/deployments.integration.ts | 88 ++++++++++- .../application/kinds/deployment/adapter.ts | 147 +++++++++++++++--- .../application/kinds/workflow/adapter.ts | 1 + .../lib/workspace-source/application/types.ts | 5 + packages/sim-cli/src/generated/v2-api.ts | 6 + .../src/codegen/workspace-text.generated.ts | 2 +- .../src/workspace/deployment.d.ts | 4 +- packages/workspace-code/DESIGN.md | 7 +- .../workspace-code/src/diagnostics/codes.ts | 7 + 11 files changed, 251 insertions(+), 23 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 583dcd29aff..0396bb5d0d8 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -26523,6 +26523,8 @@ "E_DEPLOY_CHAT_IDENTIFIER", "E_DEPLOY_PINNED_CHAT", "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", "I_DEPLOY_DRAFT_NOT_LIVE", "E_APPLY_STALE", "E_APPLY_NO_BASE", @@ -27097,6 +27099,8 @@ "E_DEPLOY_CHAT_IDENTIFIER", "E_DEPLOY_PINNED_CHAT", "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", "I_DEPLOY_DRAFT_NOT_LIVE", "E_APPLY_STALE", "E_APPLY_NO_BASE", @@ -28779,6 +28783,8 @@ "E_DEPLOY_CHAT_IDENTIFIER", "E_DEPLOY_PINNED_CHAT", "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", "I_DEPLOY_DRAFT_NOT_LIVE", "E_APPLY_STALE", "E_APPLY_NO_BASE", 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 3bf4752caf3..a2b7f717926 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -302,6 +302,7 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ async execute({ principal, input, context }): Promise { const ctx: ApplyContext = { ...sourceContext(principal, context), + writtenDrafts: new Map(), ...(input.provenance ? { provenance: input.provenance } : {}), } if (input.dryRun === true) { diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index e90f14e72b6..0b3804fc19c 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -19,6 +19,7 @@ import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' import { generateId } from '@sim/utils/id' import { toArray, toRecord } from '@sim/utils/object' import type { WorkspaceBaseV1, WorkspaceKind } from '@sim/workspace-code' +import { unchangedFiles } from '@sim/workspace-code/kinds/workflow' import { and, eq, inArray, isNull } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, vi } from 'vitest' @@ -264,7 +265,9 @@ async function editDraftOutOfBand(id: string, text: string) { .from(workflowBlocks) .where(and(eq(workflowBlocks.workflowId, id), eq(workflowBlocks.name, 'Answer'))) if (!row) throw new Error('No Answer block') - const subBlocks = JSON.parse(JSON.stringify(row.subBlocks).replace('Question: ', text)) + const stored = JSON.stringify(row.subBlocks) + const subBlocks = JSON.parse(stored.replace(/(Question|Asked): /, text)) + if (JSON.stringify(subBlocks) === stored) throw new Error('The edit changed nothing') await db.update(workflowBlocks).set({ subBlocks }).where(eq(workflowBlocks.id, row.id)) } @@ -274,6 +277,17 @@ async function draftFingerprint(id: string): Promise { return read.base.fingerprint } +/** `files` as the CLI sends them: the workflow folder, unchanged since the last write, as its base alone. */ +function asSent(files: Files, workspaceId: string): Files { + const folder = Object.fromEntries( + Object.entries(files).filter(([path]) => path.startsWith('workflows/nightly/')) + ) + const rest = Object.fromEntries( + Object.entries(files).filter(([path]) => !path.startsWith('workflows/nightly/')) + ) + return { ...rest, ...unchangedFiles('nightly', folder, workspaceId) } +} + function edited(files: Files): Files { return { ...files, [WORKFLOW]: files[WORKFLOW].replace('Question: ', 'Asked: ') } } @@ -1168,4 +1182,76 @@ describe('workspace source: deployments', () => { expect((await deployState(id)).versions).toBe(2) } ) + + check( + "live: 'draft' does not publish a draft edited outside source, and says which workflow", + async () => { + const { workspaceId, id, files, base } = await deployedWorkspace() + await editDraftOutOfBand(id, 'Edited in the editor: ') + + const result = await apply(workspaceId, asSent(files, workspaceId), { base }) + expect(result.failed).toBeUndefined() + expect(actions(result.plan)).toEqual(['noop workflow:nightly', 'noop deployment:nightly']) + expect(result.applied).toEqual([]) + const warning = result.diagnostics.find( + (finding) => finding.code === 'W_DEPLOY_DRAFT_NOT_SOURCE' + ) + expect(warning).toMatchObject({ severity: 'warning', kind: 'deployment', key: 'nightly' }) + expect(warning?.message).toContain('workflows/nightly') + expect((await deployState(id)).versions).toBe(1) + + // Writing the chat would publish that draft too, so it is refused before anything is written. + const chat = await refusal( + apply( + workspaceId, + { ...asSent(files, workspaceId), [DEPLOYMENT]: answerChat('not-source-chat') }, + { base } + ) + ) + expect(codes(chat.diagnostics)).toEqual(['E_DEPLOY_DRAFT_NOT_SOURCE_CHAT']) + expect((await deployState(id)).versions).toBe(1) + } + ) + + check( + "live: 'draft' deploys a draft that still is the directory's workflow, applied before without its deploy", + async () => { + const { workspaceId, id, files, base } = await deployedWorkspace(PINNED) + const written = await apply(workspaceId, edited(files), { base }) + expect(actions(written.applied)).toEqual(['update workflow:nightly']) + expect((await deployState(id)).versions).toBe(1) + + const now = { ...edited(files), ...written.files, [DEPLOYMENT]: DRAFT } + const result = await apply(workspaceId, asSent(now, workspaceId), { base: written.base }) + expect(result.failed).toBeUndefined() + expect(actions(result.applied)).toEqual(['update deployment:nightly']) + expect(codes(result.diagnostics, 'warning')).not.toContain('W_DEPLOY_DRAFT_NOT_SOURCE') + expect((await deployState(id)).versions).toBe(2) + } + ) + + check( + 'a deploy refuses a draft edited between the plan and the deploy, publishing nothing', + async () => { + const { workspaceId, id, files, base } = await deployedWorkspace() + const check = deploymentAdapter.storedFingerprintNow + if (!check) throw new Error('The deployment adapter checks fingerprints before writing') + // A teammate edits the draft after the workflow write, just before the deploy. + const racing = vi + .spyOn(deploymentAdapter, 'storedFingerprintNow') + .mockImplementation(async (change, ctx) => { + await editDraftOutOfBand(id, 'Edited meanwhile: ') + return check.call(deploymentAdapter, change, ctx) + }) + try { + const result = await apply(workspaceId, edited(files), { base }) + expect(racing).toHaveBeenCalledOnce() + expect(actions(result.applied)).toEqual(['update workflow:nightly']) + expect([result.failed?.key, result.failed?.code]).toEqual(['nightly', 'E_APPLY_STALE']) + expect((await deployState(id)).versions).toBe(1) + } finally { + racing.mockRestore() + } + } + ) }) diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 00dc2810cca..616d29a5f11 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -9,7 +9,12 @@ * The three-way rule covers what the server stores: the public API flag and the chat. `live` is * read on every apply against the server's "draft differs" flag instead: `'draft'` deploys when * this apply edits the workflow or the draft already differs, `'pinned'` never redeploys and says - * when the draft differs. A deploy is keyed by the deployment's fingerprint and the version it + * when the draft differs. `'draft'` publishes only a draft the directory vouches for: the one this + * apply's workflow write leaves, or one that still prints as the workflow folder's base (an edit + * of the folder applied before without its deploy). A draft holding edits the directory does not + * declare (made in the editor) is not published (`W_DEPLOY_DRAFT_NOT_SOURCE`), and the deploy + * names the vouched draft's fingerprint, so one edited between the plan and the deploy is refused + * rather than published. A deploy is keyed by the deployment's fingerprint and the version it * replaces, so a re-run after a failure replays the same deploy instead of publishing twice. * * The server keeps a chat password only encrypted, so the base records which variable the last @@ -33,6 +38,7 @@ import { deploymentCodec, deploymentDeclarationPath, } from '@sim/workspace-code/kinds/deployment' +import { workflowFolder, workflowSourceBase } from '@sim/workspace-code/kinds/workflow' import { chatDeploymentOperations } from '@/lib/chat-deployments/application/operations' import { assertChatReplaceAllowed, @@ -51,8 +57,12 @@ import { } from '@/lib/workflows/application/deployments' import { listWorkflows } from '@/lib/workflows/application/list-workflows' import { workflowOperations } from '@/lib/workflows/application/operations' +import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { updateWorkflowPublicApi } from '@/lib/workflows/application/update-workflow-deployment-settings' -import { WorkspaceSourceRejectedError } from '@/lib/workspace-source/application/errors' +import { + ResourceChangedError, + WorkspaceSourceRejectedError, +} from '@/lib/workspace-source/application/errors' import { kindFinding, planUndeclared, where } from '@/lib/workspace-source/application/findings' import { bindStored, listUpTo } from '@/lib/workspace-source/application/keys' import { @@ -104,6 +114,11 @@ export interface DeploymentPlan { workflowId?: string /** Publish the draft: a first deploy, or `live: 'draft'` with a draft that differs. */ deploy: boolean + /** + * The draft a deploy publishes: the one this apply's workflow write stores (`written`, its + * fingerprint known once written), or the draft with the `sf1:` fingerprint the plan vouched for. + */ + draft?: { written: true } | { fingerprint: string } /** The public API flag to set: on a first deploy (an undeploy keeps the old one), or a change. */ publicApi?: boolean /** Whether the chat is written or removed. */ @@ -360,6 +375,51 @@ function checkKeptOutputs( return recreated } +/** + * The draft of workflow `key` the directory vouches for, which a deploy may publish: the one this + * apply's workflow write leaves (`draftEdited`); else the stored draft when it still prints as the + * workflow folder's base, so it holds no edit the directory does not declare; else, with no folder + * declared, the stored draft of a first deploy, which publishes no earlier version over anything. + * `undefined` when the stored draft holds edits the directory does not declare. Reads the stored + * draft only when no write vouches for it. + */ +async function vouchedDraft( + ctx: PlanContext, + options: { + workflowId: string | undefined + draftEdited: boolean + folder: PlannedChange<'workflow'> | undefined + firstDeploy: boolean + } +): Promise { + if (options.draftEdited) return { written: true } + const { workflowId, folder } = options + if (!workflowId) return undefined + const base = folder?.decl ? workflowSourceBase(folder.decl) : null + if (!base && (folder || !options.firstDeploy)) return undefined + const read = await readWorkflowSource.execute({ + principal: ctx.principal, + input: { workflowId }, + }) + const fingerprint = read.base.fingerprint + if (base && (base.workflowId !== workflowId || base.fingerprint !== fingerprint)) return undefined + return { fingerprint } +} + +/** `W_DEPLOY_DRAFT_NOT_SOURCE`: the draft of workflow `key` holds edits the directory does not. */ +function draftNotSourceFinding(key: string, declared: boolean) { + return deploymentFinding( + key, + 'W_DEPLOY_DRAFT_NOT_SOURCE', + declared + ? `${where('workflow', key)}'s draft holds edits ${workflowFolder(key)}/ does not (made outside source), so this apply does not deploy it; the live version keeps running.` + : `${where('workflow', key)}'s draft differs from its live version, and this directory does not declare the workflow, so this apply does not deploy it; the live version keeps running.`, + declared + ? `To deploy those edits, get them into the directory (\`sim workspaces source get\` into a fresh directory) and apply, or deploy from the editor. To drop them, edit ${workflowFolder(key)}/ and apply.` + : `Add ${workflowFolder(key)}/ to deploy what it declares, or deploy from the editor.` + ) +} + /** Plans one declared deployment against the workflow under the same key. */ async function planDeployment( key: string, @@ -376,7 +436,8 @@ async function planDeployment( diagnostics: [], } const workflowChange = ctx.planned.find( - (planned) => planned.kind === 'workflow' && planned.key === key + (planned): planned is PlannedChange<'workflow'> => + planned.kind === 'workflow' && planned.key === key ) const creating = workflowChange?.action === 'create' const deployed = stored.bound.get(key) @@ -430,7 +491,18 @@ async function planDeployment( if ('settled' in planned) { next = planned.settled } else if (planned.action === 'create') { + const draft = await vouchedDraft(ctx, { + workflowId, + draftEdited, + folder: workflowChange, + firstDeploy: true, + }) + if (!draft) { + change.diagnostics.push(draftNotSourceFinding(key, true)) + return change + } detail.deploy = true + detail.draft = draft // An undeploy keeps the workflow's public API flag, so a first deploy always writes it. detail.publicApi = decl.api?.public === true if (decl.chat) detail.chat = 'replace' @@ -456,9 +528,30 @@ async function planDeployment( if (Object.keys(plannedOutputNames).length > 0) detail.plannedOutputNames = plannedOutputNames const draftDiffers = state.needsRedeployment || draftEdited if (draftDiffers && decl.live === 'draft') { - detail.deploy = true - next.action = 'update' - next.fields = ['live version', ...(next.fields ?? [])] + const draft = await vouchedDraft(ctx, { + workflowId, + draftEdited, + folder: workflowChange, + firstDeploy: false, + }) + if (draft) { + detail.deploy = true + detail.draft = draft + next.action = 'update' + next.fields = ['live version', ...(next.fields ?? [])] + } else { + next.diagnostics.push(draftNotSourceFinding(key, workflowChange !== undefined)) + if (detail.chat === 'replace') { + next.diagnostics.push( + deploymentFinding( + key, + 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT', + 'Writing the chat deploys the draft, which holds edits this directory does not declare.', + `Get those edits into ${workflowFolder(key)}/ first, or leave the chat as it is.` + ) + ) + } + } } else if (draftDiffers) { next.diagnostics.push( deploymentFinding( @@ -519,22 +612,38 @@ function idempotencyKey(decl: DeploymentDecl, workflowId: string, live: string | * Deploys the draft unless it already is the live version: a re-run after a deploy that * succeeded finds nothing to publish, and one after a deploy that failed replays the same key. */ -async function deployDraft(decl: DeploymentDecl, workflowId: string, ctx: ApplyContext) { +async function deployDraft( + change: DeploymentChange, + decl: DeploymentDecl, + workflowId: string, + ctx: ApplyContext +) { const { principal } = ctx + const draft = change.detail?.draft + const expectedDraftFingerprint = + draft && 'written' in draft ? ctx.writtenDrafts.get(workflowId) : draft?.fingerprint + if (!expectedDraftFingerprint) throw new Error('A deploy needs the draft it publishes') const status = await readWorkflowDeploymentStatus.execute({ principal, input: { workflowId } }) if (status.isDeployed && !status.needsRedeployment) return - await deployWorkflow.execute({ - principal, - input: { - workflowId, - requestId: generateRequestId(), - idempotencyKey: idempotencyKey( - decl, + try { + await deployWorkflow.execute({ + principal, + input: { workflowId, - status.activeDeployment?.deploymentVersionId ?? null - ), - }, - }) + requestId: generateRequestId(), + expectedDraftFingerprint, + idempotencyKey: idempotencyKey( + decl, + workflowId, + status.activeDeployment?.deploymentVersionId ?? null + ), + }, + }) + } catch (error) { + // The draft moved since the plan vouched for it (or since this apply wrote it): it is stale. + if (!(error instanceof OrchestrationError) || error.code !== 'conflict') throw error + throw new ResourceChangedError({ kind: 'workflow', key: change.key }) + } } /** The block ids a chat's outputs name, refusing a block the workflow does not have. */ @@ -812,7 +921,7 @@ export const deploymentAdapter: KindAdapter<'deployment', StoredDeployment> = { input: { workflowId, isPublicApi: detail.publicApi }, }) } - if (detail.deploy) await deployDraft(decl, workflowId, ctx) + if (detail.deploy) await deployDraft(change, decl, workflowId, ctx) if (chatInput) await replaceWorkflowChatDeployment.execute({ principal, input: chatInput }) if (detail.chat === 'delete') { await deleteWorkflowChatDeployment.execute({ principal, input: { workflowId } }) diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index 963ac7223ba..a1b4e83119c 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -881,6 +881,7 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { if (!(error instanceof WorkflowSourceRejectedError)) throw error throw new WorkspaceSourceRejectedError(inFolder(change.key, error.diagnostics)) }) + ctx.writtenDrafts.set(result.workflowId, result.base.fingerprint) const base: BaseResource = { id: result.workflowId, fingerprint: workflowFingerprint(result.base), diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index 4f8422e34a1..65f9fface2a 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -75,6 +75,11 @@ export interface PlanContext extends SourceContext { export interface ApplyContext extends SourceContext { provenance?: { client: 'cli' | 'api'; gitSha?: string } + /** + * The `sf1:` fingerprint of each draft this apply's workflow writes stored, by workflow id: a + * later deploy of that workflow publishes exactly that draft. + */ + 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. diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index c5f696a0f81..0eb3b360e87 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1281,6 +1281,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_DEPLOY_CHAT_IDENTIFIER' | 'E_DEPLOY_PINNED_CHAT' | 'W_DEPLOYED_DRAFT_CHANGED' + | 'W_DEPLOY_DRAFT_NOT_SOURCE' + | 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT' | 'I_DEPLOY_DRAFT_NOT_LIVE' | 'E_APPLY_STALE' | 'E_APPLY_NO_BASE' @@ -1570,6 +1572,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_DEPLOY_CHAT_IDENTIFIER' | 'E_DEPLOY_PINNED_CHAT' | 'W_DEPLOYED_DRAFT_CHANGED' + | 'W_DEPLOY_DRAFT_NOT_SOURCE' + | 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT' | 'I_DEPLOY_DRAFT_NOT_LIVE' | 'E_APPLY_STALE' | 'E_APPLY_NO_BASE' @@ -11028,6 +11032,8 @@ export type GetWorkspaceSourceResponse = { | 'E_DEPLOY_CHAT_IDENTIFIER' | 'E_DEPLOY_PINNED_CHAT' | 'W_DEPLOYED_DRAFT_CHANGED' + | 'W_DEPLOY_DRAFT_NOT_SOURCE' + | 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT' | 'I_DEPLOY_DRAFT_NOT_LIVE' | 'E_APPLY_STALE' | 'E_APPLY_NO_BASE' diff --git a/packages/workflow-sdk/src/codegen/workspace-text.generated.ts b/packages/workflow-sdk/src/codegen/workspace-text.generated.ts index 724b21ef94e..c57d5d713a3 100644 --- a/packages/workflow-sdk/src/codegen/workspace-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/workspace-text.generated.ts @@ -5,7 +5,7 @@ export const WORKSPACE_SDK_DTS: Readonly> = { 'credentials.d.ts': '/**\n * Credential declarations: `credentials.ts` at the root of a workspace source directory names the\n * saved credentials its workflows use, each by the provider it is for. Never a token: connect one\n * with `sim credentials connect --name ""`.\n *\n * ```ts\n * // @sim-sdk 1\n * import { defineCredentials } from \u0027@sim/workflow-sdk/workspace\u0027\n *\n * export default defineCredentials({\n * slack: { provider: \u0027slack\u0027 },\n * gmail: { provider: \u0027google-email\u0027, name: \u0027Support inbox\u0027 },\n * })\n * ```\n *\n * A workflow uses one as `credential(\u0027slack\u0027)`, which type-checks against these keys. An apply\n * binds each key to a credential of this workspace: the one bound to it already; else the only\n * credential of the provider no other declared key holds, narrowed to the display name `name`\n * when given. A key nothing binds to, or several credentials could bind to, is reported, and a\n * workflow using it is held back while the rest of the apply goes ahead. Applying the same\n * directory to another workspace binds each key to that workspace\u0027s own credential. Removing a key\n * unbinds it only with `--allow-delete`; the credential itself is never deleted.\n */\n\n/** One declared credential. */\nexport interface CredentialDeclaration {\n /** The provider the credential is for (`slack`, `google-email`, …). */\n provider: string\n /** The display name that picks one of several credentials of the provider. */\n name?: string\n}\n\n/** Declares the workspace\u0027s credentials by key. Its default export is the whole file. */\nexport declare function defineCredentials>(\n credentials: T\n): T\n\n/**\n * The credential keys a `credentials.ts` declaration adds, each with its provider, as\n * `workspace.d.ts` merges them into `credential(\u0027…\u0027)`.\n */\nexport type DeclaredCredentials = {\n [K in keyof T]: T[K] extends { provider: infer P } ? { provider: P } : never\n}\n', 'deployment.d.ts': - '/**\n * Deployment declarations: `deployments/.ts` in a workspace source directory deploys\n * `workflows//`, so its schedule, webhook, API and chat triggers run.\n *\n * ```ts\n * // @sim-sdk 1\n * import { defineDeployment, env } from \u0027@sim/workflow-sdk/workspace\u0027\n *\n * export default defineDeployment({\n * live: \u0027draft\u0027,\n * chat: {\n * identifier: \u0027support\u0027,\n * title: \u0027Support\u0027,\n * auth: { password: env.SUPPORT_CHAT_PASSWORD },\n * outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n * },\n * })\n * ```\n *\n * An apply deploys after it writes the workflows. Removing the file undeploys the workflow, which\n * stops its schedules, webhooks, API and chat, and needs `--allow-delete`. Deploying needs a\n * workspace admin and is refused to a workspace API key. Publishing to an MCP server is not part\n * of source.\n */\nimport type { EnvRef } from \u0027@sim/workflow-sdk\u0027\n\nexport { env, stored } from \u0027@sim/workflow-sdk\u0027\n\n/** Who may open a chat. */\nexport type ChatAuth =\n | \u0027public\u0027\n /**\n * A password from an environment variable, by name, never the value itself; or `stored()`, the\n * password the chat already stores (valid only for a chat that has one).\n */\n | { password: EnvRef }\n /** These emails (or `@domain.com` patterns), signing in with a code. */\n | { emails: string[] }\n /** These emails (or `@domain.com` patterns), signing in through the workspace\u0027s SSO. */\n | { sso: string[] }\n\n/** One output a chat answers with. */\nexport interface ChatOutput {\n /** The block\u0027s name, as the workflow names it. */\n block: string\n /** The output path on that block (`content`, `result.text`). */\n path: string\n}\n\n/** The chat a deployment serves. */\nexport interface ChatDeployment {\n /** The chat\u0027s URL path segment, unique across the platform. */\n identifier: string\n title: string\n description?: string\n auth: ChatAuth\n outputs?: ChatOutput[]\n /** The chat\u0027s look; an omitted field takes the platform default. */\n customizations?: { primaryColor?: string; welcomeMessage?: string; imageUrl?: string }\n /** Show the model\u0027s thinking to clients that ask for it. */\n includeThinking?: boolean\n /** Show tool calls to clients that ask for them. */\n includeToolCalls?: boolean\n}\n\n/** A deployment declaration. */\nexport interface DeploymentDeclaration {\n /**\n * `\u0027draft\u0027`: an apply deploys the draft whenever it differs from the live version (after this\n * apply\u0027s workflow edits). `\u0027pinned\u0027`: an apply never redeploys, and says when the draft differs.\n */\n live: \u0027draft\u0027 | \u0027pinned\u0027\n /** Public: anyone may run the workflow\u0027s API without a key. Private when omitted. */\n api?: { public?: boolean }\n /** The chat the deployment serves; none when omitted. */\n chat?: ChatDeployment\n}\n\n/** Declares a workflow\u0027s deployment. Its default export is the whole file. */\nexport declare function defineDeployment(deployment: DeploymentDeclaration): DeploymentDeclaration\n', + '/**\n * Deployment declarations: `deployments/.ts` in a workspace source directory deploys\n * `workflows//`, so its schedule, webhook, API and chat triggers run.\n *\n * ```ts\n * // @sim-sdk 1\n * import { defineDeployment, env } from \u0027@sim/workflow-sdk/workspace\u0027\n *\n * export default defineDeployment({\n * live: \u0027draft\u0027,\n * chat: {\n * identifier: \u0027support\u0027,\n * title: \u0027Support\u0027,\n * auth: { password: env.SUPPORT_CHAT_PASSWORD },\n * outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n * },\n * })\n * ```\n *\n * An apply deploys after it writes the workflows. Removing the file undeploys the workflow, which\n * stops its schedules, webhooks, API and chat, and needs `--allow-delete`. Deploying needs a\n * workspace admin and is refused to a workspace API key. Publishing to an MCP server is not part\n * of source.\n */\nimport type { EnvRef } from \u0027@sim/workflow-sdk\u0027\n\nexport { env, stored } from \u0027@sim/workflow-sdk\u0027\n\n/** Who may open a chat. */\nexport type ChatAuth =\n | \u0027public\u0027\n /**\n * A password from an environment variable, by name, never the value itself; or `stored()`, the\n * password the chat already stores (valid only for a chat that has one).\n */\n | { password: EnvRef }\n /** These emails (or `@domain.com` patterns), signing in with a code. */\n | { emails: string[] }\n /** These emails (or `@domain.com` patterns), signing in through the workspace\u0027s SSO. */\n | { sso: string[] }\n\n/** One output a chat answers with. */\nexport interface ChatOutput {\n /** The block\u0027s name, as the workflow names it. */\n block: string\n /** The output path on that block (`content`, `result.text`). */\n path: string\n}\n\n/** The chat a deployment serves. */\nexport interface ChatDeployment {\n /** The chat\u0027s URL path segment, unique across the platform. */\n identifier: string\n title: string\n description?: string\n auth: ChatAuth\n outputs?: ChatOutput[]\n /** The chat\u0027s look; an omitted field takes the platform default. */\n customizations?: { primaryColor?: string; welcomeMessage?: string; imageUrl?: string }\n /** Show the model\u0027s thinking to clients that ask for it. */\n includeThinking?: boolean\n /** Show tool calls to clients that ask for them. */\n includeToolCalls?: boolean\n}\n\n/** A deployment declaration. */\nexport interface DeploymentDeclaration {\n /**\n * `\u0027draft\u0027`: an apply deploys the draft whenever it differs from the live version (after this\n * apply\u0027s workflow edits), as long as it holds only what the workflow folder declares: a draft\n * edited outside source is not deployed, and the apply warns. `\u0027pinned\u0027`: an apply never\n * redeploys, and says when the draft differs.\n */\n live: \u0027draft\u0027 | \u0027pinned\u0027\n /** Public: anyone may run the workflow\u0027s API without a key. Private when omitted. */\n api?: { public?: boolean }\n /** The chat the deployment serves; none when omitted. */\n chat?: ChatDeployment\n}\n\n/** Declares a workflow\u0027s deployment. Its default export is the whole file. */\nexport declare function defineDeployment(deployment: DeploymentDeclaration): DeploymentDeclaration\n', 'file.d.ts': '/**\n * Workspace files need no declaration: every file under `files/` is one workspace file, at the\n * folder path and name it has there (`files/reports/q1.pdf` is `q1.pdf` in the `reports`\n * folder), synced by content hash. Each apply that changes a file\u0027s bytes records a new version\n * of it, so an earlier one can be restored in the Files tab. Files over 10 MB, or whose name no\n * directory can hold (a reserved character, or a path that differs only in letter case from\n * another file or folder), are left out of a get (listed in `.sim/skipped.json`) and never written\n * by an apply; a file the directory no longer holds is deleted only with `--allow-delete`.\n */\nexport {}\n', 'index.d.ts': diff --git a/packages/workflow-sdk/src/workspace/deployment.d.ts b/packages/workflow-sdk/src/workspace/deployment.d.ts index c6d0f8837cd..50b347c0e5f 100644 --- a/packages/workflow-sdk/src/workspace/deployment.d.ts +++ b/packages/workflow-sdk/src/workspace/deployment.d.ts @@ -67,7 +67,9 @@ export interface ChatDeployment { export interface DeploymentDeclaration { /** * `'draft'`: an apply deploys the draft whenever it differs from the live version (after this - * apply's workflow edits). `'pinned'`: an apply never redeploys, and says when the draft differs. + * apply's workflow edits), as long as it holds only what the workflow folder declares: a draft + * edited outside source is not deployed, and the apply warns. `'pinned'`: an apply never + * redeploys, and says when the draft differs. */ live: 'draft' | 'pinned' /** Public: anyone may run the workflow's API without a key. Private when omitted. */ diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 92a80f798de..7ba322ef8f3 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -229,7 +229,12 @@ workflow's key and claims none (`WORKSPACE_KIND_SPECS[kind].resourceKind` is `nu is the workflow's id. The three-way rule covers what the server stores (public API, chat); `live` is outside the fingerprint and read on every apply against the server's `needsRedeployment`: `'draft'` deploys when the apply edits the workflow or the draft already differs, `'pinned'` never -redeploys and reports `I_DEPLOY_DRAFT_NOT_LIVE`. A deploy's idempotency key hashes the deployment's +redeploys and reports `I_DEPLOY_DRAFT_NOT_LIVE`. `'draft'` publishes only a draft the directory +vouches for: the one this apply's workflow write stored, or one that still prints as the workflow +folder's base. A draft holding edits made outside source is not deployed +(`W_DEPLOY_DRAFT_NOT_SOURCE`; a chat write, which would deploy it, is `E_DEPLOY_DRAFT_NOT_SOURCE_CHAT`), +and every deploy names the vouched draft's `sf1:` fingerprint (`expectedDraftFingerprint`), so a draft +edited between the plan and the deploy is refused as stale rather than published. A deploy's idempotency key hashes the deployment's fingerprint and the live version it replaces. The flag, the deploy and the chat are separate writes, so the apply checks what the chat write refuses (an identifier another chat holds, `E_DEPLOY_CHAT_IDENTIFIER`, at plan time and again before the first write; the password, the diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index 810e0b7d9ee..6ed437e385e 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -217,6 +217,13 @@ const DEPLOYMENT_CODES = [ 'E_DEPLOY_PINNED_CHAT', /** An apply edits a deployed workflow that no `live: 'draft'` deployment republishes. */ 'W_DEPLOYED_DRAFT_CHANGED', + /** + * A `live: 'draft'` deployment whose draft holds edits the directory does not declare (made in + * the editor, say): the apply does not publish it. + */ + 'W_DEPLOY_DRAFT_NOT_SOURCE', + /** A chat change while the draft holds edits the directory does not: deploying a chat publishes it. */ + 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT', /** A pinned deployment's draft differs from its live version, which keeps running. */ 'I_DEPLOY_DRAFT_NOT_LIVE', ] as const From 28f206e37dbc9e505c32a35c510bc436d6afc9e3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:07:55 -0800 Subject: [PATCH 035/104] fix(workspace-source): server drift is a warning, and the plan never calls it unchanged A resource the directory leaves alone that changed, was deleted or moved on the server was an info finding (I_SERVER_*), shown only with --verbose, so a CI apply reported success while the workspace differed from git. The findings are warnings now (W_SERVER_CHANGED, W_SERVER_DELETED, W_SERVER_MOVED), say the apply keeps the server's version rather than reverting it, and count in the result's warnings. The CLI plan counts and lists such a resource as changed, deleted or moved on the server (`! key`) instead of unchanged. --- apps/docs/openapi-v2-workflows.json | 7445 ++++++----------- .../application/apply.integration.ts | 4 +- .../application/cross-kind.integration.ts | 14 +- .../application/deployments.integration.ts | 2 +- .../application/files.integration.ts | 8 +- .../workspace-source/application/findings.ts | 19 +- .../application/kinds/workflow/adapter.ts | 2 +- .../application/knowledge.integration.ts | 4 +- .../application/mcp.integration.ts | 4 +- .../application/promote.integration.ts | 6 +- .../application/tools-skills.integration.ts | 9 +- .../protocol/workspace-source-apply.test.ts | 44 +- .../protocol/workspace-source-apply.ts | 51 +- .../protocol/workspace-source-status.test.ts | 8 +- packages/sim-cli/src/generated/v2-api.ts | 1116 +-- packages/workspace-code/DESIGN.md | 2 +- .../workspace-code/src/diagnostics/codes.ts | 8 +- packages/workspace-code/src/status.ts | 6 +- 18 files changed, 2584 insertions(+), 6168 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 0396bb5d0d8..7ce3d729690 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6075,9 +6075,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -6237,195 +6237,6 @@ } } }, - "/api/v2/workflows/{workflowId}/source/plan": { - "post": { - "operationId": "planWorkflowSource", - "summary": "Plan workflow source", - "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "workflows.source.plan", - "x-oauth-scope": "api:read", - "tags": ["Workflows"], - "security": [ - { - "apiKey": [] - }, - { - "oauthBearer": ["api:read"] - } - ], - "parameters": [ - { - "name": "workflowId", - "in": "path", - "required": true, - "description": "Unique workflow identifier.", - "schema": { - "type": "string", - "minLength": 1, - "description": "Unique workflow identifier.", - "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] - } - }, - { - "name": "allowDelete", - "in": "query", - "required": false, - "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", - "schema": { - "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", - "type": "boolean" - } - } - ], - "requestBody": { - "required": true, - "description": "Edited source files with the lock and base they were read with.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PlanWorkflowSourceBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "files": { - "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" - }, - "lock": { - "version": 1, - "blocks": { - "start": { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "parent": null, - "ident": "start", - "order": 0 - } - }, - "variables": {} - }, - "base": { - "version": 1, - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", - "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" - } - } - } - } - } - } - }, - "responses": { - "200": { - "description": "The evaluated source.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PlanWorkflowSourceResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": true, - "applied": false, - "diff": { - "noop": true, - "blocks": { - "added": [], - "removed": [], - "renamed": [], - "modified": [] - }, - "edges": { - "added": 0, - "removed": 0 - }, - "variables": { - "added": [], - "removed": [], - "modified": [] - } - }, - "diagnostics": [], - "files": { - "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" - }, - "lock": { - "version": 1, - "blocks": { - "start": { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "parent": null, - "ident": "start", - "order": 0 - } - }, - "variables": {} - }, - "base": { - "version": 1, - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", - "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" - }, - "mintedIds": {}, - "notes": [], - "needsRedeployment": false - } - } - } - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, - "429": { - "$ref": "#/components/responses/RateLimited" - }, - "500": { - "$ref": "#/components/responses/InternalError" - }, - "503": { - "$ref": "#/components/responses/ServiceUnavailable" - } - } - } - }, "/api/v2/workspaces/{workspaceId}/workflows/source": { "post": { "operationId": "createWorkflowFromSource", @@ -6469,9 +6280,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -9047,20 +8858,20 @@ } } }, - "/api/v2/workspaces/{workspaceId}/source/plan": { + "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { "post": { - "operationId": "planWorkspaceSource", - "summary": "Plan workspace source", - "description": "Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "workspaces.source.plan", - "x-oauth-scope": "api:read", + "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`.", + "x-sim-operation": "workspaces.source.blobs.missing", + "x-oauth-scope": "api:write", "tags": ["Workflows"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:read"] + "oauthBearer": ["api:write"] } ], "parameters": [ @@ -9079,42 +8890,22 @@ ], "requestBody": { "required": true, - "description": "The directory files, its managed kinds and the base they were read with.", + "description": "The binary files an apply will need.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PlanWorkspaceSourceBody" + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" }, "examples": { "example1": { "summary": "Request example 1", "value": { - "files": { - "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" - }, - "kinds": ["table"], - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } - } - } - } + "blobs": [ + { + "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", + "size": 18432 } - } + ] } } } @@ -9123,7 +8914,7 @@ }, "responses": { "200": { - "description": "The planned changes.", + "description": "The binary files still to stage.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -9138,158 +8929,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PlanWorkspaceSourceResponse" - }, - "examples": { - "example1": { - "summary": "Response example 1", - "value": { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": true, - "plan": [ - { - "kind": "table", - "key": "leads", - "action": "noop", - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" - } - ], - "applied": [], - "needBlobs": [], - "files": {}, - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } - } - } - } - } - }, - "diagnostics": [] - } - } - } - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, - "429": { - "$ref": "#/components/responses/RateLimited" - }, - "500": { - "$ref": "#/components/responses/InternalError" - }, - "503": { - "$ref": "#/components/responses/ServiceUnavailable" - } - } - } - }, - "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { - "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`.", - "x-sim-operation": "workspaces.source.blobs.missing", - "x-oauth-scope": "api:write", - "tags": ["Workflows"], - "security": [ - { - "apiKey": [] - }, - { - "oauthBearer": ["api:write"] - } - ], - "parameters": [ - { - "name": "workspaceId", - "in": "path", - "required": true, - "description": "Workspace to read or apply.", - "schema": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace to read or apply." - } - } - ], - "requestBody": { - "required": true, - "description": "The binary files an apply will need.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" - }, - "examples": { - "example1": { - "summary": "Request example 1", - "value": { - "blobs": [ - { - "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", - "size": 18432 - } - ] - } - } - } - } - } - }, - "responses": { - "200": { - "description": "The binary files still to stage.", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" }, "examples": { "example1": { @@ -9856,8 +9496,7 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP", - "FEATURE_NOT_ENABLED" + "SCIM_MANAGED_MEMBERSHIP" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." @@ -19175,8 +18814,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19287,13 +18924,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -19625,8 +19259,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19737,13 +19369,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -20349,7 +19978,7 @@ } ] }, - "PlanWorkflowSourceResponse": { + "CreateWorkflowFromSourceResponse": { "type": "object", "properties": { "data": { @@ -21007,19 +20636,25 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Plan workflow source response", - "description": "What an apply would store, and every finding.", + "title": "Create workflow from source response", + "description": "The outcome, with the source re-printed from the saved workflow.", "examples": [ { "data": { "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": true, - "applied": false, + "dryRun": false, + "applied": true, "diff": { - "noop": true, + "noop": false, "blocks": { - "added": [], + "added": [ + { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "key": "start", + "type": "start_trigger" + } + ], "removed": [], "renamed": [], "modified": [] @@ -21057,14 +20692,16 @@ "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" }, - "mintedIds": {}, + "mintedIds": { + "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" + }, "notes": [], "needsRedeployment": false } } ] }, - "PlanWorkflowSourceBody": { + "CreateWorkflowFromSourceBody": { "type": "object", "properties": { "files": { @@ -21079,1370 +20716,947 @@ }, "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." }, - "lock": { + "name": { + "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "description": { + "description": "Workflow description. Defaults to the description in the source.", + "anyOf": [ + { + "type": "string", + "maxLength": 50000 + }, + { + "type": "null" + } + ] + }, + "folderPath": { + "$ref": "#/components/schemas/FolderPathInput" + }, + "provenance": { + "description": "Where the source came from, for the audit log.", "type": "object", "properties": { - "version": { - "type": "number", - "const": 1, - "description": "Lock format version." + "client": { + "type": "string", + "enum": ["cli", "copilot", "canvas", "api"], + "description": "What submitted the source." }, - "blocks": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { + "gitSha": { + "description": "The commit the source was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" + }, + "repo": { + "description": "The repository the source was taken from.", + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "required": ["client"], + "additionalProperties": false + } + }, + "required": ["files"], + "additionalProperties": false, + "title": "Create workflow from source body", + "description": "Source files and where to create the workflow." + }, + "GetSourceResourcesResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "tables": { + "type": "array", + "items": { "type": "object", "properties": { - "id": { + "key": { "type": "string", - "description": "Block id." + "description": "The key workflow source names this resource by; it never changes once assigned." }, - "parent": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Key of the enclosing loop or parallel, or null." + "id": { + "type": "string", + "description": "Resource id." }, - "branches": { - "description": "Condition or router branch key → stored branch id.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - } + "name": { + "type": "string", + "description": "Current display name." }, - "items": { - "description": "Per field, its id-bearing items (input format fields) in stored order.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Item name." - }, - "id": { - "type": "string", - "description": "Item id." + "columns": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Column name, as row data names it." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "currency", + "boolean", + "date", + "json", + "select" + ], + "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." + }, + "options": { + "description": "Option names a `select` column accepts, as table blocks read and write them.", + "type": "array", + "items": { + "type": "string" } }, - "required": ["name", "id"], - "additionalProperties": false, - "description": "One id-bearing list item." - } - } + "multiple": { + "description": "A `select` column whose cells hold several options.", + "type": "boolean" + }, + "required": { + "description": "Every row holds a value.", + "type": "boolean" + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Columns in table order." + } + }, + "required": ["key", "id", "name", "columns"], + "additionalProperties": false, + "description": "A table: `table(key)`." + }, + "description": "Tables, oldest first." + }, + "knowledgeBases": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." }, - "ident": { + "id": { "type": "string", - "description": "The `const` name the block is printed as." + "description": "Resource id." }, - "order": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991, - "description": "Declaration-order tie-break." + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A knowledge base: `knowledgeBase(key)`." + }, + "description": "Knowledge bases, oldest first." + }, + "credentials": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." }, - "layout": { - "type": "object", - "properties": { - "x": { - "type": "number", - "description": "Canvas x position." - }, - "y": { - "type": "number", - "description": "Canvas y position." - }, - "w": { - "description": "Container width.", - "type": "number" - }, - "h": { - "description": "Container height.", - "type": "number" - }, - "height": { - "description": "Stored block height.", - "type": "number" - }, - "horizontalHandles": { - "description": "Handles on the left and right.", - "type": "boolean" - } - }, - "required": ["x", "y"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Stored canvas geometry; applied only to new blocks." + "id": { + "type": "string", + "description": "Resource id." }, - "codeFile": { - "description": "Path of the block’s function-code file.", - "type": "string" + "name": { + "type": "string", + "description": "Current display name." + }, + "provider": { + "type": "string", + "description": "The provider the credential is for, e.g. `slack` or `google-email`." } }, - "required": ["id", "parent", "ident", "order"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." + "required": ["key", "id", "name", "provider"], + "additionalProperties": false, + "description": "A saved credential: `credential(key)`." + }, + "description": "Saved credentials, oldest first. Secrets are listed under `env`." + }, + "workflows": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Input field name." + }, + "type": { + "type": "string", + "description": "Input field type, e.g. `string` or `number`." + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Inputs the workflow start block declares." + } }, - "description": "One block’s identity." + "required": ["key", "id", "name", "inputs"], + "additionalProperties": false, + "description": "A workflow: `childWorkflow(key)`." }, - "description": "Block key → identity." + "description": "Workflows, oldest first." }, - "variables": { - "type": "object", - "propertyNames": { - "type": "string" + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace skill: `skill(key)`." }, - "additionalProperties": { - "type": "string" + "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." + }, + "customTools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace custom tool, by its title: `customTool(key)`." }, - "description": "Variable key → variable id." - } - }, - "required": ["version", "blocks", "variables"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." - }, - "base": { - "type": "object", - "properties": { - "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", - "type": "number", - "const": 1 + "description": "Workspace custom tools, oldest first." }, - "workflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow the source was read from; an apply to another workflow is refused." - }, - "workspaceId": { - "type": "string", - "description": "Workspace the workflow belongs to." + "mcpServers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "tools": { + "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "An MCP server the workspace consumes: `mcp(key)`." + }, + "description": "MCP servers, oldest first." }, - "fingerprint": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." + "env": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." }, - "catalogHash": { - "type": "string", - "description": "Hash of the block catalog the source was printed against." + "truncated": { + "type": "boolean", + "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." } }, - "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`." + "required": [ + "workspaceId", + "tables", + "knowledgeBases", + "credentials", + "workflows", + "skills", + "customTools", + "mcpServers", + "env", + "truncated" + ], + "additionalProperties": false, + "description": "Response data." } }, - "required": ["files", "lock", "base"], + "required": ["data"], "additionalProperties": false, - "title": "Plan workflow source body", - "description": "Edited source files with the lock and base they were read with.", + "title": "Get source resources response", + "description": "The workspace resources workflow source can name.", "examples": [ { - "files": { - "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" - }, - "lock": { - "version": 1, - "blocks": { - "start": { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "parent": null, - "ident": "start", - "order": 0 + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "tables": [ + { + "key": "tickets", + "id": "tbl_4f1c2a9e", + "name": "Tickets", + "columns": [ + { + "name": "subject", + "type": "string" + }, + { + "name": "status", + "type": "select", + "options": ["open", "closed"] + } + ] + } + ], + "knowledgeBases": [ + { + "key": "docs", + "id": "kb_93a1e7c2", + "name": "Docs" + } + ], + "credentials": [ + { + "key": "support-slack", + "id": "cred_51d0b8f4", + "name": "Support Slack", + "provider": "slack" + } + ], + "workflows": [ + { + "key": "assign-owner", + "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "name": "Assign owner", + "inputs": [ + { + "name": "leads", + "type": "array" + } + ] + } + ], + "skills": [ + { + "key": "triage", + "id": "skl_7e2a4c19", + "name": "Triage" + } + ], + "customTools": [ + { + "key": "lookup-order", + "id": "ctl_2b8d6f03", + "name": "lookup_order" + } + ], + "mcpServers": [ + { + "key": "github", + "id": "mcp-1a2b3c4d", + "name": "GitHub", + "tools": ["create_issue", "list_issues"] + } + ], + "env": ["CRM_KEY"], + "truncated": false + } + } + ] + }, + "WorkspaceForkPreview": { + "type": "object", + "properties": { + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." + }, + "sourceWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Canonical workspace the workflows and resources are copied from." + }, + "workflows": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." } }, - "variables": {} + "required": ["sourceWorkflowId", "name"], + "additionalProperties": false }, - "base": { - "version": 1, - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", - "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + "description": "Eligible workflows and their planned actions." + }, + "selectedResourceCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources explicitly selected for copying." + }, + "draftOnly": { + "type": "boolean", + "const": true, + "description": "True because fork creation produces undeployed drafts." + } + }, + "required": [ + "previewFingerprint", + "sourceWorkspaceId", + "workflows", + "selectedResourceCount", + "draftOnly" + ], + "additionalProperties": false, + "title": "Workspace fork preview", + "description": "Read-only fork plan and fingerprint." + }, + "PreviewWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceForkPreview" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workspace fork response", + "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "workflows": [], + "selectedResourceCount": 0, + "draftOnly": true } } ] }, - "CreateWorkflowFromSourceResponse": { + "PreviewWorkspaceForkBody": { "type": "object", "properties": { - "data": { - "type": "object", - "properties": { - "workflowId": { - "type": "string", - "description": "Workflow id." - }, - "workspaceId": { - "type": "string", - "description": "Workspace id." + "name": { + "description": "Display name of the workflow or workspace.", + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", + "type": "object", + "properties": { + "files": { + "description": "Workspace file IDs to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "dryRun": { - "type": "boolean", - "description": "True when nothing was written because `dryRun` was set." + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "applied": { - "type": "boolean", - "description": "True when the draft was written or the workflow renamed or redescribed; false on a dry run and on a no-op." + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "diff": { - "type": "object", - "properties": { - "noop": { - "type": "boolean", - "description": "True when the source matches the saved draft." - }, - "meta": { - "description": "The workflow name and description fields the source changes.", - "type": "array", - "items": { - "type": "string", - "enum": ["name", "description"] - } - }, - "blocks": { - "type": "object", - "properties": { - "added": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored block id." - }, - "key": { - "type": "string", - "description": "Block key in the source." - }, - "type": { - "type": "string", - "description": "Block type." - } - }, - "required": ["id", "key", "type"], - "additionalProperties": false, - "description": "An added or removed block by id, source key and type." - }, - "description": "New blocks." - }, - "removed": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored block id." - }, - "key": { - "type": "string", - "description": "Block key in the source." - }, - "type": { - "type": "string", - "description": "Block type." - } - }, - "required": ["id", "key", "type"], - "additionalProperties": false, - "description": "An added or removed block by id, source key and type." - }, - "description": "Deleted blocks." - }, - "renamed": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored block id; unchanged by the rename." - }, - "from": { - "type": "string", - "description": "Previous key." - }, - "to": { - "type": "string", - "description": "New key." - } - }, - "required": ["id", "from", "to"], - "additionalProperties": false, - "description": "A renamed block." - }, - "description": "Renamed blocks; each keeps its id." - }, - "modified": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored block id." - }, - "key": { - "type": "string", - "description": "Block key in the source." - }, - "fields": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Changed fields, modes (`modes.`) and attributes." - }, - "reparented": { - "description": "Moved into or out of a container.", - "type": "boolean" - } - }, - "required": ["id", "key", "fields"], - "additionalProperties": false, - "description": "A changed block." - }, - "description": "Changed blocks." - } - }, - "required": ["added", "removed", "renamed", "modified"], - "additionalProperties": false, - "description": "Block changes." - }, - "edges": { - "type": "object", - "properties": { - "added": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991, - "description": "Connections added." - }, - "removed": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991, - "description": "Connections removed." - } - }, - "required": ["added", "removed"], - "additionalProperties": false, - "description": "Connection changes." - }, - "variables": { - "type": "object", - "properties": { - "added": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Variable keys added." - }, - "removed": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Variable keys removed." - }, - "modified": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Variable keys changed." - } - }, - "required": ["added", "removed", "modified"], - "additionalProperties": false, - "description": "Variable changes." - } - }, - "required": ["noop", "blocks", "edges", "variables"], - "additionalProperties": false, - "description": "What the apply changed, or would change on a dry run." + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "diagnostics": { + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "E_SYNTAX", - "E_SDK_HEADER", - "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", - "E_UNSUPPORTED_SYNTAX", - "E_WORKFLOW_EXPORT", - "E_LIMIT_EXCEEDED", - "E_INVALID_CHARACTER", - "E_NUMBER_NOT_FINITE", - "W_NUMBER_PRECISION", - "E_TOO_MANY_ERRORS", - "W_TOO_MANY_WARNINGS", - "E_DUPLICATE_NAME", - "E_RESERVED_NAME", - "E_KEY_OVERRIDE", - "E_EMPTY_NAME", - "E_LOOKALIKE_NAME", - "W_LOOKALIKE_NAME", - "W_SUSPICIOUS_CHARACTER", - "E_NAME_NOT_LITERAL", - "E_UNKNOWN_IDENTIFIER", - "E_OUT_OF_SCOPE", - "E_UNKNOWN_VARIABLE", - "E_DUPLICATE_VARIABLE", - "E_VARIABLE_NAME_MISMATCH", - "E_INVALID_ENV_NAME", - "W_ENV_UNKNOWN", - "W_CHILD_INPUT_UNKNOWN", - "W_CHILD_NO_START", - "E_UNKNOWN_SUBFLOW_PROPERTY", - "W_FORWARD_REF", - "W_REF_NOT_NORMALIZED", - "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", - "E_EDGE_SCOPE", - "E_EDGE_NOTE", - "E_TARGET_TRIGGER", - "E_NO_DEFAULT_OUTPUT", - "E_DUPLICATE_EDGE", - "E_ERROR_PORT_UNSUPPORTED", - "W_ERROR_PORT_STORED", - "E_UNKNOWN_BRANCH", - "E_DUPLICATE_BRANCH_KEY", - "E_BRANCH_KEY_COLLIDES", - "E_BRANCH_ELSE_LAST", - "W_RAW_HANDLE", - "W_SUBFLOW_HANDLE_SCOPE", - "E_EDGE_CYCLE", - "W_EDGE_CYCLE", - "W_BRANCH_UNWIRED", - "E_UNKNOWN_BUILDER", - "E_UNKNOWN_PARAM", - "E_FIXED_PARAM", - "W_FIELD_NOT_APPLICABLE", - "W_REQUIRED_MISSING", - "W_UNKNOWN_OPTION", - "E_UNKNOWN_OPERATION", - "W_UNKNOWN_MODEL", - "W_LEGACY_BLOCK_TYPE", - "I_SCHEDULE_UTC", - "E_STORED_VALUE_MISSING", - "W_VALUE_KIND", - "W_OUT_OF_RANGE", - "W_TABLE_FILTER_SHAPE", - "W_LITERAL_SECRET", - "W_SUBFLOW_COUNT", - "W_UNKNOWN_OUTPUT_PATH", - "W_JSON_REF_UNTYPED", - "E_CODE_FILE_MISSING", - "E_CODE_FILE_PATH", - "W_CODE_FILE_INLINED", - "W_UNRESOLVED_REF", - "W_FORWARD_REF_LITERALIZED", - "W_COMMENT_MOVED", - "W_COMMENT_DROPPED", - "E_LOCK_JSON", - "E_LOCK_VERSION", - "E_LOCK_SHAPE", - "E_LOCK_UNKNOWN_FIELD", - "E_LOCK_KEY", - "E_LOCK_IDENT", - "E_LOCK_DUPLICATE_IDENT", - "E_LOCK_DUPLICATE_ID", - "E_LOCK_PARENT", - "E_LOCK_BRANCH", - "E_LOCK_CODE_FILE_PATH", - "E_SOURCE_META_JSON", - "E_SOURCE_META_VERSION", - "E_SOURCE_META_SHAPE", - "E_SOURCE_META_UNKNOWN_FIELD", - "E_SOURCE_META_IDENT", - "E_SOURCE_META_DUPLICATE_IDENT", - "E_SOURCE_META_ANCHOR", - "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", - "W_CANON_RESERVED_NAME", - "W_CANON_DANGLING_EDGE", - "W_CANON_DANGLING_PARENT", - "W_CANON_RAW_HANDLE", - "W_CANON_UNKNOWN_BLOCK_TYPE", - "W_CANON_UNRESOLVED_ID", - "W_CANON_TITLE_OVERRIDE", - "W_CANON_SUBFLOW_REPAIRED", - "W_CANON_SUBBLOCK_TYPE_DRIFT", - "W_CANON_UNDECODABLE_JSON", - "E_MAT_DUPLICATE_LOCK_ID", - "E_MAT_UNKNOWN_RESOURCE", - "E_MAT_UNKNOWN_VARIABLE", - "W_MAT_DELETED_SINCE_PULL", - "W_MAT_INFERRED_RENAME", - "W_MAT_RETYPE_RECREATED", - "W_MAT_LOCK_ID_CLAIMED", - "I_MAT_NEEDS_LAYOUT", - "E_APPLY_STALE", - "E_APPLY_WORKFLOW_MISMATCH", - "E_APPLY_LOCKED_BLOCK", - "E_APPLY_TYPE_NOT_ADDABLE", - "E_APPLY_INVALID_STATE", - "E_APPLY_BLOCK_NOT_FOUND", - "E_APPLY_INVALID_BLOCK_TYPE", - "E_APPLY_BLOCK_NOT_ALLOWED", - "E_APPLY_MODEL_NOT_ALLOWED", - "E_APPLY_TOOL_NOT_ALLOWED", - "E_APPLY_INVALID_EDGE_SOURCE", - "E_APPLY_INVALID_EDGE_SCOPE", - "E_APPLY_INVALID_SOURCE_HANDLE", - "E_APPLY_INVALID_TARGET_HANDLE", - "E_APPLY_INVALID_SUBBLOCK_FIELD", - "E_APPLY_MISSING_REQUIRED_PARAMS", - "E_APPLY_RETRY_NOT_SUPPORTED", - "E_APPLY_DUPLICATE_TRIGGER", - "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", - "E_APPLY_DISABLED_ANCESTOR", - "E_APPLY_CREDENTIAL_UNREACHABLE", - "W_APPLY_CREDENTIAL_KEPT", - "E_APPLY_SANDBOX_PLAN_REQUIRED", - "W_APPLY_HOSTED_KEY_DROPPED", - "W_APPLY_VALUE_NORMALIZED", - "W_APPLY_TYPE_CHANGED", - "W_APPLY_TRIGGER_REMOVED", - "W_APPLY_CATALOG_MOVED", - "W_APPLY_PROBABLE_RENAME", - "E_APPLY_LINT", - "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", - "W_APPLY_LINT", - "W_TABLE_UNKNOWN_COLUMN", - "E_APPLY_INVALID_SCHEDULE", - "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", - "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" - ], - "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." - }, - "severity": { - "type": "string", - "enum": ["error", "warning", "info"], - "description": "Diagnostic severity." - }, - "message": { - "type": "string", - "description": "What was found." - }, - "hint": { - "description": "How to address it.", - "type": "string" - }, - "blockKey": { - "description": "Block the finding is about.", - "type": "string" - }, - "param": { - "description": "Field the finding is about.", - "type": "string" - }, - "file": { - "description": "Submitted file the finding is in.", - "type": "string" - }, - "line": { - "description": "1-based line in `file`.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "column": { - "description": "1-based column in `file`.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "endLine": { - "description": "1-based line the finding ends on.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "endColumn": { - "description": "1-based column the finding ends at.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "frame": { - "description": "The source lines around the finding, with a caret row.", - "type": "string" - }, - "blockId": { - "description": "Stored id of the block the finding is about.", - "type": "string" - }, - "path": { - "description": "JSON Pointer into the lock, for a lock finding.", - "type": "string" - } - }, - "required": ["code", "severity", "message"], - "additionalProperties": false, - "description": "A finding from applying workflow source, pinned to the submitted files." - }, - "description": "Warnings, and on a dry run every error a commit would refuse." + "type": "string", + "minLength": 1 + } }, - "files": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - }, - "description": "The source re-printed from what was saved, including any normalized values." + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - "lock": { - "type": "object", - "properties": { - "version": { - "type": "number", - "const": 1, - "description": "Lock format version." - }, - "blocks": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Block id." - }, - "parent": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Key of the enclosing loop or parallel, or null." - }, - "branches": { - "description": "Condition or router branch key → stored branch id.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - } - }, - "items": { - "description": "Per field, its id-bearing items (input format fields) in stored order.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Item name." - }, - "id": { - "type": "string", - "description": "Item id." - } - }, - "required": ["name", "id"], - "additionalProperties": false, - "description": "One id-bearing list item." - } - } - }, - "ident": { - "type": "string", - "description": "The `const` name the block is printed as." - }, - "order": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991, - "description": "Declaration-order tie-break." - }, - "layout": { - "type": "object", - "properties": { - "x": { - "type": "number", - "description": "Canvas x position." - }, - "y": { - "type": "number", - "description": "Canvas y position." - }, - "w": { - "description": "Container width.", - "type": "number" - }, - "h": { - "description": "Container height.", - "type": "number" - }, - "height": { - "description": "Stored block height.", - "type": "number" - }, - "horizontalHandles": { - "description": "Handles on the left and right.", - "type": "boolean" - } - }, - "required": ["x", "y"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Stored canvas geometry; applied only to new blocks." - }, - "codeFile": { - "description": "Path of the block’s function-code file.", - "type": "string" - } - }, - "required": ["id", "parent", "ident", "order"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "One block’s identity." - }, - "description": "Block key → identity." - }, - "variables": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - }, - "description": "Variable key → variable id." - } - }, - "required": ["version", "blocks", "variables"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." - }, - "base": { - "type": "object", - "properties": { - "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", - "type": "number", - "const": 1 - }, - "workflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow the source was read from; an apply to another workflow is refused." - }, - "workspaceId": { - "type": "string", - "description": "Workspace the workflow belongs to." - }, - "fingerprint": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." - }, - "catalogHash": { - "type": "string", - "description": "Hash of the block catalog the source was printed against." - } - }, - "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], - "additionalProperties": { - "description": "An `x-` extension field, kept verbatim." - }, - "description": "Where the saved (or, on a dry run, would-be) draft was read: the next apply’s `base`." - }, - "mintedIds": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - }, - "description": "Block key → id for new blocks whose id was minted rather than taken from the lock." - }, - "notes": { + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", + "maxItems": 2000, "type": "array", "items": { - "type": "string" - }, - "description": "Non-fatal notes about the write." - }, - "needsRedeployment": { - "type": "boolean", - "description": "Whether the draft now differs from the live deployment; apply never deploys." + "type": "string", + "minLength": 1 + } } }, - "required": [ - "workflowId", - "workspaceId", - "dryRun", - "applied", - "diff", - "diagnostics", - "files", - "lock", - "base", - "mintedIds", - "notes", - "needsRedeployment" - ], - "additionalProperties": false, - "description": "Response data." + "additionalProperties": false } }, - "required": ["data"], "additionalProperties": false, - "title": "Create workflow from source response", - "description": "The outcome, with the source re-printed from the saved workflow.", - "examples": [ - { - "data": { - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, - "applied": true, - "diff": { - "noop": false, - "blocks": { - "added": [ - { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "key": "start", - "type": "start_trigger" - } - ], - "removed": [], - "renamed": [], - "modified": [] - }, - "edges": { - "added": 0, - "removed": 0 - }, - "variables": { - "added": [], - "removed": [], - "modified": [] - } - }, - "diagnostics": [], - "files": { - "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" - }, - "lock": { - "version": 1, - "blocks": { - "start": { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "parent": null, - "ident": "start", - "order": 0 - } - }, - "variables": {} - }, - "base": { - "version": 1, - "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", - "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" - }, - "mintedIds": { - "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" - }, - "notes": [], - "needsRedeployment": false - } - } - ] + "title": "Preview workspace fork request", + "description": "Optional child name and explicitly selected resource copies." }, - "CreateWorkflowFromSourceBody": { + "WorkspaceOperationReport": { "type": "object", "properties": { - "files": { - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 1024 - }, - "additionalProperties": { - "type": "string" - }, - "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Durable operation identifier to use for polling." }, - "name": { - "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", + "requestId": { "type": "string", "minLength": 1, - "maxLength": 255 + "maxLength": 128, + "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." }, - "description": { - "description": "Workflow description. Defaults to the description in the source.", - "anyOf": [ - { - "type": "string", - "maxLength": 50000 + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "kind": { + "type": "string", + "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], + "description": "Type of committed workspace operation." + }, + "applied": { + "type": "boolean", + "const": true, + "description": "The business transaction committed, including when follow-up work fails." + }, + "status": { + "type": "string", + "enum": [ + "processing", + "completed", + "completed_with_warnings", + "requires_configuration", + "failed" + ], + "description": "Operation status; failed follow-up work does not undo the committed transaction." + }, + "resourceIds": { + "maxItems": 5000, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "description": "Identifiers of resources created or changed by the committed operation." + }, + "issues": { + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable machine-readable issue code." + }, + "message": { + "type": "string", + "maxLength": 2048, + "description": "Human-readable explanation of the issue." + }, + "workflowId": { + "description": "Workflow affected by this issue or deployment attempt.", + "type": "string", + "maxLength": 256 + }, + "blockId": { + "description": "Source block identifier before graph ID regeneration.", + "type": "string", + "maxLength": 256 + }, + "subBlockKey": { + "description": "Registered source field key, including the tool index for nested Agent fields.", + "type": "string", + "maxLength": 256 + } }, - { - "type": "null" - } - ] + "required": ["code", "message"], + "additionalProperties": false + }, + "description": "Structured warnings, missing configuration, and follow-up failures." }, - "folderPath": { - "$ref": "#/components/schemas/FolderPathInput" + "idMap": { + "description": "Source graph identifiers mapped to the imported identifiers.", + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 256 + } }, - "provenance": { - "description": "Where the source came from, for the audit log.", + "deploymentOperationIds": { + "description": "Exact deployment attempts admitted by the workspace operation.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + } + }, + "deployments": { + "description": "Readiness of the exact admitted deployment attempts.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "operationId": { + "type": "string", + "maxLength": 256, + "description": "Durable operation identifier to use for polling." + }, + "workflowId": { + "type": "string", + "maxLength": 256, + "description": "Workflow affected by this issue or deployment attempt." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "Deployment version number for this admitted attempt." + }, + "status": { + "type": "string", + "enum": ["preparing", "activating", "active", "failed", "superseded"], + "description": "Status of this exact admitted deployment attempt." + }, + "ready": { + "type": "boolean", + "description": "Whether this exact deployment attempt is active and all required components are ready." + }, + "pendingComponents": { + "maxItems": 32, + "type": "array", + "items": { + "type": "string", + "maxLength": 128 + }, + "description": "Deployment components that have not finished becoming ready." + } + }, + "required": [ + "operationId", + "workflowId", + "version", + "status", + "ready", + "pendingComponents" + ], + "additionalProperties": false + } + }, + "triggerUrlChanges": { + "description": "Public trigger paths changed by this sync, with the affected workflow names.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Name of the workflow whose public trigger path stops serving." + }, + "path": { + "type": "string", + "maxLength": 4096, + "description": "Public trigger path that stops serving after this sync." + } + }, + "required": ["workflowName", "path"], + "additionalProperties": false + } + }, + "backgroundWorkId": { + "description": "Workspace activity identifier for resource-copy progress.", + "type": "string", + "maxLength": 256 + }, + "copyProgress": { + "description": "Completion status and counts for explicitly selected resource copies.", "type": "object", "properties": { - "client": { + "status": { "type": "string", - "enum": ["cli", "copilot", "canvas", "api"], - "description": "What submitted the source." + "enum": ["pending", "completed", "failed"], + "description": "Background resource-copy status." }, - "gitSha": { - "description": "The commit the source was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" + "copied": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources copied successfully." }, - "repo": { - "description": "The repository the source was taken from.", - "type": "string", - "minLength": 1, - "maxLength": 512 + "failed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources that failed to copy." } }, - "required": ["client"], + "required": ["status", "copied", "failed"], "additionalProperties": false } }, - "required": ["files"], + "required": [ + "operationId", + "requestId", + "workspaceId", + "kind", + "applied", + "status", + "resourceIds", + "issues" + ], "additionalProperties": false, - "title": "Create workflow from source body", - "description": "Source files and where to create the workflow." + "title": "Workspace operation receipt", + "description": "Committed operation receipt, resource copies, and exact deployment readiness." }, - "GetSourceResourcesResponse": { + "ForkWorkspaceResponse": { "type": "object", "properties": { "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Fork workspace response", + "description": "Committed fork receipt and resource-copy progress.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "fork-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_fork", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } + } + ] + }, + "ForkWorkspaceBody": { + "type": "object", + "properties": { + "name": { + "description": "Display name of the workflow or workspace.", + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", + "type": "object", + "properties": { + "files": { + "description": "Workspace file IDs to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "columns": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Column name, as row data names it." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "currency", - "boolean", - "date", - "json", - "select" - ], - "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." - }, - "options": { - "description": "Option names a `select` column accepts, as table blocks read and write them.", - "type": "array", - "items": { - "type": "string" - } - }, - "multiple": { - "description": "A `select` column whose cells hold several options.", - "type": "boolean" - }, - "required": { - "description": "Every row holds a value.", - "type": "boolean" - } - }, - "required": ["name", "type"], - "additionalProperties": false - }, - "description": "Columns in table order." - } - }, - "required": ["key", "id", "name", "columns"], - "additionalProperties": false, - "description": "A table: `table(key)`." - }, - "description": "Tables, oldest first." + "type": "string", + "minLength": 1 + } }, "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A knowledge base: `knowledgeBase(key)`." - }, - "description": "Knowledge bases, oldest first." + "type": "string", + "minLength": 1 + } }, - "credentials": { + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "provider": { - "type": "string", - "description": "The provider the credential is for, e.g. `slack` or `google-email`." - } - }, - "required": ["key", "id", "name", "provider"], - "additionalProperties": false, - "description": "A saved credential: `credential(key)`." - }, - "description": "Saved credentials, oldest first. Secrets are listed under `env`." + "type": "string", + "minLength": 1 + } }, - "workflows": { + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "inputs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Input field name." - }, - "type": { - "type": "string", - "description": "Input field type, e.g. `string` or `number`." - } - }, - "required": ["name", "type"], - "additionalProperties": false - }, - "description": "Inputs the workflow start block declares." - } - }, - "required": ["key", "id", "name", "inputs"], - "additionalProperties": false, - "description": "A workflow: `childWorkflow(key)`." - }, - "description": "Workflows, oldest first." + "type": "string", + "minLength": 1 + } }, - "skills": { + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace skill: `skill(key)`." - }, - "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." + "type": "string", + "minLength": 1 + } }, - "customTools": { + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", + "maxItems": 2000, "type": "array", "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace custom tool, by its title: `customTool(key)`." - }, - "description": "Workspace custom tools, oldest first." - }, - "mcpServers": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "tools": { - "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "An MCP server the workspace consumes: `mcp(key)`." - }, - "description": "MCP servers, oldest first." - }, - "env": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." - }, - "truncated": { - "type": "boolean", - "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." + "type": "string", + "minLength": 1 + } } }, - "required": [ - "workspaceId", - "tables", - "knowledgeBases", - "credentials", - "workflows", - "skills", - "customTools", - "mcpServers", - "env", - "truncated" - ], - "additionalProperties": false, - "description": "Response data." + "additionalProperties": false + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." } }, - "required": ["data"], + "required": ["requestId", "previewFingerprint"], "additionalProperties": false, - "title": "Get source resources response", - "description": "The workspace resources workflow source can name.", + "title": "Fork workspace request", + "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", "examples": [ { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "tables": [ - { - "key": "tickets", - "id": "tbl_4f1c2a9e", - "name": "Tickets", - "columns": [ - { - "name": "subject", - "type": "string" - }, - { - "name": "status", - "type": "select", - "options": ["open", "closed"] - } - ] - } - ], - "knowledgeBases": [ - { - "key": "docs", - "id": "kb_93a1e7c2", - "name": "Docs" - } - ], - "credentials": [ - { - "key": "support-slack", - "id": "cred_51d0b8f4", - "name": "Support Slack", - "provider": "slack" - } - ], - "workflows": [ - { - "key": "assign-owner", - "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "name": "Assign owner", - "inputs": [ - { - "name": "leads", - "type": "array" - } - ] - } - ], - "skills": [ - { - "key": "triage", - "id": "skl_7e2a4c19", - "name": "Triage" - } - ], - "customTools": [ - { - "key": "lookup-order", - "id": "ctl_2b8d6f03", - "name": "lookup_order" - } - ], - "mcpServers": [ - { - "key": "github", - "id": "mcp-1a2b3c4d", - "name": "GitHub", - "tools": ["create_issue", "list_issues"] - } - ], - "env": ["CRM_KEY"], - "truncated": false - } + "name": "Support sandbox", + "requestId": "fork-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" } ] }, - "WorkspaceForkPreview": { + "WorkspaceSyncPreview": { "type": "object", "properties": { "previewFingerprint": { @@ -22456,325 +21670,376 @@ "maxLength": 128, "description": "Canonical workspace the workflows and resources are copied from." }, + "targetWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Canonical workspace receiving the changes." + }, + "ready": { + "type": "boolean", + "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." + }, "workflows": { - "maxItems": 1000, + "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { + "action": { + "type": "string", + "enum": ["create", "replace", "archive"], + "description": "Planned workflow creation, replacement, or archival." + }, "sourceWorkflowId": { + "description": "Workflow identifier in the source workspace.", "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." + "minLength": 1 + }, + "targetWorkflowId": { + "description": "Existing target workflow identifier; absent when apply will create a new target.", + "type": "string", + "minLength": 1 }, "name": { "type": "string", "maxLength": 1024, "description": "Display name of the workflow or workspace." + }, + "comparison": { + "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "available", + "description": "Both exact source snapshots are available." + }, + "base": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Source deployment last successfully synced to this destination." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "base", "target"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "unavailable", + "description": "The source baseline cannot be compared." + }, + "reason": { + "type": "string", + "enum": ["new_workflow", "no_baseline", "missing_baseline"], + "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "reason", "target"], + "additionalProperties": false + } + ] } }, - "required": ["sourceWorkflowId", "name"], - "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." - }, - "selectedResourceCount": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources explicitly selected for copying." - }, - "draftOnly": { - "type": "boolean", - "const": true, - "description": "True because fork creation produces undeployed drafts." - } - }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "workflows", - "selectedResourceCount", - "draftOnly" - ], - "additionalProperties": false, - "title": "Workspace fork preview", - "description": "Read-only fork plan and fingerprint." - }, - "PreviewWorkspaceForkResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceForkPreview" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Preview workspace fork response", - "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", - "examples": [ - { - "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "workflows": [], - "selectedResourceCount": 0, - "draftOnly": true - } - } - ] - }, - "PreviewWorkspaceForkBody": { - "type": "object", - "properties": { - "name": { - "description": "Display name of the workflow or workspace.", - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", - "type": "object", - "properties": { - "files": { - "description": "Workspace file IDs to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false, - "title": "Preview workspace fork request", - "description": "Optional child name and explicitly selected resource copies." - }, - "WorkspaceOperationReport": { - "type": "object", - "properties": { - "operationId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Durable operation identifier to use for polling." - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." - }, - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." - }, - "kind": { - "type": "string", - "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], - "description": "Type of committed workspace operation." - }, - "applied": { - "type": "boolean", - "const": true, - "description": "The business transaction committed, including when follow-up work fails." - }, - "status": { - "type": "string", - "enum": [ - "processing", - "completed", - "completed_with_warnings", - "requires_configuration", - "failed" - ], - "description": "Operation status; failed follow-up work does not undo the committed transaction." - }, - "resourceIds": { - "maxItems": 5000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 256 + "required": ["action", "name"], + "additionalProperties": false }, - "description": "Identifiers of resources created or changed by the committed operation." + "description": "Eligible workflows and their planned actions." }, - "issues": { - "maxItems": 2000, + "unresolvedBindings": { + "maxItems": 10000, "type": "array", "items": { "type": "object", "properties": { - "code": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable machine-readable issue code." - }, - "message": { + "kind": { "type": "string", - "maxLength": 2048, - "description": "Human-readable explanation of the issue." + "maxLength": 256, + "description": "Resource or operation kind." }, - "workflowId": { - "description": "Workflow affected by this issue or deployment attempt.", + "sourceId": { "type": "string", - "maxLength": 256 + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." }, - "blockId": { - "description": "Source block identifier before graph ID regeneration.", + "blockName": { + "description": "Display name of the affected source block.", "type": "string", - "maxLength": 256 + "maxLength": 1024 }, - "subBlockKey": { - "description": "Registered source field key, including the tool index for nested Agent fields.", + "reason": { + "description": "Structured explanation of the unresolved binding.", "type": "string", "maxLength": 256 } }, - "required": ["code", "message"], + "required": ["kind", "sourceId"], "additionalProperties": false }, - "description": "Structured warnings, missing configuration, and follow-up failures." + "description": "Source references that still require destination mappings or explicit copy choices." }, - "idMap": { - "description": "Source graph identifiers mapped to the imported identifiers.", - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 + "configuration": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "currentValue": { + "type": "string", + "maxLength": 65536, + "description": "Persisted sync override or proposed override; empty when neither is configured." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s options.", + "type": "string", + "maxLength": 256 + }, + "discoveryWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 4096 + }, + "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." + }, + "parentKind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource kind that owns this dependent configuration." + }, + "parentSourceId": { + "type": "string", + "maxLength": 4096, + "description": "Source identifier of the parent resource being mapped." + }, + "parentContextKey": { + "description": "Selector context key supplied by the mapped parent resource.", + "type": "string", + "maxLength": 256 + } + }, + "required": [ + "sourceWorkflowId", + "sourceBlockId", + "subBlockKey", + "title", + "required", + "currentValue", + "discoveryWorkspaceId", + "context", + "parentKind", + "parentSourceId" + ], + "additionalProperties": false }, - "additionalProperties": { - "type": "string", - "maxLength": 256 - } + "description": "Dependent fields that may need destination-specific values." }, - "deploymentOperationIds": { - "description": "Exact deployment attempts admitted by the workspace operation.", + "excludedTargets": { "maxItems": 1000, "type": "array", "items": { - "type": "string", - "maxLength": 256 - } + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + } + }, + "required": ["id", "name"], + "additionalProperties": false + }, + "description": "Target workflows explicitly excluded from sync." }, - "deployments": { - "description": "Readiness of the exact admitted deployment attempts.", - "maxItems": 1000, + "triggerSlots": { + "maxItems": 10000, "type": "array", "items": { "type": "object", "properties": { - "operationId": { + "sourceWorkflowId": { "type": "string", - "maxLength": 256, - "description": "Durable operation identifier to use for polling." + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - "workflowId": { + "sourceBlockId": { "type": "string", + "minLength": 1, "maxLength": 256, - "description": "Workflow affected by this issue or deployment attempt." + "description": "Stable source trigger block identifier to use in trigger mappings." }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 9007199254740991, - "description": "Deployment version number for this admitted attempt." + "blockName": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the source trigger block." }, - "status": { + "workflowName": { "type": "string", - "enum": ["preparing", "activating", "active", "failed", "superseded"], - "description": "Status of this exact admitted deployment attempt." + "maxLength": 1024, + "description": "Display name of the source workflow." }, - "ready": { - "type": "boolean", - "description": "Whether this exact deployment attempt is active and all required components are ready." + "ownPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Existing target trigger path, preserved automatically and not configurable." }, - "pendingComponents": { - "maxItems": 32, + "adoptablePaths": { + "maxItems": 1000, "type": "array", "items": { "type": "string", - "maxLength": 128 + "minLength": 1, + "maxLength": 4096 }, - "description": "Deployment components that have not finished becoming ready." + "description": "Retiring paths in the same target workflow with a compatible trigger provider." + }, + "defaultAdoptPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Default adoption when ownPath is null; null then allocates a new path." } }, "required": [ - "operationId", - "workflowId", - "version", - "status", - "ready", - "pendingComponents" + "sourceWorkflowId", + "sourceBlockId", + "blockName", + "workflowName", + "ownPath", + "adoptablePaths", + "defaultAdoptPath" ], "additionalProperties": false - } + }, + "description": "Source triggers and the target paths available for explicit adoption choices." }, "triggerUrlChanges": { - "description": "Public trigger paths changed by this sync, with the affected workflow names.", "maxItems": 1000, "type": "array", "items": { @@ -22783,7 +22048,7 @@ "workflowName": { "type": "string", "maxLength": 1024, - "description": "Name of the workflow whose public trigger path stops serving." + "description": "Name of the affected workflow." }, "path": { "type": "string", @@ -22793,95 +22058,153 @@ }, "required": ["workflowName", "path"], "additionalProperties": false - } - }, - "backgroundWorkId": { - "description": "Workspace activity identifier for resource-copy progress.", - "type": "string", - "maxLength": 256 - }, - "copyProgress": { - "description": "Completion status and counts for explicitly selected resource copies.", - "type": "object", - "properties": { - "status": { - "type": "string", - "enum": ["pending", "completed", "failed"], - "description": "Background resource-copy status." - }, - "copied": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources copied successfully." - }, - "failed": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources that failed to copy." - } }, - "required": ["status", "copied", "failed"], - "additionalProperties": false + "description": "Retiring target trigger URLs no arriving trigger adopts." } }, "required": [ - "operationId", - "requestId", - "workspaceId", - "kind", - "applied", - "status", - "resourceIds", - "issues" + "previewFingerprint", + "sourceWorkspaceId", + "targetWorkspaceId", + "ready", + "workflows", + "unresolvedBindings", + "configuration", + "excludedTargets", + "triggerSlots", + "triggerUrlChanges" ], "additionalProperties": false, - "title": "Workspace operation receipt", - "description": "Committed operation receipt, resource copies, and exact deployment readiness." + "title": "Workspace sync preview", + "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." }, - "ForkWorkspaceResponse": { + "PreviewWorkspacePushResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + "$ref": "#/components/schemas/WorkspaceSyncPreview" } }, "required": ["data"], "additionalProperties": false, - "title": "Fork workspace response", - "description": "Committed fork receipt and resource-copy progress.", + "title": "Preview workspace push response", + "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", "examples": [ { "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "fork-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_fork", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "ready": true, + "workflows": [], + "unresolvedBindings": [], + "configuration": [], + "excludedTargets": [], + "triggerSlots": [], + "triggerUrlChanges": [] } } ] }, - "ForkWorkspaceBody": { + "PreviewWorkspacePushBody": { "type": "object", "properties": { - "name": { - "description": "Display name of the workflow or workspace.", + "otherWorkspaceId": { "type": "string", "minLength": 1, - "maxLength": 100 + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false + } + }, + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } + }, + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", "type": "object", "properties": { - "files": { - "description": "Workspace file IDs to copy.", + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", "maxItems": 2000, "type": "array", "items": { @@ -22898,15 +22221,6 @@ "minLength": 1 } }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, "customTools": { "description": "Source custom tool identifiers to copy.", "maxItems": 2000, @@ -22925,8 +22239,8 @@ "minLength": 1 } }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "files": { + "description": "Workspace file storage keys to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22934,8 +22248,8 @@ "minLength": 1 } }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", "maxItems": 2000, "type": "array", "items": { @@ -22946,211 +22260,172 @@ }, "additionalProperties": false }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - } - }, - "required": ["requestId", "previewFingerprint"], - "additionalProperties": false, - "title": "Fork workspace request", - "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", - "examples": [ - { - "name": "Support sandbox", - "requestId": "fork-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" - } - ] - }, - "WorkspaceSyncPreview": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." - }, - "sourceWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace the workflows and resources are copied from." - }, - "targetWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace receiving the changes." - }, - "ready": { - "type": "boolean", - "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." - }, - "workflows": { + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "action": { + "kind": { "type": "string", - "enum": ["create", "replace", "archive"], - "description": "Planned workflow creation, replacement, or archival." + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false + } + }, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { "sourceWorkflowId": { - "description": "Workflow identifier in the source workspace.", "type": "string", - "minLength": 1 + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - "targetWorkflowId": { - "description": "Existing target workflow identifier; absent when apply will create a new target.", + "sourceBlockId": { "type": "string", - "minLength": 1 + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "comparison": { - "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", - "oneOf": [ + "adoptPath": { + "anyOf": [ { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "available", - "description": "Both exact source snapshots are available." - }, - "base": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Source deployment last successfully synced to this destination." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "base", "target"], - "additionalProperties": false + "type": "string", + "minLength": 1, + "maxLength": 4096 }, { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "unavailable", - "description": "The source baseline cannot be compared." - }, - "reason": { - "type": "string", - "enum": ["new_workflow", "no_baseline", "missing_baseline"], - "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "reason", "target"], - "additionalProperties": false + "type": "null" } - ] + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." } }, - "required": ["action", "name"], + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." + } + } + }, + "required": ["otherWorkspaceId"], + "additionalProperties": false, + "title": "Preview workspace push request", + "description": "Other workspace and proposed source-to-target sync choices." + }, + "PushWorkspaceResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Push workspace response", + "description": "Committed push receipt with copy and deployment readiness.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "push-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_push", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } + } + ] + }, + "PushWorkspaceBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." }, - "unresolvedBindings": { - "maxItems": 10000, + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "resourceType": { "type": "string", - "maxLength": 256, - "description": "Resource or operation kind." + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." }, "sourceId": { "type": "string", + "minLength": 1, "maxLength": 4096, "description": "Source resource identifier in the canonical source workspace." }, - "blockName": { - "description": "Display name of the affected source block.", - "type": "string", - "maxLength": 1024 - }, - "reason": { - "description": "Structured explanation of the unresolved binding.", - "type": "string", - "maxLength": 256 + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." } }, - "required": ["kind", "sourceId"], + "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false - }, - "description": "Source references that still require destination mappings or explicit copy choices." + } }, - "configuration": { - "maxItems": 10000, + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, "type": "array", "items": { "type": "object", @@ -23162,56 +22437,95 @@ }, "sourceBlockId": { "type": "string", + "minLength": 1, "maxLength": 256, "description": "Block identifier in the source workflow." }, "subBlockKey": { "type": "string", + "minLength": 1, "maxLength": 1024, "description": "Registered source field key, including the tool index for nested Agent fields." }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "currentValue": { + "value": { "type": "string", "maxLength": 65536, - "description": "Persisted sync override or proposed override; empty when neither is configured." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s options.", + "description": "Destination value for the registered dependent field." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } + }, + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "maxLength": 256 - }, - "discoveryWorkspaceId": { + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." - }, - "context": { - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 4096 - }, - "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." - }, - "parentKind": { + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false + }, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": [ "credential", @@ -23227,59 +22541,22 @@ "skill", "sandbox" ], - "description": "Resource kind that owns this dependent configuration." - }, - "parentSourceId": { - "type": "string", - "maxLength": 4096, - "description": "Source identifier of the parent resource being mapped." + "description": "Resource or operation kind." }, - "parentContextKey": { - "description": "Selector context key supplied by the mapped parent resource.", - "type": "string", - "maxLength": 256 - } - }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "subBlockKey", - "title", - "required", - "currentValue", - "discoveryWorkspaceId", - "context", - "parentKind", - "parentSourceId" - ], - "additionalProperties": false - }, - "description": "Dependent fields that may need destination-specific values." - }, - "excludedTargets": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { + "sourceId": { "type": "string", "minLength": 1, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." } }, - "required": ["id", "name"], + "required": ["kind", "sourceId"], "additionalProperties": false - }, - "description": "Target workflows explicitly excluded from sync." + } }, - "triggerSlots": { - "maxItems": 10000, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, "type": "array", "items": { "type": "object", @@ -23293,106 +22570,57 @@ "type": "string", "minLength": 1, "maxLength": 256, - "description": "Stable source trigger block identifier to use in trigger mappings." - }, - "blockName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source trigger block." - }, - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source workflow." - }, - "ownPath": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Existing target trigger path, preserved automatically and not configurable." - }, - "adoptablePaths": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - "description": "Retiring paths in the same target workflow with a compatible trigger provider." + "description": "Source trigger block identifier from the sync preview." }, - "defaultAdoptPath": { + "adoptPath": { "anyOf": [ { "type": "string", + "minLength": 1, "maxLength": 4096 }, { "type": "null" } ], - "description": "Default adoption when ownPath is null; null then allocates a new path." + "description": "An adoptable path offered for this trigger, or null to allocate a new path." } }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "blockName", - "workflowName", - "ownPath", - "adoptablePaths", - "defaultAdoptPath" - ], + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], "additionalProperties": false - }, - "description": "Source triggers and the target paths available for explicit adoption choices." + } }, - "triggerUrlChanges": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Name of the affected workflow." - }, - "path": { - "type": "string", - "maxLength": 4096, - "description": "Public trigger path that stops serving after this sync." - } - }, - "required": ["workflowName", "path"], - "additionalProperties": false - }, - "description": "Retiring target trigger URLs no arriving trigger adopts." + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "confirm": { + "type": "boolean", + "const": true, + "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." } }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "targetWorkspaceId", - "ready", - "workflows", - "unresolvedBindings", - "configuration", - "excludedTargets", - "triggerSlots", - "triggerUrlChanges" - ], + "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], "additionalProperties": false, - "title": "Workspace sync preview", - "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." + "title": "Push workspace request", + "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", + "examples": [ + { + "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "requestId": "push-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "confirm": true + } + ] }, - "PreviewWorkspacePushResponse": { + "PreviewWorkspacePullResponse": { "type": "object", "properties": { "data": { @@ -23402,14 +22630,14 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Preview workspace push response", - "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", + "title": "Preview workspace pull response", + "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", "examples": [ { "data": { "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", "ready": true, "workflows": [], "unresolvedBindings": [], @@ -23421,7 +22649,7 @@ } ] }, - "PreviewWorkspacePushBody": { + "PreviewWorkspacePullBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23649,10 +22877,10 @@ }, "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "Preview workspace push request", + "title": "Preview workspace pull request", "description": "Other workspace and proposed source-to-target sync choices." }, - "PushWorkspaceResponse": { + "PullWorkspaceResponse": { "type": "object", "properties": { "data": { @@ -23662,15 +22890,15 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Push workspace response", - "description": "Committed push receipt with copy and deployment readiness.", + "title": "Pull workspace response", + "description": "Committed pull receipt with copy and deployment readiness.", "examples": [ { "data": { "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "push-support-2026-10-13", + "requestId": "pull-support-2026-10-13", "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_push", + "kind": "workspace_pull", "applied": true, "status": "processing", "resourceIds": ["destination_workflow_id"], @@ -23679,7 +22907,7 @@ } ] }, - "PushWorkspaceBody": { + "PullWorkspaceBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23923,512 +23151,415 @@ }, "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], "additionalProperties": false, - "title": "Push workspace request", - "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", + "title": "Pull workspace request", + "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", "examples": [ { "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "push-support-2026-10-13", + "requestId": "pull-support-2026-10-13", "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", "confirm": true } ] }, - "PreviewWorkspacePullResponse": { + "GetWorkspaceForkAvailabilityResult": { + "type": "object", + "properties": { + "available": { + "type": "boolean", + "description": "Whether this deployment and workspace plan enable forking." + } + }, + "required": ["available"], + "additionalProperties": false, + "title": "Get workspace fork availability result", + "description": "Fork feature availability for this workspace." + }, + "GetWorkspaceForkAvailabilityResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceSyncPreview" + "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workspace pull response", - "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", - "examples": [ - { - "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "ready": true, - "workflows": [], - "unresolvedBindings": [], - "configuration": [], - "excludedTargets": [], - "triggerSlots": [], - "triggerUrlChanges": [] - } + "title": "Get workspace fork availability response", + "description": "Whether forking is enabled for this deployment and workspace plan." + }, + "GetWorkspaceForkLineageResult": { + "type": "object", + "properties": { + "current": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." + } + }, + "required": ["id", "name", "organizationId"], + "additionalProperties": false, + "description": "The current workspace lineage node." + }, + "parent": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." + } + }, + "required": ["id", "name", "organizationId"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "The live parent workspace, or null when this workspace is not a fork." } - ] + }, + "required": ["current", "parent"], + "additionalProperties": false, + "title": "Get workspace fork lineage result", + "description": "Current workspace and its active parent." }, - "PreviewWorkspacePullBody": { + "GetWorkspaceForkLineageResponse": { "type": "object", "properties": { - "otherWorkspaceId": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace fork lineage response", + "description": "Current workspace and its active direct parent, when present." + }, + "ListWorkspaceForkChildrenResult": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "description": "Resource identifier." }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "ISO 8601 creation timestamp." + } + }, + "required": ["id", "name", "organizationId", "createdAt"], + "additionalProperties": false, + "title": "List workspace fork children result", + "description": "An active direct child workspace." + }, + "ListWorkspaceForkChildrenResponse": { + "type": "object", + "properties": { + "data": { "type": "array", "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" + }, + "description": "Items in the current page." }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", - "type": "object", - "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "files": { - "description": "Workspace file storage keys to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "nextCursor": { + "anyOf": [ + { + "type": "string" }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + { + "type": "null" } - }, - "additionalProperties": false + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace fork children response", + "description": "A page of active direct child workspaces." + }, + "ListWorkspaceForkResourcesResult": { + "type": "object", + "properties": { + "id": { + "type": "string", + "maxLength": 4096, + "description": "Resource identifier." }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - } + "label": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable resource label." + }, + "folderId": { + "description": "Containing folder identifier, or null at the workspace root.", + "anyOf": [ + { + "type": "string" }, - "required": ["kind", "sourceId"], - "additionalProperties": false - } + { + "type": "null" + } + ] }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." - }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } + "folderName": { + "description": "Containing folder name, or null at the workspace root.", + "anyOf": [ + { + "type": "string" }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } + { + "type": "null" + } + ] } }, - "required": ["otherWorkspaceId"], + "required": ["id", "label"], "additionalProperties": false, - "title": "Preview workspace pull request", - "description": "Other workspace and proposed source-to-target sync choices." + "title": "List workspace fork resources result", + "description": "A copyable resource candidate." }, - "PullWorkspaceResponse": { + "ListWorkspaceForkResourcesResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + "type": "array", + "items": { + "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." } }, - "required": ["data"], + "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "Pull workspace response", - "description": "Committed pull receipt with copy and deployment readiness.", - "examples": [ - { - "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "pull-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_pull", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] - } - } - ] + "title": "List workspace fork resources response", + "description": "A page of copyable resource candidates." }, - "PullWorkspaceBody": { + "GetWorkspaceForkMappingsResult": { "type": "object", "properties": { - "otherWorkspaceId": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, + "id": { + "type": "string", + "maxLength": 256, + "description": "Resource identifier." + } + }, + "required": ["resourceType", "sourceId", "targetId", "id"], + "additionalProperties": false, + "title": "Get workspace fork mappings result", + "description": "A saved directional mapping entry." + }, + "GetWorkspaceForkMappingsResponse": { + "type": "object", + "properties": { + "data": { "type": "array", "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" + }, + "description": "Items in the current page." }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", - "type": "object", - "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "files": { - "description": "Workspace file storage keys to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "nextCursor": { + "anyOf": [ + { + "type": "string" }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + { + "type": "null" } - }, - "additionalProperties": false + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "Get workspace fork mappings response", + "description": "A page of persisted source-to-target mapping entries." + }, + "UpdateWorkspaceForkMappingsResult": { + "type": "object", + "properties": { + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." + } + }, + "required": ["updated"], + "additionalProperties": false, + "title": "Update workspace fork mappings result", + "description": "Count of changed mapping records." + }, + "UpdateWorkspaceForkMappingsResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Update workspace fork mappings response", + "description": "Number of mapping records changed." + }, + "UpdateWorkspaceForkMappingsBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, + "direction": { + "type": "string", + "enum": ["push", "pull"], + "description": "Push means current to other; pull means other to current, independent of parent/child orientation." + }, + "mappings": { + "maxItems": 5000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "resourceType": { "type": "string", "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", + "oauth_credential", + "service_account_credential", + "env_var", "table", + "knowledge_base", "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", "skill", "sandbox" ], - "description": "Resource or operation kind." + "description": "Resource type stored on the canonical parent/child edge." }, "sourceId": { "type": "string", "minLength": 1, "maxLength": 4096, "description": "Source resource identifier in the canonical source workspace." - } - }, - "required": ["kind", "sourceId"], - "additionalProperties": false - } - }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." - }, - "adoptPath": { + "targetId": { "anyOf": [ { "type": "string", @@ -24439,669 +23570,224 @@ "type": "null" } ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." + "description": "Authorized destination identifier, or null to clear the mapping." } }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false - } - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - }, - "confirm": { - "type": "boolean", - "const": true, - "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." + }, + "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." } }, - "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], + "required": ["otherWorkspaceId", "direction", "mappings"], "additionalProperties": false, - "title": "Pull workspace request", - "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", - "examples": [ - { - "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "pull-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "confirm": true - } - ] + "title": "Update workspace fork mappings request", + "description": "Other workspace, direction, and mapping entries to update." }, - "GetWorkspaceForkAvailabilityResult": { + "RollbackWorkspaceForkResult": { "type": "object", "properties": { - "available": { - "type": "boolean", - "description": "Whether this deployment and workspace plan enable forking." + "restored": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows restored to their prior deployed version." + }, + "archived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows created by the sync and now archived." + }, + "unarchived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Previously archived workflows restored by rollback." + }, + "skipped": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Snapshot workflows no longer available to restore." + }, + "pendingActivations": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + }, + "description": "Workflows whose restored deployment is still activating." } }, - "required": ["available"], + "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], "additionalProperties": false, - "title": "Get workspace fork availability result", - "description": "Fork feature availability for this workspace." + "title": "Rollback workspace fork result", + "description": "Workflow restoration and pending-activation counts." }, - "GetWorkspaceForkAvailabilityResponse": { + "RollbackWorkspaceForkResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" + "$ref": "#/components/schemas/RollbackWorkspaceForkResult" } }, "required": ["data"], "additionalProperties": false, - "title": "Get workspace fork availability response", - "description": "Whether forking is enabled for this deployment and workspace plan." + "title": "Rollback workspace fork response", + "description": "Restored, archived, skipped, and still-activating workflow counts." }, - "GetWorkspaceForkLineageResult": { + "RollbackWorkspaceForkBody": { "type": "object", "properties": { - "current": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false, - "description": "The current workspace lineage node." - }, - "parent": { - "anyOf": [ - { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false - }, - { - "type": "null" - } - ], - "description": "The live parent workspace, or null when this workspace is not a fork." + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." } }, - "required": ["current", "parent"], + "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "Get workspace fork lineage result", - "description": "Current workspace and its active parent." + "title": "Rollback workspace fork request", + "description": "Other workspace whose latest inbound sync should be undone." }, - "GetWorkspaceForkLineageResponse": { + "UnlinkWorkspaceForkResult": { + "type": "object", + "properties": { + "unlinked": { + "type": "boolean", + "description": "Whether the fork edge was removed." + } + }, + "required": ["unlinked"], + "additionalProperties": false, + "title": "Unlink workspace fork result", + "description": "Fork-edge removal acknowledgment." + }, + "UnlinkWorkspaceForkResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" + "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" } }, "required": ["data"], "additionalProperties": false, - "title": "Get workspace fork lineage response", - "description": "Current workspace and its active direct parent, when present." + "title": "Unlink workspace fork response", + "description": "Confirmation that the relationship was removed." }, - "ListWorkspaceForkChildrenResult": { + "UnlinkWorkspaceForkBody": { "type": "object", "properties": { - "id": { + "otherWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - }, - "createdAt": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "ISO 8601 creation timestamp." + "description": "Workspace on the other side of the direct fork edge." } }, - "required": ["id", "name", "organizationId", "createdAt"], + "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "List workspace fork children result", - "description": "An active direct child workspace." + "title": "Unlink workspace fork request", + "description": "Other workspace on the direct fork edge to remove." }, - "ListWorkspaceForkChildrenResponse": { + "UpdateWorkspaceForkExclusionsResult": { "type": "object", "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." } }, - "required": ["data", "nextCursor"], + "required": ["updated"], "additionalProperties": false, - "title": "List workspace fork children response", - "description": "A page of active direct child workspaces." + "title": "Update workspace fork exclusions result", + "description": "Count of changed workflow exclusion flags." }, - "ListWorkspaceForkResourcesResult": { - "type": "object", - "properties": { - "id": { - "type": "string", - "maxLength": 4096, - "description": "Resource identifier." - }, - "label": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable resource label." - }, - "folderId": { - "description": "Containing folder identifier, or null at the workspace root.", - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "folderName": { - "description": "Containing folder name, or null at the workspace root.", - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - } - }, - "required": ["id", "label"], - "additionalProperties": false, - "title": "List workspace fork resources result", - "description": "A copyable resource candidate." - }, - "ListWorkspaceForkResourcesResponse": { + "UpdateWorkspaceForkExclusionsResponse": { "type": "object", "properties": { "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace fork resources response", - "description": "A page of copyable resource candidates." - }, - "GetWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - }, - "id": { - "type": "string", - "maxLength": 256, - "description": "Resource identifier." + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" } }, - "required": ["resourceType", "sourceId", "targetId", "id"], + "required": ["data"], "additionalProperties": false, - "title": "Get workspace fork mappings result", - "description": "A saved directional mapping entry." + "title": "Update workspace fork exclusions response", + "description": "Number of workflow exclusion flags changed." }, - "GetWorkspaceForkMappingsResponse": { + "UpdateWorkspaceForkExclusionsBody": { "type": "object", "properties": { - "data": { + "workflowIds": { + "minItems": 1, + "maxItems": 1000, "type": "array", "items": { - "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" + "type": "string", + "minLength": 1 }, - "description": "Items in the current page." + "description": "Workflow identifiers in the current workspace." }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "Get workspace fork mappings response", - "description": "A page of persisted source-to-target mapping entries." - }, - "UpdateWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork mappings result", - "description": "Count of changed mapping records." - }, - "UpdateWorkspaceForkMappingsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" + "forkSyncExcluded": { + "type": "boolean", + "description": "Whether the named workflows should be skipped as sync sources and targets." } }, - "required": ["data"], + "required": ["workflowIds", "forkSyncExcluded"], "additionalProperties": false, - "title": "Update workspace fork mappings response", - "description": "Number of mapping records changed." + "title": "Update workspace fork exclusions request", + "description": "Workflow IDs and whether to exclude them from sync." }, - "UpdateWorkspaceForkMappingsBody": { + "PreviewWorkflowImportResult": { "type": "object", "properties": { - "otherWorkspaceId": { + "previewFingerprint": { "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "minLength": 64, + "maxLength": 64, + "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." }, - "direction": { - "type": "string", - "enum": ["push", "pull"], - "description": "Push means current to other; pull means other to current, independent of parent/child orientation." + "ready": { + "type": "boolean", + "description": "Whether every required destination binding and configuration field is resolved for import." }, - "mappings": { - "maxItems": 5000, + "bindings": { + "maxItems": 10000, "type": "array", "items": { "type": "object", "properties": { - "resourceType": { + "kind": { "type": "string", "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", + "credential", + "env-var", + "knowledge-base", + "knowledge-document", "table", - "knowledge_base", "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", "skill", - "sandbox" + "sandbox", + "workflow" ], - "description": "Resource type stored on the canonical parent/child edge." + "description": "Resource or operation kind." }, "sourceId": { "type": "string", - "minLength": 1, "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - }, - "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." - } - }, - "required": ["otherWorkspaceId", "direction", "mappings"], - "additionalProperties": false, - "title": "Update workspace fork mappings request", - "description": "Other workspace, direction, and mapping entries to update." - }, - "RollbackWorkspaceForkResult": { - "type": "object", - "properties": { - "restored": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows restored to their prior deployed version." - }, - "archived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows created by the sync and now archived." - }, - "unarchived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Previously archived workflows restored by rollback." - }, - "skipped": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Snapshot workflows no longer available to restore." - }, - "pendingActivations": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "maxLength": 256 - }, - "description": "Workflows whose restored deployment is still activating." - } - }, - "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], - "additionalProperties": false, - "title": "Rollback workspace fork result", - "description": "Workflow restoration and pending-activation counts." - }, - "RollbackWorkspaceForkResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/RollbackWorkspaceForkResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Rollback workspace fork response", - "description": "Restored, archived, skipped, and still-activating workflow counts." - }, - "RollbackWorkspaceForkBody": { - "type": "object", - "properties": { - "otherWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Rollback workspace fork request", - "description": "Other workspace whose latest inbound sync should be undone." - }, - "UnlinkWorkspaceForkResult": { - "type": "object", - "properties": { - "unlinked": { - "type": "boolean", - "description": "Whether the fork edge was removed." - } - }, - "required": ["unlinked"], - "additionalProperties": false, - "title": "Unlink workspace fork result", - "description": "Fork-edge removal acknowledgment." - }, - "UnlinkWorkspaceForkResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Unlink workspace fork response", - "description": "Confirmation that the relationship was removed." - }, - "UnlinkWorkspaceForkBody": { - "type": "object", - "properties": { - "otherWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Unlink workspace fork request", - "description": "Other workspace on the direct fork edge to remove." - }, - "UpdateWorkspaceForkExclusionsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork exclusions result", - "description": "Count of changed workflow exclusion flags." - }, - "UpdateWorkspaceForkExclusionsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Update workspace fork exclusions response", - "description": "Number of workflow exclusion flags changed." - }, - "UpdateWorkspaceForkExclusionsBody": { - "type": "object", - "properties": { - "workflowIds": { - "minItems": 1, - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "description": "Workflow identifiers in the current workspace." - }, - "forkSyncExcluded": { - "type": "boolean", - "description": "Whether the named workflows should be skipped as sync sources and targets." - } - }, - "required": ["workflowIds", "forkSyncExcluded"], - "additionalProperties": false, - "title": "Update workspace fork exclusions request", - "description": "Workflow IDs and whether to exclude them from sync." - }, - "PreviewWorkflowImportResult": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "minLength": 64, - "maxLength": 64, - "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." - }, - "ready": { - "type": "boolean", - "description": "Whether every required destination binding and configuration field is resolved for import." - }, - "bindings": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox", - "workflow" - ], - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." }, "targetId": { "anyOf": [ @@ -26000,1305 +24686,235 @@ "description": "Explicit current workspace scope." }, "selectorKey": { - "type": "string", - "enum": [ - "airtable.bases", - "airtable.tables", - "asana.workspaces", - "attio.lists", - "attio.objects", - "bigquery.datasets", - "bigquery.tables", - "bitbucket.workspaces", - "bitbucket.repositories", - "calcom.eventTypes", - "calcom.schedules", - "clickup.workspaces", - "clickup.spaces", - "clickup.folders", - "clickup.lists", - "coda.docs", - "coda.pages", - "coda.tables", - "coda.columns", - "coda.rows", - "coda.formulas", - "coda.controls", - "coda.folders", - "coda.permissions", - "confluence.spaces", - "confluence.spacesById", - "confluence.pages", - "google.tasks.lists", - "gauge.organizations", - "gauge.categories", - "gauge.topics", - "gauge.prompts", - "gauge.tags", - "gauge.answers", - "fivetran.groups", - "fivetran.connections", - "gmail.labels", - "google.calendar", - "google.drive", - "google.sheets", - "harmonic.savedSearches", - "jama.projects", - "jama.itemTypes", - "flow.projects", - "flow.categories", - "flow.branches", - "helpscout.mailboxes", - "helpscout.assignees", - "hubspot.lists", - "hubspot.owners", - "hubspot.pipelines", - "hubspot.pipelineStages", - "hubspot.properties", - "jsm.requestTypes", - "jsm.serviceDesks", - "microsoft.planner.plans", - "notion.databases", - "notion.pages", - "netsuite.recordTypes", - "netsuite.asyncTasks", - "pipedrive.pipelines", - "sharepoint.lists", - "trello.boards", - "zoho_desk.organizations", - "zoho_desk.departments", - "zoho_desk.agents", - "zoom.meetings", - "slack.channels", - "snowflake.databases", - "snowflake.schemas", - "snowflake.tables", - "snowflake.warehouses", - "snowflake.roles", - "snowflake.fileFormats", - "snowflake.procedures", - "slack.users", - "outlook.folders", - "outlook.calendars", - "microsoft.teams", - "microsoft.chats", - "microsoft.channels", - "microsoft.planner", - "onedrive.files", - "onedrive.folders", - "sharepoint.sites", - "microsoft.excel", - "microsoft.excel.drives", - "microsoft.excel.sheets", - "microsoft.word", - "wealthbox.contacts", - "jira.issues", - "jira.projects", - "jira.projectKeys", - "linear.projects", - "linear.teams", - "monday.boards", - "monday.groups", - "webflow.sites", - "webflow.collections", - "webflow.items", - "planetscale.databases", - "powerbi.workspaces", - "powerbi.datasets", - "powerbi.reports", - "planetscale.branches", - "planetscale.backups", - "planetscale.deployRequests", - "planetscale.savedDatabases", - "planetscale.savedBranches", - "planetscale.savedBackups", - "planetscale.savedDeployRequests", - "cloudwatch.logGroups", - "cloudwatch.logStreams", - "cloudwatch.savedLogGroups", - "cloudwatch.savedLogStreams", - "imap.mailboxes", - "mcp.tools", - "managedAgent.agents", - "managedAgent.environments", - "managedAgent.vaults", - "managedAgent.memoryStores", - "knowledge.documents", - "sim.workflows", - "table.columns", - "table.outputColumns", - "workspace.secretNames", - "workspace.sandboxes", - "providers.ollamaEmbeddingModels", - "providers.openrouterEmbeddingModels" - ], - "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." - }, - "context": { - "default": {}, - "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - } - }, - "id": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Provider option ID to resolve with the same selector and declared context." - } - }, - "required": ["workspaceId", "selectorKey", "id"], - "additionalProperties": false, - "title": "Get selector request", - "description": "Workspace, registered selector key, context, and provider option ID." - }, - "GetWorkspaceOperationResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get workspace operation response", - "description": "Refreshed commit, copy progress, and exact deployment readiness." - }, - "ListWorkspaceOperationsResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/WorkspaceOperationReport" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace operations response", - "description": "A page of stored operation receipts." - }, - "GetWorkspaceSourceResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, - "kinds": { - "type": "array", - "items": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "description": "The kinds read; the directory manages exactly these." - }, - "files": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - }, - "description": "Directory path → file text." - }, - "blobs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Directory path of the binary file." - }, - "sha256": { - "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", - "type": "string", - "pattern": "^[0-9a-f]{64}$" - }, - "size": { - "type": "integer", - "minimum": 0, - "maximum": 10000000, - "description": "Bytes." - }, - "id": { - "type": "string", - "description": "Stored id of the binary file." - }, - "href": { - "type": "string", - "description": "Where to download its bytes." - }, - "rev": { - "description": "Content revision, present when `sha256` is absent.", - "type": "string" - } - }, - "required": ["path", "size", "id", "href"], - "additionalProperties": false - }, - "description": "Binary files, downloaded separately by `href`." - }, - "base": { - "type": "object", - "properties": { - "version": { - "type": "number", - "const": 1, - "description": "Base format version." - }, - "workspaceId": { - "type": "string", - "description": "Workspace the directory was read from." - }, - "resources": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored id the key is bound to." - }, - "fingerprint": { - "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", - "type": "string" - }, - "columns": { - "description": "Table column key → stored column.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored column id." - }, - "options": { - "description": "Select option name → option id.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - } - } - }, - "required": ["id"], - "additionalProperties": false - } - }, - "blobs": { - "description": "Binary file name → its stored id, revision and hash as last read.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored id of the binary file." - }, - "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], - "description": "Content revision as last read." - }, - "sha256": { - "type": "string", - "pattern": "^[0-9a-f]{64}$", - "description": "SHA-256 of the bytes, lowercase hex." - } - }, - "required": ["id", "rev", "sha256"], - "additionalProperties": false - } - }, - "rows": { - "description": "A table’s managed rows, as last read.", - "type": "object", - "properties": { - "fingerprint": { - "type": "string", - "description": "`rf1:` fingerprint of the managed rows as last read." - }, - "version": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "The table’s row version as last read; it moves on every row write." - } - }, - "required": ["fingerprint", "version"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - } - } - }, - "required": ["id"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - }, - "description": "One resource in the base." - }, - "description": "`kind:key` → the stored resource and its fingerprint." - } - }, - "required": ["version", "workspaceId", "resources"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - }, - "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." - }, - "skipped": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "reason": { - "type": "string", - "description": "Why it was left out." - } - }, - "required": ["kind", "key", "reason"], - "additionalProperties": false - }, - "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." - }, - "diagnostics": { - "type": "array", - "items": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "E_DECL_SYNTAX", - "E_DECL_HEADER", - "E_DECL_IMPORT", - "E_DECL_EXPORT", - "E_DECL_UNSUPPORTED", - "E_DECL_DUPLICATE_KEY", - "E_DECL_SHAPE", - "E_DECL_UNKNOWN_FIELD", - "E_DECL_UNKNOWN_FILE", - "W_PATH_NOT_SENT", - "E_BLOB_MANIFEST", - "E_BLOB_MISSING", - "E_LIMIT_EXCEEDED", - "E_KEY_INVALID", - "W_DECL_SUSPICIOUS_CHARACTER", - "E_BASE_JSON", - "E_BASE_VERSION", - "E_BASE_SHAPE", - "E_BASE_UNKNOWN_FIELD", - "E_SECRET_NAME", - "E_SECRET_MISSING", - "W_SECRET_MISSING", - "E_CREDENTIAL_MISSING", - "E_CREDENTIAL_AMBIGUOUS", - "W_CREDENTIAL_MISSING", - "W_CREDENTIAL_AMBIGUOUS", - "E_TABLE_COLUMN_NAME", - "E_TABLE_DUPLICATE_COLUMN", - "E_TABLE_TOO_MANY_COLUMNS", - "E_TABLE_OPTIONS", - "E_TABLE_TYPE_CONVERSION", - "E_TABLE_FOLDER", - "E_TABLE_ROWS", - "I_TABLE_SEED_SKIPPED", - "I_TABLE_ROWS_UNKEYED", - "W_LIKELY_RENAME", - "E_TOOL_SCHEMA", - "E_TOOL_CODE", - "E_TOOL_STORED_MISSING", - "W_TOOL_LITERAL_SECRET", - "E_SKILL_FRONTMATTER", - "E_MCP_LITERAL_SECRET", - "E_MCP_STORED_MISSING", - "E_MCP_TOOL_UNKNOWN", - "W_MCP_REPLACE", - "W_MCP_TOOLS_UNCHECKED", - "E_FILE_PATH", - "E_FILE_PATH_COLLISION", - "E_FILE_NAME", - "E_FILE_TOO_LARGE", - "E_FILE_CONTENT", - "E_KB_EMBEDDING_IMMUTABLE", - "E_KB_EMBEDDING_MODEL", - "E_KB_DOC_AMBIGUOUS", - "E_KB_DOC_NAME", - "E_KB_DOC_EMPTY", - "E_KB_CHUNKING", - "E_KB_FOLDER", - "W_KB_DOC_UNCHECKED", - "W_KB_DOC_FAILED", - "I_KB_REEMBED", - "I_KB_CHUNKING", - "I_KB_PROCESSING", - "I_KB_DOCS_UNHASHED", - "I_KB_UNMANAGED_DOCS", - "I_KB_REPLACE_UNFINISHED", - "E_DEPLOY_WORKFLOW", - "E_DEPLOY_SECRET", - "E_DEPLOY_CHAT_OUTPUT", - "E_DEPLOY_CHAT_IDENTIFIER", - "E_DEPLOY_PINNED_CHAT", - "W_DEPLOYED_DRAFT_CHANGED", - "W_DEPLOY_DRAFT_NOT_SOURCE", - "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", - "I_DEPLOY_DRAFT_NOT_LIVE", - "E_APPLY_STALE", - "E_APPLY_NO_BASE", - "E_APPLY_FORBIDDEN", - "E_APPLY_DELETE_NOT_ALLOWED", - "E_APPLY_LOCKED", - "E_APPLY_REFUSED", - "E_APPLY_FAILED", - "E_PLAN_TOO_LARGE", - "E_PLAN_REF_DELETED", - "E_PLAN_REF_HELD", - "W_RESOURCE_IN_USE", - "W_TABLE_COLUMN_RENAMED_IN_USE", - "E_NAME_TAKEN", - "E_WORKFLOW_FILES_MISSING", - "E_WORKFLOW_FOLDER_COPIED", - "W_UNDECLARED", - "W_BASE_OTHER_WORKSPACE", - "W_PROMOTE_TARGET_DELETED", - "W_PROMOTE_DELETES_TARGET_ONLY", - "I_SERVER_CHANGED", - "I_SERVER_DELETED", - "I_SERVER_MOVED", - "I_KEY_REBOUND", - "E_KEY_RENAMED", - "I_FINDINGS_TRUNCATED", - "E_SYNTAX", - "E_SDK_HEADER", - "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", - "E_UNSUPPORTED_SYNTAX", - "E_WORKFLOW_EXPORT", - "E_INVALID_CHARACTER", - "E_NUMBER_NOT_FINITE", - "W_NUMBER_PRECISION", - "E_TOO_MANY_ERRORS", - "W_TOO_MANY_WARNINGS", - "E_DUPLICATE_NAME", - "E_RESERVED_NAME", - "E_KEY_OVERRIDE", - "E_EMPTY_NAME", - "E_LOOKALIKE_NAME", - "W_LOOKALIKE_NAME", - "W_SUSPICIOUS_CHARACTER", - "E_NAME_NOT_LITERAL", - "E_UNKNOWN_IDENTIFIER", - "E_OUT_OF_SCOPE", - "E_UNKNOWN_VARIABLE", - "E_DUPLICATE_VARIABLE", - "E_VARIABLE_NAME_MISMATCH", - "E_INVALID_ENV_NAME", - "W_ENV_UNKNOWN", - "W_CHILD_INPUT_UNKNOWN", - "W_CHILD_NO_START", - "E_UNKNOWN_SUBFLOW_PROPERTY", - "W_FORWARD_REF", - "W_REF_NOT_NORMALIZED", - "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", - "E_EDGE_SCOPE", - "E_EDGE_NOTE", - "E_TARGET_TRIGGER", - "E_NO_DEFAULT_OUTPUT", - "E_DUPLICATE_EDGE", - "E_ERROR_PORT_UNSUPPORTED", - "W_ERROR_PORT_STORED", - "E_UNKNOWN_BRANCH", - "E_DUPLICATE_BRANCH_KEY", - "E_BRANCH_KEY_COLLIDES", - "E_BRANCH_ELSE_LAST", - "W_RAW_HANDLE", - "W_SUBFLOW_HANDLE_SCOPE", - "E_EDGE_CYCLE", - "W_EDGE_CYCLE", - "W_BRANCH_UNWIRED", - "E_UNKNOWN_BUILDER", - "E_UNKNOWN_PARAM", - "E_FIXED_PARAM", - "W_FIELD_NOT_APPLICABLE", - "W_REQUIRED_MISSING", - "W_UNKNOWN_OPTION", - "E_UNKNOWN_OPERATION", - "W_UNKNOWN_MODEL", - "W_LEGACY_BLOCK_TYPE", - "I_SCHEDULE_UTC", - "E_STORED_VALUE_MISSING", - "W_VALUE_KIND", - "W_OUT_OF_RANGE", - "W_TABLE_FILTER_SHAPE", - "W_LITERAL_SECRET", - "W_SUBFLOW_COUNT", - "W_UNKNOWN_OUTPUT_PATH", - "W_JSON_REF_UNTYPED", - "E_CODE_FILE_MISSING", - "E_CODE_FILE_PATH", - "W_CODE_FILE_INLINED", - "W_UNRESOLVED_REF", - "W_FORWARD_REF_LITERALIZED", - "W_COMMENT_MOVED", - "W_COMMENT_DROPPED", - "E_LOCK_JSON", - "E_LOCK_VERSION", - "E_LOCK_SHAPE", - "E_LOCK_UNKNOWN_FIELD", - "E_LOCK_KEY", - "E_LOCK_IDENT", - "E_LOCK_DUPLICATE_IDENT", - "E_LOCK_DUPLICATE_ID", - "E_LOCK_PARENT", - "E_LOCK_BRANCH", - "E_LOCK_CODE_FILE_PATH", - "E_SOURCE_META_JSON", - "E_SOURCE_META_VERSION", - "E_SOURCE_META_SHAPE", - "E_SOURCE_META_UNKNOWN_FIELD", - "E_SOURCE_META_IDENT", - "E_SOURCE_META_DUPLICATE_IDENT", - "E_SOURCE_META_ANCHOR", - "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", - "W_CANON_RESERVED_NAME", - "W_CANON_DANGLING_EDGE", - "W_CANON_DANGLING_PARENT", - "W_CANON_RAW_HANDLE", - "W_CANON_UNKNOWN_BLOCK_TYPE", - "W_CANON_UNRESOLVED_ID", - "W_CANON_TITLE_OVERRIDE", - "W_CANON_SUBFLOW_REPAIRED", - "W_CANON_SUBBLOCK_TYPE_DRIFT", - "W_CANON_UNDECODABLE_JSON", - "E_MAT_DUPLICATE_LOCK_ID", - "E_MAT_UNKNOWN_RESOURCE", - "E_MAT_UNKNOWN_VARIABLE", - "W_MAT_DELETED_SINCE_PULL", - "W_MAT_INFERRED_RENAME", - "W_MAT_RETYPE_RECREATED", - "W_MAT_LOCK_ID_CLAIMED", - "I_MAT_NEEDS_LAYOUT", - "E_APPLY_WORKFLOW_MISMATCH", - "E_APPLY_LOCKED_BLOCK", - "E_APPLY_TYPE_NOT_ADDABLE", - "E_APPLY_INVALID_STATE", - "E_APPLY_BLOCK_NOT_FOUND", - "E_APPLY_INVALID_BLOCK_TYPE", - "E_APPLY_BLOCK_NOT_ALLOWED", - "E_APPLY_MODEL_NOT_ALLOWED", - "E_APPLY_TOOL_NOT_ALLOWED", - "E_APPLY_INVALID_EDGE_SOURCE", - "E_APPLY_INVALID_EDGE_SCOPE", - "E_APPLY_INVALID_SOURCE_HANDLE", - "E_APPLY_INVALID_TARGET_HANDLE", - "E_APPLY_INVALID_SUBBLOCK_FIELD", - "E_APPLY_MISSING_REQUIRED_PARAMS", - "E_APPLY_RETRY_NOT_SUPPORTED", - "E_APPLY_DUPLICATE_TRIGGER", - "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", - "E_APPLY_DISABLED_ANCESTOR", - "E_APPLY_CREDENTIAL_UNREACHABLE", - "W_APPLY_CREDENTIAL_KEPT", - "E_APPLY_SANDBOX_PLAN_REQUIRED", - "W_APPLY_HOSTED_KEY_DROPPED", - "W_APPLY_VALUE_NORMALIZED", - "W_APPLY_TYPE_CHANGED", - "W_APPLY_TRIGGER_REMOVED", - "W_APPLY_CATALOG_MOVED", - "W_APPLY_PROBABLE_RENAME", - "E_APPLY_LINT", - "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", - "W_APPLY_LINT", - "W_TABLE_UNKNOWN_COLUMN", - "E_APPLY_INVALID_SCHEDULE", - "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" - ], - "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." - }, - "severity": { - "type": "string", - "enum": ["error", "warning", "info"], - "description": "Diagnostic severity." - }, - "message": { - "type": "string", - "description": "What was found." - }, - "hint": { - "description": "How to address it.", - "type": "string" - }, - "file": { - "description": "Directory file the finding is in.", - "type": "string" - }, - "line": { - "description": "1-based line in `file`.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "column": { - "description": "1-based column in `file`.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "endLine": { - "description": "1-based line the finding ends on.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "endColumn": { - "description": "1-based column the finding ends at.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "frame": { - "description": "The source lines around the finding, with a caret row.", - "type": "string" - }, - "path": { - "description": "JSON Pointer into a JSON file, such as the base.", - "type": "string" - }, - "kind": { - "description": "Kind of the resource the finding is about.", - "type": "string" - }, - "key": { - "description": "Key of the resource the finding is about.", - "type": "string" - }, - "blockKey": { - "description": "Workflow block the finding is about.", - "type": "string" - }, - "param": { - "description": "Block field the finding is about.", - "type": "string" - } - }, - "required": ["code", "severity", "message"], - "additionalProperties": false, - "description": "A finding about the directory, pinned to its file when it has one." - }, - "description": "Findings from reading." - } - }, - "required": [ - "workspaceId", - "kinds", - "files", - "blobs", - "base", - "skipped", - "diagnostics" - ], - "additionalProperties": false, - "description": "Response data." - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get workspace source response", - "description": "The workspace as a source directory.", - "examples": [ - { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "kinds": ["table", "workflow"], - "files": { - "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" - }, - "blobs": [], - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } - } - } - } - } - }, - "skipped": [], - "diagnostics": [] - } - } - ] - }, - "ApplyWorkspaceSourceResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, - "dryRun": { - "type": "boolean", - "description": "True when nothing was written because `dryRun` was set." - }, - "plan": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "action": { - "type": "string", - "enum": ["create", "update", "adopt", "delete", "noop"], - "description": "`adopt` binds the key to an existing resource of the same name, then updates it." - }, - "fields": { - "description": "What changes.", - "type": "array", - "items": { - "type": "string" - } - }, - "destructive": { - "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", - "type": "object", - "properties": { - "what": { - "type": "string", - "description": "What is lost." - }, - "counts": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "description": "How much is lost." - } - }, - "required": ["what", "counts"], - "additionalProperties": false - }, - "id": { - "description": "Stored id, once known.", - "type": "string" - }, - "held": { - "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", - "type": "boolean", - "const": true - } - }, - "required": ["kind", "key", "action"], - "additionalProperties": false, - "description": "One planned or applied change." - }, - "description": "Every planned change, no-ops included, in apply order." - }, - "applied": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "action": { - "type": "string", - "enum": ["create", "update", "adopt", "delete", "noop"], - "description": "`adopt` binds the key to an existing resource of the same name, then updates it." - }, - "fields": { - "description": "What changes.", - "type": "array", - "items": { - "type": "string" - } - }, - "destructive": { - "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", - "type": "object", - "properties": { - "what": { - "type": "string", - "description": "What is lost." - }, - "counts": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "description": "How much is lost." - } - }, - "required": ["what", "counts"], - "additionalProperties": false - }, - "id": { - "description": "Stored id, once known.", - "type": "string" - }, - "held": { - "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", - "type": "boolean", - "const": true - } - }, - "required": ["kind", "key", "action"], - "additionalProperties": false, - "description": "One planned or applied change." - }, - "description": "The changes written, in order." - }, - "failed": { - "description": "The change that failed mid-apply. The changes before it are written (`applied`); the rest were not attempted. Applying the same directory again continues.", - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "code": { - "type": "string", - "enum": [ - "E_DECL_SYNTAX", - "E_DECL_HEADER", - "E_DECL_IMPORT", - "E_DECL_EXPORT", - "E_DECL_UNSUPPORTED", - "E_DECL_DUPLICATE_KEY", - "E_DECL_SHAPE", - "E_DECL_UNKNOWN_FIELD", - "E_DECL_UNKNOWN_FILE", - "W_PATH_NOT_SENT", - "E_BLOB_MANIFEST", - "E_BLOB_MISSING", - "E_LIMIT_EXCEEDED", - "E_KEY_INVALID", - "W_DECL_SUSPICIOUS_CHARACTER", - "E_BASE_JSON", - "E_BASE_VERSION", - "E_BASE_SHAPE", - "E_BASE_UNKNOWN_FIELD", - "E_SECRET_NAME", - "E_SECRET_MISSING", - "W_SECRET_MISSING", - "E_CREDENTIAL_MISSING", - "E_CREDENTIAL_AMBIGUOUS", - "W_CREDENTIAL_MISSING", - "W_CREDENTIAL_AMBIGUOUS", - "E_TABLE_COLUMN_NAME", - "E_TABLE_DUPLICATE_COLUMN", - "E_TABLE_TOO_MANY_COLUMNS", - "E_TABLE_OPTIONS", - "E_TABLE_TYPE_CONVERSION", - "E_TABLE_FOLDER", - "E_TABLE_ROWS", - "I_TABLE_SEED_SKIPPED", - "I_TABLE_ROWS_UNKEYED", - "W_LIKELY_RENAME", - "E_TOOL_SCHEMA", - "E_TOOL_CODE", - "E_TOOL_STORED_MISSING", - "W_TOOL_LITERAL_SECRET", - "E_SKILL_FRONTMATTER", - "E_MCP_LITERAL_SECRET", - "E_MCP_STORED_MISSING", - "E_MCP_TOOL_UNKNOWN", - "W_MCP_REPLACE", - "W_MCP_TOOLS_UNCHECKED", - "E_FILE_PATH", - "E_FILE_PATH_COLLISION", - "E_FILE_NAME", - "E_FILE_TOO_LARGE", - "E_FILE_CONTENT", - "E_KB_EMBEDDING_IMMUTABLE", - "E_KB_EMBEDDING_MODEL", - "E_KB_DOC_AMBIGUOUS", - "E_KB_DOC_NAME", - "E_KB_DOC_EMPTY", - "E_KB_CHUNKING", - "E_KB_FOLDER", - "W_KB_DOC_UNCHECKED", - "W_KB_DOC_FAILED", - "I_KB_REEMBED", - "I_KB_CHUNKING", - "I_KB_PROCESSING", - "I_KB_DOCS_UNHASHED", - "I_KB_UNMANAGED_DOCS", - "I_KB_REPLACE_UNFINISHED", - "E_DEPLOY_WORKFLOW", - "E_DEPLOY_SECRET", - "E_DEPLOY_CHAT_OUTPUT", - "E_DEPLOY_CHAT_IDENTIFIER", - "E_DEPLOY_PINNED_CHAT", - "W_DEPLOYED_DRAFT_CHANGED", - "W_DEPLOY_DRAFT_NOT_SOURCE", - "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", - "I_DEPLOY_DRAFT_NOT_LIVE", - "E_APPLY_STALE", - "E_APPLY_NO_BASE", - "E_APPLY_FORBIDDEN", - "E_APPLY_DELETE_NOT_ALLOWED", - "E_APPLY_LOCKED", - "E_APPLY_REFUSED", - "E_APPLY_FAILED", - "E_PLAN_TOO_LARGE", - "E_PLAN_REF_DELETED", - "E_PLAN_REF_HELD", - "W_RESOURCE_IN_USE", - "W_TABLE_COLUMN_RENAMED_IN_USE", - "E_NAME_TAKEN", - "E_WORKFLOW_FILES_MISSING", - "E_WORKFLOW_FOLDER_COPIED", - "W_UNDECLARED", - "W_BASE_OTHER_WORKSPACE", - "W_PROMOTE_TARGET_DELETED", - "W_PROMOTE_DELETES_TARGET_ONLY", - "I_SERVER_CHANGED", - "I_SERVER_DELETED", - "I_SERVER_MOVED", - "I_KEY_REBOUND", - "E_KEY_RENAMED", - "I_FINDINGS_TRUNCATED", - "E_SYNTAX", - "E_SDK_HEADER", - "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", - "E_UNSUPPORTED_SYNTAX", - "E_WORKFLOW_EXPORT", - "E_INVALID_CHARACTER", - "E_NUMBER_NOT_FINITE", - "W_NUMBER_PRECISION", - "E_TOO_MANY_ERRORS", - "W_TOO_MANY_WARNINGS", - "E_DUPLICATE_NAME", - "E_RESERVED_NAME", - "E_KEY_OVERRIDE", - "E_EMPTY_NAME", - "E_LOOKALIKE_NAME", - "W_LOOKALIKE_NAME", - "W_SUSPICIOUS_CHARACTER", - "E_NAME_NOT_LITERAL", - "E_UNKNOWN_IDENTIFIER", - "E_OUT_OF_SCOPE", - "E_UNKNOWN_VARIABLE", - "E_DUPLICATE_VARIABLE", - "E_VARIABLE_NAME_MISMATCH", - "E_INVALID_ENV_NAME", - "W_ENV_UNKNOWN", - "W_CHILD_INPUT_UNKNOWN", - "W_CHILD_NO_START", - "E_UNKNOWN_SUBFLOW_PROPERTY", - "W_FORWARD_REF", - "W_REF_NOT_NORMALIZED", - "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", - "E_EDGE_SCOPE", - "E_EDGE_NOTE", - "E_TARGET_TRIGGER", - "E_NO_DEFAULT_OUTPUT", - "E_DUPLICATE_EDGE", - "E_ERROR_PORT_UNSUPPORTED", - "W_ERROR_PORT_STORED", - "E_UNKNOWN_BRANCH", - "E_DUPLICATE_BRANCH_KEY", - "E_BRANCH_KEY_COLLIDES", - "E_BRANCH_ELSE_LAST", - "W_RAW_HANDLE", - "W_SUBFLOW_HANDLE_SCOPE", - "E_EDGE_CYCLE", - "W_EDGE_CYCLE", - "W_BRANCH_UNWIRED", - "E_UNKNOWN_BUILDER", - "E_UNKNOWN_PARAM", - "E_FIXED_PARAM", - "W_FIELD_NOT_APPLICABLE", - "W_REQUIRED_MISSING", - "W_UNKNOWN_OPTION", - "E_UNKNOWN_OPERATION", - "W_UNKNOWN_MODEL", - "W_LEGACY_BLOCK_TYPE", - "I_SCHEDULE_UTC", - "E_STORED_VALUE_MISSING", - "W_VALUE_KIND", - "W_OUT_OF_RANGE", - "W_TABLE_FILTER_SHAPE", - "W_LITERAL_SECRET", - "W_SUBFLOW_COUNT", - "W_UNKNOWN_OUTPUT_PATH", - "W_JSON_REF_UNTYPED", - "E_CODE_FILE_MISSING", - "E_CODE_FILE_PATH", - "W_CODE_FILE_INLINED", - "W_UNRESOLVED_REF", - "W_FORWARD_REF_LITERALIZED", - "W_COMMENT_MOVED", - "W_COMMENT_DROPPED", - "E_LOCK_JSON", - "E_LOCK_VERSION", - "E_LOCK_SHAPE", - "E_LOCK_UNKNOWN_FIELD", - "E_LOCK_KEY", - "E_LOCK_IDENT", - "E_LOCK_DUPLICATE_IDENT", - "E_LOCK_DUPLICATE_ID", - "E_LOCK_PARENT", - "E_LOCK_BRANCH", - "E_LOCK_CODE_FILE_PATH", - "E_SOURCE_META_JSON", - "E_SOURCE_META_VERSION", - "E_SOURCE_META_SHAPE", - "E_SOURCE_META_UNKNOWN_FIELD", - "E_SOURCE_META_IDENT", - "E_SOURCE_META_DUPLICATE_IDENT", - "E_SOURCE_META_ANCHOR", - "E_CANON_LEGACY_NAME_COLLISION", - "E_CANON_EDGE_SCOPE", - "W_CANON_RESERVED_NAME", - "W_CANON_DANGLING_EDGE", - "W_CANON_DANGLING_PARENT", - "W_CANON_RAW_HANDLE", - "W_CANON_UNKNOWN_BLOCK_TYPE", - "W_CANON_UNRESOLVED_ID", - "W_CANON_TITLE_OVERRIDE", - "W_CANON_SUBFLOW_REPAIRED", - "W_CANON_SUBBLOCK_TYPE_DRIFT", - "W_CANON_UNDECODABLE_JSON", - "E_MAT_DUPLICATE_LOCK_ID", - "E_MAT_UNKNOWN_RESOURCE", - "E_MAT_UNKNOWN_VARIABLE", - "W_MAT_DELETED_SINCE_PULL", - "W_MAT_INFERRED_RENAME", - "W_MAT_RETYPE_RECREATED", - "W_MAT_LOCK_ID_CLAIMED", - "I_MAT_NEEDS_LAYOUT", - "E_APPLY_WORKFLOW_MISMATCH", - "E_APPLY_LOCKED_BLOCK", - "E_APPLY_TYPE_NOT_ADDABLE", - "E_APPLY_INVALID_STATE", - "E_APPLY_BLOCK_NOT_FOUND", - "E_APPLY_INVALID_BLOCK_TYPE", - "E_APPLY_BLOCK_NOT_ALLOWED", - "E_APPLY_MODEL_NOT_ALLOWED", - "E_APPLY_TOOL_NOT_ALLOWED", - "E_APPLY_INVALID_EDGE_SOURCE", - "E_APPLY_INVALID_EDGE_SCOPE", - "E_APPLY_INVALID_SOURCE_HANDLE", - "E_APPLY_INVALID_TARGET_HANDLE", - "E_APPLY_INVALID_SUBBLOCK_FIELD", - "E_APPLY_MISSING_REQUIRED_PARAMS", - "E_APPLY_RETRY_NOT_SUPPORTED", - "E_APPLY_DUPLICATE_TRIGGER", - "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", - "E_APPLY_DISABLED_ANCESTOR", - "E_APPLY_CREDENTIAL_UNREACHABLE", - "W_APPLY_CREDENTIAL_KEPT", - "E_APPLY_SANDBOX_PLAN_REQUIRED", - "W_APPLY_HOSTED_KEY_DROPPED", - "W_APPLY_VALUE_NORMALIZED", - "W_APPLY_TYPE_CHANGED", - "W_APPLY_TRIGGER_REMOVED", - "W_APPLY_CATALOG_MOVED", - "W_APPLY_PROBABLE_RENAME", - "E_APPLY_LINT", - "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", - "W_APPLY_LINT", - "W_TABLE_UNKNOWN_COLUMN", - "E_APPLY_INVALID_SCHEDULE", - "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" - ], - "description": "Diagnostic code." - }, - "message": { - "type": "string", - "description": "What failed." - } - }, - "required": ["kind", "key", "code", "message"], - "additionalProperties": false + "type": "string", + "enum": [ + "airtable.bases", + "airtable.tables", + "asana.workspaces", + "attio.lists", + "attio.objects", + "bigquery.datasets", + "bigquery.tables", + "bitbucket.workspaces", + "bitbucket.repositories", + "calcom.eventTypes", + "calcom.schedules", + "clickup.workspaces", + "clickup.spaces", + "clickup.folders", + "clickup.lists", + "coda.docs", + "coda.pages", + "coda.tables", + "coda.columns", + "coda.rows", + "coda.formulas", + "coda.controls", + "coda.folders", + "coda.permissions", + "confluence.spaces", + "confluence.spacesById", + "confluence.pages", + "google.tasks.lists", + "gauge.organizations", + "gauge.categories", + "gauge.topics", + "gauge.prompts", + "gauge.tags", + "gauge.answers", + "fivetran.groups", + "fivetran.connections", + "gmail.labels", + "google.calendar", + "google.drive", + "google.sheets", + "harmonic.savedSearches", + "jama.projects", + "jama.itemTypes", + "flow.projects", + "flow.categories", + "flow.branches", + "helpscout.mailboxes", + "helpscout.assignees", + "hubspot.lists", + "hubspot.owners", + "hubspot.pipelines", + "hubspot.pipelineStages", + "hubspot.properties", + "jsm.requestTypes", + "jsm.serviceDesks", + "microsoft.planner.plans", + "notion.databases", + "notion.pages", + "netsuite.recordTypes", + "netsuite.asyncTasks", + "pipedrive.pipelines", + "sharepoint.lists", + "trello.boards", + "zoho_desk.organizations", + "zoho_desk.departments", + "zoho_desk.agents", + "zoom.meetings", + "slack.channels", + "snowflake.databases", + "snowflake.schemas", + "snowflake.tables", + "snowflake.warehouses", + "snowflake.roles", + "snowflake.fileFormats", + "snowflake.procedures", + "slack.users", + "outlook.folders", + "outlook.calendars", + "microsoft.teams", + "microsoft.chats", + "microsoft.channels", + "microsoft.planner", + "onedrive.files", + "onedrive.folders", + "sharepoint.sites", + "microsoft.excel", + "microsoft.excel.drives", + "microsoft.excel.sheets", + "microsoft.word", + "wealthbox.contacts", + "jira.issues", + "jira.projects", + "jira.projectKeys", + "linear.projects", + "linear.teams", + "monday.boards", + "monday.groups", + "webflow.sites", + "webflow.collections", + "webflow.items", + "planetscale.databases", + "powerbi.workspaces", + "powerbi.datasets", + "powerbi.reports", + "planetscale.branches", + "planetscale.backups", + "planetscale.deployRequests", + "planetscale.savedDatabases", + "planetscale.savedBranches", + "planetscale.savedBackups", + "planetscale.savedDeployRequests", + "cloudwatch.logGroups", + "cloudwatch.logStreams", + "cloudwatch.savedLogGroups", + "cloudwatch.savedLogStreams", + "imap.mailboxes", + "mcp.tools", + "managedAgent.agents", + "managedAgent.environments", + "managedAgent.vaults", + "managedAgent.memoryStores", + "knowledge.documents", + "sim.workflows", + "table.columns", + "table.outputColumns", + "workspace.secretNames", + "workspace.sandboxes", + "providers.ollamaEmbeddingModels", + "providers.openrouterEmbeddingModels" + ], + "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + }, + "context": { + "default": {}, + "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + } + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Provider option ID to resolve with the same selector and declared context." + } + }, + "required": ["workspaceId", "selectorKey", "id"], + "additionalProperties": false, + "title": "Get selector request", + "description": "Workspace, registered selector key, context, and provider option ID." + }, + "GetWorkspaceOperationResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace operation response", + "description": "Refreshed commit, copy progress, and exact deployment readiness." + }, + "ListWorkspaceOperationsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkspaceOperationReport" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" }, - "needBlobs": { + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace operations response", + "description": "A page of stored operation receipts." + }, + "GetWorkspaceSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "kinds": { "type": "array", "items": { - "type": "string" + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." }, - "description": "Binary paths a write needs whose bytes are not staged: on a dry run, exactly what to stage before applying." - }, - "applyId": { - "description": "The id of an apply that wrote: every audit log entry its writes recorded carries it as `metadata.correlationId`. Absent on a dry run.", - "type": "string" + "description": "The kinds read; the directory manages exactly these." }, "files": { "type": "object", @@ -27308,7 +24924,47 @@ "additionalProperties": { "type": "string" }, - "description": "Files re-printed from what was saved, for every resource written." + "description": "Directory path → file text." + }, + "blobs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Directory path of the binary file." + }, + "sha256": { + "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 0, + "maximum": 10000000, + "description": "Bytes." + }, + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "href": { + "type": "string", + "description": "Where to download its bytes." + }, + "rev": { + "description": "Content revision, present when `sha256` is absent.", + "type": "string" + } + }, + "required": ["path", "size", "id", "href"], + "additionalProperties": false + }, + "description": "Binary files, downloaded separately by `href`." }, "base": { "type": "object", @@ -27436,7 +25092,42 @@ "additionalProperties": { "description": "An `x-` extension field, kept as written." }, - "description": "The base after this apply: the next apply’s `base`." + "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." + }, + "skipped": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "reason": { + "type": "string", + "description": "Why it was left out." + } + }, + "required": ["kind", "key", "reason"], + "additionalProperties": false + }, + "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." }, "diagnostics": { "type": "array", @@ -27518,6 +25209,8 @@ "E_DEPLOY_CHAT_IDENTIFIER", "E_DEPLOY_PINNED_CHAT", "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", "I_DEPLOY_DRAFT_NOT_LIVE", "E_APPLY_STALE", "E_APPLY_NO_BASE", @@ -27536,9 +25229,9 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", - "I_SERVER_CHANGED", - "I_SERVER_DELETED", - "I_SERVER_MOVED", + "W_SERVER_CHANGED", + "W_SERVER_DELETED", + "W_SERVER_MOVED", "I_KEY_REBOUND", "E_KEY_RENAMED", "I_FINDINGS_TRUNCATED", @@ -27574,8 +25267,6 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", - "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -27685,13 +25376,10 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", - "E_APPLY_REF_OUT_OF_SCOPE", - "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", - "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." @@ -27729,384 +25417,101 @@ "description": "1-based line the finding ends on.", "type": "integer", "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "endColumn": { - "description": "1-based column the finding ends at.", - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "frame": { - "description": "The source lines around the finding, with a caret row.", - "type": "string" - }, - "path": { - "description": "JSON Pointer into a JSON file, such as the base.", - "type": "string" - }, - "kind": { - "description": "Kind of the resource the finding is about.", - "type": "string" - }, - "key": { - "description": "Key of the resource the finding is about.", - "type": "string" - }, - "blockKey": { - "description": "Workflow block the finding is about.", - "type": "string" - }, - "param": { - "description": "Block field the finding is about.", - "type": "string" - } - }, - "required": ["code", "severity", "message"], - "additionalProperties": false, - "description": "A finding about the directory, pinned to its file when it has one." - }, - "description": "Warnings, and on a dry run every error." - } - }, - "required": [ - "workspaceId", - "dryRun", - "plan", - "applied", - "needBlobs", - "files", - "base", - "diagnostics" - ], - "additionalProperties": false, - "description": "Response data." - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Apply workspace source response", - "description": "The plan, what was written, and the files re-printed from it.", - "examples": [ - { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, - "plan": [ - { - "kind": "table", - "key": "leads", - "action": "noop", - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" - } - ], - "applied": [], - "needBlobs": [], - "files": {}, - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } - } - } - } - } - }, - "diagnostics": [] - } - } - ] - }, - "ApplyWorkspaceSourceBody": { - "type": "object", - "properties": { - "files": { - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 1024 - }, - "additionalProperties": { - "type": "string" - }, - "description": "Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged." - }, - "blobs": { - "description": "Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.", - "maxItems": 20000, - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Directory path of the binary file." - }, - "sha256": { - "type": "string", - "pattern": "^[0-9a-f]{64}$", - "description": "SHA-256 of the bytes, lowercase hex." - }, - "size": { - "type": "integer", - "minimum": 0, - "maximum": 10000000, - "description": "Bytes." - } - }, - "required": ["path", "sha256", "size"], - "additionalProperties": false - } - }, - "base": { - "type": "object", - "properties": { - "version": { - "type": "number", - "const": 1, - "description": "Base format version." - }, - "workspaceId": { - "type": "string", - "description": "Workspace the directory was read from." - }, - "resources": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored id the key is bound to." - }, - "fingerprint": { - "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", - "type": "string" - }, - "columns": { - "description": "Table column key → stored column.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored column id." - }, - "options": { - "description": "Select option name → option id.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "string" - } - } - }, - "required": ["id"] - } + "maximum": 9007199254740991 }, - "blobs": { - "description": "Binary file name → its stored id, revision and hash as last read.", - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Stored id of the binary file." - }, - "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], - "description": "Content revision as last read." - }, - "sha256": { - "type": "string", - "pattern": "^[0-9a-f]{64}$", - "description": "SHA-256 of the bytes, lowercase hex." - } - }, - "required": ["id", "rev", "sha256"] - } + "endColumn": { + "description": "1-based column the finding ends at.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "rows": { - "description": "A table’s managed rows, as last read.", - "type": "object", - "properties": { - "fingerprint": { - "type": "string", - "description": "`rf1:` fingerprint of the managed rows as last read." - }, - "version": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "The table’s row version as last read; it moves on every row write." - } - }, - "required": ["fingerprint", "version"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - } + "frame": { + "description": "The source lines around the finding, with a caret row.", + "type": "string" + }, + "path": { + "description": "JSON Pointer into a JSON file, such as the base.", + "type": "string" + }, + "kind": { + "description": "Kind of the resource the finding is about.", + "type": "string" + }, + "key": { + "description": "Key of the resource the finding is about.", + "type": "string" + }, + "blockKey": { + "description": "Workflow block the finding is about.", + "type": "string" + }, + "param": { + "description": "Block field the finding is about.", + "type": "string" } }, - "required": ["id"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - }, - "description": "One resource in the base." + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding about the directory, pinned to its file when it has one." }, - "description": "`kind:key` → the stored resource and its fingerprint." - } - }, - "required": ["version", "workspaceId", "resources"], - "additionalProperties": { - "description": "An `x-` extension field, kept as written." - }, - "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." - }, - "kinds": { - "maxItems": 10, - "type": "array", - "items": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "description": "The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent." - }, - "options": { - "description": "How far the apply may go.", - "type": "object", - "properties": { - "allowDelete": { - "description": "Delete resources, columns and data the directory no longer declares.", - "type": "boolean" - }, - "only": { - "description": "Apply only these kinds.", - "type": "array", - "items": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - } - } - }, - "additionalProperties": false - }, - "provenance": { - "description": "Where the directory came from, for the audit log.", - "type": "object", - "properties": { - "client": { - "type": "string", - "enum": ["cli", "api"], - "description": "What submitted the directory." - }, - "gitSha": { - "description": "The commit the directory was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" + "description": "Findings from reading." } }, - "required": ["client"], - "additionalProperties": false + "required": [ + "workspaceId", + "kinds", + "files", + "blobs", + "base", + "skipped", + "diagnostics" + ], + "additionalProperties": false, + "description": "Response data." } }, - "required": ["files", "kinds"], + "required": ["data"], "additionalProperties": false, - "title": "Apply workspace source body", - "description": "The directory files, its managed kinds and the base they were read with.", + "title": "Get workspace source response", + "description": "The workspace as a source directory.", "examples": [ { - "files": { - "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" - }, - "kinds": ["table"], - "base": { - "version": 1, + "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" + "kinds": ["table", "workflow"], + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "blobs": [], + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } } } } } - } + }, + "skipped": [], + "diagnostics": [] } } ] }, - "PlanWorkspaceSourceResponse": { + "ApplyWorkspaceSourceResponse": { "type": "object", "properties": { "data": { @@ -28373,6 +25778,8 @@ "E_DEPLOY_CHAT_IDENTIFIER", "E_DEPLOY_PINNED_CHAT", "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", "I_DEPLOY_DRAFT_NOT_LIVE", "E_APPLY_STALE", "E_APPLY_NO_BASE", @@ -28391,9 +25798,9 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", - "I_SERVER_CHANGED", - "I_SERVER_DELETED", - "I_SERVER_MOVED", + "W_SERVER_CHANGED", + "W_SERVER_DELETED", + "W_SERVER_MOVED", "I_KEY_REBOUND", "E_KEY_RENAMED", "I_FINDINGS_TRUNCATED", @@ -28803,11 +26210,9 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", - "W_PROMOTE_TARGET_DELETED", - "W_PROMOTE_DELETES_TARGET_ONLY", - "I_SERVER_CHANGED", - "I_SERVER_DELETED", - "I_SERVER_MOVED", + "W_SERVER_CHANGED", + "W_SERVER_DELETED", + "W_SERVER_MOVED", "I_KEY_REBOUND", "E_KEY_RENAMED", "I_FINDINGS_TRUNCATED", @@ -29049,13 +26454,13 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Plan workspace source response", - "description": "The plan an apply would carry out.", + "title": "Apply workspace source response", + "description": "The plan, what was written, and the files re-printed from it.", "examples": [ { "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": true, + "dryRun": false, "plan": [ { "kind": "table", @@ -29094,7 +26499,7 @@ } ] }, - "PlanWorkspaceSourceBody": { + "ApplyWorkspaceSourceBody": { "type": "object", "properties": { "files": { @@ -29315,11 +26720,29 @@ } }, "additionalProperties": false + }, + "provenance": { + "description": "Where the directory came from, for the audit log.", + "type": "object", + "properties": { + "client": { + "type": "string", + "enum": ["cli", "api"], + "description": "What submitted the directory." + }, + "gitSha": { + "description": "The commit the directory was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" + } + }, + "required": ["client"], + "additionalProperties": false } }, "required": ["files", "kinds"], "additionalProperties": false, - "title": "Plan workspace source body", + "title": "Apply workspace source body", "description": "The directory files, its managed kinds and the base they were read with.", "examples": [ { diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index c2c72dc1bce..56350785cf3 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -444,7 +444,7 @@ describe('workspace source apply', () => { const untouched = await apply(workspaceId, read.files, { base: read.base }) expect(untouched.applied).toEqual([]) - expect(codes(untouched.diagnostics, 'info')).toContain('I_SERVER_CHANGED') + expect(codes(untouched.diagnostics, 'warning')).toContain('W_SERVER_CHANGED') expect(await tableSnapshot(workspaceId)).toEqual(before) } ) @@ -563,7 +563,7 @@ describe('workspace source apply', () => { const untouched = await apply(workspaceId, read.files, { base: read.base, only: ['table'] }) expect(untouched.applied).toEqual([]) - expect(codes(untouched.diagnostics, 'info')).toContain('I_SERVER_DELETED') + expect(codes(untouched.diagnostics, 'warning')).toContain('W_SERVER_DELETED') expect(await tables(workspaceId)).toEqual([]) const { 'table:leads': _deleted, ...resources } = read.base.resources diff --git a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts index d1cc50a3570..3dc509ad6d5 100644 --- a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts +++ b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts @@ -477,14 +477,14 @@ describe('workspace source across kinds', () => { expect(writes(unchanged)).toEqual([]) expect(unchanged.needBlobs).toEqual([]) - expect(findings(unchanged.diagnostics, 'info')).toEqual( + expect(findings(unchanged.diagnostics, 'warning')).toEqual( [ - 'I_SERVER_DELETED custom-tool:lookup', - 'I_SERVER_DELETED file:notes.txt', - 'I_SERVER_DELETED knowledge-base:policies', - 'I_SERVER_DELETED skill:tone', - 'I_SERVER_DELETED table:leads', - 'I_SERVER_DELETED workflow:ingest', + 'W_SERVER_DELETED custom-tool:lookup', + 'W_SERVER_DELETED file:notes.txt', + 'W_SERVER_DELETED knowledge-base:policies', + 'W_SERVER_DELETED skill:tone', + 'W_SERVER_DELETED table:leads', + 'W_SERVER_DELETED workflow:ingest', ].sort(compareStrings) ) expect(await snapshot(workspaceId)).toEqual(empty) diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index 0b3804fc19c..f90e654f367 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -1032,7 +1032,7 @@ describe('workspace source: deployments', () => { ) expect(codes(stale.diagnostics)).toEqual(['E_APPLY_STALE']) const unchanged = await apply(workspaceId, files, { base }) - expect(codes(unchanged.diagnostics, 'info')).toContain('I_SERVER_CHANGED') + expect(codes(unchanged.diagnostics, 'warning')).toContain('W_SERVER_CHANGED') }) check('warns when an apply edits a deployed workflow no deployment file covers', async () => { diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index b049c8cce33..2568dbcb76f 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -321,7 +321,7 @@ describe('workspace source files', () => { const unchanged = await apply(workspaceId, STARTER, { base: read.base }) expect(summary(unchanged.plan)).toEqual(['noop notes.txt', 'noop docs/plan.md']) - expect(codes(unchanged.diagnostics, 'info')).toEqual(['I_SERVER_CHANGED']) + expect(codes(unchanged.diagnostics, 'warning')).toEqual(['W_SERVER_CHANGED']) const refused = await refusal( apply( @@ -728,7 +728,7 @@ describe('workspace source files', () => { 'noop docs/plan.md', 'noop renamed.txt', ]) - const moved = unchanged.diagnostics.find((finding) => finding.code === 'I_SERVER_MOVED') + const moved = unchanged.diagnostics.find((finding) => finding.code === 'W_SERVER_MOVED') expect(moved?.message).toContain('files/renamed.txt') expect(unchanged.needBlobs).toEqual([]) @@ -1030,10 +1030,10 @@ export default workflow('Reader', {}, () => { expect( unchanged.diagnostics - .filter((finding) => finding.code === 'I_SERVER_CHANGED') + .filter((finding) => finding.code === 'W_SERVER_CHANGED') .map((finding) => `${finding.code} ${finding.key}`) .sort() - ).toEqual(['I_SERVER_CHANGED docs/plan.md', 'I_SERVER_CHANGED notes.txt']) + ).toEqual(['W_SERVER_CHANGED docs/plan.md', 'W_SERVER_CHANGED notes.txt']) expect(unchanged.applied).toEqual([]) expect(await storedFiles(workspaceId)).toEqual(before) diff --git a/apps/sim/lib/workspace-source/application/findings.ts b/apps/sim/lib/workspace-source/application/findings.ts index 95e50564369..de2a3a4aa27 100644 --- a/apps/sim/lib/workspace-source/application/findings.ts +++ b/apps/sim/lib/workspace-source/application/findings.ts @@ -109,13 +109,21 @@ export function unreadAdoptFinding( ) } -/** `I_SERVER_CHANGED`: the server drifted; the directory leaves the resource as it is. */ +/** How to bring a change made on the server into the directory. */ +export const DRIFT_HINT = + 'Run `sim workspaces source get` into a fresh directory to see what changed.' + +/** + * `W_SERVER_CHANGED`: the server drifted from the directory, which leaves the resource as the + * server has it: the apply keeps the server's version and never reverts it. + */ export function serverChangedFinding(kind: WorkspaceKind, key: string): WorkspaceSourceDiagnostic { return kindFinding( kind, key, - 'I_SERVER_CHANGED', - `${where(kind, key)} changed on the server; this directory leaves it as it is, and the next get shows the change.` + 'W_SERVER_CHANGED', + `${where(kind, key)} changed on the server since this directory was read; the apply keeps the server's version (not reverted).`, + { hint: DRIFT_HINT } ) } @@ -212,8 +220,9 @@ export function serverGoneFinding( return kindFinding( kind, key, - movedTo === undefined ? 'I_SERVER_DELETED' : 'I_SERVER_MOVED', - `${where(kind, key)} was ${gone}; this directory does not create it again, and the next get shows that.` + movedTo === undefined ? 'W_SERVER_DELETED' : 'W_SERVER_MOVED', + `${where(kind, key)} was ${gone}; the apply keeps it that way (not created again).`, + { hint: DRIFT_HINT } ) } diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index a1b4e83119c..91d8b8e2aa6 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -9,7 +9,7 @@ * 409, re-checked under the workflow row lock), which keeps the folder appliable on its own with * `sim workflows source apply`. The root base's fingerprint only guards a delete. * - A folder sent unchanged (only its base, `isUnchanged`) is a no-op with no drift check, so it - * never reports `I_SERVER_CHANGED`. The workflow's fingerprint hashes its canonicalized stored + * never reports `W_SERVER_CHANGED`. The workflow's fingerprint hashes its canonicalized stored * graph, so telling whether it drifted means reading and canonicalizing every declared workflow * on every apply, the cost the unchanged folder exists to avoid; no cheaper stored token tracks * it (the row's `updatedAt` also moves on a drag or a resize, which source never shows). The diff --git a/apps/sim/lib/workspace-source/application/knowledge.integration.ts b/apps/sim/lib/workspace-source/application/knowledge.integration.ts index 436c51b0d8e..8deeafbc44e 100644 --- a/apps/sim/lib/workspace-source/application/knowledge.integration.ts +++ b/apps/sim/lib/workspace-source/application/knowledge.integration.ts @@ -711,7 +711,7 @@ describe('knowledge bases as workspace source', () => { const untouched = await apply(workspaceId, dir, { base: read.base, carry: 'none' }) expect(untouched.applied).toEqual([]) - expect(codes(untouched.diagnostics, 'info')).toContain('I_SERVER_CHANGED') + expect(codes(untouched.diagnostics, 'warning')).toContain('W_SERVER_CHANGED') expect(await snapshot(workspaceId)).toEqual(before) } ) @@ -1299,7 +1299,7 @@ describe('knowledge bases as workspace source', () => { const unchanged = await apply(workspaceId, dir, { base: read.base, carry: 'none' }) expect(unchanged.applied).toEqual([]) - expect(codes(unchanged.diagnostics, 'info')).toEqual(['I_SERVER_CHANGED']) + expect(codes(unchanged.diagnostics, 'warning')).toEqual(['W_SERVER_CHANGED']) expect(await snapshot(workspaceId)).toEqual(before) const stale = await refusal( diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index 15d0fa58ec9..08907ef7914 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -694,8 +694,8 @@ describe('MCP servers as workspace source', () => { }) const gone = await apply(workspaceId, edited.files, { base: edited.base }) expect(findings(gone.diagnostics, 'error')).toEqual([]) - expect(findings(gone.diagnostics, 'info')).toEqual([ - `I_SERVER_DELETED mcp-server:${path.slice(4, -3)}`, + expect(findings(gone.diagnostics, 'warning')).toEqual([ + `W_SERVER_DELETED mcp-server:${path.slice(4, -3)}`, ]) expect(gone.applied).toEqual([]) } diff --git a/apps/sim/lib/workspace-source/application/promote.integration.ts b/apps/sim/lib/workspace-source/application/promote.integration.ts index 2813a116021..6f878503ba4 100644 --- a/apps/sim/lib/workspace-source/application/promote.integration.ts +++ b/apps/sim/lib/workspace-source/application/promote.integration.ts @@ -310,9 +310,9 @@ describe('workspace source promotion', () => { const untouched = await promoteRecorded(await runner.get(dev), prod, first.record) expect(untouched.result.applied).toEqual([]) - expect(codes(untouched.result.diagnostics, 'info').sort()).toEqual([ - 'I_SERVER_DELETED', - 'I_SERVER_DELETED', + expect(codes(untouched.result.diagnostics, 'warning').sort()).toEqual([ + 'W_SERVER_DELETED', + 'W_SERVER_DELETED', ]) expect((await liveWorkflows(prod)).map((row) => row.name)).toEqual(['Ingest']) expect((await runner.get(prod)).files['skills/tone.md']).toBeUndefined() diff --git a/apps/sim/lib/workspace-source/application/tools-skills.integration.ts b/apps/sim/lib/workspace-source/application/tools-skills.integration.ts index dbbabf5bb18..ea3d93b5496 100644 --- a/apps/sim/lib/workspace-source/application/tools-skills.integration.ts +++ b/apps/sim/lib/workspace-source/application/tools-skills.integration.ts @@ -347,7 +347,10 @@ describe('workspace source: custom tools and skills', () => { const untouched = await apply(workspaceId, read.files, { base: read.base }) expect(untouched.applied).toEqual([]) - expect(codes(untouched.diagnostics, 'info')).toEqual(['I_SERVER_CHANGED', 'I_SERVER_CHANGED']) + expect(codes(untouched.diagnostics, 'warning')).toEqual([ + 'W_SERVER_CHANGED', + 'W_SERVER_CHANGED', + ]) }) check('refuses a title another tool holds, naming its key, and an invalid schema', async () => { @@ -582,7 +585,7 @@ describe('workspace source: custom tools and skills', () => { const untouched = await apply(workspaceId, read.files, { base: read.base }) expect(untouched.applied).toEqual([]) - expect(codes(untouched.diagnostics, 'info')).toContain('I_SERVER_DELETED') + expect(codes(untouched.diagnostics, 'warning')).toContain('W_SERVER_DELETED') expect((await snapshot(workspaceId)).skills).toEqual([]) const { 'skill:tone': _deleted, ...resources } = read.base.resources @@ -962,7 +965,7 @@ describe('workspace source: custom tools and skills', () => { { base: retitled.base } ) expect(codes(gone.diagnostics)).toEqual([]) - expect(codes(gone.diagnostics, 'info')).toEqual(['I_SERVER_DELETED']) + expect(codes(gone.diagnostics, 'warning')).toEqual(['W_SERVER_DELETED']) expect(gone.applied).toEqual([]) } ) 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 e9398915942..12ff529156f 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 @@ -163,6 +163,42 @@ describe('workspaces source apply', () => { expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toContain('+ leads') }) + it('counts and lists a resource the server changed or deleted, never as unchanged, and keeps its warning in the JSON', async () => { + const drift = (code: string, kind: string, key: string) => ({ + code, + severity: 'warning', + message: `${kind} ${key} drifted.`, + kind, + key, + }) + request.mockResolvedValue( + answer({ + dryRun: true, + plan: [ + { kind: 'skill', key: 'tone', action: 'noop' }, + { kind: 'file', key: 'notes.txt', action: 'noop' }, + { kind: 'file', key: 'partial.txt', action: 'noop' }, + ], + diagnostics: [ + drift('W_SERVER_CHANGED', 'skill', 'tone'), + drift('W_SERVER_DELETED', 'file', 'partial.txt'), + ], + }) + ) + + await apply('--dry-run') + + const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + expect(stderr).toContain('skills: 1 changed on the server') + expect(stderr).toContain('files: 1 unchanged, 1 deleted on the server') + expect(stderr).toContain(' ! partial.txt (deleted on the server; kept as the server has it)') + const printed = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect(printed.diagnostics.map((finding: { code: string }) => finding.code)).toEqual([ + 'W_SERVER_CHANGED', + 'W_SERVER_DELETED', + ]) + }) + it('puts each finding of a dry run in the JSON on stdout', async () => { const finding = { code: 'E_DECL_SHAPE', @@ -479,9 +515,9 @@ describe('workspaces source apply', () => { ], diagnostics: [ { - code: 'I_SERVER_DELETED', - severity: 'info', - message: 'tables/gone was deleted on the server; the next get shows that.', + code: 'W_SERVER_DELETED', + severity: 'warning', + message: 'tables/gone was deleted on the server; the apply keeps it deleted.', kind: 'table', key: 'gone', }, @@ -505,7 +541,7 @@ describe('workspaces source apply', () => { expect(byCode('W_PROMOTE_TARGET_DELETED')).toEqual([ expect.objectContaining({ kind: 'table', key: 'gone' }), ]) - expect(byCode('I_SERVER_DELETED')).toEqual([]) + expect(byCode('W_SERVER_DELETED')).toEqual([]) expect(byCode('W_PROMOTE_DELETES_TARGET_ONLY')).toEqual([ expect.objectContaining({ kind: 'table', key: 'prod-only' }), ]) 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 6ecd17463e3..47dd4eedf30 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -19,6 +19,7 @@ import { promotionRecordPath, promotionSubmission, } from '@sim/workspace-code/promote' +import { serverResourceChanges } from '@sim/workspace-code/status' import type { Command } from 'commander' import { printError } from '#sim-cli/output/io' import { DEFERRED_INTERRUPT_BOUND_MS, deferInterrupts } from '#sim-cli/terminal/interrupts' @@ -181,19 +182,51 @@ function outcomeText(change: Change, outcome: PlanOutcome): string { } /** - * The plan as a person reads it: per kind, the counts, then each change with what it touches. + * The plan as a person reads it: per kind, the counts, then each change with what it touches. A + * resource the apply leaves alone that the server changed, deleted or moved since the directory + * was read (`diagnostics` say which) counts as that, never as unchanged, and is listed with `!`. * With `outcome` (an apply that stopped part-way), each change says whether it was written. */ -function printPlan(plan: Change[], outcome?: PlanOutcome): void { +function printPlan( + plan: Change[], + diagnostics: ApplyData['diagnostics'], + outcome?: PlanOutcome +): void { + const drifted = new Map( + serverResourceChanges(diagnostics) + .filter((change) => change.server !== 'added') + .map((change) => [`${change.kind}:${change.key}`, change.server]) + ) + // A promotion reports the target's delete as W_PROMOTE_TARGET_DELETED in place of the server's W_SERVER_DELETED. + for (const finding of diagnostics) { + if (finding.code === 'W_PROMOTE_TARGET_DELETED' && finding.kind && finding.key) { + drifted.set(`${finding.kind}:${finding.key}`, 'deleted') + } + } + const driftOf = (change: Change) => + change.action === 'noop' ? drifted.get(`${change.kind}:${change.key}`) : undefined for (const kind of APPLY_ORDER) { const changes = plan.filter((change) => change.kind === kind) if (changes.length === 0) continue const counts = new Map() - for (const change of changes) counts.set(change.action, (counts.get(change.action) ?? 0) + 1) + for (const change of changes) { + const drift = driftOf(change) + const label = drift + ? `${drift} on the server` + : change.action === 'noop' + ? 'unchanged' + : change.action + counts.set(label, (counts.get(label) ?? 0) + 1) + } printError( - `${KIND_DIRS[kind]}: ${[...counts].map(([action, count]) => `${count} ${action === 'noop' ? 'unchanged' : action}`).join(', ')}` + `${KIND_DIRS[kind]}: ${[...counts].map(([label, count]) => `${count} ${label}`).join(', ')}` ) for (const change of changes) { + const drift = driftOf(change) + if (drift) { + printError(` ! ${change.key} (${drift} on the server; kept as the server has it)`) + continue + } if (change.action === 'noop') continue const fields = change.fields && change.fields.length > 0 ? ` (${change.fields.join(', ')})` : '' @@ -525,13 +558,13 @@ function promotionHint(code: string, target: string): string | undefined { /** * The server's findings as a promotion reports them: refusals carry the promotion's hint, and the - * server's `I_SERVER_DELETED` for a resource the promotion warns about itself + * server's `W_SERVER_DELETED` for a resource the promotion warns about itself * (`W_PROMOTE_TARGET_DELETED`) is left out. */ function promotionDiagnostics(diagnostics: readonly Finding[], promotion: Promotion): Finding[] { const warned = new Set(promotion.deletedInTarget) return diagnostics.flatMap((finding) => { - if (finding.code === 'I_SERVER_DELETED' && warned.has(`${finding.kind}:${finding.key}`)) { + if (finding.code === 'W_SERVER_DELETED' && warned.has(`${finding.kind}:${finding.key}`)) { return [] } const hint = promotionHint(finding.code, promotion.target) @@ -744,7 +777,7 @@ export function attachWorkspaceSourceApply(source: Command): void { let preview: ApplyData | null = null if (mode !== 'write') { preview = reported(await send(submission, true)) - printPlan(preview.plan) + printPlan(preview.plan, preview.diagnostics) printTargetOnlyDeletes(promotion, preview.plan) findings.print(preview.diagnostics) const errors = preview.diagnostics.some((finding) => finding.severity === 'error') @@ -791,8 +824,8 @@ export function attachWorkspaceSourceApply(source: Command): void { ) if (data.failed) { printError('The apply stopped part-way; each planned change:') - printPlan(data.plan, data) - } else if (mode === 'write') printPlan(data.plan) + printPlan(data.plan, data.diagnostics, data) + } else if (mode === 'write') printPlan(data.plan, data.diagnostics) const held = data.plan.filter((change) => change.held) if (held.length > 0) { printError( 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 878bdfb9733..8088ed0bd14 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 @@ -435,7 +435,13 @@ describe('workspaces source status', () => { dryRun( [{ kind: 'workflow', key: 'ingest', action: 'noop' }], [ - { code: 'I_SERVER_CHANGED', severity: 'info', message: 'm', kind: 'table', key: 'leads' }, + { + code: 'W_SERVER_CHANGED', + severity: 'warning', + message: 'm', + kind: 'table', + key: 'leads', + }, { code: 'E_APPLY_STALE', severity: 'error', diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 0eb3b360e87..de6fa7529de 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -844,8 +844,6 @@ export type ApplyWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -956,13 +954,10 @@ export type ApplyWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -1301,11 +1296,9 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' - | 'W_PROMOTE_TARGET_DELETED' - | 'W_PROMOTE_DELETES_TARGET_ONLY' - | 'I_SERVER_CHANGED' - | 'I_SERVER_DELETED' - | 'I_SERVER_MOVED' + | 'W_SERVER_CHANGED' + | 'W_SERVER_DELETED' + | 'W_SERVER_MOVED' | 'I_KEY_REBOUND' | 'E_KEY_RENAMED' | 'I_FINDINGS_TRUNCATED' @@ -1341,8 +1334,6 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1452,13 +1443,10 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' message: string } @@ -1592,11 +1580,9 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' - | 'W_PROMOTE_TARGET_DELETED' - | 'W_PROMOTE_DELETES_TARGET_ONLY' - | 'I_SERVER_CHANGED' - | 'I_SERVER_DELETED' - | 'I_SERVER_MOVED' + | 'W_SERVER_CHANGED' + | 'W_SERVER_DELETED' + | 'W_SERVER_MOVED' | 'I_KEY_REBOUND' | 'E_KEY_RENAMED' | 'I_FINDINGS_TRUNCATED' @@ -1632,8 +1618,6 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1743,13 +1727,10 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -5298,8 +5279,6 @@ export type CreateWorkflowFromSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -5410,13 +5389,10 @@ export type CreateWorkflowFromSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -10400,8 +10376,6 @@ export type GetWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -10512,13 +10486,10 @@ export type GetWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -11052,11 +11023,9 @@ export type GetWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' - | 'W_PROMOTE_TARGET_DELETED' - | 'W_PROMOTE_DELETES_TARGET_ONLY' - | 'I_SERVER_CHANGED' - | 'I_SERVER_DELETED' - | 'I_SERVER_MOVED' + | 'W_SERVER_CHANGED' + | 'W_SERVER_DELETED' + | 'W_SERVER_MOVED' | 'I_KEY_REBOUND' | 'E_KEY_RENAMED' | 'I_FINDINGS_TRUNCATED' @@ -11092,8 +11061,6 @@ export type GetWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' - | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -11203,13 +11170,10 @@ export type GetWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' - | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -14283,995 +14247,6 @@ export type MoveWorkflowsResponse = { data: MoveWorkflowsResponseRef0 } -/** `POST /api/v2/workflows/[workflowId]/source/plan` */ -export type PlanWorkflowSourceParams = { - workflowId: string -} - -export type PlanWorkflowSourceQuery = { - allowDelete?: boolean -} - -export type PlanWorkflowSourceBody = { - files: Record - lock: { - version: 1 - blocks: Record< - string, - { - id: string - parent: string | null - branches?: Record - items?: Record< - string, - Array<{ - name: string - id: string - }> - > - ident: string - order: number - layout?: { - x: number - y: number - w?: number - h?: number - height?: number - horizontalHandles?: boolean - [key: string]: unknown - } - codeFile?: string - [key: string]: unknown - } - > - variables: Record - [key: string]: unknown - } - base: { - version?: 1 - workflowId: string - workspaceId: string - fingerprint: string - catalogHash: string - [key: string]: unknown - } -} - -export type PlanWorkflowSourceResponse = { - data: { - workflowId: string - workspaceId: string - dryRun: boolean - applied: boolean - diff: { - noop: boolean - meta?: Array<'name' | 'description'> - blocks: { - added: Array<{ - id: string - key: string - type: string - }> - removed: Array<{ - id: string - key: string - type: string - }> - renamed: Array<{ - id: string - from: string - to: string - }> - modified: Array<{ - id: string - key: string - fields: Array - reparented?: boolean - }> - } - edges: { - added: number - removed: number - } - variables: { - added: Array - removed: Array - modified: Array - } - } - diagnostics: Array<{ - code: - | 'E_SYNTAX' - | 'E_SDK_HEADER' - | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' - | 'E_UNSUPPORTED_SYNTAX' - | 'E_WORKFLOW_EXPORT' - | 'E_LIMIT_EXCEEDED' - | 'E_INVALID_CHARACTER' - | 'E_NUMBER_NOT_FINITE' - | 'W_NUMBER_PRECISION' - | 'E_TOO_MANY_ERRORS' - | 'W_TOO_MANY_WARNINGS' - | 'E_DUPLICATE_NAME' - | 'E_RESERVED_NAME' - | 'E_KEY_OVERRIDE' - | 'E_EMPTY_NAME' - | 'E_LOOKALIKE_NAME' - | 'W_LOOKALIKE_NAME' - | 'W_SUSPICIOUS_CHARACTER' - | 'E_NAME_NOT_LITERAL' - | 'E_UNKNOWN_IDENTIFIER' - | 'E_OUT_OF_SCOPE' - | 'E_UNKNOWN_VARIABLE' - | 'E_DUPLICATE_VARIABLE' - | 'E_VARIABLE_NAME_MISMATCH' - | 'E_INVALID_ENV_NAME' - | 'W_ENV_UNKNOWN' - | 'W_CHILD_INPUT_UNKNOWN' - | 'W_CHILD_NO_START' - | 'E_UNKNOWN_SUBFLOW_PROPERTY' - | 'W_FORWARD_REF' - | 'W_REF_NOT_NORMALIZED' - | 'E_REF_UNREPRESENTABLE' - | 'E_EDGE_SCOPE' - | 'E_EDGE_NOTE' - | 'E_TARGET_TRIGGER' - | 'E_NO_DEFAULT_OUTPUT' - | 'E_DUPLICATE_EDGE' - | 'E_ERROR_PORT_UNSUPPORTED' - | 'W_ERROR_PORT_STORED' - | 'E_UNKNOWN_BRANCH' - | 'E_DUPLICATE_BRANCH_KEY' - | 'E_BRANCH_KEY_COLLIDES' - | 'E_BRANCH_ELSE_LAST' - | 'W_RAW_HANDLE' - | 'W_SUBFLOW_HANDLE_SCOPE' - | 'E_EDGE_CYCLE' - | 'W_EDGE_CYCLE' - | 'W_BRANCH_UNWIRED' - | 'E_UNKNOWN_BUILDER' - | 'E_UNKNOWN_PARAM' - | 'E_FIXED_PARAM' - | 'W_FIELD_NOT_APPLICABLE' - | 'W_REQUIRED_MISSING' - | 'W_UNKNOWN_OPTION' - | 'E_UNKNOWN_OPERATION' - | 'W_UNKNOWN_MODEL' - | 'W_LEGACY_BLOCK_TYPE' - | 'I_SCHEDULE_UTC' - | 'E_STORED_VALUE_MISSING' - | 'W_VALUE_KIND' - | 'W_OUT_OF_RANGE' - | 'W_TABLE_FILTER_SHAPE' - | 'W_LITERAL_SECRET' - | 'W_SUBFLOW_COUNT' - | 'W_UNKNOWN_OUTPUT_PATH' - | 'W_JSON_REF_UNTYPED' - | 'E_CODE_FILE_MISSING' - | 'E_CODE_FILE_PATH' - | 'W_CODE_FILE_INLINED' - | 'W_UNRESOLVED_REF' - | 'W_FORWARD_REF_LITERALIZED' - | 'W_COMMENT_MOVED' - | 'W_COMMENT_DROPPED' - | 'E_LOCK_JSON' - | 'E_LOCK_VERSION' - | 'E_LOCK_SHAPE' - | 'E_LOCK_UNKNOWN_FIELD' - | 'E_LOCK_KEY' - | 'E_LOCK_IDENT' - | 'E_LOCK_DUPLICATE_IDENT' - | 'E_LOCK_DUPLICATE_ID' - | 'E_LOCK_PARENT' - | 'E_LOCK_BRANCH' - | 'E_LOCK_CODE_FILE_PATH' - | 'E_SOURCE_META_JSON' - | 'E_SOURCE_META_VERSION' - | 'E_SOURCE_META_SHAPE' - | 'E_SOURCE_META_UNKNOWN_FIELD' - | 'E_SOURCE_META_IDENT' - | 'E_SOURCE_META_DUPLICATE_IDENT' - | 'E_SOURCE_META_ANCHOR' - | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' - | 'W_CANON_RESERVED_NAME' - | 'W_CANON_DANGLING_EDGE' - | 'W_CANON_DANGLING_PARENT' - | 'W_CANON_RAW_HANDLE' - | 'W_CANON_UNKNOWN_BLOCK_TYPE' - | 'W_CANON_UNRESOLVED_ID' - | 'W_CANON_TITLE_OVERRIDE' - | 'W_CANON_SUBFLOW_REPAIRED' - | 'W_CANON_SUBBLOCK_TYPE_DRIFT' - | 'W_CANON_UNDECODABLE_JSON' - | 'E_MAT_DUPLICATE_LOCK_ID' - | 'E_MAT_UNKNOWN_RESOURCE' - | 'E_MAT_UNKNOWN_VARIABLE' - | 'W_MAT_DELETED_SINCE_PULL' - | 'W_MAT_INFERRED_RENAME' - | 'W_MAT_RETYPE_RECREATED' - | 'W_MAT_LOCK_ID_CLAIMED' - | 'I_MAT_NEEDS_LAYOUT' - | 'E_APPLY_STALE' - | 'E_APPLY_WORKFLOW_MISMATCH' - | 'E_APPLY_LOCKED_BLOCK' - | 'E_APPLY_TYPE_NOT_ADDABLE' - | 'E_APPLY_INVALID_STATE' - | 'E_APPLY_BLOCK_NOT_FOUND' - | 'E_APPLY_INVALID_BLOCK_TYPE' - | 'E_APPLY_BLOCK_NOT_ALLOWED' - | 'E_APPLY_MODEL_NOT_ALLOWED' - | 'E_APPLY_TOOL_NOT_ALLOWED' - | 'E_APPLY_INVALID_EDGE_SOURCE' - | 'E_APPLY_INVALID_EDGE_SCOPE' - | 'E_APPLY_INVALID_SOURCE_HANDLE' - | 'E_APPLY_INVALID_TARGET_HANDLE' - | 'E_APPLY_INVALID_SUBBLOCK_FIELD' - | 'E_APPLY_MISSING_REQUIRED_PARAMS' - | 'E_APPLY_RETRY_NOT_SUPPORTED' - | 'E_APPLY_DUPLICATE_TRIGGER' - | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' - | 'E_APPLY_DISABLED_ANCESTOR' - | 'E_APPLY_CREDENTIAL_UNREACHABLE' - | 'W_APPLY_CREDENTIAL_KEPT' - | 'E_APPLY_SANDBOX_PLAN_REQUIRED' - | 'W_APPLY_HOSTED_KEY_DROPPED' - | 'W_APPLY_VALUE_NORMALIZED' - | 'W_APPLY_TYPE_CHANGED' - | 'W_APPLY_TRIGGER_REMOVED' - | 'W_APPLY_CATALOG_MOVED' - | 'W_APPLY_PROBABLE_RENAME' - | 'E_APPLY_LINT' - | 'E_APPLY_UNRESOLVED_REF' - | 'W_APPLY_LINT' - | 'W_TABLE_UNKNOWN_COLUMN' - | 'E_APPLY_INVALID_SCHEDULE' - | 'E_APPLY_BLOCK_DELETE' - | 'E_NAME_TAKEN' - | 'E_WORKFLOW_META_INVALID' - severity: 'error' | 'warning' | 'info' - message: string - hint?: string - blockKey?: string - param?: string - file?: string - line?: number - column?: number - endLine?: number - endColumn?: number - frame?: string - blockId?: string - path?: string - }> - files: Record - lock: { - version: 1 - blocks: Record< - string, - { - id: string - parent: string | null - branches?: Record - items?: Record< - string, - Array<{ - name: string - id: string - }> - > - ident: string - order: number - layout?: { - x: number - y: number - w?: number - h?: number - height?: number - horizontalHandles?: boolean - [key: string]: unknown - } - codeFile?: string - [key: string]: unknown - } - > - variables: Record - [key: string]: unknown - } - base: { - version: 1 - workflowId: string - workspaceId: string - fingerprint: string - catalogHash: string - [key: string]: unknown - } - mintedIds: Record - notes: Array - needsRedeployment: boolean - } -} - -/** `POST /api/v2/workspaces/[workspaceId]/source/plan` */ -export type PlanWorkspaceSourceParams = { - workspaceId: string -} - -export type PlanWorkspaceSourceQuery = Record - -export type PlanWorkspaceSourceBody = { - files: Record - blobs?: Array<{ - path: string - sha256: string - size: number - }> - base?: { - version: 1 - workspaceId: string - resources: Record< - string, - { - id: string - fingerprint?: string - columns?: Record< - string, - { - id: string - options?: Record - } - > - blobs?: Record< - string, - { - id: string - rev: number | string - sha256: string - } - > - rows?: { - fingerprint: string - version: number - [key: string]: unknown - } - [key: string]: unknown - } - > - [key: string]: unknown - } - kinds: Array< - | 'secret' - | 'credential' - | 'custom-tool' - | 'skill' - | 'mcp-server' - | 'table' - | 'knowledge-base' - | 'file' - | 'workflow' - | 'deployment' - > - options?: { - allowDelete?: boolean - only?: Array< - | 'secret' - | 'credential' - | 'custom-tool' - | 'skill' - | 'mcp-server' - | 'table' - | 'knowledge-base' - | 'file' - | 'workflow' - | 'deployment' - > - } -} - -export type PlanWorkspaceSourceResponse = { - data: { - workspaceId: string - dryRun: boolean - plan: Array<{ - kind: - | 'secret' - | 'credential' - | 'custom-tool' - | 'skill' - | 'mcp-server' - | 'table' - | 'knowledge-base' - | 'file' - | 'workflow' - | 'deployment' - key: string - action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' - fields?: Array - destructive?: { - what: string - counts: Record - } - id?: string - held?: true - }> - applied: Array<{ - kind: - | 'secret' - | 'credential' - | 'custom-tool' - | 'skill' - | 'mcp-server' - | 'table' - | 'knowledge-base' - | 'file' - | 'workflow' - | 'deployment' - key: string - action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' - fields?: Array - destructive?: { - what: string - counts: Record - } - id?: string - held?: true - }> - failed?: { - kind: - | 'secret' - | 'credential' - | 'custom-tool' - | 'skill' - | 'mcp-server' - | 'table' - | 'knowledge-base' - | 'file' - | 'workflow' - | 'deployment' - key: string - code: - | 'E_DECL_SYNTAX' - | 'E_DECL_HEADER' - | 'E_DECL_IMPORT' - | 'E_DECL_EXPORT' - | 'E_DECL_UNSUPPORTED' - | 'E_DECL_DUPLICATE_KEY' - | 'E_DECL_SHAPE' - | 'E_DECL_UNKNOWN_FIELD' - | 'E_DECL_UNKNOWN_FILE' - | 'W_PATH_NOT_SENT' - | 'E_BLOB_MANIFEST' - | 'E_BLOB_MISSING' - | 'E_LIMIT_EXCEEDED' - | 'E_KEY_INVALID' - | 'W_DECL_SUSPICIOUS_CHARACTER' - | 'E_BASE_JSON' - | 'E_BASE_VERSION' - | 'E_BASE_SHAPE' - | 'E_BASE_UNKNOWN_FIELD' - | 'E_SECRET_NAME' - | 'E_SECRET_MISSING' - | 'W_SECRET_MISSING' - | 'E_CREDENTIAL_MISSING' - | 'E_CREDENTIAL_AMBIGUOUS' - | 'W_CREDENTIAL_MISSING' - | 'W_CREDENTIAL_AMBIGUOUS' - | 'E_TABLE_COLUMN_NAME' - | 'E_TABLE_DUPLICATE_COLUMN' - | 'E_TABLE_TOO_MANY_COLUMNS' - | 'E_TABLE_OPTIONS' - | 'E_TABLE_TYPE_CONVERSION' - | 'E_TABLE_FOLDER' - | 'E_TABLE_ROWS' - | 'I_TABLE_SEED_SKIPPED' - | 'I_TABLE_ROWS_UNKEYED' - | 'W_LIKELY_RENAME' - | 'E_TOOL_SCHEMA' - | 'E_TOOL_CODE' - | 'E_TOOL_STORED_MISSING' - | 'W_TOOL_LITERAL_SECRET' - | 'E_SKILL_FRONTMATTER' - | 'E_MCP_LITERAL_SECRET' - | 'E_MCP_STORED_MISSING' - | 'E_MCP_TOOL_UNKNOWN' - | 'W_MCP_REPLACE' - | 'W_MCP_TOOLS_UNCHECKED' - | 'E_FILE_PATH' - | 'E_FILE_PATH_COLLISION' - | 'E_FILE_NAME' - | 'E_FILE_TOO_LARGE' - | 'E_FILE_CONTENT' - | 'E_KB_EMBEDDING_IMMUTABLE' - | 'E_KB_EMBEDDING_MODEL' - | 'E_KB_DOC_AMBIGUOUS' - | 'E_KB_DOC_NAME' - | 'E_KB_DOC_EMPTY' - | 'E_KB_CHUNKING' - | 'E_KB_FOLDER' - | 'W_KB_DOC_UNCHECKED' - | 'W_KB_DOC_FAILED' - | 'I_KB_REEMBED' - | 'I_KB_CHUNKING' - | 'I_KB_PROCESSING' - | 'I_KB_DOCS_UNHASHED' - | 'I_KB_UNMANAGED_DOCS' - | 'I_KB_REPLACE_UNFINISHED' - | 'E_DEPLOY_WORKFLOW' - | 'E_DEPLOY_SECRET' - | 'E_DEPLOY_CHAT_OUTPUT' - | 'E_DEPLOY_CHAT_IDENTIFIER' - | 'E_DEPLOY_PINNED_CHAT' - | 'W_DEPLOYED_DRAFT_CHANGED' - | 'I_DEPLOY_DRAFT_NOT_LIVE' - | 'E_APPLY_STALE' - | 'E_APPLY_NO_BASE' - | 'E_APPLY_FORBIDDEN' - | 'E_APPLY_DELETE_NOT_ALLOWED' - | 'E_APPLY_LOCKED' - | 'E_APPLY_REFUSED' - | 'E_APPLY_FAILED' - | 'E_PLAN_TOO_LARGE' - | 'E_PLAN_REF_DELETED' - | 'E_PLAN_REF_HELD' - | 'W_RESOURCE_IN_USE' - | 'W_TABLE_COLUMN_RENAMED_IN_USE' - | 'E_NAME_TAKEN' - | 'E_WORKFLOW_FILES_MISSING' - | 'E_WORKFLOW_FOLDER_COPIED' - | 'W_UNDECLARED' - | 'W_BASE_OTHER_WORKSPACE' - | 'I_SERVER_CHANGED' - | 'I_SERVER_DELETED' - | 'I_SERVER_MOVED' - | 'I_KEY_REBOUND' - | 'E_KEY_RENAMED' - | 'I_FINDINGS_TRUNCATED' - | 'E_SYNTAX' - | 'E_SDK_HEADER' - | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' - | 'E_UNSUPPORTED_SYNTAX' - | 'E_WORKFLOW_EXPORT' - | 'E_INVALID_CHARACTER' - | 'E_NUMBER_NOT_FINITE' - | 'W_NUMBER_PRECISION' - | 'E_TOO_MANY_ERRORS' - | 'W_TOO_MANY_WARNINGS' - | 'E_DUPLICATE_NAME' - | 'E_RESERVED_NAME' - | 'E_KEY_OVERRIDE' - | 'E_EMPTY_NAME' - | 'E_LOOKALIKE_NAME' - | 'W_LOOKALIKE_NAME' - | 'W_SUSPICIOUS_CHARACTER' - | 'E_NAME_NOT_LITERAL' - | 'E_UNKNOWN_IDENTIFIER' - | 'E_OUT_OF_SCOPE' - | 'E_UNKNOWN_VARIABLE' - | 'E_DUPLICATE_VARIABLE' - | 'E_VARIABLE_NAME_MISMATCH' - | 'E_INVALID_ENV_NAME' - | 'W_ENV_UNKNOWN' - | 'W_CHILD_INPUT_UNKNOWN' - | 'W_CHILD_NO_START' - | 'E_UNKNOWN_SUBFLOW_PROPERTY' - | 'W_FORWARD_REF' - | 'W_REF_NOT_NORMALIZED' - | 'E_REF_UNREPRESENTABLE' - | 'E_EDGE_SCOPE' - | 'E_EDGE_NOTE' - | 'E_TARGET_TRIGGER' - | 'E_NO_DEFAULT_OUTPUT' - | 'E_DUPLICATE_EDGE' - | 'E_ERROR_PORT_UNSUPPORTED' - | 'W_ERROR_PORT_STORED' - | 'E_UNKNOWN_BRANCH' - | 'E_DUPLICATE_BRANCH_KEY' - | 'E_BRANCH_KEY_COLLIDES' - | 'E_BRANCH_ELSE_LAST' - | 'W_RAW_HANDLE' - | 'W_SUBFLOW_HANDLE_SCOPE' - | 'E_EDGE_CYCLE' - | 'W_EDGE_CYCLE' - | 'W_BRANCH_UNWIRED' - | 'E_UNKNOWN_BUILDER' - | 'E_UNKNOWN_PARAM' - | 'E_FIXED_PARAM' - | 'W_FIELD_NOT_APPLICABLE' - | 'W_REQUIRED_MISSING' - | 'W_UNKNOWN_OPTION' - | 'E_UNKNOWN_OPERATION' - | 'W_UNKNOWN_MODEL' - | 'W_LEGACY_BLOCK_TYPE' - | 'I_SCHEDULE_UTC' - | 'E_STORED_VALUE_MISSING' - | 'W_VALUE_KIND' - | 'W_OUT_OF_RANGE' - | 'W_TABLE_FILTER_SHAPE' - | 'W_LITERAL_SECRET' - | 'W_SUBFLOW_COUNT' - | 'W_UNKNOWN_OUTPUT_PATH' - | 'W_JSON_REF_UNTYPED' - | 'E_CODE_FILE_MISSING' - | 'E_CODE_FILE_PATH' - | 'W_CODE_FILE_INLINED' - | 'W_UNRESOLVED_REF' - | 'W_FORWARD_REF_LITERALIZED' - | 'W_COMMENT_MOVED' - | 'W_COMMENT_DROPPED' - | 'E_LOCK_JSON' - | 'E_LOCK_VERSION' - | 'E_LOCK_SHAPE' - | 'E_LOCK_UNKNOWN_FIELD' - | 'E_LOCK_KEY' - | 'E_LOCK_IDENT' - | 'E_LOCK_DUPLICATE_IDENT' - | 'E_LOCK_DUPLICATE_ID' - | 'E_LOCK_PARENT' - | 'E_LOCK_BRANCH' - | 'E_LOCK_CODE_FILE_PATH' - | 'E_SOURCE_META_JSON' - | 'E_SOURCE_META_VERSION' - | 'E_SOURCE_META_SHAPE' - | 'E_SOURCE_META_UNKNOWN_FIELD' - | 'E_SOURCE_META_IDENT' - | 'E_SOURCE_META_DUPLICATE_IDENT' - | 'E_SOURCE_META_ANCHOR' - | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' - | 'W_CANON_RESERVED_NAME' - | 'W_CANON_DANGLING_EDGE' - | 'W_CANON_DANGLING_PARENT' - | 'W_CANON_RAW_HANDLE' - | 'W_CANON_UNKNOWN_BLOCK_TYPE' - | 'W_CANON_UNRESOLVED_ID' - | 'W_CANON_TITLE_OVERRIDE' - | 'W_CANON_SUBFLOW_REPAIRED' - | 'W_CANON_SUBBLOCK_TYPE_DRIFT' - | 'W_CANON_UNDECODABLE_JSON' - | 'E_MAT_DUPLICATE_LOCK_ID' - | 'E_MAT_UNKNOWN_RESOURCE' - | 'E_MAT_UNKNOWN_VARIABLE' - | 'W_MAT_DELETED_SINCE_PULL' - | 'W_MAT_INFERRED_RENAME' - | 'W_MAT_RETYPE_RECREATED' - | 'W_MAT_LOCK_ID_CLAIMED' - | 'I_MAT_NEEDS_LAYOUT' - | 'E_APPLY_WORKFLOW_MISMATCH' - | 'E_APPLY_LOCKED_BLOCK' - | 'E_APPLY_TYPE_NOT_ADDABLE' - | 'E_APPLY_INVALID_STATE' - | 'E_APPLY_BLOCK_NOT_FOUND' - | 'E_APPLY_INVALID_BLOCK_TYPE' - | 'E_APPLY_BLOCK_NOT_ALLOWED' - | 'E_APPLY_MODEL_NOT_ALLOWED' - | 'E_APPLY_TOOL_NOT_ALLOWED' - | 'E_APPLY_INVALID_EDGE_SOURCE' - | 'E_APPLY_INVALID_EDGE_SCOPE' - | 'E_APPLY_INVALID_SOURCE_HANDLE' - | 'E_APPLY_INVALID_TARGET_HANDLE' - | 'E_APPLY_INVALID_SUBBLOCK_FIELD' - | 'E_APPLY_MISSING_REQUIRED_PARAMS' - | 'E_APPLY_RETRY_NOT_SUPPORTED' - | 'E_APPLY_DUPLICATE_TRIGGER' - | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' - | 'E_APPLY_DISABLED_ANCESTOR' - | 'E_APPLY_CREDENTIAL_UNREACHABLE' - | 'W_APPLY_CREDENTIAL_KEPT' - | 'E_APPLY_SANDBOX_PLAN_REQUIRED' - | 'W_APPLY_HOSTED_KEY_DROPPED' - | 'W_APPLY_VALUE_NORMALIZED' - | 'W_APPLY_TYPE_CHANGED' - | 'W_APPLY_TRIGGER_REMOVED' - | 'W_APPLY_CATALOG_MOVED' - | 'W_APPLY_PROBABLE_RENAME' - | 'E_APPLY_LINT' - | 'E_APPLY_UNRESOLVED_REF' - | 'W_APPLY_LINT' - | 'W_TABLE_UNKNOWN_COLUMN' - | 'E_APPLY_INVALID_SCHEDULE' - | 'E_APPLY_BLOCK_DELETE' - | 'E_WORKFLOW_META_INVALID' - message: string - } - needBlobs: Array - applyId?: string - files: Record - base: { - version: 1 - workspaceId: string - resources: Record< - string, - { - id: string - fingerprint?: string - columns?: Record< - string, - { - id: string - options?: Record - } - > - blobs?: Record< - string, - { - id: string - rev: number | string - sha256: string - } - > - rows?: { - fingerprint: string - version: number - [key: string]: unknown - } - [key: string]: unknown - } - > - [key: string]: unknown - } - diagnostics: Array<{ - code: - | 'E_DECL_SYNTAX' - | 'E_DECL_HEADER' - | 'E_DECL_IMPORT' - | 'E_DECL_EXPORT' - | 'E_DECL_UNSUPPORTED' - | 'E_DECL_DUPLICATE_KEY' - | 'E_DECL_SHAPE' - | 'E_DECL_UNKNOWN_FIELD' - | 'E_DECL_UNKNOWN_FILE' - | 'W_PATH_NOT_SENT' - | 'E_BLOB_MANIFEST' - | 'E_BLOB_MISSING' - | 'E_LIMIT_EXCEEDED' - | 'E_KEY_INVALID' - | 'W_DECL_SUSPICIOUS_CHARACTER' - | 'E_BASE_JSON' - | 'E_BASE_VERSION' - | 'E_BASE_SHAPE' - | 'E_BASE_UNKNOWN_FIELD' - | 'E_SECRET_NAME' - | 'E_SECRET_MISSING' - | 'W_SECRET_MISSING' - | 'E_CREDENTIAL_MISSING' - | 'E_CREDENTIAL_AMBIGUOUS' - | 'W_CREDENTIAL_MISSING' - | 'W_CREDENTIAL_AMBIGUOUS' - | 'E_TABLE_COLUMN_NAME' - | 'E_TABLE_DUPLICATE_COLUMN' - | 'E_TABLE_TOO_MANY_COLUMNS' - | 'E_TABLE_OPTIONS' - | 'E_TABLE_TYPE_CONVERSION' - | 'E_TABLE_FOLDER' - | 'E_TABLE_ROWS' - | 'I_TABLE_SEED_SKIPPED' - | 'I_TABLE_ROWS_UNKEYED' - | 'W_LIKELY_RENAME' - | 'E_TOOL_SCHEMA' - | 'E_TOOL_CODE' - | 'E_TOOL_STORED_MISSING' - | 'W_TOOL_LITERAL_SECRET' - | 'E_SKILL_FRONTMATTER' - | 'E_MCP_LITERAL_SECRET' - | 'E_MCP_STORED_MISSING' - | 'E_MCP_TOOL_UNKNOWN' - | 'W_MCP_REPLACE' - | 'W_MCP_TOOLS_UNCHECKED' - | 'E_FILE_PATH' - | 'E_FILE_PATH_COLLISION' - | 'E_FILE_NAME' - | 'E_FILE_TOO_LARGE' - | 'E_FILE_CONTENT' - | 'E_KB_EMBEDDING_IMMUTABLE' - | 'E_KB_EMBEDDING_MODEL' - | 'E_KB_DOC_AMBIGUOUS' - | 'E_KB_DOC_NAME' - | 'E_KB_DOC_EMPTY' - | 'E_KB_CHUNKING' - | 'E_KB_FOLDER' - | 'W_KB_DOC_UNCHECKED' - | 'W_KB_DOC_FAILED' - | 'I_KB_REEMBED' - | 'I_KB_CHUNKING' - | 'I_KB_PROCESSING' - | 'I_KB_DOCS_UNHASHED' - | 'I_KB_UNMANAGED_DOCS' - | 'I_KB_REPLACE_UNFINISHED' - | 'E_DEPLOY_WORKFLOW' - | 'E_DEPLOY_SECRET' - | 'E_DEPLOY_CHAT_OUTPUT' - | 'E_DEPLOY_CHAT_IDENTIFIER' - | 'E_DEPLOY_PINNED_CHAT' - | 'W_DEPLOYED_DRAFT_CHANGED' - | 'I_DEPLOY_DRAFT_NOT_LIVE' - | 'E_APPLY_STALE' - | 'E_APPLY_NO_BASE' - | 'E_APPLY_FORBIDDEN' - | 'E_APPLY_DELETE_NOT_ALLOWED' - | 'E_APPLY_LOCKED' - | 'E_APPLY_REFUSED' - | 'E_APPLY_FAILED' - | 'E_PLAN_TOO_LARGE' - | 'E_PLAN_REF_DELETED' - | 'E_PLAN_REF_HELD' - | 'W_RESOURCE_IN_USE' - | 'W_TABLE_COLUMN_RENAMED_IN_USE' - | 'E_NAME_TAKEN' - | 'E_WORKFLOW_FILES_MISSING' - | 'E_WORKFLOW_FOLDER_COPIED' - | 'W_UNDECLARED' - | 'W_BASE_OTHER_WORKSPACE' - | 'I_SERVER_CHANGED' - | 'I_SERVER_DELETED' - | 'I_SERVER_MOVED' - | 'I_KEY_REBOUND' - | 'E_KEY_RENAMED' - | 'I_FINDINGS_TRUNCATED' - | 'E_SYNTAX' - | 'E_SDK_HEADER' - | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' - | 'E_UNSUPPORTED_SYNTAX' - | 'E_WORKFLOW_EXPORT' - | 'E_INVALID_CHARACTER' - | 'E_NUMBER_NOT_FINITE' - | 'W_NUMBER_PRECISION' - | 'E_TOO_MANY_ERRORS' - | 'W_TOO_MANY_WARNINGS' - | 'E_DUPLICATE_NAME' - | 'E_RESERVED_NAME' - | 'E_KEY_OVERRIDE' - | 'E_EMPTY_NAME' - | 'E_LOOKALIKE_NAME' - | 'W_LOOKALIKE_NAME' - | 'W_SUSPICIOUS_CHARACTER' - | 'E_NAME_NOT_LITERAL' - | 'E_UNKNOWN_IDENTIFIER' - | 'E_OUT_OF_SCOPE' - | 'E_UNKNOWN_VARIABLE' - | 'E_DUPLICATE_VARIABLE' - | 'E_VARIABLE_NAME_MISMATCH' - | 'E_INVALID_ENV_NAME' - | 'W_ENV_UNKNOWN' - | 'W_CHILD_INPUT_UNKNOWN' - | 'W_CHILD_NO_START' - | 'E_UNKNOWN_SUBFLOW_PROPERTY' - | 'W_FORWARD_REF' - | 'W_REF_NOT_NORMALIZED' - | 'E_REF_UNREPRESENTABLE' - | 'E_EDGE_SCOPE' - | 'E_EDGE_NOTE' - | 'E_TARGET_TRIGGER' - | 'E_NO_DEFAULT_OUTPUT' - | 'E_DUPLICATE_EDGE' - | 'E_ERROR_PORT_UNSUPPORTED' - | 'W_ERROR_PORT_STORED' - | 'E_UNKNOWN_BRANCH' - | 'E_DUPLICATE_BRANCH_KEY' - | 'E_BRANCH_KEY_COLLIDES' - | 'E_BRANCH_ELSE_LAST' - | 'W_RAW_HANDLE' - | 'W_SUBFLOW_HANDLE_SCOPE' - | 'E_EDGE_CYCLE' - | 'W_EDGE_CYCLE' - | 'W_BRANCH_UNWIRED' - | 'E_UNKNOWN_BUILDER' - | 'E_UNKNOWN_PARAM' - | 'E_FIXED_PARAM' - | 'W_FIELD_NOT_APPLICABLE' - | 'W_REQUIRED_MISSING' - | 'W_UNKNOWN_OPTION' - | 'E_UNKNOWN_OPERATION' - | 'W_UNKNOWN_MODEL' - | 'W_LEGACY_BLOCK_TYPE' - | 'I_SCHEDULE_UTC' - | 'E_STORED_VALUE_MISSING' - | 'W_VALUE_KIND' - | 'W_OUT_OF_RANGE' - | 'W_TABLE_FILTER_SHAPE' - | 'W_LITERAL_SECRET' - | 'W_SUBFLOW_COUNT' - | 'W_UNKNOWN_OUTPUT_PATH' - | 'W_JSON_REF_UNTYPED' - | 'E_CODE_FILE_MISSING' - | 'E_CODE_FILE_PATH' - | 'W_CODE_FILE_INLINED' - | 'W_UNRESOLVED_REF' - | 'W_FORWARD_REF_LITERALIZED' - | 'W_COMMENT_MOVED' - | 'W_COMMENT_DROPPED' - | 'E_LOCK_JSON' - | 'E_LOCK_VERSION' - | 'E_LOCK_SHAPE' - | 'E_LOCK_UNKNOWN_FIELD' - | 'E_LOCK_KEY' - | 'E_LOCK_IDENT' - | 'E_LOCK_DUPLICATE_IDENT' - | 'E_LOCK_DUPLICATE_ID' - | 'E_LOCK_PARENT' - | 'E_LOCK_BRANCH' - | 'E_LOCK_CODE_FILE_PATH' - | 'E_SOURCE_META_JSON' - | 'E_SOURCE_META_VERSION' - | 'E_SOURCE_META_SHAPE' - | 'E_SOURCE_META_UNKNOWN_FIELD' - | 'E_SOURCE_META_IDENT' - | 'E_SOURCE_META_DUPLICATE_IDENT' - | 'E_SOURCE_META_ANCHOR' - | 'E_CANON_LEGACY_NAME_COLLISION' - | 'E_CANON_EDGE_SCOPE' - | 'W_CANON_RESERVED_NAME' - | 'W_CANON_DANGLING_EDGE' - | 'W_CANON_DANGLING_PARENT' - | 'W_CANON_RAW_HANDLE' - | 'W_CANON_UNKNOWN_BLOCK_TYPE' - | 'W_CANON_UNRESOLVED_ID' - | 'W_CANON_TITLE_OVERRIDE' - | 'W_CANON_SUBFLOW_REPAIRED' - | 'W_CANON_SUBBLOCK_TYPE_DRIFT' - | 'W_CANON_UNDECODABLE_JSON' - | 'E_MAT_DUPLICATE_LOCK_ID' - | 'E_MAT_UNKNOWN_RESOURCE' - | 'E_MAT_UNKNOWN_VARIABLE' - | 'W_MAT_DELETED_SINCE_PULL' - | 'W_MAT_INFERRED_RENAME' - | 'W_MAT_RETYPE_RECREATED' - | 'W_MAT_LOCK_ID_CLAIMED' - | 'I_MAT_NEEDS_LAYOUT' - | 'E_APPLY_WORKFLOW_MISMATCH' - | 'E_APPLY_LOCKED_BLOCK' - | 'E_APPLY_TYPE_NOT_ADDABLE' - | 'E_APPLY_INVALID_STATE' - | 'E_APPLY_BLOCK_NOT_FOUND' - | 'E_APPLY_INVALID_BLOCK_TYPE' - | 'E_APPLY_BLOCK_NOT_ALLOWED' - | 'E_APPLY_MODEL_NOT_ALLOWED' - | 'E_APPLY_TOOL_NOT_ALLOWED' - | 'E_APPLY_INVALID_EDGE_SOURCE' - | 'E_APPLY_INVALID_EDGE_SCOPE' - | 'E_APPLY_INVALID_SOURCE_HANDLE' - | 'E_APPLY_INVALID_TARGET_HANDLE' - | 'E_APPLY_INVALID_SUBBLOCK_FIELD' - | 'E_APPLY_MISSING_REQUIRED_PARAMS' - | 'E_APPLY_RETRY_NOT_SUPPORTED' - | 'E_APPLY_DUPLICATE_TRIGGER' - | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' - | 'E_APPLY_DISABLED_ANCESTOR' - | 'E_APPLY_CREDENTIAL_UNREACHABLE' - | 'W_APPLY_CREDENTIAL_KEPT' - | 'E_APPLY_SANDBOX_PLAN_REQUIRED' - | 'W_APPLY_HOSTED_KEY_DROPPED' - | 'W_APPLY_VALUE_NORMALIZED' - | 'W_APPLY_TYPE_CHANGED' - | 'W_APPLY_TRIGGER_REMOVED' - | 'W_APPLY_CATALOG_MOVED' - | 'W_APPLY_PROBABLE_RENAME' - | 'E_APPLY_LINT' - | 'E_APPLY_UNRESOLVED_REF' - | 'W_APPLY_LINT' - | 'W_TABLE_UNKNOWN_COLUMN' - | 'E_APPLY_INVALID_SCHEDULE' - | 'E_APPLY_BLOCK_DELETE' - | 'E_WORKFLOW_META_INVALID' - severity: 'error' | 'warning' | 'info' - message: string - hint?: string - file?: string - line?: number - column?: number - endLine?: number - endColumn?: number - frame?: string - path?: string - kind?: string - key?: string - blockKey?: string - param?: string - }> - } -} - /** `POST /api/v2/organizations/[organizationId]/search/sources/prepare` */ export type PrepareSearchSourcesParams = { organizationId: string @@ -20595,7 +19570,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', }, }, body: { @@ -22252,7 +21227,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', }, }, body: { @@ -27520,75 +26495,6 @@ export const V2_OPERATIONS = { }, }, }, - planWorkflowSource: { - method: 'POST', - path: '/api/v2/workflows/[workflowId]/source/plan', - pathParams: ['workflowId'] as const, - pathParamDocs: { workflowId: 'Unique workflow identifier.' }, - responseMode: 'json', - summary: 'Plan workflow source', - workspaceKeyUnsupported: true, - query: { - allowDelete: { - kind: 'boolean', - describe: - 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.', - }, - }, - body: { - files: { - kind: 'object', - required: true, - describe: - 'Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks.', - }, - lock: { - kind: 'object', - required: true, - describe: - 'Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids.', - }, - base: { - kind: 'object', - required: true, - describe: - 'Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`.', - }, - }, - }, - planWorkspaceSource: { - method: 'POST', - path: '/api/v2/workspaces/[workspaceId]/source/plan', - pathParams: ['workspaceId'] as const, - pathParamDocs: { workspaceId: 'Workspace to read or apply.' }, - responseMode: 'json', - summary: 'Plan workspace source', - body: { - files: { - kind: 'object', - required: true, - describe: - 'Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged.', - }, - blobs: { - kind: 'array', - describe: - 'Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.', - }, - base: { - kind: 'object', - describe: - '`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change.', - }, - kinds: { - kind: 'array', - required: true, - describe: - 'The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent.', - }, - options: { kind: 'object', describe: 'How far the apply may go.' }, - }, - }, prepareSearchSources: { method: 'POST', path: '/api/v2/organizations/[organizationId]/search/sources/prepare', diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 7ba322ef8f3..d2955d043de 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -93,7 +93,7 @@ and on the server now: | local vs base | server vs base | outcome | |---|---|---| -| equal | any | `noop` (`I_SERVER_CHANGED` when the server drifted) | +| equal | any | `noop` (`W_SERVER_CHANGED` when the server drifted) | | differs | equal | `apply` | | differs | differs | `noop` if local equals server (base refreshed), else `stale` | diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index 6ed437e385e..4e3ebcfc4a1 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -280,12 +280,12 @@ const PLAN_CODES = [ * not declare it). */ 'W_PROMOTE_DELETES_TARGET_ONLY', - /** The server changed a resource the directory leaves as it was; the next get shows it. */ - 'I_SERVER_CHANGED', + /** The server changed a resource the directory leaves alone; the apply keeps it. */ + 'W_SERVER_CHANGED', /** The server deleted a resource the directory leaves as it was; it is not created again. */ - 'I_SERVER_DELETED', + 'W_SERVER_DELETED', /** The server moved a resource the directory leaves as it was; it is not created again. */ - 'I_SERVER_MOVED', + 'W_SERVER_MOVED', /** A key bound to a deleted resource was bound to the one this apply wrote. */ 'I_KEY_REBOUND', /** A declaration under a new key for a resource the base read under another: keys never move. */ diff --git a/packages/workspace-code/src/status.ts b/packages/workspace-code/src/status.ts index 13ee8de944a..ff009660297 100644 --- a/packages/workspace-code/src/status.ts +++ b/packages/workspace-code/src/status.ts @@ -133,9 +133,9 @@ export function localResourceChanges(files: readonly ChangedFile[]): LocalResour */ const SERVER_FINDINGS: ReadonlyMap = new Map( Object.entries({ - I_SERVER_CHANGED: 'changed', - I_SERVER_DELETED: 'deleted', - I_SERVER_MOVED: 'moved', + W_SERVER_CHANGED: 'changed', + W_SERVER_DELETED: 'deleted', + W_SERVER_MOVED: 'moved', E_APPLY_STALE: 'changed', W_UNDECLARED: 'added', E_APPLY_NO_BASE: 'added', From 867762ff621f84eede95bec0b4bbba3b1a5603dd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:08:04 -0800 Subject: [PATCH 036/104] fix(workspace-source): managed rows the server wrote are reported as drift Rows the directory did not change were never read, so a server edit of a managed table's rows went unnoticed by status and apply. Each plan now compares the table's row version with the one the base recorded and reports a moved version as W_SERVER_CHANGED on the table, keeping the server's rows. No row is read for it. --- .../application/kinds/table/adapter.ts | 18 +++++++++++++++- .../application/rows.integration.ts | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) 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 cc4f497d78f..0c048c49637 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts @@ -56,6 +56,7 @@ import { getTableById } from '@/lib/table/service' import type { RowData } from '@/lib/table/types' import { validateRowSize } from '@/lib/table/validation' import { + DRIFT_HINT, GET_HINT, keyRenamedChange, kindFinding, @@ -391,7 +392,22 @@ async function planRows( const local = tableRowsFingerprint(rows) const based = entry?.id === state.table.id ? entry.rows : undefined const marked = storedKey === rows.key - if (based && based.fingerprint === local && marked) return outcome + if (based && based.fingerprint === local && marked) { + // Rows the directory leaves alone are not read, but a row version that moved says the server + // wrote them since: drift the apply keeps, which the plan says. + if ((await rowsVersion(ctx, state.table.id)) !== based.version) { + outcome.diagnostics.push( + kindFinding( + 'table', + key, + 'W_SERVER_CHANGED', + `The rows of table "${state.table.name}" were written on the server since this directory was read; the apply keeps the server's rows (not reverted to ${tableRowsPath(key)}).`, + { hint: DRIFT_HINT } + ) + ) + } + return outcome + } const rowKey = rows.key ?? '' const stored = await readStoredRows(ctx, state.table, keyById) const kept = unkeyedRows(stored, rowKey) diff --git a/apps/sim/lib/workspace-source/application/rows.integration.ts b/apps/sim/lib/workspace-source/application/rows.integration.ts index cf488fa126e..f528ff4d4b3 100644 --- a/apps/sim/lib/workspace-source/application/rows.integration.ts +++ b/apps/sim/lib/workspace-source/application/rows.integration.ts @@ -549,6 +549,27 @@ export default defineTable({ expect(codes(refused.diagnostics)).toContain('E_APPLY_REFUSED') }) + check( + 'reports managed rows the server wrote since the base as drift, and keeps them', + async () => { + const workspaceId = await newWorkspace() + const read = await managedPlans(workspaceId) + const clean = await apply(workspaceId, read.files, { base: read.base, dryRun: true }) + expect(codes(clean.diagnostics, 'warning')).toEqual([]) + + await editStoredSeats(workspaceId, 'team', 25) + const drifted = await apply(workspaceId, read.files, { base: read.base }) + + expect(drifted.applied).toEqual([]) + expect( + drifted.diagnostics + .filter((finding) => finding.severity === 'warning') + .map((finding) => `${finding.code} ${finding.kind}:${finding.key}`) + ).toEqual(['W_SERVER_CHANGED table:plans']) + expect((await storedRows(workspaceId))[1]).toMatchObject({ code: 'team', seats: 25 }) + } + ) + check('refuses rows edited here that the server changed since the base', async () => { const workspaceId = await newWorkspace() const read = await managedPlans(workspaceId) From 033f50dc2c78638c83a981110cbfd1437b154b88 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:08:10 -0800 Subject: [PATCH 037/104] fix(sim-cli): keep machine-local blob stats out of the committed .sim/written.json written.json carried each blob's device, inode and times, so a no-op apply on any other machine or clone rewrote it and every CI write-back commit was noise. written.json now holds only the digests, sorted by path; the stats move to .sim/cache/stats.json beside the digest they were taken with, in a folder that ignores itself. An untouched blob's digest is still reused on the machine that took it, and a stat whose digest no longer matches is ignored. --- .../src/commands/protocol/source-dir.ts | 76 ++++++++++++++----- .../protocol/workspace-source-apply.test.ts | 20 ++++- .../protocol/workspace-source-apply.ts | 5 +- .../commands/protocol/workspace-source-dir.ts | 2 +- .../protocol/workspace-source-get.test.ts | 4 +- .../commands/protocol/workspace-source-get.ts | 5 +- 6 files changed, 85 insertions(+), 27 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index b04d1380eb9..a31733e3d5f 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -67,6 +67,14 @@ export const SOURCE_GITIGNORE_FILE = '.gitignore' * edit from a file it may replace. The CLI's own record: never sent to the server. */ export const SOURCE_WRITTEN_FILE = '.sim/written.json' +/** + * Machine-local cache the CLI keeps beside its records: the stat each blob digest was taken at, + * which names this machine's files (device, inode, times) and so is never committed. The folder + * ignores itself (`.sim/cache/.gitignore`), whatever the repository's own `.gitignore` says. + */ +const SOURCE_CACHE_DIR = '.sim/cache' +const SOURCE_STATS_FILE = `${SOURCE_CACHE_DIR}/stats.json` +const SOURCE_CACHE_IGNORE_FILE = `${SOURCE_CACHE_DIR}/.gitignore` /** * The workspace a starter written by `workflows source create` was typed for, so the create that * follows targets that workspace. The CLI's own record: never sent, and removed once the workflow @@ -533,17 +541,29 @@ export interface StatDigest extends FileStat { } /** - * `.sim/written.json`: each source file's digest as the CLI last wrote it, normalized, and for a - * blob the stat its digest was taken at, so a later command reuses the digest of an untouched blob - * instead of reading it again. + * `.sim/written.json`: each source file's digest as the CLI last wrote it, normalized, sorted by + * path. It holds nothing about this machine, so a clone reads it the same and a write that changes + * no file leaves it byte for byte. */ interface WrittenRecord { version: 1 files: Record - stats?: Record } -/** `.sim/written.json` as one command reads it, once. */ +/** + * `.sim/cache/stats.json`: for a blob, the stat its digest was taken at, beside that digest, so a + * later command on this machine reuses the digest of an untouched blob instead of reading it + * again. A stat whose digest is not the one `.sim/written.json` records is ignored. + */ +interface StatsRecord { + version: 1 + stats: Record +} + +/** + * What the CLI last wrote, as one command reads it, once: the digests from `.sim/written.json` + * and the stats from `.sim/cache/stats.json` that still match them. + */ export interface Written { digests: Record stats: Record @@ -574,14 +594,32 @@ export function writtenRecord( return { digests, stats: Object.fromEntries(recorded) } } -/** The text of `.sim/written.json` for `written`. */ -export function writtenFile(written: Written): string { - const record: WrittenRecord = { - version: 1, - files: written.digests, - ...(Object.keys(written.stats).length > 0 ? { stats: written.stats } : {}), - } - return `${JSON.stringify(record, null, 2)}\n` +/** `record` with its keys in path order, so the same entries always print the same text. */ +function sortedByPath(record: Record): Record { + return Object.fromEntries(Object.entries(record).sort(([a], [b]) => compareStrings(a, b))) +} + +/** + * The files that record `written`: `.sim/written.json` (committed) and, when a blob stat is + * recorded, the machine-local `.sim/cache/stats.json` with the cache folder's own `.gitignore`. + */ +export function writtenFiles(written: Written): Array { + const record: WrittenRecord = { version: 1, files: sortedByPath(written.digests) } + const files: Array = [ + [SOURCE_WRITTEN_FILE, `${JSON.stringify(record, null, 2)}\n`], + ] + const stats = Object.entries(written.stats).flatMap(([path, stat]) => + Object.hasOwn(written.digests, path) + ? [[path, { sha256: written.digests[path], ...fileStatOf(stat) }] as const] + : [] + ) + if (stats.length === 0) return files + const cache: StatsRecord = { version: 1, stats: sortedByPath(Object.fromEntries(stats)) } + return [ + ...files, + [SOURCE_STATS_FILE, `${JSON.stringify(cache, null, 2)}\n`], + [SOURCE_CACHE_IGNORE_FILE, '*\n'], + ] } /** What the CLI recorded for its last write, empty when it recorded nothing. */ @@ -592,10 +630,14 @@ export async function readWritten(dir: string): Promise { (entry): entry is [string, string] => typeof entry[1] === 'string' ) ) + const cache = toRecord(await readSourceJson(dir, SOURCE_STATS_FILE)) const stats: Record = {} - for (const [path, stat] of Object.entries(toRecord(record.stats))) { - const { dev, ino, size, mtimeMs, ctimeMs } = toRecord(stat) + for (const [path, stat] of Object.entries(toRecord(cache.stats))) { + const { sha256, dev, ino, size, mtimeMs, ctimeMs } = toRecord(stat) if ( + typeof sha256 === 'string' && + Object.hasOwn(digests, path) && + digests[path] === sha256 && typeof dev === 'number' && typeof ino === 'number' && typeof size === 'number' && @@ -738,7 +780,7 @@ async function recordFolderWrite( ), } const write: Array = [ - [SOURCE_WRITTEN_FILE, writtenFile({ digests, stats: record.stats })], + ...writtenFiles({ digests, stats: record.stats }), ] const workspaceBase = toRecord(await readSourceJson(folder.root, SOURCE_BASE_FILE)) const resources = toRecord(workspaceBase.resources) @@ -838,7 +880,7 @@ export async function writeBack( ] const write = [ ...printed, - ...(folder ? [] : [[SOURCE_WRITTEN_FILE, writtenFile(writtenRecord(files))] as const]), + ...(folder ? [] : writtenFiles(writtenRecord(files))), ...extra.write, ] const orphaned = orphanedCodeFiles(previousLock, answer.lock, Object.keys(answer.files)) 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 12ff529156f..990314b7a7b 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 @@ -995,15 +995,33 @@ describe('workspaces source apply', () => { await apply('--yes') const written = JSON.parse(readFileSync(join(dir, '.sim/written.json'), 'utf8')) expect(written.files['files/a.bin']).toBe(held) - expect(written.stats['files/a.bin']).toBeDefined() + expect(written.stats).toBeUndefined() + const cached = JSON.parse(readFileSync(join(dir, '.sim/cache/stats.json'), 'utf8')) + expect(cached.stats['files/a.bin']).toMatchObject({ sha256: held }) + expect(readFileSync(join(dir, '.sim/cache/.gitignore'), 'utf8')).toBe('*\n') } + it('keeps the committed record free of this machine: a no-op apply of a fresh clone leaves it byte for byte', async () => { + await applyOnce() + rmSync(join(dir, '.sim/cache'), { recursive: true, force: true }) + const committed = readFileSync(join(dir, '.sim/written.json'), 'utf8') + + await apply('--yes') + + expect(readFileSync(join(dir, '.sim/written.json'), 'utf8')).toBe(committed) + expect(existsSync(join(dir, '.sim/cache/stats.json'))).toBe(true) + }) + it('stands while the file is untouched, so the file is not read', async () => { await applyOnce() const path = join(dir, '.sim/written.json') const written = JSON.parse(readFileSync(path, 'utf8')) const recorded = 'f'.repeat(64) writeFileSync(path, JSON.stringify({ ...written, files: { 'files/a.bin': recorded } })) + const statsPath = join(dir, '.sim/cache/stats.json') + const cached = JSON.parse(readFileSync(statsPath, 'utf8')) + cached.stats['files/a.bin'].sha256 = recorded + writeFileSync(statsPath, JSON.stringify(cached)) await apply('--dry-run') 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 47dd4eedf30..1acdd054f65 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -42,11 +42,10 @@ import { readSourceJson, readWritten, recordedStats, - SOURCE_WRITTEN_FILE, updateSourceDir, type Written, withSourceDirLock, - writtenFile, + writtenFiles, writtenRecord, } from './source-dir' import { SOURCE_WRITE_EXIT_CODES_HELP } from './source-exit-codes' @@ -427,7 +426,7 @@ async function saveApplied( write: [ ...Object.entries(data.files), [WORKSPACE_BASE_FILE, `${JSON.stringify(data.base, null, 2)}\n`], - [SOURCE_WRITTEN_FILE, writtenFile(record)], + ...writtenFiles(record), ...records, ], remove: [...orphaned, ...removedWorkflowRecords(deleted)], 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 2394ecf5569..31166010e36 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -168,7 +168,7 @@ const ADVANCED_GUIDE = `# Sim workspace source: advanced ## Git and CI -- Commit the whole directory, \`.sim/\` included: \`${WORKSPACE_BASE_FILE}\`, each workflow's \`.sim/\` and \`.sim/written.json\` are what a later apply compares with, from any clone. The generated \`.gitignore\` leaves out only what a command keeps while it runs (\`.sim/downloads/\`, \`.sim/command.lock/\`, \`.sim-staging-*\`) and \`${TSCONFIG_FULL_FILE}\`, which names the CLI's cache on this machine (\`check\` writes it again), and \`.gitattributes\` keeps workspace files and documents byte for byte. +- Commit the whole directory, \`.sim/\` included: \`${WORKSPACE_BASE_FILE}\`, each workflow's \`.sim/\` and \`.sim/written.json\` are what a later apply compares with, from any clone. \`.sim/cache/\` holds this machine's file stats and ignores itself. The generated \`.gitignore\` leaves out only what a command keeps while it runs (\`.sim/downloads/\`, \`.sim/command.lock/\`, \`.sim-staging-*\`) and \`${TSCONFIG_FULL_FILE}\`, which names the CLI's cache on this machine (\`check\` writes it again), and \`.gitattributes\` keeps workspace files and documents byte for byte. - A fresh clone runs \`check\` (it downloads the block catalog once when none is cached), \`apply --dry-run\` and \`apply --yes\` with only the committed files. A workspace API key may 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 (deployments an admin's). - Plan on every pull request (\`apply --dry-run\`), apply on merge, and commit the files the apply rewrote. Two branches that each applied: merge them, then run the dry run. No changes means the merged files match the workspace. Exit 5 means a resource changed since the base this branch holds: \`sim workspaces source get --dir \`, carry the edit over, and apply from there. - \`sim workspaces source get --dir .\` refreshes the workspace \`${WORKSPACE_BASE_FILE}\` names, whatever the profile's default; a \`--workspace\` naming another is refused. diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 36ef0fe69d4..431278db1aa 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -576,8 +576,8 @@ describe('workspaces source get', () => { const file = join(dir, 'files/report.bin') utimesSync(file, MTIME, MTIME) await get() - const written = JSON.parse(readFileSync(join(dir, '.sim/written.json'), 'utf8')) - expect(written.stats['files/report.bin']).toBeDefined() + const cached = JSON.parse(readFileSync(join(dir, '.sim/cache/stats.json'), 'utf8')) + expect(cached.stats['files/report.bin']).toBeDefined() return file } 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 78dde8cb6bd..aefbe831b6c 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -35,10 +35,9 @@ import { recordedStats, SOURCE_DIR_BUSY_HELP, SOURCE_DOWNLOADS_DIR, - SOURCE_WRITTEN_FILE, updateSourceDir, withSourceDirLock, - writtenFile, + writtenFiles, writtenRecord, } from './source-dir' import { @@ -295,7 +294,7 @@ async function writeWorkspaceSource( return marker === null ? [] : [[marker, ''] as const] }), [WORKSPACE_BASE_FILE, `${JSON.stringify(base, null, 2)}\n`], - [SOURCE_WRITTEN_FILE, writtenFile(record)], + ...writtenFiles(record), ...(skipped ? [[WORKSPACE_SKIPPED_FILE, skipped] as const] : []), ...workflowRecords, ...tree.change.write, From 398c4f3ee910a0d0e00f53e98adf0d63c75a4415 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:08:16 -0800 Subject: [PATCH 038/104] fix(workflow-code): source applies carry the git commit and repository into the audit log The CLI sent only { client: 'cli' }, so an apply could not be traced to a commit, and provenance.repo was accepted on workflow applies but never recorded. Workflow and workspace applies (and source create) now send the directory's git HEAD and its origin remote, stripped of credentials, query and fragment, when the directory is in a git repository. Both audit entries record repo beside gitSha, workspace applies accept repo too, and the server refuses a repo URL that carries credentials. --- apps/docs/openapi-v2-workflows.json | 14 ++-- .../lib/api/contracts/v2/workflow-source.ts | 25 +++++-- .../lib/api/contracts/v2/workspace-source.ts | 6 +- .../apply-workflow-source.integration.ts | 9 ++- .../application/apply-workflow-source.ts | 1 + .../application/apply-workspace-source.ts | 1 + .../application/apply.integration.ts | 37 ++++++++++ .../lib/workspace-source/application/types.ts | 2 +- .../commands/protocol/git-provenance.test.ts | 56 +++++++++++++++ .../src/commands/protocol/git-provenance.ts | 71 +++++++++++++++++++ .../protocol/workflow-source-apply.ts | 10 ++- .../protocol/workspace-source-apply.ts | 4 +- packages/sim-cli/src/generated/v2-api.ts | 1 + 13 files changed, 220 insertions(+), 17 deletions(-) create mode 100644 packages/sim-cli/src/commands/protocol/git-provenance.test.ts create mode 100644 packages/sim-cli/src/commands/protocol/git-provenance.ts diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 7ce3d729690..6cb8a73c751 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -19937,10 +19937,10 @@ "pattern": "^[0-9a-f]{7,64}$" }, "repo": { - "description": "The repository the source was taken from.", "type": "string", "minLength": 1, - "maxLength": 512 + "maxLength": 512, + "description": "The repository the source was taken from (its remote URL); recorded in the audit log." } }, "required": ["client"], @@ -20752,10 +20752,10 @@ "pattern": "^[0-9a-f]{7,64}$" }, "repo": { - "description": "The repository the source was taken from.", "type": "string", "minLength": 1, - "maxLength": 512 + "maxLength": 512, + "description": "The repository the source was taken from (its remote URL); recorded in the audit log." } }, "required": ["client"], @@ -26734,6 +26734,12 @@ "description": "The commit the directory was taken from; recorded in the audit log.", "type": "string", "pattern": "^[0-9a-f]{7,64}$" + }, + "repo": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "The repository the source was taken from (its remote URL); recorded in the audit log." } }, "required": ["client"], diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 3f307bead6e..4814ad729e7 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -66,6 +66,24 @@ const sourceFilesSchema = z `Relative path → file text: \`workflow.ts\` plus every function-code file it references (for example \`functions/score.js\`). At most ${SOURCE_LIMITS.maxFiles} files and ${SOURCE_LIMITS.maxTotalBytes} bytes together, for a workflow of at most ${SOURCE_LIMITS.maxBlocks} blocks.` ) +/** Whether a repository URL carries credentials: any user in an `http(s)` URL, or a password. */ +function carriesCredentials(repo: string): boolean { + const userinfo = /^([a-z][a-z0-9+.-]*):\/\/([^/@]*)@/i.exec(repo) + if (!userinfo) return false + return /^https?$/i.test(userinfo[1]) || userinfo[2].includes(':') +} + +/** `provenance.repo`: the repository a source or directory was taken from, never with credentials. */ +export const provenanceRepoSchema = z + .string() + .min(1, 'provenance.repo cannot be empty') + .max(512, 'provenance.repo is too long') + .refine((repo) => !carriesCredentials(repo), { + message: + 'provenance.repo must not carry credentials: send the URL without its user and password', + }) + .describe('The repository the source was taken from (its remote URL); recorded in the audit log.') + const provenanceSchema = z .object({ client: z @@ -78,12 +96,7 @@ const provenanceSchema = z .regex(/^[0-9a-f]{7,64}$/, 'provenance.gitSha must be a hexadecimal commit hash') .optional() .describe('The commit the source was taken from; recorded in the audit log.'), - repo: z - .string() - .min(1, 'provenance.repo cannot be empty') - .max(512, 'provenance.repo is too long') - .optional() - .describe('The repository the source was taken from.'), + repo: provenanceRepoSchema.optional(), }) .strict() .optional() diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index 608076e804d..509a8c5ffa3 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -11,7 +11,10 @@ import { } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' import { v2DataResponse } from '@/lib/api/contracts/v2/shared' -import { SOURCE_PATH_MAX_LENGTH } from '@/lib/api/contracts/v2/workflow-source' +import { + provenanceRepoSchema, + SOURCE_PATH_MAX_LENGTH, +} from '@/lib/api/contracts/v2/workflow-source' const kindSchema = z .enum(APPLY_ORDER, { @@ -286,6 +289,7 @@ const applyBodySchema = z .regex(/^[0-9a-f]{7,64}$/, 'provenance.gitSha must be a hexadecimal commit hash') .optional() .describe('The commit the directory was taken from; recorded in the audit log.'), + repo: provenanceRepoSchema.optional(), }) .strict() .optional() 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 4fcb163a9ab..be4ffda675c 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2158,13 +2158,17 @@ export default workflow('', {}, () => { ) check( - 'a committed apply records one audit row carrying the client, git sha and counts', + 'a committed apply records one audit row carrying the client, git sha, repository and counts', async () => { const seeded = await seedWorkflow() const source = await getSource(seeded.workflowId) const result = await apply(source, edit(source.files, SCORE_CODE, 'return 81'), { - provenance: { client: 'cli', gitSha: '0123abcd' }, + provenance: { + client: 'cli', + gitSha: '0123abcd', + repo: 'https://github.com/acme/flows.git', + }, }) const rows = await settledAuditRows(seeded.workflowId, 1) @@ -2173,6 +2177,7 @@ export default workflow('', {}, () => { op: 'apply_source', client: 'cli', gitSha: '0123abcd', + repo: 'https://github.com/acme/flows.git', blocksAdded: 0, blocksRemoved: 0, blocksModified: 1, diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index c86179fb9ad..7be803f4356 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -427,6 +427,7 @@ function sourceAuditMetadata( catalogHash: result.base.catalogHash, ...(input.provenance ? { client: input.provenance.client } : {}), ...(input.provenance?.gitSha ? { gitSha: input.provenance.gitSha } : {}), + ...(input.provenance?.repo ? { repo: input.provenance.repo } : {}), source: principalAuditSource(principal), } } 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 a2b7f717926..ac47ebe91a2 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -379,6 +379,7 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ ...(result.failed ? { failed: `${result.failed.kind}:${result.failed.key}` } : {}), ...(input.provenance ? { client: input.provenance.client } : {}), ...(input.provenance?.gitSha ? { gitSha: input.provenance.gitSha } : {}), + ...(input.provenance?.repo ? { repo: input.provenance.repo } : {}), source: principalAuditSource(principal), }, } diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index 56350785cf3..a97ec64c0dc 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -289,6 +289,43 @@ describe('workspace source apply', () => { } ) + check( + 'the commit and repository an apply names are in its audit entries, the workflow writes included', + async () => { + const workspaceId = await newWorkspace() + const provenance = { + client: 'cli' as const, + gitSha: '0123abcd', + repo: 'git@github.com:acme/flows.git', + } + + const applied = await apply(workspaceId, STARTER, { provenance }) + + await vi.waitFor(async () => { + const rows = await db + .select({ action: auditLog.action, metadata: auditLog.metadata }) + .from(auditLog) + .where(eq(auditLog.workspaceId, workspaceId)) + const recorded = rows + .filter( + (row) => + isRecordLike(row.metadata) && + row.metadata.correlationId === applied.applyId && + (row.action === 'workspace.updated' || row.action === 'workflow.created') + ) + .map((row) => row.metadata) + expect(recorded).toHaveLength(2) + for (const metadata of recorded) { + expect(metadata).toMatchObject({ + client: 'cli', + gitSha: '0123abcd', + repo: provenance.repo, + }) + } + }) + } + ) + check('the workflow-code flag off refuses a get, and no key is allocated', async () => { const workspaceId = await newWorkspace() await setUp(workspaceId) diff --git a/apps/sim/lib/workspace-source/application/types.ts b/apps/sim/lib/workspace-source/application/types.ts index 65f9fface2a..e4dcca210e3 100644 --- a/apps/sim/lib/workspace-source/application/types.ts +++ b/apps/sim/lib/workspace-source/application/types.ts @@ -74,7 +74,7 @@ export interface PlanContext extends SourceContext { } export interface ApplyContext extends SourceContext { - provenance?: { client: 'cli' | 'api'; gitSha?: string } + provenance?: { client: 'cli' | 'api'; gitSha?: string; repo?: string } /** * The `sf1:` fingerprint of each draft this apply's workflow writes stored, by workflow id: a * later deploy of that workflow publishes exactly that draft. diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.test.ts b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts new file mode 100644 index 00000000000..aa030c88725 --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts @@ -0,0 +1,56 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { gitProvenance } from './git-provenance' + +let root: string + +function git(...args: string[]): string { + return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim() +} + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), 'sim-git-provenance-'))) +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +describe('gitProvenance', () => { + it('names the checked-out commit and the origin remote without its credentials', async () => { + git('init', '-q') + git('config', 'user.email', 'source@example.invalid') + git('config', 'user.name', 'Source') + mkdirSync(join(root, 'workspace')) + writeFileSync(join(root, 'workspace', 'secrets.ts'), '// @sim-sdk 1\n') + git('add', '.') + git('commit', '-q', '-m', 'workspace') + git( + 'remote', + 'add', + 'origin', + 'https://x-access-token:ghp_secret@github.com/acme/flows.git?t=1' + ) + + const provenance = await gitProvenance(join(root, 'workspace')) + + expect(provenance).toEqual({ + gitSha: git('rev-parse', 'HEAD'), + repo: 'https://github.com/acme/flows.git', + }) + }) + + it('keeps an scp-style remote, and sends no commit before the first one', async () => { + git('init', '-q') + git('remote', 'add', 'origin', 'git@github.com:acme/flows.git') + + expect(await gitProvenance(root)).toEqual({ repo: 'git@github.com:acme/flows.git' }) + }) + + it('sends nothing for a directory outside any repository', async () => { + expect(await gitProvenance(root)).toEqual({}) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.ts b/packages/sim-cli/src/commands/protocol/git-provenance.ts new file mode 100644 index 00000000000..3f54b0af56b --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/git-provenance.ts @@ -0,0 +1,71 @@ +/** + * Where a source directory came from in git, for the audit log of the apply that sends it: the + * commit checked out (`HEAD`) and the `origin` remote, read with the `git` binary. Best effort: a + * directory outside a repository, a missing `git`, or an embedded host (no local checkout) sends + * neither, and the apply goes ahead. + */ +import { execFile } from 'node:child_process' +import { embedStore } from '../../embed-context' + +/** How long one `git` call may take before the apply goes ahead without it. */ +const GIT_TIMEOUT_MS = 2_000 + +/** The longest repository URL the server records. */ +const MAX_REPO_LENGTH = 512 + +/** What an apply's `provenance` carries about git, each field only when read. */ +export interface GitProvenance { + gitSha?: string + repo?: string +} + +/** `git ` run in `dir`, trimmed; `null` when it fails or finds nothing. */ +function git(dir: string, args: readonly string[]): Promise { + return new Promise((resolve) => { + execFile( + 'git', + ['-C', dir, ...args], + { timeout: GIT_TIMEOUT_MS, windowsHide: true }, + (error, stdout) => { + const out = error ? '' : String(stdout).trim() + resolve(out === '' ? null : out) + } + ) + }) +} + +/** + * A remote URL with its credentials, query and fragment dropped (`https://token@host/x` → + * `https://host/x`); an scp-style address (`git@host:org/repo.git`) carries none and is kept. + * `null` for one too long to record. + */ +function sanitizedRepoUrl(remote: string): string | null { + let repo = remote + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(remote)) { + try { + const url = new URL(remote) + url.username = '' + url.password = '' + url.search = '' + url.hash = '' + repo = url.toString() + } catch { + return null + } + } + return repo.length > 0 && repo.length <= MAX_REPO_LENGTH ? repo : null +} + +/** The git commit and remote of `dir`, as far as they can be read. */ +export async function gitProvenance(dir: string): Promise { + if (embedStore.getStore()) return {} + const [head, remote] = await Promise.all([ + git(dir, ['rev-parse', 'HEAD']), + git(dir, ['config', '--get', 'remote.origin.url']), + ]) + const repo = remote ? sanitizedRepoUrl(remote) : null + return { + ...(head && /^[0-9a-f]{40,64}$/.test(head) ? { gitSha: head } : {}), + ...(repo ? { repo } : {}), + } +} 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 ef4d4f446b4..8dc745a54ae 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -21,6 +21,7 @@ import type { import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { searchTasks } from '../search' +import { gitProvenance } from './git-provenance' import { printProtocolResult } from './result' import { absoluteDirOption, @@ -507,7 +508,12 @@ export function attachWorkflowSourceApply(source: Command): void { client, operation: 'applyWorkflowSource', params: { workflowId }, - body: { files, lock, base, provenance: { client: 'cli' } }, + body: { + files, + lock, + base, + provenance: { client: 'cli', ...(await gitProvenance(options.dir)) }, + }, save: async (data) => { const edges = storedEdgesWrite( data, @@ -608,7 +614,7 @@ export function attachWorkflowSourceCreate(source: Command): void { files, ...(options.name !== undefined ? { name: options.name } : {}), ...(options.folder !== undefined ? { folderPath: options.folder } : {}), - provenance: { client: 'cli' }, + provenance: { client: 'cli', ...(await gitProvenance(options.dir)) }, }, }) }) 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 1acdd054f65..537c3838a7b 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -33,6 +33,7 @@ import type { import { SimApiError } from '../../http/client' import { apiCommand, type OperationClient } from '../../runtime/called-operations' import { searchTasks } from '../search' +import { gitProvenance } from './git-provenance' import { printProtocolResult } from './result' import { absoluteDirOption, @@ -670,6 +671,7 @@ export function attachWorkspaceSourceApply(source: Command): void { `Run it without --workspace to apply it to ${from}, or promote it with --to ${named}: its resources bind by key to that workspace's own, and the directory stays bound to ${from}.` ) ?? undefined ) + const provenance = await gitProvenance(options.dir) const post = async (submission: WorkspaceSubmission, dryRun: boolean) => { const body: ApplyWorkspaceSourceBody = { files: submission.files, @@ -680,7 +682,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ...(options.allowDelete ? { allowDelete: true } : {}), ...(only ? { only } : {}), }, - provenance: { client: 'cli' }, + provenance: { client: 'cli', ...provenance }, } const response = await client.request( 'applyWorkspaceSource', diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index de6fa7529de..65db3d26f91 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1139,6 +1139,7 @@ export type ApplyWorkspaceSourceBody = { provenance?: { client: 'cli' | 'api' gitSha?: string + repo?: string } } From 1d946657945776516a0ad00a5126436c97e43a15 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:31:42 -0800 Subject: [PATCH 039/104] fix(workspace-source): a chat write publishes only the draft the plan vouched for Writing a chat redeploys the workflow when its draft differs from the live version, and that redeploy published whatever the draft was, so a draft edited between a vouched deploy (or the plan) and the chat write went live through it. The chat replace use case takes expectedDraftFingerprint and admits its redeploy's snapshot through the same check a deploy uses, refusing a moved draft with WorkflowDraftChangedError. The deployment adapter passes the vouched draft, or for a chat write without a deploy the draft its plan saw, and reports a moved draft as stale. --- .../application/workflow-chat-deployment.ts | 21 ++++++ .../lib/workflows/application/deployments.ts | 49 ++++++++++---- .../workflows/orchestration/chat-deploy.ts | 4 ++ .../application/deployments.integration.ts | 30 +++++++++ .../application/kinds/deployment/adapter.ts | 65 +++++++++++++++---- packages/workspace-code/DESIGN.md | 5 +- 6 files changed, 148 insertions(+), 26 deletions(-) diff --git a/apps/sim/lib/chat-deployments/application/workflow-chat-deployment.ts b/apps/sim/lib/chat-deployments/application/workflow-chat-deployment.ts index 970d69e4c7e..8fe59a1bc59 100644 --- a/apps/sim/lib/chat-deployments/application/workflow-chat-deployment.ts +++ b/apps/sim/lib/chat-deployments/application/workflow-chat-deployment.ts @@ -29,6 +29,8 @@ import { buildChatDeploymentUrl } from '@/lib/chat-deployments/urls' import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { resolveCopilotSecretReference } from '@/lib/core/application/environment-reference' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { expectedDraft } from '@/lib/workflows/application/deployments' +import { resolvePrincipalWorkflowContext } from '@/lib/workflows/application/principal-scope' import { performChatDeploy, performChatUndeploy } from '@/lib/workflows/orchestration' import { validateChatDeployAuth } from '@/ee/access-control/utils/permission-check' @@ -71,6 +73,12 @@ export interface ReplaceWorkflowChatDeploymentInput extends WorkflowChatDeployme includeThinking?: boolean includeToolCalls?: boolean requestId: string + /** + * The `sf1:` fingerprint of the draft the caller vouches for: when the write must redeploy the + * workflow (its draft differs from the live version), a draft that no longer has it is refused + * with `conflict`, nothing deployed or written. + */ + expectedDraftFingerprint?: string } export interface WorkflowChatDeploymentResult { @@ -264,6 +272,17 @@ export const replaceWorkflowChatDeployment = defineAuthorizedWorkspaceUseCase({ const attribution = resolvePrincipalAttribution(principal, { workspaceBillingOwnerUserId: context.billedAccountUserId, }) + const draftCheck = + input.expectedDraftFingerprint !== undefined + ? expectedDraft( + principal, + await resolvePrincipalWorkflowContext({ + principal, + input: { workflowId: context.workflowId }, + }), + input.expectedDraftFingerprint + ) + : undefined const result = await performChatDeploy({ workflowId: context.workflowId, userId: attribution.attributedUserId, @@ -282,7 +301,9 @@ export const replaceWorkflowChatDeployment = defineAuthorizedWorkspaceUseCase({ workspaceId: context.workspaceId, requestId: input.requestId, projectLegacyAudit: false, + ...(draftCheck ? { admitDraft: draftCheck.admitDraft } : {}), }).catch(chatIdentifierUniquenessConflict(input.identifier)) + draftCheck?.assertAdmitted() if (!result.success) { /** diff --git a/apps/sim/lib/workflows/application/deployments.ts b/apps/sim/lib/workflows/application/deployments.ts index de76678eba9..3fc8e62f30d 100644 --- a/apps/sim/lib/workflows/application/deployments.ts +++ b/apps/sim/lib/workflows/application/deployments.ts @@ -153,19 +153,43 @@ async function lintDeployedVersion( } } +/** A publish refused because the draft no longer has the fingerprint its caller expected. */ +export class WorkflowDraftChangedError extends OrchestrationError { + constructor() { + super( + 'conflict', + 'The workflow draft changed since it was applied, so it was not deployed. Read it again to review the change, then deploy.' + ) + this.name = 'WorkflowDraftChangedError' + } +} + /** - * A deploy's draft check: the snapshot it publishes must print with `expected`, the fingerprint of - * the draft the caller reviewed or wrote. + * A publish's draft check: the snapshot it publishes must print with `expected`, the fingerprint + * of the draft the caller reviewed or wrote. Every path that may publish a draft for a caller + * holding such a fingerprint (a deploy, a chat write that redeploys) admits its snapshot through + * `admitDraft`; after a failed publish, `assertAdmitted` throws {@link WorkflowDraftChangedError} + * when this check is what refused it. */ -function expectedDraft( +export function expectedDraft( principal: Principal, context: ActiveWorkflowApplicationContext, expected: string -): (draft: WorkflowState) => Promise { - return async (draft) => - (await draftSourceFingerprint(principal, context, draft)) === expected - ? null - : 'The workflow draft changed since it was applied, so it was not deployed. Read it again to review the change, then deploy.' +): { + admitDraft: (draft: WorkflowState) => Promise + assertAdmitted: () => void +} { + let refused = false + return { + async admitDraft(draft) { + if ((await draftSourceFingerprint(principal, context, draft)) === expected) return null + refused = true + return new WorkflowDraftChangedError().message + }, + assertAdmitted() { + if (refused) throw new WorkflowDraftChangedError() + }, + } } export const deployWorkflow = defineAuthorizedWorkflowUseCase({ @@ -176,6 +200,10 @@ export const deployWorkflow = defineAuthorizedWorkflowUseCase({ const attribution = resolvePrincipalAttribution(principal, { workspaceBillingOwnerUserId: context.billedAccountUserId, }) + const draftCheck = + input.expectedDraftFingerprint !== undefined + ? expectedDraft(principal, context, input.expectedDraftFingerprint) + : undefined const result = await performFullDeploy({ workflowId: context.workflowId, userId: attribution.attributedUserId, @@ -186,10 +214,9 @@ export const deployWorkflow = defineAuthorizedWorkflowUseCase({ versionDescription: input.description, requestId: input.requestId, idempotencyKey: input.idempotencyKey, - ...(input.expectedDraftFingerprint !== undefined - ? { admitDraft: expectedDraft(principal, context, input.expectedDraftFingerprint) } - : {}), + ...(draftCheck ? { admitDraft: draftCheck.admitDraft } : {}), }) + draftCheck?.assertAdmitted() if (!result.success) throwDeploymentFailure(result, 'Failed to deploy workflow') const lint = input.lintDeployedVersion && result.deploymentVersionId diff --git a/apps/sim/lib/workflows/orchestration/chat-deploy.ts b/apps/sim/lib/workflows/orchestration/chat-deploy.ts index 0b01e31ad6a..ca61bcc0f14 100644 --- a/apps/sim/lib/workflows/orchestration/chat-deploy.ts +++ b/apps/sim/lib/workflows/orchestration/chat-deploy.ts @@ -12,6 +12,7 @@ import { encryptSecret } from '@/lib/core/security/encryption' import { checkNeedsRedeployment } from '@/lib/workflows/deployment-status' import { getWorkflowDeploymentSummary, + type PerformFullDeployParams, performFullDeploy, } from '@/lib/workflows/orchestration/deploy' @@ -45,6 +46,8 @@ export interface ChatDeployPayload { captureDeploymentAnalytics?: false projectLegacyAudit?: boolean captureLegacyTelemetry?: boolean + /** Checks the draft a redeploy this chat write needs would publish (see `performFullDeploy`). */ + admitDraft?: PerformFullDeployParams['admitDraft'] } export interface PerformChatDeployResult { @@ -206,6 +209,7 @@ export async function performChatDeploy( versionName: params.versionName, idempotencyKey: params.idempotencyKey, captureAnalytics: params.captureDeploymentAnalytics, + ...(params.admitDraft ? { admitDraft: params.admitDraft } : {}), }) if (!deployResult.success) { return { diff --git a/apps/sim/lib/workspace-source/application/deployments.integration.ts b/apps/sim/lib/workspace-source/application/deployments.integration.ts index f90e654f367..be7e2c32faa 100644 --- a/apps/sim/lib/workspace-source/application/deployments.integration.ts +++ b/apps/sim/lib/workspace-source/application/deployments.integration.ts @@ -1254,4 +1254,34 @@ describe('workspace source: deployments', () => { } } ) + + check( + 'a chat write refuses a draft edited between the plan and the write, publishing nothing', + async () => { + const { workspaceId, id, files, base } = await deployedWorkspace() + const check = deploymentAdapter.storedFingerprintNow + if (!check) throw new Error('The deployment adapter checks fingerprints before writing') + // A teammate edits the draft just before the chat write, which would redeploy it. + const racing = vi + .spyOn(deploymentAdapter, 'storedFingerprintNow') + .mockImplementation(async (change, ctx) => { + await editDraftOutOfBand(id, 'Edited meanwhile: ') + return check.call(deploymentAdapter, change, ctx) + }) + try { + const result = await apply( + workspaceId, + { ...asSent(files, workspaceId), [DEPLOYMENT]: answerChat('racing-chat') }, + { base } + ) + expect(racing).toHaveBeenCalledOnce() + expect([result.failed?.key, result.failed?.code]).toEqual(['nightly', 'E_APPLY_STALE']) + const after = await deployState(id) + expect(after.versions).toBe(1) + expect(after.chat).toBeUndefined() + } finally { + racing.mockRestore() + } + } + ) }) diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 616d29a5f11..37346edc310 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -54,6 +54,7 @@ import { deployWorkflow, readWorkflowDeploymentStatus, undeployWorkflow, + WorkflowDraftChangedError, } from '@/lib/workflows/application/deployments' import { listWorkflows } from '@/lib/workflows/application/list-workflows' import { workflowOperations } from '@/lib/workflows/application/operations' @@ -115,8 +116,9 @@ export interface DeploymentPlan { /** Publish the draft: a first deploy, or `live: 'draft'` with a draft that differs. */ deploy: boolean /** - * The draft a deploy publishes: the one this apply's workflow write stores (`written`, its - * fingerprint known once written), or the draft with the `sf1:` fingerprint the plan vouched for. + * The draft a deploy, or a chat write that redeploys, may publish: the one this apply's workflow + * write stores (`written`, its fingerprint known once written), or the draft with the `sf1:` + * fingerprint the plan vouched for (for a chat write without a deploy, the draft it saw). */ draft?: { written: true } | { fingerprint: string } /** The public API flag to set: on a first deploy (an undeploy keeps the old one), or a change. */ @@ -588,6 +590,15 @@ async function planDeployment( } } const writesChat = detail.chat === 'replace' + // A chat write redeploys a draft that differs from the live version: it may publish only the + // draft the plan vouched for, or else the one it saw, never one edited since. + if (writesChat && !detail.draft && workflowId) { + const seen = await readWorkflowSource.execute({ + principal: ctx.principal, + input: { workflowId }, + }) + detail.draft = { fingerprint: seen.base.fingerprint } + } // A chat the apply keeps goes live with the edited draft all the same. const publishesEditedDraft = detail.deploy && draftEdited if (decl.chat && (writesChat || publishesEditedDraft)) { @@ -612,6 +623,29 @@ function idempotencyKey(decl: DeploymentDecl, workflowId: string, live: string | * Deploys the draft unless it already is the live version: a re-run after a deploy that * succeeded finds nothing to publish, and one after a deploy that failed replays the same key. */ +/** + * The `sf1:` fingerprint of the draft change `change` may publish on workflow `workflowId`, or + * `undefined` when its plan vouched for none (a chat write on a workflow this apply creates). + */ +function expectedDraftOf( + change: DeploymentChange, + workflowId: string, + ctx: ApplyContext +): string | undefined { + const draft = change.detail?.draft + return draft && 'written' in draft ? ctx.writtenDrafts.get(workflowId) : draft?.fingerprint +} + +/** Runs a publish, refusing as stale a draft that moved since the plan vouched for it. */ +async function publishing(change: DeploymentChange, publish: () => Promise) { + try { + await publish() + } catch (error) { + if (!(error instanceof WorkflowDraftChangedError)) throw error + throw new ResourceChangedError({ kind: 'workflow', key: change.key }) + } +} + async function deployDraft( change: DeploymentChange, decl: DeploymentDecl, @@ -619,14 +653,12 @@ async function deployDraft( ctx: ApplyContext ) { const { principal } = ctx - const draft = change.detail?.draft - const expectedDraftFingerprint = - draft && 'written' in draft ? ctx.writtenDrafts.get(workflowId) : draft?.fingerprint + const expectedDraftFingerprint = expectedDraftOf(change, workflowId, ctx) if (!expectedDraftFingerprint) throw new Error('A deploy needs the draft it publishes') const status = await readWorkflowDeploymentStatus.execute({ principal, input: { workflowId } }) if (status.isDeployed && !status.needsRedeployment) return - try { - await deployWorkflow.execute({ + await publishing(change, () => + deployWorkflow.execute({ principal, input: { workflowId, @@ -639,11 +671,7 @@ async function deployDraft( ), }, }) - } catch (error) { - // The draft moved since the plan vouched for it (or since this apply wrote it): it is stale. - if (!(error instanceof OrchestrationError) || error.code !== 'conflict') throw error - throw new ResourceChangedError({ kind: 'workflow', key: change.key }) - } + ) } /** The block ids a chat's outputs name, refusing a block the workflow does not have. */ @@ -922,7 +950,18 @@ export const deploymentAdapter: KindAdapter<'deployment', StoredDeployment> = { }) } if (detail.deploy) await deployDraft(change, decl, workflowId, ctx) - if (chatInput) await replaceWorkflowChatDeployment.execute({ principal, input: chatInput }) + if (chatInput) { + const expectedDraftFingerprint = expectedDraftOf(change, workflowId, ctx) + await publishing(change, () => + replaceWorkflowChatDeployment.execute({ + principal, + input: { + ...chatInput, + ...(expectedDraftFingerprint ? { expectedDraftFingerprint } : {}), + }, + }) + ) + } if (detail.chat === 'delete') { await deleteWorkflowChatDeployment.execute({ principal, input: { workflowId } }) } diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index d2955d043de..7e40ef9d54d 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -233,8 +233,9 @@ redeploys and reports `I_DEPLOY_DRAFT_NOT_LIVE`. `'draft'` publishes only a draf vouches for: the one this apply's workflow write stored, or one that still prints as the workflow folder's base. A draft holding edits made outside source is not deployed (`W_DEPLOY_DRAFT_NOT_SOURCE`; a chat write, which would deploy it, is `E_DEPLOY_DRAFT_NOT_SOURCE_CHAT`), -and every deploy names the vouched draft's `sf1:` fingerprint (`expectedDraftFingerprint`), so a draft -edited between the plan and the deploy is refused as stale rather than published. A deploy's idempotency key hashes the deployment's +and every deploy, and every chat write (which redeploys a draft that differs), names the vouched +draft's `sf1:` fingerprint (`expectedDraftFingerprint`), so a draft edited between the plan and the +write is refused as stale rather than published. A deploy's idempotency key hashes the deployment's fingerprint and the live version it replaces. The flag, the deploy and the chat are separate writes, so the apply checks what the chat write refuses (an identifier another chat holds, `E_DEPLOY_CHAT_IDENTIFIER`, at plan time and again before the first write; the password, the From 1bc0a1a5beb8daabc0aa868faa98b3f67da11cb1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:55:31 -0800 Subject: [PATCH 040/104] fix(workflow-code): the source plan reads check the preview flag like every source operation The status plan operations (workflows.source.plan, workspaces.source.plan) were added on a base where each use case called requireWorkflowCodeEnabled and the workspace operations spread SOURCE_PRINCIPAL_POLICY. The flag check now lives on the operation (feature: WORKFLOW_CODE_FEATURE), checked after authorization, and the per-use-case helper is gone: both plan operations declare the feature and drop their own check, and the deploy draft fingerprint keeps the Principal type import the flag cleanup removed. The workflow-code rule now describes the operation-level gate. --- .claude/rules/sim-workflow-code.md | 7 ++++--- .cursor/rules/sim-workflow-code.mdc | 7 ++++--- .../sim/lib/workflows/application/apply-workflow-source.ts | 1 - apps/sim/lib/workflows/application/operations.ts | 1 + apps/sim/lib/workflows/application/read-workflow-source.ts | 2 +- .../workspace-source/application/apply-workspace-source.ts | 1 - apps/sim/lib/workspace-source/application/operations.ts | 2 +- 7 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index 361534c96ec..91aeb6975ad 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -73,9 +73,10 @@ and "The catalog". One global flag, `workflow-code` (`lib/core/config/feature-flags.ts`, env fallback `WORKFLOW_CODE`), gates workflow source, workspace source, the source catalog and resources, and -the Code tab. Every use case calls `requireWorkflowCodeEnabled()` -(`lib/workflows/code/feature-flag.ts`); the UI reads it from the workspace layout's flags. A new -surface gates through the same function, never its own check. +the Code tab. Every operation declares `feature: WORKFLOW_CODE_FEATURE` +(`lib/workflows/application/operations.ts`), which the shared use-case wrapper checks after +authorization (`FEATURE_NOT_ENABLED`); the UI reads it from the workspace layout's flags. A new +operation declares the same feature, never its own check. ## Adding things diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index bb37474bbe5..fdd56c3e701 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -63,9 +63,10 @@ and "The catalog". One global flag, `workflow-code` (`lib/core/config/feature-flags.ts`, env fallback `WORKFLOW_CODE`), gates workflow source, workspace source, the source catalog and resources, and -the Code tab. Every use case calls `requireWorkflowCodeEnabled()` -(`lib/workflows/code/feature-flag.ts`); the UI reads it from the workspace layout's flags. A new -surface gates through the same function, never its own check. +the Code tab. Every operation declares `feature: WORKFLOW_CODE_FEATURE` +(`lib/workflows/application/operations.ts`), which the shared use-case wrapper checks after +authorization (`FEATURE_NOT_ENABLED`); the UI reads it from the workspace layout's flags. A new +operation declares the same feature, never its own check. ## Adding things diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 7be803f4356..fcb0ec7574c 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -317,7 +317,6 @@ export const planWorkflowSource = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.planSource, resolveContext: resolvePrincipalWorkflowContext, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) return runSourceApply( principal, { files: input.files, lock: input.lock, dryRun: true }, diff --git a/apps/sim/lib/workflows/application/operations.ts b/apps/sim/lib/workflows/application/operations.ts index eb8c42efba9..6b70b15d895 100644 --- a/apps/sim/lib/workflows/application/operations.ts +++ b/apps/sim/lib/workflows/application/operations.ts @@ -261,6 +261,7 @@ export const workflowOperations = { // permission-group-exempt: a plan stores nothing; the block and value gates it reports are judged per block against the principal's human subject, as for applySource planSource: defineWorkspaceOperation({ id: 'workflows.source.plan', + feature: WORKFLOW_CODE_FEATURE, oauthScope: 'api:read', minimumRole: 'read', workspaceApiKey: 'deny', diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index 8b884b198c4..a9b0f9fcaf9 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -1,4 +1,4 @@ -import { resolvePrincipalSubjectUserId } from '@sim/auth/principal' +import { type Principal, resolvePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import { mapWithConcurrency } from '@sim/utils/concurrency' import { compareStrings } from '@sim/utils/string' 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 ac47ebe91a2..f03ebff47f0 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -278,7 +278,6 @@ export const readWorkspaceSourcePlan = defineAuthorizedWorkspaceUseCase({ resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }): Promise { - await requireWorkflowCodeEnabled(principal, context) const plan = await planWorkspaceSource(input, sourceContext(principal, context)) return planned(plan, context.workspaceId, true) }, diff --git a/apps/sim/lib/workspace-source/application/operations.ts b/apps/sim/lib/workspace-source/application/operations.ts index 34c9d100a0b..0e35ae96400 100644 --- a/apps/sim/lib/workspace-source/application/operations.ts +++ b/apps/sim/lib/workspace-source/application/operations.ts @@ -37,7 +37,7 @@ export const workspaceSourceOperations = { minimumRole: 'read', workspaceApiKey: 'allow', capability: 'none', - ...SOURCE_PRINCIPAL_POLICY, + ...SOURCE_OPERATION_POLICY, }), // permission-group-exempt: each change runs through the use case that owns it, which applies that kind's capability apply: defineWorkspaceOperation({ From a812a0ed8f05a4d467e4a320565d0d7e8dd00884 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:55:31 -0800 Subject: [PATCH 041/104] chore(generated): regenerate OpenAPI, CLI API and CLI docs for the wave-1 fixes --- apps/docs/content/docs/cli/reference.mdx | 6 +- apps/docs/content/docs/cli/workflows.mdx | 4 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 9744 +++++++++++++-------- packages/sim-cli/src/generated/v2-api.ts | 1121 ++- 5 files changed, 7297 insertions(+), 3580 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index ece8e7a24dd..a9a19b587cc 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8580,7 +8580,7 @@ sim workflows source apply [workflowId] [options] | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | +| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | @@ -8641,7 +8641,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -10019,7 +10019,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 67ee2371941..e6c6a16dea1 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1396,7 +1396,7 @@ sim workflows source apply [workflowId] [options] | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | | `--deploy` | No | After the write is saved, deploy the workflow (as `sim workflows deploy ` does). | -| `--allow-delete` | No | Delete blocks the source no longer declares; without it, an apply that deletes a block is refused. | +| `--allow-delete` | No | Delete blocks and variables the source no longer declares; without it, an apply that deletes one is refused. | @@ -1445,7 +1445,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index e7a6ba6c4c7..6a60ac84c57 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF. --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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in every mode, as the server refuses it. In workflow.ts, W_UNKNOWN_OUTPUT_PATH and W_UNRESOLVED_REF (a reference to an output or block that does not exist) are the error E_APPLY_UNRESOLVED_REF on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). 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. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 6cb8a73c751..e6152101193 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6075,9 +6075,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -6237,6 +6237,195 @@ } } }, + "/api/v2/workflows/{workflowId}/source/plan": { + "post": { + "operationId": "planWorkflowSource", + "summary": "Plan workflow source", + "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workflows.source.plan", + "x-oauth-scope": "api:read", + "tags": ["Workflows"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:read"] + } + ], + "parameters": [ + { + "name": "workflowId", + "in": "path", + "required": true, + "description": "Unique workflow identifier.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Unique workflow identifier.", + "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] + } + }, + { + "name": "allowDelete", + "in": "query", + "required": false, + "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "schema": { + "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "type": "boolean" + } + } + ], + "requestBody": { + "required": true, + "description": "Edited source files with the lock and base they were read with.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlanWorkflowSourceBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The evaluated source.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlanWorkflowSourceResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": true, + "applied": false, + "diff": { + "noop": true, + "blocks": { + "added": [], + "removed": [], + "renamed": [], + "modified": [] + }, + "edges": { + "added": 0, + "removed": 0 + }, + "variables": { + "added": [], + "removed": [], + "modified": [] + } + }, + "diagnostics": [], + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + }, + "mintedIds": {}, + "notes": [], + "needsRedeployment": false + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v2/workspaces/{workspaceId}/workflows/source": { "post": { "operationId": "createWorkflowFromSource", @@ -6280,9 +6469,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "schema": { - "description": "Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.", + "description": "Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.", "type": "boolean" } } @@ -8858,20 +9047,20 @@ } } }, - "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { + "/api/v2/workspaces/{workspaceId}/source/plan": { "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`.", - "x-sim-operation": "workspaces.source.blobs.missing", - "x-oauth-scope": "api:write", + "operationId": "planWorkspaceSource", + "summary": "Plan workspace source", + "description": "Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workspaces.source.plan", + "x-oauth-scope": "api:read", "tags": ["Workflows"], "security": [ { "apiKey": [] }, { - "oauthBearer": ["api:write"] + "oauthBearer": ["api:read"] } ], "parameters": [ @@ -8890,22 +9079,42 @@ ], "requestBody": { "required": true, - "description": "The binary files an apply will need.", + "description": "The directory files, its managed kinds and the base they were read with.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" + "$ref": "#/components/schemas/PlanWorkspaceSourceBody" }, "examples": { "example1": { "summary": "Request example 1", "value": { - "blobs": [ - { - "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", - "size": 18432 + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "kinds": ["table"], + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } } - ] + } } } } @@ -8914,7 +9123,7 @@ }, "responses": { "200": { - "description": "The binary files still to stage.", + "description": "The planned changes.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -8929,7 +9138,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" + "$ref": "#/components/schemas/PlanWorkspaceSourceResponse" }, "examples": { "example1": { @@ -8937,40 +9146,191 @@ "value": { "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "missing": [ - "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e" - ] - } - } - } - } - } - } - }, - "400": { - "$ref": "#/components/responses/BadRequest" - }, - "401": { - "$ref": "#/components/responses/Unauthorized" - }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, - "404": { - "$ref": "#/components/responses/NotFound" - }, - "409": { - "$ref": "#/components/responses/Conflict" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, - "423": { - "$ref": "#/components/responses/Locked" - }, + "dryRun": true, + "plan": [ + { + "kind": "table", + "key": "leads", + "action": "noop", + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" + } + ], + "applied": [], + "needBlobs": [], + "files": {}, + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "diagnostics": [] + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/workspaces/{workspaceId}/source/blobs/missing": { + "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`.", + "x-sim-operation": "workspaces.source.blobs.missing", + "x-oauth-scope": "api:write", + "tags": ["Workflows"], + "security": [ + { + "apiKey": [] + }, + { + "oauthBearer": ["api:write"] + } + ], + "parameters": [ + { + "name": "workspaceId", + "in": "path", + "required": true, + "description": "Workspace to read or apply.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace to read or apply." + } + } + ], + "requestBody": { + "required": true, + "description": "The binary files an apply will need.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsBody" + }, + "examples": { + "example1": { + "summary": "Request example 1", + "value": { + "blobs": [ + { + "sha256": "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e", + "size": 18432 + } + ] + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The binary files still to stage.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FindMissingWorkspaceSourceBlobsResponse" + }, + "examples": { + "example1": { + "summary": "Response example 1", + "value": { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "missing": [ + "9f2c4e6a8b0d1f3e5a7c9b2d4f6e8a0c1b3d5f7e9a2c4b6d8f0e1a3c5b7d9f2e" + ] + } + } + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, + "423": { + "$ref": "#/components/responses/Locked" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -9496,7 +9856,8 @@ "INTEGRATION_NOT_ALLOWED", "INSUFFICIENT_SCOPE", "READ_ONLY_API_KEY", - "SCIM_MANAGED_MEMBERSHIP" + "SCIM_MANAGED_MEMBERSHIP", + "FEATURE_NOT_ENABLED" ], "title": "Forbidden detail code", "description": "Stable cause code for an actionable `403` response." @@ -18814,6 +19175,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -18924,10 +19287,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -19259,6 +19625,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19369,10 +19737,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -19978,7 +20349,7 @@ } ] }, - "CreateWorkflowFromSourceResponse": { + "PlanWorkflowSourceResponse": { "type": "object", "properties": { "data": { @@ -20221,6 +20592,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -20331,10 +20704,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", "E_WORKFLOW_META_INVALID" ], @@ -20636,25 +21012,19 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Create workflow from source response", - "description": "The outcome, with the source re-printed from the saved workflow.", + "title": "Plan workflow source response", + "description": "What an apply would store, and every finding.", "examples": [ { "data": { "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, - "applied": true, + "dryRun": true, + "applied": false, "diff": { - "noop": false, + "noop": true, "blocks": { - "added": [ - { - "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", - "key": "start", - "type": "start_trigger" - } - ], + "added": [], "removed": [], "renamed": [], "modified": [] @@ -20692,16 +21062,14 @@ "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" }, - "mintedIds": { - "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" - }, + "mintedIds": {}, "notes": [], "needsRedeployment": false } } ] }, - "CreateWorkflowFromSourceBody": { + "PlanWorkflowSourceBody": { "type": "object", "properties": { "files": { @@ -20716,1716 +21084,1385 @@ }, "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." }, - "name": { - "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", - "type": "string", - "minLength": 1, - "maxLength": 255 - }, - "description": { - "description": "Workflow description. Defaults to the description in the source.", - "anyOf": [ - { - "type": "string", - "maxLength": 50000 - }, - { - "type": "null" - } - ] - }, - "folderPath": { - "$ref": "#/components/schemas/FolderPathInput" - }, - "provenance": { - "description": "Where the source came from, for the audit log.", + "lock": { "type": "object", "properties": { - "client": { - "type": "string", - "enum": ["cli", "copilot", "canvas", "api"], - "description": "What submitted the source." - }, - "gitSha": { - "description": "The commit the source was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" + "version": { + "type": "number", + "const": 1, + "description": "Lock format version." }, - "repo": { - "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "The repository the source was taken from (its remote URL); recorded in the audit log." - } - }, - "required": ["client"], - "additionalProperties": false - } - }, - "required": ["files"], - "additionalProperties": false, - "title": "Create workflow from source body", - "description": "Source files and where to create the workflow." - }, - "GetSourceResourcesResponse": { - "type": "object", - "properties": { - "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, - "tables": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "columns": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Column name, as row data names it." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "currency", - "boolean", - "date", - "json", - "select" - ], - "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." - }, - "options": { - "description": "Option names a `select` column accepts, as table blocks read and write them.", - "type": "array", - "items": { - "type": "string" - } - }, - "multiple": { - "description": "A `select` column whose cells hold several options.", - "type": "boolean" - }, - "required": { - "description": "Every row holds a value.", - "type": "boolean" - } - }, - "required": ["name", "type"], - "additionalProperties": false - }, - "description": "Columns in table order." - } - }, - "required": ["key", "id", "name", "columns"], - "additionalProperties": false, - "description": "A table: `table(key)`." + "blocks": { + "type": "object", + "propertyNames": { + "type": "string" }, - "description": "Tables, oldest first." - }, - "knowledgeBases": { - "type": "array", - "items": { + "additionalProperties": { "type": "object", "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, "id": { "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A knowledge base: `knowledgeBase(key)`." - }, - "description": "Knowledge bases, oldest first." - }, - "credentials": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." + "description": "Block id." }, - "id": { - "type": "string", - "description": "Resource id." + "parent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Key of the enclosing loop or parallel, or null." }, - "name": { - "type": "string", - "description": "Current display name." + "branches": { + "description": "Condition or router branch key → stored branch id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } }, - "provider": { - "type": "string", - "description": "The provider the credential is for, e.g. `slack` or `google-email`." - } - }, - "required": ["key", "id", "name", "provider"], - "additionalProperties": false, - "description": "A saved credential: `credential(key)`." - }, - "description": "Saved credentials, oldest first. Secrets are listed under `env`." - }, - "workflows": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." + "items": { + "description": "Per field, its id-bearing items (input format fields) in stored order.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Item name." + }, + "id": { + "type": "string", + "description": "Item id." + } + }, + "required": ["name", "id"], + "additionalProperties": false, + "description": "One id-bearing list item." + } + } }, - "id": { + "ident": { "type": "string", - "description": "Resource id." + "description": "The `const` name the block is printed as." }, - "name": { - "type": "string", - "description": "Current display name." + "order": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Declaration-order tie-break." }, - "inputs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Input field name." - }, - "type": { - "type": "string", - "description": "Input field type, e.g. `string` or `number`." - } + "layout": { + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "Canvas x position." }, - "required": ["name", "type"], - "additionalProperties": false + "y": { + "type": "number", + "description": "Canvas y position." + }, + "w": { + "description": "Container width.", + "type": "number" + }, + "h": { + "description": "Container height.", + "type": "number" + }, + "height": { + "description": "Stored block height.", + "type": "number" + }, + "horizontalHandles": { + "description": "Handles on the left and right.", + "type": "boolean" + } }, - "description": "Inputs the workflow start block declares." + "required": ["x", "y"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Stored canvas geometry; applied only to new blocks." + }, + "codeFile": { + "description": "Path of the block’s function-code file.", + "type": "string" } }, - "required": ["key", "id", "name", "inputs"], - "additionalProperties": false, - "description": "A workflow: `childWorkflow(key)`." + "required": ["id", "parent", "ident", "order"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "One block’s identity." }, - "description": "Workflows, oldest first." + "description": "Block key → identity." }, - "skills": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace skill: `skill(key)`." + "variables": { + "type": "object", + "propertyNames": { + "type": "string" }, - "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." - }, - "customTools": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "A workspace custom tool, by its title: `customTool(key)`." + "additionalProperties": { + "type": "string" }, - "description": "Workspace custom tools, oldest first." + "description": "Variable key → variable id." + } + }, + "required": ["version", "blocks", "variables"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." + }, + "base": { + "type": "object", + "properties": { + "version": { + "default": 1, + "description": "Base format version; a base written before it existed reads as 1.", + "type": "number", + "const": 1 }, - "mcpServers": { - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "type": "string", - "description": "The key workflow source names this resource by; it never changes once assigned." - }, - "id": { - "type": "string", - "description": "Resource id." - }, - "name": { - "type": "string", - "description": "Current display name." - }, - "tools": { - "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": ["key", "id", "name"], - "additionalProperties": false, - "description": "An MCP server the workspace consumes: `mcp(key)`." - }, - "description": "MCP servers, oldest first." + "workflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow the source was read from; an apply to another workflow is refused." }, - "env": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." + "workspaceId": { + "type": "string", + "description": "Workspace the workflow belongs to." }, - "truncated": { - "type": "boolean", - "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." + "fingerprint": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." + }, + "catalogHash": { + "type": "string", + "description": "Hash of the block catalog the source was printed against." } }, - "required": [ - "workspaceId", - "tables", - "knowledgeBases", - "credentials", - "workflows", - "skills", - "customTools", - "mcpServers", - "env", - "truncated" - ], - "additionalProperties": false, - "description": "Response data." + "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`." } }, - "required": ["data"], + "required": ["files", "lock", "base"], "additionalProperties": false, - "title": "Get source resources response", - "description": "The workspace resources workflow source can name.", + "title": "Plan workflow source body", + "description": "Edited source files with the lock and base they were read with.", "examples": [ { - "data": { - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "tables": [ - { - "key": "tickets", - "id": "tbl_4f1c2a9e", - "name": "Tickets", - "columns": [ - { - "name": "subject", - "type": "string" - }, - { - "name": "status", - "type": "select", - "options": ["open", "closed"] - } - ] - } - ], - "knowledgeBases": [ - { - "key": "docs", - "id": "kb_93a1e7c2", - "name": "Docs" - } - ], - "credentials": [ - { - "key": "support-slack", - "id": "cred_51d0b8f4", - "name": "Support Slack", - "provider": "slack" - } - ], - "workflows": [ - { - "key": "assign-owner", - "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", - "name": "Assign owner", - "inputs": [ - { - "name": "leads", - "type": "array" - } - ] - } - ], - "skills": [ - { - "key": "triage", - "id": "skl_7e2a4c19", - "name": "Triage" - } - ], - "customTools": [ - { - "key": "lookup-order", - "id": "ctl_2b8d6f03", - "name": "lookup_order" - } - ], - "mcpServers": [ - { - "key": "github", - "id": "mcp-1a2b3c4d", - "name": "GitHub", - "tools": ["create_issue", "list_issues"] + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 } - ], - "env": ["CRM_KEY"], - "truncated": false + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" } } ] }, - "WorkspaceForkPreview": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." - }, - "sourceWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace the workflows and resources are copied from." - }, - "workflows": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - } - }, - "required": ["sourceWorkflowId", "name"], - "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." - }, - "selectedResourceCount": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources explicitly selected for copying." - }, - "draftOnly": { - "type": "boolean", - "const": true, - "description": "True because fork creation produces undeployed drafts." - } - }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "workflows", - "selectedResourceCount", - "draftOnly" - ], - "additionalProperties": false, - "title": "Workspace fork preview", - "description": "Read-only fork plan and fingerprint." - }, - "PreviewWorkspaceForkResponse": { + "CreateWorkflowFromSourceResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceForkPreview" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Preview workspace fork response", - "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", - "examples": [ - { - "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "workflows": [], - "selectedResourceCount": 0, - "draftOnly": true - } - } - ] - }, - "PreviewWorkspaceForkBody": { - "type": "object", - "properties": { - "name": { - "description": "Display name of the workflow or workspace.", - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "files": { - "description": "Workspace file IDs to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "workflowId": { + "type": "string", + "description": "Workflow id." }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "workspaceId": { + "type": "string", + "description": "Workspace id." }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "dryRun": { + "type": "boolean", + "description": "True when nothing was written because `dryRun` was set." }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false, - "title": "Preview workspace fork request", - "description": "Optional child name and explicitly selected resource copies." - }, - "WorkspaceOperationReport": { - "type": "object", - "properties": { - "operationId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Durable operation identifier to use for polling." - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." - }, - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." - }, - "kind": { - "type": "string", - "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], - "description": "Type of committed workspace operation." - }, - "applied": { - "type": "boolean", - "const": true, - "description": "The business transaction committed, including when follow-up work fails." - }, - "status": { - "type": "string", - "enum": [ - "processing", - "completed", - "completed_with_warnings", - "requires_configuration", - "failed" - ], - "description": "Operation status; failed follow-up work does not undo the committed transaction." - }, - "resourceIds": { - "maxItems": 5000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - "description": "Identifiers of resources created or changed by the committed operation." - }, - "issues": { - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "code": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable machine-readable issue code." - }, - "message": { - "type": "string", - "maxLength": 2048, - "description": "Human-readable explanation of the issue." - }, - "workflowId": { - "description": "Workflow affected by this issue or deployment attempt.", - "type": "string", - "maxLength": 256 - }, - "blockId": { - "description": "Source block identifier before graph ID regeneration.", - "type": "string", - "maxLength": 256 - }, - "subBlockKey": { - "description": "Registered source field key, including the tool index for nested Agent fields.", - "type": "string", - "maxLength": 256 - } + "applied": { + "type": "boolean", + "description": "True when the draft was written or the workflow renamed or redescribed; false on a dry run and on a no-op." }, - "required": ["code", "message"], - "additionalProperties": false - }, - "description": "Structured warnings, missing configuration, and follow-up failures." - }, - "idMap": { - "description": "Source graph identifiers mapped to the imported identifiers.", - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 256 - } - }, - "deploymentOperationIds": { - "description": "Exact deployment attempts admitted by the workspace operation.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "maxLength": 256 - } - }, - "deployments": { - "description": "Readiness of the exact admitted deployment attempts.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "operationId": { - "type": "string", - "maxLength": 256, - "description": "Durable operation identifier to use for polling." - }, - "workflowId": { - "type": "string", - "maxLength": 256, - "description": "Workflow affected by this issue or deployment attempt." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 9007199254740991, - "description": "Deployment version number for this admitted attempt." - }, - "status": { - "type": "string", - "enum": ["preparing", "activating", "active", "failed", "superseded"], - "description": "Status of this exact admitted deployment attempt." - }, - "ready": { - "type": "boolean", - "description": "Whether this exact deployment attempt is active and all required components are ready." - }, - "pendingComponents": { - "maxItems": 32, - "type": "array", - "items": { - "type": "string", - "maxLength": 128 + "diff": { + "type": "object", + "properties": { + "noop": { + "type": "boolean", + "description": "True when the source matches the saved draft." }, - "description": "Deployment components that have not finished becoming ready." - } - }, - "required": [ - "operationId", - "workflowId", - "version", - "status", - "ready", - "pendingComponents" - ], - "additionalProperties": false - } - }, - "triggerUrlChanges": { - "description": "Public trigger paths changed by this sync, with the affected workflow names.", - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Name of the workflow whose public trigger path stops serving." + "meta": { + "description": "The workflow name and description fields the source changes.", + "type": "array", + "items": { + "type": "string", + "enum": ["name", "description"] + } + }, + "blocks": { + "type": "object", + "properties": { + "added": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "type": { + "type": "string", + "description": "Block type." + } + }, + "required": ["id", "key", "type"], + "additionalProperties": false, + "description": "An added or removed block by id, source key and type." + }, + "description": "New blocks." + }, + "removed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "type": { + "type": "string", + "description": "Block type." + } + }, + "required": ["id", "key", "type"], + "additionalProperties": false, + "description": "An added or removed block by id, source key and type." + }, + "description": "Deleted blocks." + }, + "renamed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id; unchanged by the rename." + }, + "from": { + "type": "string", + "description": "Previous key." + }, + "to": { + "type": "string", + "description": "New key." + } + }, + "required": ["id", "from", "to"], + "additionalProperties": false, + "description": "A renamed block." + }, + "description": "Renamed blocks; each keeps its id." + }, + "modified": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored block id." + }, + "key": { + "type": "string", + "description": "Block key in the source." + }, + "fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Changed fields, modes (`modes.`) and attributes." + }, + "reparented": { + "description": "Moved into or out of a container.", + "type": "boolean" + } + }, + "required": ["id", "key", "fields"], + "additionalProperties": false, + "description": "A changed block." + }, + "description": "Changed blocks." + } + }, + "required": ["added", "removed", "renamed", "modified"], + "additionalProperties": false, + "description": "Block changes." + }, + "edges": { + "type": "object", + "properties": { + "added": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Connections added." + }, + "removed": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Connections removed." + } + }, + "required": ["added", "removed"], + "additionalProperties": false, + "description": "Connection changes." + }, + "variables": { + "type": "object", + "properties": { + "added": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys added." + }, + "removed": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys removed." + }, + "modified": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Variable keys changed." + } + }, + "required": ["added", "removed", "modified"], + "additionalProperties": false, + "description": "Variable changes." + } }, - "path": { - "type": "string", - "maxLength": 4096, - "description": "Public trigger path that stops serving after this sync." - } + "required": ["noop", "blocks", "edges", "variables"], + "additionalProperties": false, + "description": "What the apply changed, or would change on a dry run." }, - "required": ["workflowName", "path"], - "additionalProperties": false - } - }, - "backgroundWorkId": { - "description": "Workspace activity identifier for resource-copy progress.", - "type": "string", - "maxLength": 256 - }, - "copyProgress": { - "description": "Completion status and counts for explicitly selected resource copies.", - "type": "object", - "properties": { - "status": { - "type": "string", - "enum": ["pending", "completed", "failed"], - "description": "Background resource-copy status." - }, - "copied": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources copied successfully." - }, - "failed": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of resources that failed to copy." - } - }, - "required": ["status", "copied", "failed"], - "additionalProperties": false - } - }, - "required": [ - "operationId", - "requestId", - "workspaceId", - "kind", - "applied", - "status", - "resourceIds", - "issues" - ], - "additionalProperties": false, - "title": "Workspace operation receipt", - "description": "Committed operation receipt, resource copies, and exact deployment readiness." - }, - "ForkWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Fork workspace response", - "description": "Committed fork receipt and resource-copy progress.", - "examples": [ - { - "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "fork-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_fork", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] - } - } - ] - }, - "ForkWorkspaceBody": { - "type": "object", - "properties": { - "name": { - "description": "Display name of the workflow or workspace.", - "type": "string", - "minLength": 1, - "maxLength": 100 - }, - "copy": { - "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", - "type": "object", - "properties": { - "files": { - "description": "Workspace file IDs to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - }, - "workflowMcpServers": { - "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", - "maxItems": 2000, + "diagnostics": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - } - }, - "required": ["requestId", "previewFingerprint"], - "additionalProperties": false, - "title": "Fork workspace request", - "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", - "examples": [ - { - "name": "Support sandbox", - "requestId": "fork-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" - } - ] - }, - "WorkspaceSyncPreview": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." - }, - "sourceWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace the workflows and resources are copied from." - }, - "targetWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Canonical workspace receiving the changes." - }, - "ready": { - "type": "boolean", - "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." - }, - "workflows": { - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "action": { - "type": "string", - "enum": ["create", "replace", "archive"], - "description": "Planned workflow creation, replacement, or archival." - }, - "sourceWorkflowId": { - "description": "Workflow identifier in the source workspace.", - "type": "string", - "minLength": 1 - }, - "targetWorkflowId": { - "description": "Existing target workflow identifier; absent when apply will create a new target.", - "type": "string", - "minLength": 1 - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "comparison": { - "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", - "oneOf": [ - { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "available", - "description": "Both exact source snapshots are available." - }, - "base": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Source deployment last successfully synced to this destination." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "base", "target"], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "unavailable", - "description": "The source baseline cannot be compared." - }, - "reason": { - "type": "string", - "enum": ["new_workflow", "no_baseline", "missing_baseline"], - "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." - }, - "target": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Exact source deployment snapshot identifier." - }, - "version": { - "type": "integer", - "minimum": 1, - "maximum": 2147483647, - "description": "Saved version number in the source workflow." - } - }, - "required": ["id", "version"], - "additionalProperties": false, - "description": "Pinned source deployment that this sync would copy." - } - }, - "required": ["status", "reason", "target"], - "additionalProperties": false - } - ] - } - }, - "required": ["action", "name"], - "additionalProperties": false - }, - "description": "Eligible workflows and their planned actions." - }, - "unresolvedBindings": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "maxLength": 256, - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "blockName": { - "description": "Display name of the affected source block.", - "type": "string", - "maxLength": 1024 - }, - "reason": { - "description": "Structured explanation of the unresolved binding.", - "type": "string", - "maxLength": 256 - } - }, - "required": ["kind", "sourceId"], - "additionalProperties": false - }, - "description": "Source references that still require destination mappings or explicit copy choices." - }, - "configuration": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "currentValue": { - "type": "string", - "maxLength": 65536, - "description": "Persisted sync override or proposed override; empty when neither is configured." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s options.", - "type": "string", - "maxLength": 256 - }, - "discoveryWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." - }, - "context": { "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 4096 - }, - "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." - }, - "parentKind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource kind that owns this dependent configuration." - }, - "parentSourceId": { - "type": "string", - "maxLength": 4096, - "description": "Source identifier of the parent resource being mapped." - }, - "parentContextKey": { - "description": "Selector context key supplied by the mapped parent resource.", - "type": "string", - "maxLength": 256 - } - }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "subBlockKey", - "title", - "required", - "currentValue", - "discoveryWorkspaceId", - "context", - "parentKind", - "parentSourceId" - ], - "additionalProperties": false - }, - "description": "Dependent fields that may need destination-specific values." - }, - "excludedTargets": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - } - }, - "required": ["id", "name"], - "additionalProperties": false - }, - "description": "Target workflows explicitly excluded from sync." - }, - "triggerSlots": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Stable source trigger block identifier to use in trigger mappings." - }, - "blockName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source trigger block." - }, - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the source workflow." - }, - "ownPath": { - "anyOf": [ - { + "properties": { + "code": { "type": "string", - "maxLength": 4096 + "enum": [ + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_LIMIT_EXCEEDED", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_STALE", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_NAME_TAKEN", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, - { - "type": "null" - } - ], - "description": "Existing target trigger path, preserved automatically and not configurable." - }, - "adoptablePaths": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - "description": "Retiring paths in the same target workflow with a compatible trigger provider." - }, - "defaultAdoptPath": { - "anyOf": [ - { + "severity": { "type": "string", - "maxLength": 4096 + "enum": ["error", "warning", "info"], + "description": "Diagnostic severity." }, - { - "type": "null" + "message": { + "type": "string", + "description": "What was found." + }, + "hint": { + "description": "How to address it.", + "type": "string" + }, + "blockKey": { + "description": "Block the finding is about.", + "type": "string" + }, + "param": { + "description": "Field the finding is about.", + "type": "string" + }, + "file": { + "description": "Submitted file the finding is in.", + "type": "string" + }, + "line": { + "description": "1-based line in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "column": { + "description": "1-based column in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endLine": { + "description": "1-based line the finding ends on.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endColumn": { + "description": "1-based column the finding ends at.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "frame": { + "description": "The source lines around the finding, with a caret row.", + "type": "string" + }, + "blockId": { + "description": "Stored id of the block the finding is about.", + "type": "string" + }, + "path": { + "description": "JSON Pointer into the lock, for a lock finding.", + "type": "string" } - ], - "description": "Default adoption when ownPath is null; null then allocates a new path." - } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding from applying workflow source, pinned to the submitted files." + }, + "description": "Warnings, and on a dry run every error a commit would refuse." }, - "required": [ - "sourceWorkflowId", - "sourceBlockId", - "blockName", - "workflowName", - "ownPath", - "adoptablePaths", - "defaultAdoptPath" - ], - "additionalProperties": false - }, - "description": "Source triggers and the target paths available for explicit adoption choices." - }, - "triggerUrlChanges": { - "maxItems": 1000, - "type": "array", - "items": { - "type": "object", - "properties": { - "workflowName": { - "type": "string", - "maxLength": 1024, - "description": "Name of the affected workflow." + "files": { + "type": "object", + "propertyNames": { + "type": "string" }, - "path": { - "type": "string", - "maxLength": 4096, - "description": "Public trigger path that stops serving after this sync." - } + "additionalProperties": { + "type": "string" + }, + "description": "The source re-printed from what was saved, including any normalized values." }, - "required": ["workflowName", "path"], - "additionalProperties": false + "lock": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Lock format version." + }, + "blocks": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Block id." + }, + "parent": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Key of the enclosing loop or parallel, or null." + }, + "branches": { + "description": "Condition or router branch key → stored branch id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + }, + "items": { + "description": "Per field, its id-bearing items (input format fields) in stored order.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Item name." + }, + "id": { + "type": "string", + "description": "Item id." + } + }, + "required": ["name", "id"], + "additionalProperties": false, + "description": "One id-bearing list item." + } + } + }, + "ident": { + "type": "string", + "description": "The `const` name the block is printed as." + }, + "order": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Declaration-order tie-break." + }, + "layout": { + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "Canvas x position." + }, + "y": { + "type": "number", + "description": "Canvas y position." + }, + "w": { + "description": "Container width.", + "type": "number" + }, + "h": { + "description": "Container height.", + "type": "number" + }, + "height": { + "description": "Stored block height.", + "type": "number" + }, + "horizontalHandles": { + "description": "Handles on the left and right.", + "type": "boolean" + } + }, + "required": ["x", "y"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Stored canvas geometry; applied only to new blocks." + }, + "codeFile": { + "description": "Path of the block’s function-code file.", + "type": "string" + } + }, + "required": ["id", "parent", "ident", "order"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "One block’s identity." + }, + "description": "Block key → identity." + }, + "variables": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Variable key → variable id." + } + }, + "required": ["version", "blocks", "variables"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids." + }, + "base": { + "type": "object", + "properties": { + "version": { + "default": 1, + "description": "Base format version; a base written before it existed reads as 1.", + "type": "number", + "const": 1 + }, + "workflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow the source was read from; an apply to another workflow is refused." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the workflow belongs to." + }, + "fingerprint": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Freshness token of the draft the source was read at: a hash of the canonical workflow and its ids. It ignores canvas positions, so moving blocks does not change it." + }, + "catalogHash": { + "type": "string", + "description": "Hash of the block catalog the source was printed against." + } + }, + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], + "additionalProperties": { + "description": "An `x-` extension field, kept verbatim." + }, + "description": "Where the saved (or, on a dry run, would-be) draft was read: the next apply’s `base`." + }, + "mintedIds": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Block key → id for new blocks whose id was minted rather than taken from the lock." + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Non-fatal notes about the write." + }, + "needsRedeployment": { + "type": "boolean", + "description": "Whether the draft now differs from the live deployment; apply never deploys." + } }, - "description": "Retiring target trigger URLs no arriving trigger adopts." + "required": [ + "workflowId", + "workspaceId", + "dryRun", + "applied", + "diff", + "diagnostics", + "files", + "lock", + "base", + "mintedIds", + "notes", + "needsRedeployment" + ], + "additionalProperties": false, + "description": "Response data." } }, - "required": [ - "previewFingerprint", - "sourceWorkspaceId", - "targetWorkspaceId", - "ready", - "workflows", - "unresolvedBindings", - "configuration", - "excludedTargets", - "triggerSlots", - "triggerUrlChanges" - ], + "required": ["data"], "additionalProperties": false, - "title": "Workspace sync preview", - "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." - }, - "PreviewWorkspacePushResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceSyncPreview" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Preview workspace push response", - "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", + "title": "Create workflow from source response", + "description": "The outcome, with the source re-printed from the saved workflow.", "examples": [ { "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "ready": true, - "workflows": [], - "unresolvedBindings": [], - "configuration": [], - "excludedTargets": [], - "triggerSlots": [], - "triggerUrlChanges": [] + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": false, + "applied": true, + "diff": { + "noop": false, + "blocks": { + "added": [ + { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "key": "start", + "type": "start_trigger" + } + ], + "removed": [], + "renamed": [], + "modified": [] + }, + "edges": { + "added": 0, + "removed": 0 + }, + "variables": { + "added": [], + "removed": [], + "modified": [] + } + }, + "diagnostics": [], + "files": { + "workflow.ts": "// @sim-sdk 1\nimport { trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Support triage', () => {\n const start = trigger.start('Start')\n})\n" + }, + "lock": { + "version": 1, + "blocks": { + "start": { + "id": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77", + "parent": null, + "ident": "start", + "order": 0 + } + }, + "variables": {} + }, + "base": { + "version": 1, + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "fingerprint": "sf1:9c1d4e7f0a3b6c9d2e5f8a1b4c7d0e3f6a9b2c5d8e1f4a7b0c3d6e9f2a5b8c1d", + "catalogHash": "3f0c1a9e5b7d2c4f6a8e0b1d3c5f7a9e2b4d6f8a0c2e4b6d8f0a2c4e6b8d0f2a" + }, + "mintedIds": { + "start": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" + }, + "notes": [], + "needsRedeployment": false } } ] }, - "PreviewWorkspacePushBody": { + "CreateWorkflowFromSourceBody": { "type": "object", "properties": { - "otherWorkspaceId": { + "files": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "additionalProperties": { + "type": "string" + }, + "description": "Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks." + }, + "name": { + "description": "Workflow name. Defaults to the name in the source's `workflow('…')` call.", "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "maxLength": 255 }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } + "description": { + "description": "Workflow description. Defaults to the description in the source.", + "anyOf": [ + { + "type": "string", + "maxLength": 50000 }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + { + "type": "null" + } + ] }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "folderPath": { + "$ref": "#/components/schemas/FolderPathInput" }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "provenance": { + "description": "Where the source came from, for the audit log.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "client": { + "type": "string", + "enum": ["cli", "copilot", "canvas", "api"], + "description": "What submitted the source." }, - "tables": { - "description": "Source table identifiers whose schemas and rows are copied.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "gitSha": { + "description": "The commit the source was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" }, - "customTools": { - "description": "Source custom tool identifiers to copy.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } + "repo": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "The repository the source was taken from (its remote URL); recorded in the audit log." + } + }, + "required": ["client"], + "additionalProperties": false + } + }, + "required": ["files"], + "additionalProperties": false, + "title": "Create workflow from source body", + "description": "Source files and where to create the workflow." + }, + "GetSourceResourcesResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." }, - "skills": { - "description": "Source skill identifiers to copy.", - "maxItems": 2000, + "tables": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "columns": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Column name, as row data names it." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "currency", + "boolean", + "date", + "json", + "select" + ], + "description": "Column type, e.g. `string`, `number`, `boolean`, `json`, `select`." + }, + "options": { + "description": "Option names a `select` column accepts, as table blocks read and write them.", + "type": "array", + "items": { + "type": "string" + } + }, + "multiple": { + "description": "A `select` column whose cells hold several options.", + "type": "boolean" + }, + "required": { + "description": "Every row holds a value.", + "type": "boolean" + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Columns in table order." + } + }, + "required": ["key", "id", "name", "columns"], + "additionalProperties": false, + "description": "A table: `table(key)`." + }, + "description": "Tables, oldest first." }, - "files": { - "description": "Workspace file storage keys to copy.", - "maxItems": 2000, + "knowledgeBases": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A knowledge base: `knowledgeBase(key)`." + }, + "description": "Knowledge bases, oldest first." }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", - "maxItems": 2000, + "credentials": { "type": "array", "items": { - "type": "string", - "minLength": 1 - } - } - }, - "additionalProperties": false - }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "provider": { + "type": "string", + "description": "The provider the credential is for, e.g. `slack` or `google-email`." + } + }, + "required": ["key", "id", "name", "provider"], + "additionalProperties": false, + "description": "A saved credential: `credential(key)`." }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - } + "description": "Saved credentials, oldest first. Secrets are listed under `env`." }, - "required": ["kind", "sourceId"], - "additionalProperties": false - } - }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." + "workflows": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Input field name." + }, + "type": { + "type": "string", + "description": "Input field type, e.g. `string` or `number`." + } + }, + "required": ["name", "type"], + "additionalProperties": false + }, + "description": "Inputs the workflow start block declares." + } + }, + "required": ["key", "id", "name", "inputs"], + "additionalProperties": false, + "description": "A workflow: `childWorkflow(key)`." }, - "adoptPath": { - "anyOf": [ - { + "description": "Workflows, oldest first." + }, + "skills": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { "type": "string", - "minLength": 1, - "maxLength": 4096 + "description": "The key workflow source names this resource by; it never changes once assigned." }, - { - "type": "null" + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace skill: `skill(key)`." + }, + "description": "Workspace skills, oldest first. Built-in skills have no key and are not listed." }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Preview workspace push request", - "description": "Other workspace and proposed source-to-target sync choices." - }, - "PushWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + "customTools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "A workspace custom tool, by its title: `customTool(key)`." + }, + "description": "Workspace custom tools, oldest first." + }, + "mcpServers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The key workflow source names this resource by; it never changes once assigned." + }, + "id": { + "type": "string", + "description": "Resource id." + }, + "name": { + "type": "string", + "description": "Current display name." + }, + "tools": { + "description": "Tool names the server listed, for `mcp(key).tool(name)`; absent when it could not be listed (unreachable, or not listable by this caller).", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["key", "id", "name"], + "additionalProperties": false, + "description": "An MCP server the workspace consumes: `mcp(key)`." + }, + "description": "MCP servers, oldest first." + }, + "env": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Environment variable names a run can read as `env.NAME`: the workspace secrets and, for a user, their personal ones. Never values." + }, + "truncated": { + "type": "boolean", + "description": "True when a kind had more than 1000 resources; only the oldest 1000 of that kind are listed." + } + }, + "required": [ + "workspaceId", + "tables", + "knowledgeBases", + "credentials", + "workflows", + "skills", + "customTools", + "mcpServers", + "env", + "truncated" + ], + "additionalProperties": false, + "description": "Response data." } }, "required": ["data"], "additionalProperties": false, - "title": "Push workspace response", - "description": "Committed push receipt with copy and deployment readiness.", + "title": "Get source resources response", + "description": "The workspace resources workflow source can name.", "examples": [ { "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "push-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_push", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "tables": [ + { + "key": "tickets", + "id": "tbl_4f1c2a9e", + "name": "Tickets", + "columns": [ + { + "name": "subject", + "type": "string" + }, + { + "name": "status", + "type": "select", + "options": ["open", "closed"] + } + ] + } + ], + "knowledgeBases": [ + { + "key": "docs", + "id": "kb_93a1e7c2", + "name": "Docs" + } + ], + "credentials": [ + { + "key": "support-slack", + "id": "cred_51d0b8f4", + "name": "Support Slack", + "provider": "slack" + } + ], + "workflows": [ + { + "key": "assign-owner", + "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "name": "Assign owner", + "inputs": [ + { + "name": "leads", + "type": "array" + } + ] + } + ], + "skills": [ + { + "key": "triage", + "id": "skl_7e2a4c19", + "name": "Triage" + } + ], + "customTools": [ + { + "key": "lookup-order", + "id": "ctl_2b8d6f03", + "name": "lookup_order" + } + ], + "mcpServers": [ + { + "key": "github", + "id": "mcp-1a2b3c4d", + "name": "GitHub", + "tools": ["create_issue", "list_issues"] + } + ], + "env": ["CRM_KEY"], + "truncated": false } } ] }, - "PushWorkspaceBody": { + "WorkspaceForkPreview": { "type": "object", "properties": { - "otherWorkspaceId": { + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." + }, + "sourceWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } + "description": "Canonical workspace the workflows and resources are copied from." }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, + "workflows": { + "maxItems": 1000, "type": "array", "items": { "type": "object", @@ -22435,34 +22472,79 @@ "minLength": 1, "description": "Workflow identifier in the source workspace." }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { + "name": { "type": "string", - "minLength": 1, "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." + "description": "Display name of the workflow or workspace." } }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "required": ["sourceWorkflowId", "name"], "additionalProperties": false - } + }, + "description": "Eligible workflows and their planned actions." }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "selectedResourceCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources explicitly selected for copying." + }, + "draftOnly": { + "type": "boolean", + "const": true, + "description": "True because fork creation produces undeployed drafts." + } + }, + "required": [ + "previewFingerprint", + "sourceWorkspaceId", + "workflows", + "selectedResourceCount", + "draftOnly" + ], + "additionalProperties": false, + "title": "Workspace fork preview", + "description": "Read-only fork plan and fingerprint." + }, + "PreviewWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceForkPreview" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workspace fork response", + "description": "Deployed source workflows, selected-copy count, and a preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "workflows": [], + "selectedResourceCount": 0, + "draftOnly": true + } + } + ] + }, + "PreviewWorkspaceForkBody": { + "type": "object", + "properties": { + "name": { + "description": "Display name of the workflow or workspace.", + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", + "files": { + "description": "Workspace file IDs to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22479,6 +22561,15 @@ "minLength": 1 } }, + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, "customTools": { "description": "Source custom tool identifiers to copy.", "maxItems": 2000, @@ -22497,8 +22588,8 @@ "minLength": 1 } }, - "files": { - "description": "Workspace file storage keys to copy.", + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", "maxItems": 2000, "type": "array", "items": { @@ -22506,8 +22597,8 @@ "minLength": 1 } }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", "maxItems": 2000, "type": "array", "items": { @@ -22517,236 +22608,285 @@ } }, "additionalProperties": false + } + }, + "additionalProperties": false, + "title": "Preview workspace fork request", + "description": "Optional child name and explicitly selected resource copies." + }, + "WorkspaceOperationReport": { + "type": "object", + "properties": { + "operationId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Durable operation identifier to use for polling." }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Client request ID used to commit this operation. Reuse identical mutation inputs with this ID after an uncertain response." + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "kind": { + "type": "string", + "enum": ["workflow_import", "workspace_fork", "workspace_push", "workspace_pull"], + "description": "Type of committed workspace operation." + }, + "applied": { + "type": "boolean", + "const": true, + "description": "The business transaction committed, including when follow-up work fails." + }, + "status": { + "type": "string", + "enum": [ + "processing", + "completed", + "completed_with_warnings", + "requires_configuration", + "failed" + ], + "description": "Operation status; failed follow-up work does not undo the committed transaction." + }, + "resourceIds": { + "maxItems": 5000, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "description": "Identifiers of resources created or changed by the committed operation." + }, + "issues": { "maxItems": 2000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "code": { "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], - "description": "Resource or operation kind." + "minLength": 1, + "maxLength": 128, + "description": "Stable machine-readable issue code." }, - "sourceId": { + "message": { "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." + "maxLength": 2048, + "description": "Human-readable explanation of the issue." + }, + "workflowId": { + "description": "Workflow affected by this issue or deployment attempt.", + "type": "string", + "maxLength": 256 + }, + "blockId": { + "description": "Source block identifier before graph ID regeneration.", + "type": "string", + "maxLength": 256 + }, + "subBlockKey": { + "description": "Registered source field key, including the tool index for nested Agent fields.", + "type": "string", + "maxLength": 256 } }, - "required": ["kind", "sourceId"], + "required": ["code", "message"], "additionalProperties": false + }, + "description": "Structured warnings, missing configuration, and follow-up failures." + }, + "idMap": { + "description": "Source graph identifiers mapped to the imported identifiers.", + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 256 } }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, + "deploymentOperationIds": { + "description": "Exact deployment attempts admitted by the workspace operation.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + } + }, + "deployments": { + "description": "Readiness of the exact admitted deployment attempts.", + "maxItems": 1000, "type": "array", "items": { "type": "object", "properties": { - "sourceWorkflowId": { + "operationId": { "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." + "maxLength": 256, + "description": "Durable operation identifier to use for polling." }, - "sourceBlockId": { + "workflowId": { "type": "string", - "minLength": 1, "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." + "description": "Workflow affected by this issue or deployment attempt." }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - }, - "confirm": { - "type": "boolean", - "const": true, - "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." + "version": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "Deployment version number for this admitted attempt." + }, + "status": { + "type": "string", + "enum": ["preparing", "activating", "active", "failed", "superseded"], + "description": "Status of this exact admitted deployment attempt." + }, + "ready": { + "type": "boolean", + "description": "Whether this exact deployment attempt is active and all required components are ready." + }, + "pendingComponents": { + "maxItems": 32, + "type": "array", + "items": { + "type": "string", + "maxLength": 128 + }, + "description": "Deployment components that have not finished becoming ready." + } + }, + "required": [ + "operationId", + "workflowId", + "version", + "status", + "ready", + "pendingComponents" + ], + "additionalProperties": false + } + }, + "triggerUrlChanges": { + "description": "Public trigger paths changed by this sync, with the affected workflow names.", + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Name of the workflow whose public trigger path stops serving." + }, + "path": { + "type": "string", + "maxLength": 4096, + "description": "Public trigger path that stops serving after this sync." + } + }, + "required": ["workflowName", "path"], + "additionalProperties": false + } + }, + "backgroundWorkId": { + "description": "Workspace activity identifier for resource-copy progress.", + "type": "string", + "maxLength": 256 + }, + "copyProgress": { + "description": "Completion status and counts for explicitly selected resource copies.", + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": ["pending", "completed", "failed"], + "description": "Background resource-copy status." + }, + "copied": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources copied successfully." + }, + "failed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of resources that failed to copy." + } + }, + "required": ["status", "copied", "failed"], + "additionalProperties": false } }, - "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], + "required": [ + "operationId", + "requestId", + "workspaceId", + "kind", + "applied", + "status", + "resourceIds", + "issues" + ], "additionalProperties": false, - "title": "Push workspace request", - "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", - "examples": [ - { - "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "push-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "confirm": true - } - ] + "title": "Workspace operation receipt", + "description": "Committed operation receipt, resource copies, and exact deployment readiness." }, - "PreviewWorkspacePullResponse": { + "ForkWorkspaceResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceSyncPreview" + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workspace pull response", - "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", + "title": "Fork workspace response", + "description": "Committed fork receipt and resource-copy progress.", "examples": [ { "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "ready": true, - "workflows": [], - "unresolvedBindings": [], - "configuration": [], - "excludedTargets": [], - "triggerSlots": [], - "triggerUrlChanges": [] + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "fork-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_fork", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] } } ] }, - "PreviewWorkspacePullBody": { + "ForkWorkspaceBody": { "type": "object", "properties": { - "otherWorkspaceId": { + "name": { + "description": "Display name of the workflow or workspace.", "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." - }, - "mappings": { - "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["resourceType", "sourceId", "targetId"], - "additionalProperties": false - } - }, - "dependentValues": { - "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "sourceWorkflowId": { - "type": "string", - "minLength": 1, - "description": "Workflow identifier in the source workspace." - }, - "sourceBlockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Block identifier in the source workflow." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 65536, - "description": "Destination value for the registered dependent field." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], - "additionalProperties": false - } + "maxLength": 100 }, - "copyResources": { - "description": "Explicit source resources to copy before syncing the workflows.", + "copy": { + "description": "Explicit resource selections to copy into the new fork; omitted resource kinds are not copied.", "type": "object", "properties": { - "knowledgeBases": { - "description": "Source knowledge base identifiers whose documents and content are copied.", + "files": { + "description": "Workspace file IDs to copy.", "maxItems": 2000, "type": "array", "items": { @@ -22763,6 +22903,15 @@ "minLength": 1 } }, + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, "customTools": { "description": "Source custom tool identifiers to copy.", "maxItems": 2000, @@ -22781,8 +22930,8 @@ "minLength": 1 } }, - "files": { - "description": "Workspace file storage keys to copy.", + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", "maxItems": 2000, "type": "array", "items": { @@ -22790,8 +22939,8 @@ "minLength": 1 } }, - "mcpServers": { - "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "workflowMcpServers": { + "description": "Workflow-publishing MCP server identifiers to copy as empty configuration shells.", "maxItems": 2000, "type": "array", "items": { @@ -22802,45 +22951,211 @@ }, "additionalProperties": false }, - "dropReferences": { - "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + } + }, + "required": ["requestId", "previewFingerprint"], + "additionalProperties": false, + "title": "Fork workspace request", + "description": "Child name and copy choices, with the actual preview fingerprint and a stable request ID.", + "examples": [ + { + "name": "Support sandbox", + "requestId": "fork-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a" + } + ] + }, + "WorkspaceSyncPreview": { + "type": "object", + "properties": { + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint to submit when applying this preview with the same choices. Preview again after changing a choice." + }, + "sourceWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Canonical workspace the workflows and resources are copied from." + }, + "targetWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Canonical workspace receiving the changes." + }, + "ready": { + "type": "boolean", + "description": "Whether required bindings, configuration, and sync blockers are resolved. This does not mean the target is already deployed." + }, + "workflows": { "maxItems": 2000, "type": "array", + "items": { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["create", "replace", "archive"], + "description": "Planned workflow creation, replacement, or archival." + }, + "sourceWorkflowId": { + "description": "Workflow identifier in the source workspace.", + "type": "string", + "minLength": 1 + }, + "targetWorkflowId": { + "description": "Existing target workflow identifier; absent when apply will create a new target.", + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "comparison": { + "description": "Last successfully synced source deployment compared with the source deployment pinned by this preview. Absent for archive actions.", + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "available", + "description": "Both exact source snapshots are available." + }, + "base": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Source deployment last successfully synced to this destination." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "base", "target"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "const": "unavailable", + "description": "The source baseline cannot be compared." + }, + "reason": { + "type": "string", + "enum": ["new_workflow", "no_baseline", "missing_baseline"], + "description": "New destination workflow, no recorded successful sync, or deleted baseline snapshot." + }, + "target": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Exact source deployment snapshot identifier." + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647, + "description": "Saved version number in the source workflow." + } + }, + "required": ["id", "version"], + "additionalProperties": false, + "description": "Pinned source deployment that this sync would copy." + } + }, + "required": ["status", "reason", "target"], + "additionalProperties": false + } + ] + } + }, + "required": ["action", "name"], + "additionalProperties": false + }, + "description": "Eligible workflows and their planned actions." + }, + "unresolvedBindings": { + "maxItems": 10000, + "type": "array", "items": { "type": "object", "properties": { "kind": { "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox" - ], + "maxLength": 256, "description": "Resource or operation kind." }, "sourceId": { "type": "string", - "minLength": 1, "maxLength": 4096, "description": "Source resource identifier in the canonical source workspace." + }, + "blockName": { + "description": "Display name of the affected source block.", + "type": "string", + "maxLength": 1024 + }, + "reason": { + "description": "Structured explanation of the unresolved binding.", + "type": "string", + "maxLength": 256 } }, "required": ["kind", "sourceId"], "additionalProperties": false - } + }, + "description": "Source references that still require destination mappings or explicit copy choices." }, - "triggerMappings": { - "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", - "maxItems": 500, + "configuration": { + "maxItems": 10000, "type": "array", "items": { "type": "object", @@ -22852,62 +23167,266 @@ }, "sourceBlockId": { "type": "string", - "minLength": 1, "maxLength": 256, - "description": "Source trigger block identifier from the sync preview." + "description": "Block identifier in the source workflow." }, - "adoptPath": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "An adoptable path offered for this trigger, or null to allocate a new path." - } - }, - "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], - "additionalProperties": false - } - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Preview workspace pull request", - "description": "Other workspace and proposed source-to-target sync choices." - }, - "PullWorkspaceResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Pull workspace response", - "description": "Committed pull receipt with copy and deployment readiness.", - "examples": [ - { - "data": { - "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", - "requestId": "pull-support-2026-10-13", - "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "kind": "workspace_pull", - "applied": true, - "status": "processing", - "resourceIds": ["destination_workflow_id"], - "issues": [] + "subBlockKey": { + "type": "string", + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "currentValue": { + "type": "string", + "maxLength": 65536, + "description": "Persisted sync override or proposed override; empty when neither is configured." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s options.", + "type": "string", + "maxLength": 256 + }, + "discoveryWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace scope for selector discovery: source for a parent being copied, otherwise destination." + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 4096 + }, + "description": "Allowlisted selector dependencies scoped to discoveryWorkspaceId." + }, + "parentKind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource kind that owns this dependent configuration." + }, + "parentSourceId": { + "type": "string", + "maxLength": 4096, + "description": "Source identifier of the parent resource being mapped." + }, + "parentContextKey": { + "description": "Selector context key supplied by the mapped parent resource.", + "type": "string", + "maxLength": 256 + } + }, + "required": [ + "sourceWorkflowId", + "sourceBlockId", + "subBlockKey", + "title", + "required", + "currentValue", + "discoveryWorkspaceId", + "context", + "parentKind", + "parentSourceId" + ], + "additionalProperties": false + }, + "description": "Dependent fields that may need destination-specific values." + }, + "excludedTargets": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + } + }, + "required": ["id", "name"], + "additionalProperties": false + }, + "description": "Target workflows explicitly excluded from sync." + }, + "triggerSlots": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Stable source trigger block identifier to use in trigger mappings." + }, + "blockName": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the source trigger block." + }, + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the source workflow." + }, + "ownPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Existing target trigger path, preserved automatically and not configurable." + }, + "adoptablePaths": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + "description": "Retiring paths in the same target workflow with a compatible trigger provider." + }, + "defaultAdoptPath": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Default adoption when ownPath is null; null then allocates a new path." + } + }, + "required": [ + "sourceWorkflowId", + "sourceBlockId", + "blockName", + "workflowName", + "ownPath", + "adoptablePaths", + "defaultAdoptPath" + ], + "additionalProperties": false + }, + "description": "Source triggers and the target paths available for explicit adoption choices." + }, + "triggerUrlChanges": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowName": { + "type": "string", + "maxLength": 1024, + "description": "Name of the affected workflow." + }, + "path": { + "type": "string", + "maxLength": 4096, + "description": "Public trigger path that stops serving after this sync." + } + }, + "required": ["workflowName", "path"], + "additionalProperties": false + }, + "description": "Retiring target trigger URLs no arriving trigger adopts." + } + }, + "required": [ + "previewFingerprint", + "sourceWorkspaceId", + "targetWorkspaceId", + "ready", + "workflows", + "unresolvedBindings", + "configuration", + "excludedTargets", + "triggerSlots", + "triggerUrlChanges" + ], + "additionalProperties": false, + "title": "Workspace sync preview", + "description": "Read-only sync actions, bindings, configuration, and trigger-path choices." + }, + "PreviewWorkspacePushResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceSyncPreview" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workspace push response", + "description": "Current-to-other workflow actions, required choices, and preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "targetWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "ready": true, + "workflows": [], + "unresolvedBindings": [], + "configuration": [], + "excludedTargets": [], + "triggerSlots": [], + "triggerUrlChanges": [] } } ] }, - "PullWorkspaceBody": { + "PreviewWorkspacePushBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23131,391 +23650,325 @@ "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], "additionalProperties": false } - }, - "requestId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." - }, - "previewFingerprint": { - "type": "string", - "pattern": "^[a-f0-9]{64}$", - "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." - }, - "confirm": { - "type": "boolean", - "const": true, - "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." - } - }, - "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], - "additionalProperties": false, - "title": "Pull workspace request", - "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", - "examples": [ - { - "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", - "requestId": "pull-support-2026-10-13", - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "confirm": true - } - ] - }, - "GetWorkspaceForkAvailabilityResult": { - "type": "object", - "properties": { - "available": { - "type": "boolean", - "description": "Whether this deployment and workspace plan enable forking." } }, - "required": ["available"], + "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "Get workspace fork availability result", - "description": "Fork feature availability for this workspace." + "title": "Preview workspace push request", + "description": "Other workspace and proposed source-to-target sync choices." }, - "GetWorkspaceForkAvailabilityResponse": { + "PushWorkspaceResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, "required": ["data"], "additionalProperties": false, - "title": "Get workspace fork availability response", - "description": "Whether forking is enabled for this deployment and workspace plan." - }, - "GetWorkspaceForkLineageResult": { - "type": "object", - "properties": { - "current": { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false, - "description": "The current workspace lineage node." - }, - "parent": { - "anyOf": [ - { - "type": "object", - "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." - }, - "organizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." - } - }, - "required": ["id", "name", "organizationId"], - "additionalProperties": false - }, - { - "type": "null" - } - ], - "description": "The live parent workspace, or null when this workspace is not a fork." - } - }, - "required": ["current", "parent"], - "additionalProperties": false, - "title": "Get workspace fork lineage result", - "description": "Current workspace and its active parent." - }, - "GetWorkspaceForkLineageResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" + "title": "Push workspace response", + "description": "Committed push receipt with copy and deployment readiness.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "push-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_push", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Get workspace fork lineage response", - "description": "Current workspace and its active direct parent, when present." + ] }, - "ListWorkspaceForkChildrenResult": { + "PushWorkspaceBody": { "type": "object", "properties": { - "id": { + "otherWorkspaceId": { "type": "string", "minLength": 1, "maxLength": 128, - "description": "Resource identifier." - }, - "name": { - "type": "string", - "maxLength": 1024, - "description": "Display name of the workflow or workspace." + "description": "Workspace on the other side of the direct fork edge." }, - "organizationId": { - "anyOf": [ - { - "type": "string" + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } }, - { - "type": "null" - } - ], - "description": "Owning organization, or null for a personal workspace." + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false + } }, - "createdAt": { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", - "description": "ISO 8601 creation timestamp." - } - }, - "required": ["id", "name", "organizationId", "createdAt"], - "additionalProperties": false, - "title": "List workspace fork children result", - "description": "An active direct child workspace." - }, - "ListWorkspaceForkChildrenResponse": { - "type": "object", - "properties": { - "data": { + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, "type": "array", "items": { - "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "List workspace fork children response", - "description": "A page of active direct child workspaces." - }, - "ListWorkspaceForkResourcesResult": { - "type": "object", - "properties": { - "id": { - "type": "string", - "maxLength": 4096, - "description": "Resource identifier." - }, - "label": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable resource label." + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } }, - "folderId": { - "description": "Containing folder identifier, or null at the workspace root.", - "anyOf": [ - { - "type": "string" + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } }, - { - "type": "null" + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } } - ] + }, + "additionalProperties": false }, - "folderName": { - "description": "Containing folder name, or null at the workspace root.", - "anyOf": [ - { - "type": "string" + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } }, - { - "type": "null" - } - ] + "required": ["kind", "sourceId"], + "additionalProperties": false + } + }, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." + }, + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "additionalProperties": false + } + }, + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." + }, + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "confirm": { + "type": "boolean", + "const": true, + "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." } }, - "required": ["id", "label"], + "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], "additionalProperties": false, - "title": "List workspace fork resources result", - "description": "A copyable resource candidate." + "title": "Push workspace request", + "description": "Confirmed current-to-other choices, actual preview fingerprint, and stable request ID.", + "examples": [ + { + "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "requestId": "push-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "confirm": true + } + ] }, - "ListWorkspaceForkResourcesResponse": { + "PreviewWorkspacePullResponse": { "type": "object", "properties": { "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceSyncPreview" } }, - "required": ["data", "nextCursor"], + "required": ["data"], "additionalProperties": false, - "title": "List workspace fork resources response", - "description": "A page of copyable resource candidates." - }, - "GetWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "resourceType": { - "type": "string", - "enum": [ - "oauth_credential", - "service_account_credential", - "env_var", - "table", - "knowledge_base", - "file", - "file_folder", - "mcp_server", - "custom_block", - "custom_tool", - "skill", - "sandbox" - ], - "description": "Resource type stored on the canonical parent/child edge." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Source resource identifier in the canonical source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - }, - "id": { - "type": "string", - "maxLength": 256, - "description": "Resource identifier." - } - }, - "required": ["resourceType", "sourceId", "targetId", "id"], - "additionalProperties": false, - "title": "Get workspace fork mappings result", - "description": "A saved directional mapping entry." - }, - "GetWorkspaceForkMappingsResponse": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" - }, - "description": "Items in the current page." - }, - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." - } - }, - "required": ["data", "nextCursor"], - "additionalProperties": false, - "title": "Get workspace fork mappings response", - "description": "A page of persisted source-to-target mapping entries." - }, - "UpdateWorkspaceForkMappingsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork mappings result", - "description": "Count of changed mapping records." - }, - "UpdateWorkspaceForkMappingsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" + "title": "Preview workspace pull response", + "description": "Other-to-current workflow actions, required choices, and preview fingerprint.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "sourceWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "targetWorkspaceId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "ready": true, + "workflows": [], + "unresolvedBindings": [], + "configuration": [], + "excludedTargets": [], + "triggerSlots": [], + "triggerUrlChanges": [] + } } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Update workspace fork mappings response", - "description": "Number of mapping records changed." + ] }, - "UpdateWorkspaceForkMappingsBody": { + "PreviewWorkspacePullBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23524,12 +23977,8 @@ "maxLength": 128, "description": "Workspace on the other side of the direct fork edge." }, - "direction": { - "type": "string", - "enum": ["push", "pull"], - "description": "Push means current to other; pull means other to current, independent of parent/child orientation." - }, "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", "maxItems": 5000, "type": "array", "items": { @@ -23575,112 +24024,209 @@ }, "required": ["resourceType", "sourceId", "targetId"], "additionalProperties": false - }, - "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." - } - }, - "required": ["otherWorkspaceId", "direction", "mappings"], - "additionalProperties": false, - "title": "Update workspace fork mappings request", - "description": "Other workspace, direction, and mapping entries to update." - }, - "RollbackWorkspaceForkResult": { - "type": "object", - "properties": { - "restored": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows restored to their prior deployed version." - }, - "archived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Workflows created by the sync and now archived." + } }, - "unarchived": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Previously archived workflows restored by rollback." + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], + "additionalProperties": false + } }, - "skipped": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Snapshot workflows no longer available to restore." + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "additionalProperties": false }, - "pendingActivations": { - "maxItems": 1000, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, "type": "array", "items": { - "type": "string", - "maxLength": 256 - }, - "description": "Workflows whose restored deployment is still activating." - } - }, - "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], - "additionalProperties": false, - "title": "Rollback workspace fork result", - "description": "Workflow restoration and pending-activation counts." - }, - "RollbackWorkspaceForkResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/RollbackWorkspaceForkResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Rollback workspace fork response", - "description": "Restored, archived, skipped, and still-activating workflow counts." - }, - "RollbackWorkspaceForkBody": { - "type": "object", - "properties": { - "otherWorkspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace on the other side of the direct fork edge." + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + } + }, + "required": ["kind", "sourceId"], + "additionalProperties": false + } + }, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." + }, + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." + }, + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." + } + }, + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], + "additionalProperties": false + } } }, "required": ["otherWorkspaceId"], "additionalProperties": false, - "title": "Rollback workspace fork request", - "description": "Other workspace whose latest inbound sync should be undone." - }, - "UnlinkWorkspaceForkResult": { - "type": "object", - "properties": { - "unlinked": { - "type": "boolean", - "description": "Whether the fork edge was removed." - } - }, - "required": ["unlinked"], - "additionalProperties": false, - "title": "Unlink workspace fork result", - "description": "Fork-edge removal acknowledgment." + "title": "Preview workspace pull request", + "description": "Other workspace and proposed source-to-target sync choices." }, - "UnlinkWorkspaceForkResponse": { + "PullWorkspaceResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" + "$ref": "#/components/schemas/WorkspaceOperationReport" } }, "required": ["data"], "additionalProperties": false, - "title": "Unlink workspace fork response", - "description": "Confirmation that the relationship was removed." + "title": "Pull workspace response", + "description": "Committed pull receipt with copy and deployment readiness.", + "examples": [ + { + "data": { + "operationId": "e4f8d2b6-9a1c-4e3d-8b7f-5c0a2d9e6f13", + "requestId": "pull-support-2026-10-13", + "workspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "kind": "workspace_pull", + "applied": true, + "status": "processing", + "resourceIds": ["destination_workflow_id"], + "issues": [] + } + } + ] }, - "UnlinkWorkspaceForkBody": { + "PullWorkspaceBody": { "type": "object", "properties": { "otherWorkspaceId": { @@ -23688,111 +24234,43 @@ "minLength": 1, "maxLength": 128, "description": "Workspace on the other side of the direct fork edge." - } - }, - "required": ["otherWorkspaceId"], - "additionalProperties": false, - "title": "Unlink workspace fork request", - "description": "Other workspace on the direct fork edge to remove." - }, - "UpdateWorkspaceForkExclusionsResult": { - "type": "object", - "properties": { - "updated": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991, - "description": "Number of records changed." - } - }, - "required": ["updated"], - "additionalProperties": false, - "title": "Update workspace fork exclusions result", - "description": "Count of changed workflow exclusion flags." - }, - "UpdateWorkspaceForkExclusionsResponse": { - "type": "object", - "properties": { - "data": { - "description": "Response data.", - "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" - } - }, - "required": ["data"], - "additionalProperties": false, - "title": "Update workspace fork exclusions response", - "description": "Number of workflow exclusion flags changed." - }, - "UpdateWorkspaceForkExclusionsBody": { - "type": "object", - "properties": { - "workflowIds": { - "minItems": 1, - "maxItems": 1000, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - }, - "description": "Workflow identifiers in the current workspace." - }, - "forkSyncExcluded": { - "type": "boolean", - "description": "Whether the named workflows should be skipped as sync sources and targets." - } - }, - "required": ["workflowIds", "forkSyncExcluded"], - "additionalProperties": false, - "title": "Update workspace fork exclusions request", - "description": "Workflow IDs and whether to exclude them from sync." - }, - "PreviewWorkflowImportResult": { - "type": "object", - "properties": { - "previewFingerprint": { - "type": "string", - "minLength": 64, - "maxLength": 64, - "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." - }, - "ready": { - "type": "boolean", - "description": "Whether every required destination binding and configuration field is resolved for import." }, - "bindings": { - "maxItems": 10000, + "mappings": { + "description": "Proposed mapping entries addressed by resource type and `sourceId`. Preview does not save them; apply commits them with the sync.", + "maxItems": 5000, "type": "array", "items": { "type": "object", "properties": { - "kind": { + "resourceType": { "type": "string", "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", + "oauth_credential", + "service_account_credential", + "env_var", "table", + "knowledge_base", "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", "skill", - "sandbox", - "workflow" + "sandbox" ], - "description": "Resource or operation kind." + "description": "Resource type stored on the canonical parent/child edge." }, "sourceId": { "type": "string", + "minLength": 1, "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + "description": "Source resource identifier in the canonical source workspace." }, "targetId": { "anyOf": [ { "type": "string", + "minLength": 1, "maxLength": 4096 }, { @@ -23800,73 +24278,110 @@ } ], "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false + } + }, + "dependentValues": { + "description": "Destination-specific choices addressed by source workflow ID, source block ID, and field key. Omission keeps saved overrides; an explicit empty array clears them.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceWorkflowId": { + "type": "string", + "minLength": 1, + "description": "Workflow identifier in the source workspace." }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "occurrence": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "maxItems": 8, - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - }, - "encoding": { - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - } - }, - "required": ["blockId", "subBlockKey", "valuePath", "encoding"], - "additionalProperties": false, - "description": "Registered source field occurrence addressed by this binding." + "sourceBlockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Block identifier in the source workflow." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 65536, + "description": "Destination value for the registered dependent field." } }, - "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "required": ["sourceWorkflowId", "sourceBlockId", "subBlockKey", "value"], "additionalProperties": false + } + }, + "copyResources": { + "description": "Explicit source resources to copy before syncing the workflows.", + "type": "object", + "properties": { + "knowledgeBases": { + "description": "Source knowledge base identifiers whose documents and content are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "tables": { + "description": "Source table identifiers whose schemas and rows are copied.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "customTools": { + "description": "Source custom tool identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "skills": { + "description": "Source skill identifiers to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "files": { + "description": "Workspace file storage keys to copy.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mcpServers": { + "description": "External MCP server identifiers to copy; OAuth connections require authorization in the destination.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } }, - "description": "Resolved and unresolved source occurrences with their destination selections." + "additionalProperties": false }, - "unresolvedBindings": { - "maxItems": 10000, + "dropReferences": { + "description": "Source-deleted references explicitly acknowledged for removal; live source references cannot be dropped.", + "maxItems": 2000, "type": "array", "items": { "type": "object", @@ -23885,987 +24400,392 @@ "custom-tool", "custom-block", "skill", - "sandbox", - "workflow" + "sandbox" ], "description": "Resource or operation kind." }, "sourceId": { "type": "string", + "minLength": 1, "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "occurrence": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "maxItems": 8, - "type": "array", - "items": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 - } - }, - "encoding": { - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - } - }, - "required": ["blockId", "subBlockKey", "valuePath", "encoding"], - "additionalProperties": false, - "description": "Registered source field occurrence addressed by this binding." + "description": "Source resource identifier in the canonical source workspace." } }, - "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "required": ["kind", "sourceId"], "additionalProperties": false - }, - "description": "Source references that still require destination mappings or explicit copy choices." + } }, - "configuration": { - "maxItems": 10000, + "triggerMappings": { + "description": "Public trigger path choices from preview.triggerSlots, addressed by source workflow and block IDs. Duplicate or unavailable choices are rejected.", + "maxItems": 500, "type": "array", "items": { "type": "object", "properties": { - "blockId": { + "sourceWorkflowId": { "type": "string", "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." + "description": "Workflow identifier in the source workspace." }, - "subBlockKey": { + "sourceBlockId": { "type": "string", "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "configured": { - "type": "boolean", - "description": "Whether this destination field currently has a nonempty value." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s destination options.", - "type": "string", - "maxLength": 256 + "maxLength": 256, + "description": "Source trigger block identifier from the sync preview." }, - "context": { - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - }, - "description": "Allowlisted selector dependencies scoped to the destination workspace." - }, - "requiresAuthentication": { - "type": "boolean", - "description": "Whether a human must connect the provider before choices can be discovered." + "adoptPath": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "An adoptable path offered for this trigger, or null to allocate a new path." } }, - "required": [ - "blockId", - "subBlockKey", - "title", - "required", - "configured", - "context", - "requiresAuthentication" - ], + "required": ["sourceWorkflowId", "sourceBlockId", "adoptPath"], "additionalProperties": false - }, - "description": "Dependent fields that may need destination-specific values." + } }, - "unresolvedConfiguration": { - "maxItems": 10000, - "type": "array", - "items": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "title": { - "type": "string", - "maxLength": 1024, - "description": "Human-readable configuration field label." - }, - "required": { - "type": "boolean", - "description": "Whether the reference or configuration is required for this operation." - }, - "configured": { - "type": "boolean", - "description": "Whether this destination field currently has a nonempty value." - }, - "multiSelect": { - "description": "Whether the field accepts comma-separated selections.", - "type": "boolean" - }, - "selectorKey": { - "description": "Registered selector key for discovering this field’s destination options.", - "type": "string", - "maxLength": 256 - }, - "context": { - "type": "object", - "propertyNames": { - "type": "string", - "maxLength": 256 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - }, - "description": "Allowlisted selector dependencies scoped to the destination workspace." - }, - "requiresAuthentication": { - "type": "boolean", - "description": "Whether a human must connect the provider before choices can be discovered." - } - }, - "required": [ - "blockId", - "subBlockKey", - "title", - "required", - "configured", - "context", - "requiresAuthentication" - ], - "additionalProperties": false - }, - "description": "Required destination configuration that remains empty." + "requestId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Stable client request ID. Reuse it with identical inputs after an uncertain response; changed inputs return 409. A new ID can apply another operation." }, - "discovery": { - "maxItems": 32, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "maxLength": 256, - "description": "Resource or operation kind." - }, - "command": { - "type": "string", - "maxLength": 1024, - "description": "CLI command to enumerate destination candidates." - }, - "humanAuthorizationMayBeRequired": { - "type": "boolean", - "description": "Whether discovery may require a human OAuth authorization step." - } - }, - "required": ["kind", "command", "humanAuthorizationMayBeRequired"], - "additionalProperties": false - }, - "description": "CLI operations for discovering suitable destination resources." + "previewFingerprint": { + "type": "string", + "pattern": "^[a-f0-9]{64}$", + "description": "Fingerprint returned by a preview with the same choices. A changed plan returns 409; preview again. The example hash is illustrative; use the actual preview value." + }, + "confirm": { + "type": "boolean", + "const": true, + "description": "Confirm replacement of mapped target drafts and archival of mapped targets whose sources were deleted or archived." } }, - "required": [ - "previewFingerprint", - "ready", - "bindings", - "unresolvedBindings", - "configuration", - "unresolvedConfiguration", - "discovery" - ], + "required": ["otherWorkspaceId", "requestId", "previewFingerprint", "confirm"], "additionalProperties": false, - "title": "Workflow import preview", - "description": "Import readiness, unresolved bindings, and destination discovery instructions." + "title": "Pull workspace request", + "description": "Confirmed other-to-current choices, actual preview fingerprint, and stable request ID.", + "examples": [ + { + "otherWorkspaceId": "9f4c2a10-3b7e-4d58-8f6a-2c1d0e5b7a94", + "requestId": "pull-support-2026-10-13", + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "confirm": true + } + ] }, - "PreviewWorkflowImportResponse": { + "GetWorkspaceForkAvailabilityResult": { + "type": "object", + "properties": { + "available": { + "type": "boolean", + "description": "Whether this deployment and workspace plan enable forking." + } + }, + "required": ["available"], + "additionalProperties": false, + "title": "Get workspace fork availability result", + "description": "Fork feature availability for this workspace." + }, + "GetWorkspaceForkAvailabilityResponse": { "type": "object", "properties": { "data": { "description": "Response data.", - "$ref": "#/components/schemas/PreviewWorkflowImportResult" + "$ref": "#/components/schemas/GetWorkspaceForkAvailabilityResult" } }, "required": ["data"], "additionalProperties": false, - "title": "Preview workflow import response", - "description": "Import readiness, unresolved bindings, and destination discovery instructions.", - "examples": [ - { - "data": { - "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", - "ready": true, - "bindings": [], - "unresolvedBindings": [], - "configuration": [], - "unresolvedConfiguration": [], - "discovery": [] - } - } - ] + "title": "Get workspace fork availability response", + "description": "Whether forking is enabled for this deployment and workspace plan." }, - "ImportWorkflowRequest": { + "GetWorkspaceForkLineageResult": { "type": "object", "properties": { - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Workspace in which to import the workflow." - }, - "workflow": { - "anyOf": [ - { + "current": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1, - "description": "JSON string containing a workflow export object or bare workflow state." + "maxLength": 128, + "description": "Resource identifier." }, - { - "type": "object", - "additionalProperties": true, - "description": "Workflow export object or bare workflow state." + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Owning organization, or null for a personal workspace." } - ], - "description": "Workflow export object, bare workflow state, or JSON string containing either form." - }, - "folderPath": { - "description": "Destination folder path; omit for the workspace root.", - "$ref": "#/components/schemas/FolderPathInput" - }, - "name": { - "description": "Override for the imported workflow name.", - "type": "string", - "minLength": 1, - "maxLength": 200 + }, + "required": ["id", "name", "organizationId"], + "additionalProperties": false, + "description": "The current workspace lineage node." }, - "description": { - "description": "Override for the imported workflow description.", - "type": "string", - "maxLength": 2000 - }, - "mappings": { - "description": "Mapping entries addressed by resource kind and source identifier.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox", - "workflow" - ], - "description": "Resource or operation kind." - }, - "sourceId": { - "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["kind", "sourceId", "targetId"], - "additionalProperties": false - } - }, - "bindings": { - "description": "Resolved and unresolved source occurrences with their destination selections.", - "maxItems": 5000, - "type": "array", - "items": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "valuePath": { - "default": [], - "maxItems": 8, - "type": "array", - "items": { + "parent": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." + }, + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { "anyOf": [ { - "type": "string", - "minLength": 1, - "maxLength": 256 + "type": "string" }, { - "type": "integer", - "minimum": 0, - "maximum": 2000 + "type": "null" } - ] - }, - "description": "Path within the field value; strings address properties and numbers address array entries." - }, - "positions": { - "description": "Positions occupied by this identifier in a multi-value field.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "integer", - "minimum": 0, - "maximum": 2000 + ], + "description": "Owning organization, or null for a personal workspace." } }, - "encoding": { - "default": "scalar", - "type": "string", - "enum": ["scalar", "array", "csv", "files", "environment"], - "description": "Registered encoding used to discover and rewrite the reference." - }, - "kind": { - "type": "string", - "enum": [ - "credential", - "env-var", - "knowledge-base", - "knowledge-document", - "table", - "file", - "file-folder", - "mcp-server", - "custom-tool", - "custom-block", - "skill", - "sandbox", - "workflow" - ], - "description": "Resource or operation kind." - }, - "targetId": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 4096 - }, - { - "type": "null" - } - ], - "description": "Authorized destination identifier, or null to clear the mapping." - } - }, - "required": ["blockId", "subBlockKey", "kind", "targetId"], - "additionalProperties": false - } - }, - "dependentValues": { - "description": "Destination-specific values addressed by the source block ID and field key, before imported IDs are regenerated.", - "maxItems": 2000, - "type": "array", - "items": { - "type": "object", - "properties": { - "blockId": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Source block identifier before graph ID regeneration." - }, - "subBlockKey": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Registered source field key, including the tool index for nested Agent fields." - }, - "value": { - "type": "string", - "maxLength": 16384, - "description": "Destination value for the registered dependent field." - } + "required": ["id", "name", "organizationId"], + "additionalProperties": false }, - "required": ["blockId", "subBlockKey", "value"], - "additionalProperties": false - } + { + "type": "null" + } + ], + "description": "The live parent workspace, or null when this workspace is not a fork." } }, - "required": ["workspaceId", "workflow"], + "required": ["current", "parent"], "additionalProperties": false, - "title": "Import workflow request", - "description": "Portable workflow data and destination metadata for an import." + "title": "Get workspace fork lineage result", + "description": "Current workspace and its active parent." }, - "SelectorOption": { + "GetWorkspaceForkLineageResponse": { "type": "object", "properties": { - "id": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Provider resource identifier." - }, - "label": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Human-readable provider resource name." - }, - "meta": { - "description": "Safe scalar metadata for presenting or configuring this choice.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 128 - }, - "additionalProperties": { - "anyOf": [ - { - "type": "string", - "maxLength": 16384 - }, - { - "type": "number" - }, - { - "type": "boolean" - }, - { - "type": "null" - } - ] - } + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/GetWorkspaceForkLineageResult" } }, - "required": ["id", "label"], + "required": ["data"], "additionalProperties": false, - "title": "SelectorOption", - "description": "The SelectorOption result." + "title": "Get workspace fork lineage response", + "description": "Current workspace and its active direct parent, when present." }, - "ListSelectorResponse": { + "ListWorkspaceForkChildrenResult": { "type": "object", "properties": { - "data": { - "maxItems": 100, - "type": "array", - "items": { - "$ref": "#/components/schemas/SelectorOption" - }, - "description": "Authorized provider options in this page." + "id": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Resource identifier." }, - "nextCursor": { + "name": { + "type": "string", + "maxLength": 1024, + "description": "Display name of the workflow or workspace." + }, + "organizationId": { "anyOf": [ { - "type": "string", - "maxLength": 32768 + "type": "string" }, { "type": "null" } ], - "description": "Opaque cursor for the next page. Send it back as `cursor`; null means there is nothing further to fetch. Never construct one yourself." - }, - "truncated": { - "type": "boolean", - "description": "Whether provider limits left the result incomplete. A null `nextCursor` with `truncated: true` does not establish that all options were searched." - } - }, - "required": ["data", "nextCursor", "truncated"], - "additionalProperties": false, - "title": "List selector response", - "description": "A page of authorized options, continuation cursor, and truncation status." - }, - "ListSelectorBody": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." - }, - "selectorKey": { - "type": "string", - "enum": [ - "airtable.bases", - "airtable.tables", - "asana.workspaces", - "attio.lists", - "attio.objects", - "bigquery.datasets", - "bigquery.tables", - "bitbucket.workspaces", - "bitbucket.repositories", - "calcom.eventTypes", - "calcom.schedules", - "clickup.workspaces", - "clickup.spaces", - "clickup.folders", - "clickup.lists", - "coda.docs", - "coda.pages", - "coda.tables", - "coda.columns", - "coda.rows", - "coda.formulas", - "coda.controls", - "coda.folders", - "coda.permissions", - "confluence.spaces", - "confluence.spacesById", - "confluence.pages", - "google.tasks.lists", - "gauge.organizations", - "gauge.categories", - "gauge.topics", - "gauge.prompts", - "gauge.tags", - "gauge.answers", - "fivetran.groups", - "fivetran.connections", - "gmail.labels", - "google.calendar", - "google.drive", - "google.sheets", - "harmonic.savedSearches", - "jama.projects", - "jama.itemTypes", - "flow.projects", - "flow.categories", - "flow.branches", - "helpscout.mailboxes", - "helpscout.assignees", - "hubspot.lists", - "hubspot.owners", - "hubspot.pipelines", - "hubspot.pipelineStages", - "hubspot.properties", - "jsm.requestTypes", - "jsm.serviceDesks", - "microsoft.planner.plans", - "notion.databases", - "notion.pages", - "netsuite.recordTypes", - "netsuite.asyncTasks", - "pipedrive.pipelines", - "sharepoint.lists", - "trello.boards", - "zoho_desk.organizations", - "zoho_desk.departments", - "zoho_desk.agents", - "zoom.meetings", - "slack.channels", - "snowflake.databases", - "snowflake.schemas", - "snowflake.tables", - "snowflake.warehouses", - "snowflake.roles", - "snowflake.fileFormats", - "snowflake.procedures", - "slack.users", - "outlook.folders", - "outlook.calendars", - "microsoft.teams", - "microsoft.chats", - "microsoft.channels", - "microsoft.planner", - "onedrive.files", - "onedrive.folders", - "sharepoint.sites", - "microsoft.excel", - "microsoft.excel.drives", - "microsoft.excel.sheets", - "microsoft.word", - "wealthbox.contacts", - "jira.issues", - "jira.projects", - "jira.projectKeys", - "linear.projects", - "linear.teams", - "monday.boards", - "monday.groups", - "webflow.sites", - "webflow.collections", - "webflow.items", - "planetscale.databases", - "powerbi.workspaces", - "powerbi.datasets", - "powerbi.reports", - "planetscale.branches", - "planetscale.backups", - "planetscale.deployRequests", - "planetscale.savedDatabases", - "planetscale.savedBranches", - "planetscale.savedBackups", - "planetscale.savedDeployRequests", - "cloudwatch.logGroups", - "cloudwatch.logStreams", - "cloudwatch.savedLogGroups", - "cloudwatch.savedLogStreams", - "imap.mailboxes", - "mcp.tools", - "managedAgent.agents", - "managedAgent.environments", - "managedAgent.vaults", - "managedAgent.memoryStores", - "knowledge.documents", - "sim.workflows", - "table.columns", - "table.outputColumns", - "workspace.secretNames", - "workspace.sandboxes", - "providers.ollamaEmbeddingModels", - "providers.openrouterEmbeddingModels" - ], - "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." - }, - "context": { - "default": {}, - "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - } - }, - "search": { - "description": "Provider option search text.", - "type": "string", - "minLength": 1, - "maxLength": 1024 + "description": "Owning organization, or null for a personal workspace." }, - "cursor": { - "description": "Cursor returned by the preceding page. Keep `workspaceId`, `selectorKey`, `context`, and `search` unchanged; only `limit` may change. Restart without a cursor after a changed-page 409.", + "createdAt": { "type": "string", - "minLength": 1, - "maxLength": 32768 - }, - "limit": { - "default": 50, - "description": "Maximum options per page, from 1 to 100. Defaults to 50.", - "type": "integer", - "minimum": 1, - "maximum": 100 + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "ISO 8601 creation timestamp." } }, - "required": ["workspaceId", "selectorKey"], + "required": ["id", "name", "organizationId", "createdAt"], "additionalProperties": false, - "title": "List selector request", - "description": "Workspace, registered selector key, context, and optional search/cursor." + "title": "List workspace fork children result", + "description": "An active direct child workspace." }, - "GetSelectorResponse": { + "ListWorkspaceForkChildrenResponse": { "type": "object", "properties": { "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ListWorkspaceForkChildrenResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { "anyOf": [ { - "$ref": "#/components/schemas/SelectorOption" + "type": "string" }, { "type": "null" } ], - "description": "Response data." + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." } }, - "required": ["data"], + "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "Get selector response", - "description": "The authorized option, or data:null when absent from complete results." + "title": "List workspace fork children response", + "description": "A page of active direct child workspaces." }, - "GetSelectorBody": { + "ListWorkspaceForkResourcesResult": { "type": "object", "properties": { - "workspaceId": { + "id": { "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "Explicit current workspace scope." + "maxLength": 4096, + "description": "Resource identifier." }, - "selectorKey": { + "label": { "type": "string", - "enum": [ - "airtable.bases", - "airtable.tables", - "asana.workspaces", - "attio.lists", - "attio.objects", - "bigquery.datasets", - "bigquery.tables", - "bitbucket.workspaces", - "bitbucket.repositories", - "calcom.eventTypes", - "calcom.schedules", - "clickup.workspaces", - "clickup.spaces", - "clickup.folders", - "clickup.lists", - "coda.docs", - "coda.pages", - "coda.tables", - "coda.columns", - "coda.rows", - "coda.formulas", - "coda.controls", - "coda.folders", - "coda.permissions", - "confluence.spaces", - "confluence.spacesById", - "confluence.pages", - "google.tasks.lists", - "gauge.organizations", - "gauge.categories", - "gauge.topics", - "gauge.prompts", - "gauge.tags", - "gauge.answers", - "fivetran.groups", - "fivetran.connections", - "gmail.labels", - "google.calendar", - "google.drive", - "google.sheets", - "harmonic.savedSearches", - "jama.projects", - "jama.itemTypes", - "flow.projects", - "flow.categories", - "flow.branches", - "helpscout.mailboxes", - "helpscout.assignees", - "hubspot.lists", - "hubspot.owners", - "hubspot.pipelines", - "hubspot.pipelineStages", - "hubspot.properties", - "jsm.requestTypes", - "jsm.serviceDesks", - "microsoft.planner.plans", - "notion.databases", - "notion.pages", - "netsuite.recordTypes", - "netsuite.asyncTasks", - "pipedrive.pipelines", - "sharepoint.lists", - "trello.boards", - "zoho_desk.organizations", - "zoho_desk.departments", - "zoho_desk.agents", - "zoom.meetings", - "slack.channels", - "snowflake.databases", - "snowflake.schemas", - "snowflake.tables", - "snowflake.warehouses", - "snowflake.roles", - "snowflake.fileFormats", - "snowflake.procedures", - "slack.users", - "outlook.folders", - "outlook.calendars", - "microsoft.teams", - "microsoft.chats", - "microsoft.channels", - "microsoft.planner", - "onedrive.files", - "onedrive.folders", - "sharepoint.sites", - "microsoft.excel", - "microsoft.excel.drives", - "microsoft.excel.sheets", - "microsoft.word", - "wealthbox.contacts", - "jira.issues", - "jira.projects", - "jira.projectKeys", - "linear.projects", - "linear.teams", - "monday.boards", - "monday.groups", - "webflow.sites", - "webflow.collections", - "webflow.items", - "planetscale.databases", - "powerbi.workspaces", - "powerbi.datasets", - "powerbi.reports", - "planetscale.branches", - "planetscale.backups", - "planetscale.deployRequests", - "planetscale.savedDatabases", - "planetscale.savedBranches", - "planetscale.savedBackups", - "planetscale.savedDeployRequests", - "cloudwatch.logGroups", - "cloudwatch.logStreams", - "cloudwatch.savedLogGroups", - "cloudwatch.savedLogStreams", - "imap.mailboxes", - "mcp.tools", - "managedAgent.agents", - "managedAgent.environments", - "managedAgent.vaults", - "managedAgent.memoryStores", - "knowledge.documents", - "sim.workflows", - "table.columns", - "table.outputColumns", - "workspace.secretNames", - "workspace.sandboxes", - "providers.ollamaEmbeddingModels", - "providers.openrouterEmbeddingModels" - ], - "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + "maxLength": 1024, + "description": "Human-readable resource label." }, - "context": { - "default": {}, - "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", - "type": "object", - "propertyNames": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "additionalProperties": { - "type": "string", - "maxLength": 16384 - } + "folderId": { + "description": "Containing folder identifier, or null at the workspace root.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] }, - "id": { - "type": "string", - "minLength": 1, - "maxLength": 16384, - "description": "Provider option ID to resolve with the same selector and declared context." + "folderName": { + "description": "Containing folder name, or null at the workspace root.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] } }, - "required": ["workspaceId", "selectorKey", "id"], + "required": ["id", "label"], "additionalProperties": false, - "title": "Get selector request", - "description": "Workspace, registered selector key, context, and provider option ID." + "title": "List workspace fork resources result", + "description": "A copyable resource candidate." }, - "GetWorkspaceOperationResponse": { + "ListWorkspaceForkResourcesResponse": { "type": "object", "properties": { "data": { - "description": "Response data.", - "$ref": "#/components/schemas/WorkspaceOperationReport" + "type": "array", + "items": { + "$ref": "#/components/schemas/ListWorkspaceForkResourcesResult" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." } }, - "required": ["data"], + "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "Get workspace operation response", - "description": "Refreshed commit, copy progress, and exact deployment readiness." + "title": "List workspace fork resources response", + "description": "A page of copyable resource candidates." }, - "ListWorkspaceOperationsResponse": { + "GetWorkspaceForkMappingsResult": { + "type": "object", + "properties": { + "resourceType": { + "type": "string", + "enum": [ + "oauth_credential", + "service_account_credential", + "env_var", + "table", + "knowledge_base", + "file", + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" + ], + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "id": { + "type": "string", + "maxLength": 256, + "description": "Resource identifier." + } + }, + "required": ["resourceType", "sourceId", "targetId", "id"], + "additionalProperties": false, + "title": "Get workspace fork mappings result", + "description": "A saved directional mapping entry." + }, + "GetWorkspaceForkMappingsResponse": { "type": "object", "properties": { "data": { "type": "array", "items": { - "$ref": "#/components/schemas/WorkspaceOperationReport" + "$ref": "#/components/schemas/GetWorkspaceForkMappingsResult" }, "description": "Items in the current page." }, @@ -24883,38 +24803,2507 @@ }, "required": ["data", "nextCursor"], "additionalProperties": false, - "title": "List workspace operations response", - "description": "A page of stored operation receipts." + "title": "Get workspace fork mappings response", + "description": "A page of persisted source-to-target mapping entries." }, - "GetWorkspaceSourceResponse": { + "UpdateWorkspaceForkMappingsResult": { "type": "object", "properties": { - "data": { - "type": "object", - "properties": { - "workspaceId": { - "type": "string", - "description": "Workspace id." - }, - "kinds": { - "type": "array", - "items": { + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." + } + }, + "required": ["updated"], + "additionalProperties": false, + "title": "Update workspace fork mappings result", + "description": "Count of changed mapping records." + }, + "UpdateWorkspaceForkMappingsResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkMappingsResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Update workspace fork mappings response", + "description": "Number of mapping records changed." + }, + "UpdateWorkspaceForkMappingsBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + }, + "direction": { + "type": "string", + "enum": ["push", "pull"], + "description": "Push means current to other; pull means other to current, independent of parent/child orientation." + }, + "mappings": { + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "resourceType": { "type": "string", "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", + "oauth_credential", + "service_account_credential", + "env_var", "table", - "knowledge-base", + "knowledge_base", "file", - "workflow", - "deployment" + "file_folder", + "mcp_server", + "custom_block", + "custom_tool", + "skill", + "sandbox" ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + "description": "Resource type stored on the canonical parent/child edge." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Source resource identifier in the canonical source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["resourceType", "sourceId", "targetId"], + "additionalProperties": false + }, + "description": "Mapping entries addressed by resource type and `sourceId`. `targetId: null` clears a mapping." + } + }, + "required": ["otherWorkspaceId", "direction", "mappings"], + "additionalProperties": false, + "title": "Update workspace fork mappings request", + "description": "Other workspace, direction, and mapping entries to update." + }, + "RollbackWorkspaceForkResult": { + "type": "object", + "properties": { + "restored": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows restored to their prior deployed version." + }, + "archived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Workflows created by the sync and now archived." + }, + "unarchived": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Previously archived workflows restored by rollback." + }, + "skipped": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Snapshot workflows no longer available to restore." + }, + "pendingActivations": { + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "maxLength": 256 + }, + "description": "Workflows whose restored deployment is still activating." + } + }, + "required": ["restored", "archived", "unarchived", "skipped", "pendingActivations"], + "additionalProperties": false, + "title": "Rollback workspace fork result", + "description": "Workflow restoration and pending-activation counts." + }, + "RollbackWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/RollbackWorkspaceForkResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Rollback workspace fork response", + "description": "Restored, archived, skipped, and still-activating workflow counts." + }, + "RollbackWorkspaceForkBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + } + }, + "required": ["otherWorkspaceId"], + "additionalProperties": false, + "title": "Rollback workspace fork request", + "description": "Other workspace whose latest inbound sync should be undone." + }, + "UnlinkWorkspaceForkResult": { + "type": "object", + "properties": { + "unlinked": { + "type": "boolean", + "description": "Whether the fork edge was removed." + } + }, + "required": ["unlinked"], + "additionalProperties": false, + "title": "Unlink workspace fork result", + "description": "Fork-edge removal acknowledgment." + }, + "UnlinkWorkspaceForkResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UnlinkWorkspaceForkResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Unlink workspace fork response", + "description": "Confirmation that the relationship was removed." + }, + "UnlinkWorkspaceForkBody": { + "type": "object", + "properties": { + "otherWorkspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace on the other side of the direct fork edge." + } + }, + "required": ["otherWorkspaceId"], + "additionalProperties": false, + "title": "Unlink workspace fork request", + "description": "Other workspace on the direct fork edge to remove." + }, + "UpdateWorkspaceForkExclusionsResult": { + "type": "object", + "properties": { + "updated": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Number of records changed." + } + }, + "required": ["updated"], + "additionalProperties": false, + "title": "Update workspace fork exclusions result", + "description": "Count of changed workflow exclusion flags." + }, + "UpdateWorkspaceForkExclusionsResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/UpdateWorkspaceForkExclusionsResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Update workspace fork exclusions response", + "description": "Number of workflow exclusion flags changed." + }, + "UpdateWorkspaceForkExclusionsBody": { + "type": "object", + "properties": { + "workflowIds": { + "minItems": 1, + "maxItems": 1000, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "Workflow identifiers in the current workspace." + }, + "forkSyncExcluded": { + "type": "boolean", + "description": "Whether the named workflows should be skipped as sync sources and targets." + } + }, + "required": ["workflowIds", "forkSyncExcluded"], + "additionalProperties": false, + "title": "Update workspace fork exclusions request", + "description": "Workflow IDs and whether to exclude them from sync." + }, + "PreviewWorkflowImportResult": { + "type": "object", + "properties": { + "previewFingerprint": { + "type": "string", + "minLength": 64, + "maxLength": 64, + "description": "Fingerprint to send when applying this import with the same choices. Preview again after changing any choice." + }, + "ready": { + "type": "boolean", + "description": "Whether every required destination binding and configuration field is resolved for import." + }, + "bindings": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "occurrence": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + } + }, + "required": ["blockId", "subBlockKey", "valuePath", "encoding"], + "additionalProperties": false, + "description": "Registered source field occurrence addressed by this binding." + } + }, + "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "additionalProperties": false + }, + "description": "Resolved and unresolved source occurrences with their destination selections." + }, + "unresolvedBindings": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "occurrence": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + } + }, + "required": ["blockId", "subBlockKey", "valuePath", "encoding"], + "additionalProperties": false, + "description": "Registered source field occurrence addressed by this binding." + } + }, + "required": ["kind", "sourceId", "targetId", "required", "occurrence"], + "additionalProperties": false + }, + "description": "Source references that still require destination mappings or explicit copy choices." + }, + "configuration": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "configured": { + "type": "boolean", + "description": "Whether this destination field currently has a nonempty value." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s destination options.", + "type": "string", + "maxLength": 256 + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + }, + "description": "Allowlisted selector dependencies scoped to the destination workspace." + }, + "requiresAuthentication": { + "type": "boolean", + "description": "Whether a human must connect the provider before choices can be discovered." + } + }, + "required": [ + "blockId", + "subBlockKey", + "title", + "required", + "configured", + "context", + "requiresAuthentication" + ], + "additionalProperties": false + }, + "description": "Dependent fields that may need destination-specific values." + }, + "unresolvedConfiguration": { + "maxItems": 10000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "title": { + "type": "string", + "maxLength": 1024, + "description": "Human-readable configuration field label." + }, + "required": { + "type": "boolean", + "description": "Whether the reference or configuration is required for this operation." + }, + "configured": { + "type": "boolean", + "description": "Whether this destination field currently has a nonempty value." + }, + "multiSelect": { + "description": "Whether the field accepts comma-separated selections.", + "type": "boolean" + }, + "selectorKey": { + "description": "Registered selector key for discovering this field’s destination options.", + "type": "string", + "maxLength": 256 + }, + "context": { + "type": "object", + "propertyNames": { + "type": "string", + "maxLength": 256 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + }, + "description": "Allowlisted selector dependencies scoped to the destination workspace." + }, + "requiresAuthentication": { + "type": "boolean", + "description": "Whether a human must connect the provider before choices can be discovered." + } + }, + "required": [ + "blockId", + "subBlockKey", + "title", + "required", + "configured", + "context", + "requiresAuthentication" + ], + "additionalProperties": false + }, + "description": "Required destination configuration that remains empty." + }, + "discovery": { + "maxItems": 32, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "maxLength": 256, + "description": "Resource or operation kind." + }, + "command": { + "type": "string", + "maxLength": 1024, + "description": "CLI command to enumerate destination candidates." + }, + "humanAuthorizationMayBeRequired": { + "type": "boolean", + "description": "Whether discovery may require a human OAuth authorization step." + } + }, + "required": ["kind", "command", "humanAuthorizationMayBeRequired"], + "additionalProperties": false + }, + "description": "CLI operations for discovering suitable destination resources." + } + }, + "required": [ + "previewFingerprint", + "ready", + "bindings", + "unresolvedBindings", + "configuration", + "unresolvedConfiguration", + "discovery" + ], + "additionalProperties": false, + "title": "Workflow import preview", + "description": "Import readiness, unresolved bindings, and destination discovery instructions." + }, + "PreviewWorkflowImportResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/PreviewWorkflowImportResult" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Preview workflow import response", + "description": "Import readiness, unresolved bindings, and destination discovery instructions.", + "examples": [ + { + "data": { + "previewFingerprint": "c7d158e8cbc5137a2d0a4fc37ddaeb51a3b9757485679a6ad82a7de3fdac4e3a", + "ready": true, + "bindings": [], + "unresolvedBindings": [], + "configuration": [], + "unresolvedConfiguration": [], + "discovery": [] + } + } + ] + }, + "ImportWorkflowRequest": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace in which to import the workflow." + }, + "workflow": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "description": "JSON string containing a workflow export object or bare workflow state." + }, + { + "type": "object", + "additionalProperties": true, + "description": "Workflow export object or bare workflow state." + } + ], + "description": "Workflow export object, bare workflow state, or JSON string containing either form." + }, + "folderPath": { + "description": "Destination folder path; omit for the workspace root.", + "$ref": "#/components/schemas/FolderPathInput" + }, + "name": { + "description": "Override for the imported workflow name.", + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "description": { + "description": "Override for the imported workflow description.", + "type": "string", + "maxLength": 2000 + }, + "mappings": { + "description": "Mapping entries addressed by resource kind and source identifier.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "sourceId": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Untrusted source reference label; imports never use it to authorize or query a source workspace." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["kind", "sourceId", "targetId"], + "additionalProperties": false + } + }, + "bindings": { + "description": "Resolved and unresolved source occurrences with their destination selections.", + "maxItems": 5000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "valuePath": { + "default": [], + "maxItems": 8, + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + ] + }, + "description": "Path within the field value; strings address properties and numbers address array entries." + }, + "positions": { + "description": "Positions occupied by this identifier in a multi-value field.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 2000 + } + }, + "encoding": { + "default": "scalar", + "type": "string", + "enum": ["scalar", "array", "csv", "files", "environment"], + "description": "Registered encoding used to discover and rewrite the reference." + }, + "kind": { + "type": "string", + "enum": [ + "credential", + "env-var", + "knowledge-base", + "knowledge-document", + "table", + "file", + "file-folder", + "mcp-server", + "custom-tool", + "custom-block", + "skill", + "sandbox", + "workflow" + ], + "description": "Resource or operation kind." + }, + "targetId": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 4096 + }, + { + "type": "null" + } + ], + "description": "Authorized destination identifier, or null to clear the mapping." + } + }, + "required": ["blockId", "subBlockKey", "kind", "targetId"], + "additionalProperties": false + } + }, + "dependentValues": { + "description": "Destination-specific values addressed by the source block ID and field key, before imported IDs are regenerated.", + "maxItems": 2000, + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Source block identifier before graph ID regeneration." + }, + "subBlockKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered source field key, including the tool index for nested Agent fields." + }, + "value": { + "type": "string", + "maxLength": 16384, + "description": "Destination value for the registered dependent field." + } + }, + "required": ["blockId", "subBlockKey", "value"], + "additionalProperties": false + } + } + }, + "required": ["workspaceId", "workflow"], + "additionalProperties": false, + "title": "Import workflow request", + "description": "Portable workflow data and destination metadata for an import." + }, + "SelectorOption": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Provider resource identifier." + }, + "label": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Human-readable provider resource name." + }, + "meta": { + "description": "Safe scalar metadata for presenting or configuring this choice.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "maxLength": 16384 + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + } + ] + } + } + }, + "required": ["id", "label"], + "additionalProperties": false, + "title": "SelectorOption", + "description": "The SelectorOption result." + }, + "ListSelectorResponse": { + "type": "object", + "properties": { + "data": { + "maxItems": 100, + "type": "array", + "items": { + "$ref": "#/components/schemas/SelectorOption" + }, + "description": "Authorized provider options in this page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string", + "maxLength": 32768 + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; null means there is nothing further to fetch. Never construct one yourself." + }, + "truncated": { + "type": "boolean", + "description": "Whether provider limits left the result incomplete. A null `nextCursor` with `truncated: true` does not establish that all options were searched." + } + }, + "required": ["data", "nextCursor", "truncated"], + "additionalProperties": false, + "title": "List selector response", + "description": "A page of authorized options, continuation cursor, and truncation status." + }, + "ListSelectorBody": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "selectorKey": { + "type": "string", + "enum": [ + "airtable.bases", + "airtable.tables", + "asana.workspaces", + "attio.lists", + "attio.objects", + "bigquery.datasets", + "bigquery.tables", + "bitbucket.workspaces", + "bitbucket.repositories", + "calcom.eventTypes", + "calcom.schedules", + "clickup.workspaces", + "clickup.spaces", + "clickup.folders", + "clickup.lists", + "coda.docs", + "coda.pages", + "coda.tables", + "coda.columns", + "coda.rows", + "coda.formulas", + "coda.controls", + "coda.folders", + "coda.permissions", + "confluence.spaces", + "confluence.spacesById", + "confluence.pages", + "google.tasks.lists", + "gauge.organizations", + "gauge.categories", + "gauge.topics", + "gauge.prompts", + "gauge.tags", + "gauge.answers", + "fivetran.groups", + "fivetran.connections", + "gmail.labels", + "google.calendar", + "google.drive", + "google.sheets", + "harmonic.savedSearches", + "jama.projects", + "jama.itemTypes", + "flow.projects", + "flow.categories", + "flow.branches", + "helpscout.mailboxes", + "helpscout.assignees", + "hubspot.lists", + "hubspot.owners", + "hubspot.pipelines", + "hubspot.pipelineStages", + "hubspot.properties", + "jsm.requestTypes", + "jsm.serviceDesks", + "microsoft.planner.plans", + "notion.databases", + "notion.pages", + "netsuite.recordTypes", + "netsuite.asyncTasks", + "pipedrive.pipelines", + "sharepoint.lists", + "trello.boards", + "zoho_desk.organizations", + "zoho_desk.departments", + "zoho_desk.agents", + "zoom.meetings", + "slack.channels", + "snowflake.databases", + "snowflake.schemas", + "snowflake.tables", + "snowflake.warehouses", + "snowflake.roles", + "snowflake.fileFormats", + "snowflake.procedures", + "slack.users", + "outlook.folders", + "outlook.calendars", + "microsoft.teams", + "microsoft.chats", + "microsoft.channels", + "microsoft.planner", + "onedrive.files", + "onedrive.folders", + "sharepoint.sites", + "microsoft.excel", + "microsoft.excel.drives", + "microsoft.excel.sheets", + "microsoft.word", + "wealthbox.contacts", + "jira.issues", + "jira.projects", + "jira.projectKeys", + "linear.projects", + "linear.teams", + "monday.boards", + "monday.groups", + "webflow.sites", + "webflow.collections", + "webflow.items", + "planetscale.databases", + "powerbi.workspaces", + "powerbi.datasets", + "powerbi.reports", + "planetscale.branches", + "planetscale.backups", + "planetscale.deployRequests", + "planetscale.savedDatabases", + "planetscale.savedBranches", + "planetscale.savedBackups", + "planetscale.savedDeployRequests", + "cloudwatch.logGroups", + "cloudwatch.logStreams", + "cloudwatch.savedLogGroups", + "cloudwatch.savedLogStreams", + "imap.mailboxes", + "mcp.tools", + "managedAgent.agents", + "managedAgent.environments", + "managedAgent.vaults", + "managedAgent.memoryStores", + "knowledge.documents", + "sim.workflows", + "table.columns", + "table.outputColumns", + "workspace.secretNames", + "workspace.sandboxes", + "providers.ollamaEmbeddingModels", + "providers.openrouterEmbeddingModels" + ], + "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + }, + "context": { + "default": {}, + "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + } + }, + "search": { + "description": "Provider option search text.", + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "cursor": { + "description": "Cursor returned by the preceding page. Keep `workspaceId`, `selectorKey`, `context`, and `search` unchanged; only `limit` may change. Restart without a cursor after a changed-page 409.", + "type": "string", + "minLength": 1, + "maxLength": 32768 + }, + "limit": { + "default": 50, + "description": "Maximum options per page, from 1 to 100. Defaults to 50.", + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": ["workspaceId", "selectorKey"], + "additionalProperties": false, + "title": "List selector request", + "description": "Workspace, registered selector key, context, and optional search/cursor." + }, + "GetSelectorResponse": { + "type": "object", + "properties": { + "data": { + "anyOf": [ + { + "$ref": "#/components/schemas/SelectorOption" + }, + { + "type": "null" + } + ], + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get selector response", + "description": "The authorized option, or data:null when absent from complete results." + }, + "GetSelectorBody": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Explicit current workspace scope." + }, + "selectorKey": { + "type": "string", + "enum": [ + "airtable.bases", + "airtable.tables", + "asana.workspaces", + "attio.lists", + "attio.objects", + "bigquery.datasets", + "bigquery.tables", + "bitbucket.workspaces", + "bitbucket.repositories", + "calcom.eventTypes", + "calcom.schedules", + "clickup.workspaces", + "clickup.spaces", + "clickup.folders", + "clickup.lists", + "coda.docs", + "coda.pages", + "coda.tables", + "coda.columns", + "coda.rows", + "coda.formulas", + "coda.controls", + "coda.folders", + "coda.permissions", + "confluence.spaces", + "confluence.spacesById", + "confluence.pages", + "google.tasks.lists", + "gauge.organizations", + "gauge.categories", + "gauge.topics", + "gauge.prompts", + "gauge.tags", + "gauge.answers", + "fivetran.groups", + "fivetran.connections", + "gmail.labels", + "google.calendar", + "google.drive", + "google.sheets", + "harmonic.savedSearches", + "jama.projects", + "jama.itemTypes", + "flow.projects", + "flow.categories", + "flow.branches", + "helpscout.mailboxes", + "helpscout.assignees", + "hubspot.lists", + "hubspot.owners", + "hubspot.pipelines", + "hubspot.pipelineStages", + "hubspot.properties", + "jsm.requestTypes", + "jsm.serviceDesks", + "microsoft.planner.plans", + "notion.databases", + "notion.pages", + "netsuite.recordTypes", + "netsuite.asyncTasks", + "pipedrive.pipelines", + "sharepoint.lists", + "trello.boards", + "zoho_desk.organizations", + "zoho_desk.departments", + "zoho_desk.agents", + "zoom.meetings", + "slack.channels", + "snowflake.databases", + "snowflake.schemas", + "snowflake.tables", + "snowflake.warehouses", + "snowflake.roles", + "snowflake.fileFormats", + "snowflake.procedures", + "slack.users", + "outlook.folders", + "outlook.calendars", + "microsoft.teams", + "microsoft.chats", + "microsoft.channels", + "microsoft.planner", + "onedrive.files", + "onedrive.folders", + "sharepoint.sites", + "microsoft.excel", + "microsoft.excel.drives", + "microsoft.excel.sheets", + "microsoft.word", + "wealthbox.contacts", + "jira.issues", + "jira.projects", + "jira.projectKeys", + "linear.projects", + "linear.teams", + "monday.boards", + "monday.groups", + "webflow.sites", + "webflow.collections", + "webflow.items", + "planetscale.databases", + "powerbi.workspaces", + "powerbi.datasets", + "powerbi.reports", + "planetscale.branches", + "planetscale.backups", + "planetscale.deployRequests", + "planetscale.savedDatabases", + "planetscale.savedBranches", + "planetscale.savedBackups", + "planetscale.savedDeployRequests", + "cloudwatch.logGroups", + "cloudwatch.logStreams", + "cloudwatch.savedLogGroups", + "cloudwatch.savedLogStreams", + "imap.mailboxes", + "mcp.tools", + "managedAgent.agents", + "managedAgent.environments", + "managedAgent.vaults", + "managedAgent.memoryStores", + "knowledge.documents", + "sim.workflows", + "table.columns", + "table.outputColumns", + "workspace.secretNames", + "workspace.sandboxes", + "providers.ollamaEmbeddingModels", + "providers.openrouterEmbeddingModels" + ], + "description": "Registered selector key from an import or sync preview, such as `gmail.labels`." + }, + "context": { + "default": {}, + "description": "Only the dependencies declared by the selector, such as oauthCredential and channelId. Missing OAuth connections require human authorization.", + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "additionalProperties": { + "type": "string", + "maxLength": 16384 + } + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "description": "Provider option ID to resolve with the same selector and declared context." + } + }, + "required": ["workspaceId", "selectorKey", "id"], + "additionalProperties": false, + "title": "Get selector request", + "description": "Workspace, registered selector key, context, and provider option ID." + }, + "GetWorkspaceOperationResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkspaceOperationReport" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace operation response", + "description": "Refreshed commit, copy progress, and exact deployment readiness." + }, + "ListWorkspaceOperationsResponse": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkspaceOperationReport" + }, + "description": "Items in the current page." + }, + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Opaque cursor for the next page. Send it back as `cursor`; `null` means there are no more pages. Do not construct a cursor yourself." + } + }, + "required": ["data", "nextCursor"], + "additionalProperties": false, + "title": "List workspace operations response", + "description": "A page of stored operation receipts." + }, + "GetWorkspaceSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "kinds": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "description": "The kinds read; the directory manages exactly these." + }, + "files": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + }, + "description": "Directory path → file text." + }, + "blobs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Directory path of the binary file." + }, + "sha256": { + "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 0, + "maximum": 10000000, + "description": "Bytes." + }, + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "href": { + "type": "string", + "description": "Where to download its bytes." + }, + "rev": { + "description": "Content revision, present when `sha256` is absent.", + "type": "string" + } + }, + "required": ["path", "size", "id", "href"], + "additionalProperties": false + }, + "description": "Binary files, downloaded separately by `href`." + }, + "base": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Base format version." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the directory was read from." + }, + "resources": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id the key is bound to." + }, + "fingerprint": { + "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", + "type": "string" + }, + "columns": { + "description": "Table column key → stored column.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored column id." + }, + "options": { + "description": "Select option name → option id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["id"], + "additionalProperties": false + } + }, + "blobs": { + "description": "Binary file name → its stored id, revision and hash as last read.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "rev": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "string" + } + ], + "description": "Content revision as last read." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + } + }, + "required": ["id", "rev", "sha256"], + "additionalProperties": false + } + }, + "rows": { + "description": "A table’s managed rows, as last read.", + "type": "object", + "properties": { + "fingerprint": { + "type": "string", + "description": "`rf1:` fingerprint of the managed rows as last read." + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "The table’s row version as last read; it moves on every row write." + } + }, + "required": ["fingerprint", "version"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + } + } + }, + "required": ["id"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "One resource in the base." + }, + "description": "`kind:key` → the stored resource and its fingerprint." + } + }, + "required": ["version", "workspaceId", "resources"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." + }, + "skipped": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "reason": { + "type": "string", + "description": "Why it was left out." + } + }, + "required": ["kind", "key", "reason"], + "additionalProperties": false + }, + "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "E_DECL_SYNTAX", + "E_DECL_HEADER", + "E_DECL_IMPORT", + "E_DECL_EXPORT", + "E_DECL_UNSUPPORTED", + "E_DECL_DUPLICATE_KEY", + "E_DECL_SHAPE", + "E_DECL_UNKNOWN_FIELD", + "E_DECL_UNKNOWN_FILE", + "W_PATH_NOT_SENT", + "E_BLOB_MANIFEST", + "E_BLOB_MISSING", + "E_LIMIT_EXCEEDED", + "E_KEY_INVALID", + "W_DECL_SUSPICIOUS_CHARACTER", + "E_BASE_JSON", + "E_BASE_VERSION", + "E_BASE_SHAPE", + "E_BASE_UNKNOWN_FIELD", + "E_SECRET_NAME", + "E_SECRET_MISSING", + "W_SECRET_MISSING", + "E_CREDENTIAL_MISSING", + "E_CREDENTIAL_AMBIGUOUS", + "W_CREDENTIAL_MISSING", + "W_CREDENTIAL_AMBIGUOUS", + "E_TABLE_COLUMN_NAME", + "E_TABLE_DUPLICATE_COLUMN", + "E_TABLE_TOO_MANY_COLUMNS", + "E_TABLE_OPTIONS", + "E_TABLE_TYPE_CONVERSION", + "E_TABLE_FOLDER", + "E_TABLE_ROWS", + "I_TABLE_SEED_SKIPPED", + "I_TABLE_ROWS_UNKEYED", + "W_LIKELY_RENAME", + "E_TOOL_SCHEMA", + "E_TOOL_CODE", + "E_TOOL_STORED_MISSING", + "W_TOOL_LITERAL_SECRET", + "E_SKILL_FRONTMATTER", + "E_MCP_LITERAL_SECRET", + "E_MCP_STORED_MISSING", + "E_MCP_TOOL_UNKNOWN", + "W_MCP_REPLACE", + "W_MCP_TOOLS_UNCHECKED", + "E_FILE_PATH", + "E_FILE_PATH_COLLISION", + "E_FILE_NAME", + "E_FILE_TOO_LARGE", + "E_FILE_CONTENT", + "E_KB_EMBEDDING_IMMUTABLE", + "E_KB_EMBEDDING_MODEL", + "E_KB_DOC_AMBIGUOUS", + "E_KB_DOC_NAME", + "E_KB_DOC_EMPTY", + "E_KB_CHUNKING", + "E_KB_FOLDER", + "W_KB_DOC_UNCHECKED", + "W_KB_DOC_FAILED", + "I_KB_REEMBED", + "I_KB_CHUNKING", + "I_KB_PROCESSING", + "I_KB_DOCS_UNHASHED", + "I_KB_UNMANAGED_DOCS", + "I_KB_REPLACE_UNFINISHED", + "E_DEPLOY_WORKFLOW", + "E_DEPLOY_SECRET", + "E_DEPLOY_CHAT_OUTPUT", + "E_DEPLOY_CHAT_IDENTIFIER", + "E_DEPLOY_PINNED_CHAT", + "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", + "I_DEPLOY_DRAFT_NOT_LIVE", + "E_APPLY_STALE", + "E_APPLY_NO_BASE", + "E_APPLY_FORBIDDEN", + "E_APPLY_DELETE_NOT_ALLOWED", + "E_APPLY_LOCKED", + "E_APPLY_REFUSED", + "E_APPLY_FAILED", + "E_PLAN_TOO_LARGE", + "E_PLAN_REF_DELETED", + "E_PLAN_REF_HELD", + "W_RESOURCE_IN_USE", + "W_TABLE_COLUMN_RENAMED_IN_USE", + "E_NAME_TAKEN", + "E_WORKFLOW_FILES_MISSING", + "E_WORKFLOW_FOLDER_COPIED", + "W_UNDECLARED", + "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", + "W_SERVER_CHANGED", + "W_SERVER_DELETED", + "W_SERVER_MOVED", + "I_KEY_REBOUND", + "E_KEY_RENAMED", + "I_FINDINGS_TRUNCATED", + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." + }, + "severity": { + "type": "string", + "enum": ["error", "warning", "info"], + "description": "Diagnostic severity." + }, + "message": { + "type": "string", + "description": "What was found." + }, + "hint": { + "description": "How to address it.", + "type": "string" + }, + "file": { + "description": "Directory file the finding is in.", + "type": "string" + }, + "line": { + "description": "1-based line in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "column": { + "description": "1-based column in `file`.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endLine": { + "description": "1-based line the finding ends on.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "endColumn": { + "description": "1-based column the finding ends at.", + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "frame": { + "description": "The source lines around the finding, with a caret row.", + "type": "string" + }, + "path": { + "description": "JSON Pointer into a JSON file, such as the base.", + "type": "string" + }, + "kind": { + "description": "Kind of the resource the finding is about.", + "type": "string" + }, + "key": { + "description": "Key of the resource the finding is about.", + "type": "string" + }, + "blockKey": { + "description": "Workflow block the finding is about.", + "type": "string" + }, + "param": { + "description": "Block field the finding is about.", + "type": "string" + } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding about the directory, pinned to its file when it has one." + }, + "description": "Findings from reading." + } + }, + "required": [ + "workspaceId", + "kinds", + "files", + "blobs", + "base", + "skipped", + "diagnostics" + ], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get workspace source response", + "description": "The workspace as a source directory.", + "examples": [ + { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "kinds": ["table", "workflow"], + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "blobs": [], + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "skipped": [], + "diagnostics": [] + } + } + ] + }, + "ApplyWorkspaceSourceResponse": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "description": "Workspace id." + }, + "dryRun": { + "type": "boolean", + "description": "True when nothing was written because `dryRun` was set." + }, + "plan": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "action": { + "type": "string", + "enum": ["create", "update", "adopt", "delete", "noop"], + "description": "`adopt` binds the key to an existing resource of the same name, then updates it." + }, + "fields": { + "description": "What changes.", + "type": "array", + "items": { + "type": "string" + } + }, + "destructive": { + "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", + "type": "object", + "properties": { + "what": { + "type": "string", + "description": "What is lost." + }, + "counts": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "description": "How much is lost." + } + }, + "required": ["what", "counts"], + "additionalProperties": false + }, + "id": { + "description": "Stored id, once known.", + "type": "string" + }, + "held": { + "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", + "type": "boolean", + "const": true + } + }, + "required": ["kind", "key", "action"], + "additionalProperties": false, + "description": "One planned or applied change." + }, + "description": "Every planned change, no-ops included, in apply order." + }, + "applied": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "action": { + "type": "string", + "enum": ["create", "update", "adopt", "delete", "noop"], + "description": "`adopt` binds the key to an existing resource of the same name, then updates it." + }, + "fields": { + "description": "What changes.", + "type": "array", + "items": { + "type": "string" + } + }, + "destructive": { + "description": "Data the change deletes: dropped columns, removed select options and the cells they empty, or a deleted resource. A dry run shows it whether or not `allowDelete` is set.", + "type": "object", + "properties": { + "what": { + "type": "string", + "description": "What is lost." + }, + "counts": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "description": "How much is lost." + } + }, + "required": ["what", "counts"], + "additionalProperties": false + }, + "id": { + "description": "Stored id, once known.", + "type": "string" + }, + "held": { + "description": "Held back: the change uses a declared secret the workspace has no value for, or a declared credential key nothing binds to (see its errors). It is not written; the rest of the apply goes ahead.", + "type": "boolean", + "const": true + } + }, + "required": ["kind", "key", "action"], + "additionalProperties": false, + "description": "One planned or applied change." + }, + "description": "The changes written, in order." + }, + "failed": { + "description": "The change that failed mid-apply. The changes before it are written (`applied`); the rest were not attempted. Applying the same directory again continues.", + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "key": { + "type": "string", + "description": "Resource key." + }, + "code": { + "type": "string", + "enum": [ + "E_DECL_SYNTAX", + "E_DECL_HEADER", + "E_DECL_IMPORT", + "E_DECL_EXPORT", + "E_DECL_UNSUPPORTED", + "E_DECL_DUPLICATE_KEY", + "E_DECL_SHAPE", + "E_DECL_UNKNOWN_FIELD", + "E_DECL_UNKNOWN_FILE", + "W_PATH_NOT_SENT", + "E_BLOB_MANIFEST", + "E_BLOB_MISSING", + "E_LIMIT_EXCEEDED", + "E_KEY_INVALID", + "W_DECL_SUSPICIOUS_CHARACTER", + "E_BASE_JSON", + "E_BASE_VERSION", + "E_BASE_SHAPE", + "E_BASE_UNKNOWN_FIELD", + "E_SECRET_NAME", + "E_SECRET_MISSING", + "W_SECRET_MISSING", + "E_CREDENTIAL_MISSING", + "E_CREDENTIAL_AMBIGUOUS", + "W_CREDENTIAL_MISSING", + "W_CREDENTIAL_AMBIGUOUS", + "E_TABLE_COLUMN_NAME", + "E_TABLE_DUPLICATE_COLUMN", + "E_TABLE_TOO_MANY_COLUMNS", + "E_TABLE_OPTIONS", + "E_TABLE_TYPE_CONVERSION", + "E_TABLE_FOLDER", + "E_TABLE_ROWS", + "I_TABLE_SEED_SKIPPED", + "I_TABLE_ROWS_UNKEYED", + "W_LIKELY_RENAME", + "E_TOOL_SCHEMA", + "E_TOOL_CODE", + "E_TOOL_STORED_MISSING", + "W_TOOL_LITERAL_SECRET", + "E_SKILL_FRONTMATTER", + "E_MCP_LITERAL_SECRET", + "E_MCP_STORED_MISSING", + "E_MCP_TOOL_UNKNOWN", + "W_MCP_REPLACE", + "W_MCP_TOOLS_UNCHECKED", + "E_FILE_PATH", + "E_FILE_PATH_COLLISION", + "E_FILE_NAME", + "E_FILE_TOO_LARGE", + "E_FILE_CONTENT", + "E_KB_EMBEDDING_IMMUTABLE", + "E_KB_EMBEDDING_MODEL", + "E_KB_DOC_AMBIGUOUS", + "E_KB_DOC_NAME", + "E_KB_DOC_EMPTY", + "E_KB_CHUNKING", + "E_KB_FOLDER", + "W_KB_DOC_UNCHECKED", + "W_KB_DOC_FAILED", + "I_KB_REEMBED", + "I_KB_CHUNKING", + "I_KB_PROCESSING", + "I_KB_DOCS_UNHASHED", + "I_KB_UNMANAGED_DOCS", + "I_KB_REPLACE_UNFINISHED", + "E_DEPLOY_WORKFLOW", + "E_DEPLOY_SECRET", + "E_DEPLOY_CHAT_OUTPUT", + "E_DEPLOY_CHAT_IDENTIFIER", + "E_DEPLOY_PINNED_CHAT", + "W_DEPLOYED_DRAFT_CHANGED", + "W_DEPLOY_DRAFT_NOT_SOURCE", + "E_DEPLOY_DRAFT_NOT_SOURCE_CHAT", + "I_DEPLOY_DRAFT_NOT_LIVE", + "E_APPLY_STALE", + "E_APPLY_NO_BASE", + "E_APPLY_FORBIDDEN", + "E_APPLY_DELETE_NOT_ALLOWED", + "E_APPLY_LOCKED", + "E_APPLY_REFUSED", + "E_APPLY_FAILED", + "E_PLAN_TOO_LARGE", + "E_PLAN_REF_DELETED", + "E_PLAN_REF_HELD", + "W_RESOURCE_IN_USE", + "W_TABLE_COLUMN_RENAMED_IN_USE", + "E_NAME_TAKEN", + "E_WORKFLOW_FILES_MISSING", + "E_WORKFLOW_FOLDER_COPIED", + "W_UNDECLARED", + "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", + "W_SERVER_CHANGED", + "W_SERVER_DELETED", + "W_SERVER_MOVED", + "I_KEY_REBOUND", + "E_KEY_RENAMED", + "I_FINDINGS_TRUNCATED", + "E_SYNTAX", + "E_SDK_HEADER", + "E_SDK_MAJOR", + "E_SDK_MAJOR_OLD", + "E_UNSUPPORTED_SYNTAX", + "E_WORKFLOW_EXPORT", + "E_INVALID_CHARACTER", + "E_NUMBER_NOT_FINITE", + "W_NUMBER_PRECISION", + "E_TOO_MANY_ERRORS", + "W_TOO_MANY_WARNINGS", + "E_DUPLICATE_NAME", + "E_RESERVED_NAME", + "E_KEY_OVERRIDE", + "E_EMPTY_NAME", + "E_LOOKALIKE_NAME", + "W_LOOKALIKE_NAME", + "W_SUSPICIOUS_CHARACTER", + "E_NAME_NOT_LITERAL", + "E_UNKNOWN_IDENTIFIER", + "E_OUT_OF_SCOPE", + "E_UNKNOWN_VARIABLE", + "E_DUPLICATE_VARIABLE", + "E_VARIABLE_NAME_MISMATCH", + "E_INVALID_ENV_NAME", + "W_ENV_UNKNOWN", + "W_CHILD_INPUT_UNKNOWN", + "W_CHILD_NO_START", + "E_UNKNOWN_SUBFLOW_PROPERTY", + "W_FORWARD_REF", + "W_REF_NOT_NORMALIZED", + "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", + "E_EDGE_SCOPE", + "E_EDGE_NOTE", + "E_TARGET_TRIGGER", + "E_NO_DEFAULT_OUTPUT", + "E_DUPLICATE_EDGE", + "E_ERROR_PORT_UNSUPPORTED", + "W_ERROR_PORT_STORED", + "E_UNKNOWN_BRANCH", + "E_DUPLICATE_BRANCH_KEY", + "E_BRANCH_KEY_COLLIDES", + "E_BRANCH_ELSE_LAST", + "W_RAW_HANDLE", + "W_SUBFLOW_HANDLE_SCOPE", + "E_EDGE_CYCLE", + "W_EDGE_CYCLE", + "W_BRANCH_UNWIRED", + "E_UNKNOWN_BUILDER", + "E_UNKNOWN_PARAM", + "E_FIXED_PARAM", + "W_FIELD_NOT_APPLICABLE", + "W_REQUIRED_MISSING", + "W_UNKNOWN_OPTION", + "E_UNKNOWN_OPERATION", + "W_UNKNOWN_MODEL", + "W_LEGACY_BLOCK_TYPE", + "I_SCHEDULE_UTC", + "E_STORED_VALUE_MISSING", + "W_VALUE_KIND", + "W_OUT_OF_RANGE", + "W_TABLE_FILTER_SHAPE", + "W_LITERAL_SECRET", + "W_SUBFLOW_COUNT", + "W_UNKNOWN_OUTPUT_PATH", + "W_JSON_REF_UNTYPED", + "E_CODE_FILE_MISSING", + "E_CODE_FILE_PATH", + "W_CODE_FILE_INLINED", + "W_UNRESOLVED_REF", + "W_FORWARD_REF_LITERALIZED", + "W_COMMENT_MOVED", + "W_COMMENT_DROPPED", + "E_LOCK_JSON", + "E_LOCK_VERSION", + "E_LOCK_SHAPE", + "E_LOCK_UNKNOWN_FIELD", + "E_LOCK_KEY", + "E_LOCK_IDENT", + "E_LOCK_DUPLICATE_IDENT", + "E_LOCK_DUPLICATE_ID", + "E_LOCK_PARENT", + "E_LOCK_BRANCH", + "E_LOCK_CODE_FILE_PATH", + "E_SOURCE_META_JSON", + "E_SOURCE_META_VERSION", + "E_SOURCE_META_SHAPE", + "E_SOURCE_META_UNKNOWN_FIELD", + "E_SOURCE_META_IDENT", + "E_SOURCE_META_DUPLICATE_IDENT", + "E_SOURCE_META_ANCHOR", + "E_CANON_LEGACY_NAME_COLLISION", + "E_CANON_EDGE_SCOPE", + "W_CANON_RESERVED_NAME", + "W_CANON_DANGLING_EDGE", + "W_CANON_DANGLING_PARENT", + "W_CANON_RAW_HANDLE", + "W_CANON_UNKNOWN_BLOCK_TYPE", + "W_CANON_UNRESOLVED_ID", + "W_CANON_TITLE_OVERRIDE", + "W_CANON_SUBFLOW_REPAIRED", + "W_CANON_SUBBLOCK_TYPE_DRIFT", + "W_CANON_UNDECODABLE_JSON", + "E_MAT_DUPLICATE_LOCK_ID", + "E_MAT_UNKNOWN_RESOURCE", + "E_MAT_UNKNOWN_VARIABLE", + "W_MAT_DELETED_SINCE_PULL", + "W_MAT_INFERRED_RENAME", + "W_MAT_RETYPE_RECREATED", + "W_MAT_LOCK_ID_CLAIMED", + "I_MAT_NEEDS_LAYOUT", + "E_APPLY_WORKFLOW_MISMATCH", + "E_APPLY_LOCKED_BLOCK", + "E_APPLY_TYPE_NOT_ADDABLE", + "E_APPLY_INVALID_STATE", + "E_APPLY_BLOCK_NOT_FOUND", + "E_APPLY_INVALID_BLOCK_TYPE", + "E_APPLY_BLOCK_NOT_ALLOWED", + "E_APPLY_MODEL_NOT_ALLOWED", + "E_APPLY_TOOL_NOT_ALLOWED", + "E_APPLY_INVALID_EDGE_SOURCE", + "E_APPLY_INVALID_EDGE_SCOPE", + "E_APPLY_INVALID_SOURCE_HANDLE", + "E_APPLY_INVALID_TARGET_HANDLE", + "E_APPLY_INVALID_SUBBLOCK_FIELD", + "E_APPLY_MISSING_REQUIRED_PARAMS", + "E_APPLY_RETRY_NOT_SUPPORTED", + "E_APPLY_DUPLICATE_TRIGGER", + "E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK", + "E_APPLY_DISABLED_ANCESTOR", + "E_APPLY_CREDENTIAL_UNREACHABLE", + "W_APPLY_CREDENTIAL_KEPT", + "E_APPLY_SANDBOX_PLAN_REQUIRED", + "W_APPLY_HOSTED_KEY_DROPPED", + "W_APPLY_VALUE_NORMALIZED", + "W_APPLY_TYPE_CHANGED", + "W_APPLY_TRIGGER_REMOVED", + "W_APPLY_CATALOG_MOVED", + "W_APPLY_PROBABLE_RENAME", + "E_APPLY_LINT", + "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", + "W_APPLY_LINT", + "W_TABLE_UNKNOWN_COLUMN", + "E_APPLY_INVALID_SCHEDULE", + "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", + "E_WORKFLOW_META_INVALID" + ], + "description": "Diagnostic code." + }, + "message": { + "type": "string", + "description": "What failed." + } }, - "description": "The kinds read; the directory manages exactly these." + "required": ["kind", "key", "code", "message"], + "additionalProperties": false + }, + "needBlobs": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Binary paths a write needs whose bytes are not staged: on a dry run, exactly what to stage before applying." + }, + "applyId": { + "description": "The id of an apply that wrote: every audit log entry its writes recorded carries it as `metadata.correlationId`. Absent on a dry run.", + "type": "string" }, "files": { "type": "object", @@ -24924,47 +27313,7 @@ "additionalProperties": { "type": "string" }, - "description": "Directory path → file text." - }, - "blobs": { - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string", - "minLength": 1, - "maxLength": 1024, - "description": "Directory path of the binary file." - }, - "sha256": { - "description": "Absent when the server did not hash the bytes within the request; hash the downloaded bytes and record them in the base with `id` and `rev`.", - "type": "string", - "pattern": "^[0-9a-f]{64}$" - }, - "size": { - "type": "integer", - "minimum": 0, - "maximum": 10000000, - "description": "Bytes." - }, - "id": { - "type": "string", - "description": "Stored id of the binary file." - }, - "href": { - "type": "string", - "description": "Where to download its bytes." - }, - "rev": { - "description": "Content revision, present when `sha256` is absent.", - "type": "string" - } - }, - "required": ["path", "size", "id", "href"], - "additionalProperties": false - }, - "description": "Binary files, downloaded separately by `href`." + "description": "Files re-printed from what was saved, for every resource written." }, "base": { "type": "object", @@ -25092,42 +27441,7 @@ "additionalProperties": { "description": "An `x-` extension field, kept as written." }, - "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." - }, - "skipped": { - "type": "array", - "items": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "secret", - "credential", - "custom-tool", - "skill", - "mcp-server", - "table", - "knowledge-base", - "file", - "workflow", - "deployment" - ], - "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." - }, - "key": { - "type": "string", - "description": "Resource key." - }, - "reason": { - "type": "string", - "description": "Why it was left out." - } - }, - "required": ["kind", "key", "reason"], - "additionalProperties": false - }, - "description": "Resources left out, with why: too large to read as source, not readable by the caller, or past the directory's declaration or binary-file budget." + "description": "The base after this apply: the next apply’s `base`." }, "diagnostics": { "type": "array", @@ -25229,6 +27543,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "W_SERVER_CHANGED", "W_SERVER_DELETED", "W_SERVER_MOVED", @@ -25267,6 +27583,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25376,10 +27694,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." @@ -25441,77 +27762,366 @@ "description": "Key of the resource the finding is about.", "type": "string" }, - "blockKey": { - "description": "Workflow block the finding is about.", - "type": "string" + "blockKey": { + "description": "Workflow block the finding is about.", + "type": "string" + }, + "param": { + "description": "Block field the finding is about.", + "type": "string" + } + }, + "required": ["code", "severity", "message"], + "additionalProperties": false, + "description": "A finding about the directory, pinned to its file when it has one." + }, + "description": "Warnings, and on a dry run every error." + } + }, + "required": [ + "workspaceId", + "dryRun", + "plan", + "applied", + "needBlobs", + "files", + "base", + "diagnostics" + ], + "additionalProperties": false, + "description": "Response data." + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Apply workspace source response", + "description": "The plan, what was written, and the files re-printed from it.", + "examples": [ + { + "data": { + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "dryRun": false, + "plan": [ + { + "kind": "table", + "key": "leads", + "action": "noop", + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c" + } + ], + "applied": [], + "needBlobs": [], + "files": {}, + "base": { + "version": 1, + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" + } + } + } + } + } + }, + "diagnostics": [] + } + } + ] + }, + "ApplyWorkspaceSourceBody": { + "type": "object", + "properties": { + "files": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "additionalProperties": { + "type": "string" + }, + "description": "Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged." + }, + "blobs": { + "description": "Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.", + "maxItems": 20000, + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "Directory path of the binary file." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + }, + "size": { + "type": "integer", + "minimum": 0, + "maximum": 10000000, + "description": "Bytes." + } + }, + "required": ["path", "sha256", "size"], + "additionalProperties": false + } + }, + "base": { + "type": "object", + "properties": { + "version": { + "type": "number", + "const": 1, + "description": "Base format version." + }, + "workspaceId": { + "type": "string", + "description": "Workspace the directory was read from." + }, + "resources": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id the key is bound to." + }, + "fingerprint": { + "description": "`rf1:` fingerprint of the resource as last read; absent for a workflow, and for a binary file listed without `sha256` until the client records its hash.", + "type": "string" + }, + "columns": { + "description": "Table column key → stored column.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored column id." + }, + "options": { + "description": "Select option name → option id.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": ["id"] + } + }, + "blobs": { + "description": "Binary file name → its stored id, revision and hash as last read.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stored id of the binary file." + }, + "rev": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "string" + } + ], + "description": "Content revision as last read." + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$", + "description": "SHA-256 of the bytes, lowercase hex." + } + }, + "required": ["id", "rev", "sha256"] + } }, - "param": { - "description": "Block field the finding is about.", - "type": "string" + "rows": { + "description": "A table’s managed rows, as last read.", + "type": "object", + "properties": { + "fingerprint": { + "type": "string", + "description": "`rf1:` fingerprint of the managed rows as last read." + }, + "version": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "The table’s row version as last read; it moves on every row write." + } + }, + "required": ["fingerprint", "version"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + } } }, - "required": ["code", "severity", "message"], - "additionalProperties": false, - "description": "A finding about the directory, pinned to its file when it has one." + "required": ["id"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "One resource in the base." }, - "description": "Findings from reading." + "description": "`kind:key` → the stored resource and its fingerprint." } }, - "required": [ - "workspaceId", - "kinds", - "files", - "blobs", - "base", - "skipped", - "diagnostics" - ], - "additionalProperties": false, - "description": "Response data." + "required": ["version", "workspaceId", "resources"], + "additionalProperties": { + "description": "An `x-` extension field, kept as written." + }, + "description": "`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change." + }, + "kinds": { + "maxItems": 10, + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + }, + "description": "The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent." + }, + "options": { + "description": "How far the apply may go.", + "type": "object", + "properties": { + "allowDelete": { + "description": "Delete resources, columns and data the directory no longer declares.", + "type": "boolean" + }, + "only": { + "description": "Apply only these kinds.", + "type": "array", + "items": { + "type": "string", + "enum": [ + "secret", + "credential", + "custom-tool", + "skill", + "mcp-server", + "table", + "knowledge-base", + "file", + "workflow", + "deployment" + ], + "description": "A resource kind: `secret`, `credential`, `custom-tool`, `skill`, `mcp-server`, `table`, `knowledge-base`, `file`, `workflow`, `deployment`." + } + } + }, + "additionalProperties": false + }, + "provenance": { + "description": "Where the directory came from, for the audit log.", + "type": "object", + "properties": { + "client": { + "type": "string", + "enum": ["cli", "api"], + "description": "What submitted the directory." + }, + "gitSha": { + "description": "The commit the directory was taken from; recorded in the audit log.", + "type": "string", + "pattern": "^[0-9a-f]{7,64}$" + }, + "repo": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "The repository the source was taken from (its remote URL); recorded in the audit log." + } + }, + "required": ["client"], + "additionalProperties": false } }, - "required": ["data"], + "required": ["files", "kinds"], "additionalProperties": false, - "title": "Get workspace source response", - "description": "The workspace as a source directory.", + "title": "Apply workspace source body", + "description": "The directory files, its managed kinds and the base they were read with.", "examples": [ { - "data": { + "files": { + "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" + }, + "kinds": ["table"], + "base": { + "version": 1, "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "kinds": ["table", "workflow"], - "files": { - "tables/leads.ts": "// @sim-sdk 1\nimport { column, defineTable } from '@sim/workflow-sdk/workspace'\n\nexport default defineTable({\n name: 'leads',\n columns: {\n email: column.string({ required: true, unique: true }),\n status: column.select({ options: ['new', 'won'] }),\n },\n})\n" - }, - "blobs": [], - "base": { - "version": 1, - "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "resources": { - "table:leads": { - "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", - "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", - "columns": { - "email": { - "id": "col_8e1c4a7b2d5f" - }, - "status": { - "id": "col_3b6d9f2a5c8e", - "options": { - "new": "k2Pq9x", - "won": "r7Tn4m" - } + "resources": { + "table:leads": { + "id": "tbl_5c0e2a7b9d1f4e3a8b6c2d0f7e9a1b3c", + "fingerprint": "rf1:4b8d2f6a0c3e7b1d5f9a2c6e0b4d8f3a7c1e5b9d2f6a0c4e8b3d7f1a5c9e2b6d", + "columns": { + "email": { + "id": "col_8e1c4a7b2d5f" + }, + "status": { + "id": "col_3b6d9f2a5c8e", + "options": { + "new": "k2Pq9x", + "won": "r7Tn4m" } } } } - }, - "skipped": [], - "diagnostics": [] + } } } ] }, - "ApplyWorkspaceSourceResponse": { + "PlanWorkspaceSourceResponse": { "type": "object", "properties": { "data": { @@ -25798,6 +28408,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "W_SERVER_CHANGED", "W_SERVER_DELETED", "W_SERVER_MOVED", @@ -25836,6 +28448,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -25945,10 +28559,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code." @@ -26210,6 +28827,8 @@ "E_WORKFLOW_FOLDER_COPIED", "W_UNDECLARED", "W_BASE_OTHER_WORKSPACE", + "W_PROMOTE_TARGET_DELETED", + "W_PROMOTE_DELETES_TARGET_ONLY", "W_SERVER_CHANGED", "W_SERVER_DELETED", "W_SERVER_MOVED", @@ -26248,6 +28867,8 @@ "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", + "W_REF_OUT_OF_SCOPE", + "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -26357,10 +28978,13 @@ "W_APPLY_PROBABLE_RENAME", "E_APPLY_LINT", "E_APPLY_UNRESOLVED_REF", + "E_APPLY_REF_OUT_OF_SCOPE", + "E_APPLY_CODE_FILE_REF_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", + "E_APPLY_VARIABLE_DELETE", "E_WORKFLOW_META_INVALID" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." @@ -26454,13 +29078,13 @@ }, "required": ["data"], "additionalProperties": false, - "title": "Apply workspace source response", - "description": "The plan, what was written, and the files re-printed from it.", + "title": "Plan workspace source response", + "description": "The plan an apply would carry out.", "examples": [ { "data": { "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", - "dryRun": false, + "dryRun": true, "plan": [ { "kind": "table", @@ -26499,7 +29123,7 @@ } ] }, - "ApplyWorkspaceSourceBody": { + "PlanWorkspaceSourceBody": { "type": "object", "properties": { "files": { @@ -26720,35 +29344,11 @@ } }, "additionalProperties": false - }, - "provenance": { - "description": "Where the directory came from, for the audit log.", - "type": "object", - "properties": { - "client": { - "type": "string", - "enum": ["cli", "api"], - "description": "What submitted the directory." - }, - "gitSha": { - "description": "The commit the directory was taken from; recorded in the audit log.", - "type": "string", - "pattern": "^[0-9a-f]{7,64}$" - }, - "repo": { - "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "The repository the source was taken from (its remote URL); recorded in the audit log." - } - }, - "required": ["client"], - "additionalProperties": false } }, "required": ["files", "kinds"], "additionalProperties": false, - "title": "Apply workspace source body", + "title": "Plan workspace source body", "description": "The directory files, its managed kinds and the base they were read with.", "examples": [ { diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 65db3d26f91..3efe7c0150a 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -844,6 +844,8 @@ export type ApplyWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -954,10 +956,13 @@ export type ApplyWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -1297,6 +1302,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'W_SERVER_CHANGED' | 'W_SERVER_DELETED' | 'W_SERVER_MOVED' @@ -1335,6 +1342,8 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1444,10 +1453,13 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' message: string } @@ -1581,6 +1593,8 @@ export type ApplyWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'W_SERVER_CHANGED' | 'W_SERVER_DELETED' | 'W_SERVER_MOVED' @@ -1619,6 +1633,8 @@ export type ApplyWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1728,10 +1744,13 @@ export type ApplyWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -5280,6 +5299,8 @@ export type CreateWorkflowFromSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -5390,10 +5411,13 @@ export type CreateWorkflowFromSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -10377,6 +10401,8 @@ export type GetWorkflowSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -10487,10 +10513,13 @@ export type GetWorkflowSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_NAME_TAKEN' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' @@ -11024,6 +11053,8 @@ export type GetWorkspaceSourceResponse = { | 'E_WORKFLOW_FOLDER_COPIED' | 'W_UNDECLARED' | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' | 'W_SERVER_CHANGED' | 'W_SERVER_DELETED' | 'W_SERVER_MOVED' @@ -11062,6 +11093,8 @@ export type GetWorkspaceSourceResponse = { | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -11171,10 +11204,13 @@ export type GetWorkspaceSourceResponse = { | 'W_APPLY_PROBABLE_RENAME' | 'E_APPLY_LINT' | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' | 'E_WORKFLOW_META_INVALID' severity: 'error' | 'warning' | 'info' message: string @@ -14248,6 +14284,1018 @@ export type MoveWorkflowsResponse = { data: MoveWorkflowsResponseRef0 } +/** `POST /api/v2/workflows/[workflowId]/source/plan` */ +export type PlanWorkflowSourceParams = { + workflowId: string +} + +export type PlanWorkflowSourceQuery = { + allowDelete?: boolean +} + +export type PlanWorkflowSourceBody = { + files: Record + lock: { + version: 1 + blocks: Record< + string, + { + id: string + parent: string | null + branches?: Record + items?: Record< + string, + Array<{ + name: string + id: string + }> + > + ident: string + order: number + layout?: { + x: number + y: number + w?: number + h?: number + height?: number + horizontalHandles?: boolean + [key: string]: unknown + } + codeFile?: string + [key: string]: unknown + } + > + variables: Record + [key: string]: unknown + } + base: { + version?: 1 + workflowId: string + workspaceId: string + fingerprint: string + catalogHash: string + [key: string]: unknown + } +} + +export type PlanWorkflowSourceResponse = { + data: { + workflowId: string + workspaceId: string + dryRun: boolean + applied: boolean + diff: { + noop: boolean + meta?: Array<'name' | 'description'> + blocks: { + added: Array<{ + id: string + key: string + type: string + }> + removed: Array<{ + id: string + key: string + type: string + }> + renamed: Array<{ + id: string + from: string + to: string + }> + modified: Array<{ + id: string + key: string + fields: Array + reparented?: boolean + }> + } + edges: { + added: number + removed: number + } + variables: { + added: Array + removed: Array + modified: Array + } + } + diagnostics: Array<{ + code: + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_LIMIT_EXCEEDED' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_STALE' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_META_INVALID' + severity: 'error' | 'warning' | 'info' + message: string + hint?: string + blockKey?: string + param?: string + file?: string + line?: number + column?: number + endLine?: number + endColumn?: number + frame?: string + blockId?: string + path?: string + }> + files: Record + lock: { + version: 1 + blocks: Record< + string, + { + id: string + parent: string | null + branches?: Record + items?: Record< + string, + Array<{ + name: string + id: string + }> + > + ident: string + order: number + layout?: { + x: number + y: number + w?: number + h?: number + height?: number + horizontalHandles?: boolean + [key: string]: unknown + } + codeFile?: string + [key: string]: unknown + } + > + variables: Record + [key: string]: unknown + } + base: { + version: 1 + workflowId: string + workspaceId: string + fingerprint: string + catalogHash: string + [key: string]: unknown + } + mintedIds: Record + notes: Array + needsRedeployment: boolean + } +} + +/** `POST /api/v2/workspaces/[workspaceId]/source/plan` */ +export type PlanWorkspaceSourceParams = { + workspaceId: string +} + +export type PlanWorkspaceSourceQuery = Record + +export type PlanWorkspaceSourceBody = { + files: Record + blobs?: Array<{ + path: string + sha256: string + size: number + }> + base?: { + version: 1 + workspaceId: string + resources: Record< + string, + { + id: string + fingerprint?: string + columns?: Record< + string, + { + id: string + options?: Record + } + > + blobs?: Record< + string, + { + id: string + rev: number | string + sha256: string + } + > + rows?: { + fingerprint: string + version: number + [key: string]: unknown + } + [key: string]: unknown + } + > + [key: string]: unknown + } + kinds: Array< + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + > + options?: { + allowDelete?: boolean + only?: Array< + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + > + } +} + +export type PlanWorkspaceSourceResponse = { + data: { + workspaceId: string + dryRun: boolean + plan: Array<{ + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' + fields?: Array + destructive?: { + what: string + counts: Record + } + id?: string + held?: true + }> + applied: Array<{ + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + action: 'create' | 'update' | 'adopt' | 'delete' | 'noop' + fields?: Array + destructive?: { + what: string + counts: Record + } + id?: string + held?: true + }> + failed?: { + kind: + | 'secret' + | 'credential' + | 'custom-tool' + | 'skill' + | 'mcp-server' + | 'table' + | 'knowledge-base' + | 'file' + | 'workflow' + | 'deployment' + key: string + code: + | 'E_DECL_SYNTAX' + | 'E_DECL_HEADER' + | 'E_DECL_IMPORT' + | 'E_DECL_EXPORT' + | 'E_DECL_UNSUPPORTED' + | 'E_DECL_DUPLICATE_KEY' + | 'E_DECL_SHAPE' + | 'E_DECL_UNKNOWN_FIELD' + | 'E_DECL_UNKNOWN_FILE' + | 'W_PATH_NOT_SENT' + | 'E_BLOB_MANIFEST' + | 'E_BLOB_MISSING' + | 'E_LIMIT_EXCEEDED' + | 'E_KEY_INVALID' + | 'W_DECL_SUSPICIOUS_CHARACTER' + | 'E_BASE_JSON' + | 'E_BASE_VERSION' + | 'E_BASE_SHAPE' + | 'E_BASE_UNKNOWN_FIELD' + | 'E_SECRET_NAME' + | 'E_SECRET_MISSING' + | 'W_SECRET_MISSING' + | 'E_CREDENTIAL_MISSING' + | 'E_CREDENTIAL_AMBIGUOUS' + | 'W_CREDENTIAL_MISSING' + | 'W_CREDENTIAL_AMBIGUOUS' + | 'E_TABLE_COLUMN_NAME' + | 'E_TABLE_DUPLICATE_COLUMN' + | 'E_TABLE_TOO_MANY_COLUMNS' + | 'E_TABLE_OPTIONS' + | 'E_TABLE_TYPE_CONVERSION' + | 'E_TABLE_FOLDER' + | 'E_TABLE_ROWS' + | 'I_TABLE_SEED_SKIPPED' + | 'I_TABLE_ROWS_UNKEYED' + | 'W_LIKELY_RENAME' + | 'E_TOOL_SCHEMA' + | 'E_TOOL_CODE' + | 'E_TOOL_STORED_MISSING' + | 'W_TOOL_LITERAL_SECRET' + | 'E_SKILL_FRONTMATTER' + | 'E_MCP_LITERAL_SECRET' + | 'E_MCP_STORED_MISSING' + | 'E_MCP_TOOL_UNKNOWN' + | 'W_MCP_REPLACE' + | 'W_MCP_TOOLS_UNCHECKED' + | 'E_FILE_PATH' + | 'E_FILE_PATH_COLLISION' + | 'E_FILE_NAME' + | 'E_FILE_TOO_LARGE' + | 'E_FILE_CONTENT' + | 'E_KB_EMBEDDING_IMMUTABLE' + | 'E_KB_EMBEDDING_MODEL' + | 'E_KB_DOC_AMBIGUOUS' + | 'E_KB_DOC_NAME' + | 'E_KB_DOC_EMPTY' + | 'E_KB_CHUNKING' + | 'E_KB_FOLDER' + | 'W_KB_DOC_UNCHECKED' + | 'W_KB_DOC_FAILED' + | 'I_KB_REEMBED' + | 'I_KB_CHUNKING' + | 'I_KB_PROCESSING' + | 'I_KB_DOCS_UNHASHED' + | 'I_KB_UNMANAGED_DOCS' + | 'I_KB_REPLACE_UNFINISHED' + | 'E_DEPLOY_WORKFLOW' + | 'E_DEPLOY_SECRET' + | 'E_DEPLOY_CHAT_OUTPUT' + | 'E_DEPLOY_CHAT_IDENTIFIER' + | 'E_DEPLOY_PINNED_CHAT' + | 'W_DEPLOYED_DRAFT_CHANGED' + | 'W_DEPLOY_DRAFT_NOT_SOURCE' + | 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT' + | 'I_DEPLOY_DRAFT_NOT_LIVE' + | 'E_APPLY_STALE' + | 'E_APPLY_NO_BASE' + | 'E_APPLY_FORBIDDEN' + | 'E_APPLY_DELETE_NOT_ALLOWED' + | 'E_APPLY_LOCKED' + | 'E_APPLY_REFUSED' + | 'E_APPLY_FAILED' + | 'E_PLAN_TOO_LARGE' + | 'E_PLAN_REF_DELETED' + | 'E_PLAN_REF_HELD' + | 'W_RESOURCE_IN_USE' + | 'W_TABLE_COLUMN_RENAMED_IN_USE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_FILES_MISSING' + | 'E_WORKFLOW_FOLDER_COPIED' + | 'W_UNDECLARED' + | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' + | 'W_SERVER_CHANGED' + | 'W_SERVER_DELETED' + | 'W_SERVER_MOVED' + | 'I_KEY_REBOUND' + | 'E_KEY_RENAMED' + | 'I_FINDINGS_TRUNCATED' + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' + | 'E_WORKFLOW_META_INVALID' + message: string + } + needBlobs: Array + applyId?: string + files: Record + base: { + version: 1 + workspaceId: string + resources: Record< + string, + { + id: string + fingerprint?: string + columns?: Record< + string, + { + id: string + options?: Record + } + > + blobs?: Record< + string, + { + id: string + rev: number | string + sha256: string + } + > + rows?: { + fingerprint: string + version: number + [key: string]: unknown + } + [key: string]: unknown + } + > + [key: string]: unknown + } + diagnostics: Array<{ + code: + | 'E_DECL_SYNTAX' + | 'E_DECL_HEADER' + | 'E_DECL_IMPORT' + | 'E_DECL_EXPORT' + | 'E_DECL_UNSUPPORTED' + | 'E_DECL_DUPLICATE_KEY' + | 'E_DECL_SHAPE' + | 'E_DECL_UNKNOWN_FIELD' + | 'E_DECL_UNKNOWN_FILE' + | 'W_PATH_NOT_SENT' + | 'E_BLOB_MANIFEST' + | 'E_BLOB_MISSING' + | 'E_LIMIT_EXCEEDED' + | 'E_KEY_INVALID' + | 'W_DECL_SUSPICIOUS_CHARACTER' + | 'E_BASE_JSON' + | 'E_BASE_VERSION' + | 'E_BASE_SHAPE' + | 'E_BASE_UNKNOWN_FIELD' + | 'E_SECRET_NAME' + | 'E_SECRET_MISSING' + | 'W_SECRET_MISSING' + | 'E_CREDENTIAL_MISSING' + | 'E_CREDENTIAL_AMBIGUOUS' + | 'W_CREDENTIAL_MISSING' + | 'W_CREDENTIAL_AMBIGUOUS' + | 'E_TABLE_COLUMN_NAME' + | 'E_TABLE_DUPLICATE_COLUMN' + | 'E_TABLE_TOO_MANY_COLUMNS' + | 'E_TABLE_OPTIONS' + | 'E_TABLE_TYPE_CONVERSION' + | 'E_TABLE_FOLDER' + | 'E_TABLE_ROWS' + | 'I_TABLE_SEED_SKIPPED' + | 'I_TABLE_ROWS_UNKEYED' + | 'W_LIKELY_RENAME' + | 'E_TOOL_SCHEMA' + | 'E_TOOL_CODE' + | 'E_TOOL_STORED_MISSING' + | 'W_TOOL_LITERAL_SECRET' + | 'E_SKILL_FRONTMATTER' + | 'E_MCP_LITERAL_SECRET' + | 'E_MCP_STORED_MISSING' + | 'E_MCP_TOOL_UNKNOWN' + | 'W_MCP_REPLACE' + | 'W_MCP_TOOLS_UNCHECKED' + | 'E_FILE_PATH' + | 'E_FILE_PATH_COLLISION' + | 'E_FILE_NAME' + | 'E_FILE_TOO_LARGE' + | 'E_FILE_CONTENT' + | 'E_KB_EMBEDDING_IMMUTABLE' + | 'E_KB_EMBEDDING_MODEL' + | 'E_KB_DOC_AMBIGUOUS' + | 'E_KB_DOC_NAME' + | 'E_KB_DOC_EMPTY' + | 'E_KB_CHUNKING' + | 'E_KB_FOLDER' + | 'W_KB_DOC_UNCHECKED' + | 'W_KB_DOC_FAILED' + | 'I_KB_REEMBED' + | 'I_KB_CHUNKING' + | 'I_KB_PROCESSING' + | 'I_KB_DOCS_UNHASHED' + | 'I_KB_UNMANAGED_DOCS' + | 'I_KB_REPLACE_UNFINISHED' + | 'E_DEPLOY_WORKFLOW' + | 'E_DEPLOY_SECRET' + | 'E_DEPLOY_CHAT_OUTPUT' + | 'E_DEPLOY_CHAT_IDENTIFIER' + | 'E_DEPLOY_PINNED_CHAT' + | 'W_DEPLOYED_DRAFT_CHANGED' + | 'W_DEPLOY_DRAFT_NOT_SOURCE' + | 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT' + | 'I_DEPLOY_DRAFT_NOT_LIVE' + | 'E_APPLY_STALE' + | 'E_APPLY_NO_BASE' + | 'E_APPLY_FORBIDDEN' + | 'E_APPLY_DELETE_NOT_ALLOWED' + | 'E_APPLY_LOCKED' + | 'E_APPLY_REFUSED' + | 'E_APPLY_FAILED' + | 'E_PLAN_TOO_LARGE' + | 'E_PLAN_REF_DELETED' + | 'E_PLAN_REF_HELD' + | 'W_RESOURCE_IN_USE' + | 'W_TABLE_COLUMN_RENAMED_IN_USE' + | 'E_NAME_TAKEN' + | 'E_WORKFLOW_FILES_MISSING' + | 'E_WORKFLOW_FOLDER_COPIED' + | 'W_UNDECLARED' + | 'W_BASE_OTHER_WORKSPACE' + | 'W_PROMOTE_TARGET_DELETED' + | 'W_PROMOTE_DELETES_TARGET_ONLY' + | 'W_SERVER_CHANGED' + | 'W_SERVER_DELETED' + | 'W_SERVER_MOVED' + | 'I_KEY_REBOUND' + | 'E_KEY_RENAMED' + | 'I_FINDINGS_TRUNCATED' + | 'E_SYNTAX' + | 'E_SDK_HEADER' + | 'E_SDK_MAJOR' + | 'E_SDK_MAJOR_OLD' + | 'E_UNSUPPORTED_SYNTAX' + | 'E_WORKFLOW_EXPORT' + | 'E_INVALID_CHARACTER' + | 'E_NUMBER_NOT_FINITE' + | 'W_NUMBER_PRECISION' + | 'E_TOO_MANY_ERRORS' + | 'W_TOO_MANY_WARNINGS' + | 'E_DUPLICATE_NAME' + | 'E_RESERVED_NAME' + | 'E_KEY_OVERRIDE' + | 'E_EMPTY_NAME' + | 'E_LOOKALIKE_NAME' + | 'W_LOOKALIKE_NAME' + | 'W_SUSPICIOUS_CHARACTER' + | 'E_NAME_NOT_LITERAL' + | 'E_UNKNOWN_IDENTIFIER' + | 'E_OUT_OF_SCOPE' + | 'E_UNKNOWN_VARIABLE' + | 'E_DUPLICATE_VARIABLE' + | 'E_VARIABLE_NAME_MISMATCH' + | 'E_INVALID_ENV_NAME' + | 'W_ENV_UNKNOWN' + | 'W_CHILD_INPUT_UNKNOWN' + | 'W_CHILD_NO_START' + | 'E_UNKNOWN_SUBFLOW_PROPERTY' + | 'W_FORWARD_REF' + | 'W_REF_NOT_NORMALIZED' + | 'E_REF_UNREPRESENTABLE' + | 'W_REF_OUT_OF_SCOPE' + | 'W_CODE_FILE_REF_SYNTAX' + | 'E_EDGE_SCOPE' + | 'E_EDGE_NOTE' + | 'E_TARGET_TRIGGER' + | 'E_NO_DEFAULT_OUTPUT' + | 'E_DUPLICATE_EDGE' + | 'E_ERROR_PORT_UNSUPPORTED' + | 'W_ERROR_PORT_STORED' + | 'E_UNKNOWN_BRANCH' + | 'E_DUPLICATE_BRANCH_KEY' + | 'E_BRANCH_KEY_COLLIDES' + | 'E_BRANCH_ELSE_LAST' + | 'W_RAW_HANDLE' + | 'W_SUBFLOW_HANDLE_SCOPE' + | 'E_EDGE_CYCLE' + | 'W_EDGE_CYCLE' + | 'W_BRANCH_UNWIRED' + | 'E_UNKNOWN_BUILDER' + | 'E_UNKNOWN_PARAM' + | 'E_FIXED_PARAM' + | 'W_FIELD_NOT_APPLICABLE' + | 'W_REQUIRED_MISSING' + | 'W_UNKNOWN_OPTION' + | 'E_UNKNOWN_OPERATION' + | 'W_UNKNOWN_MODEL' + | 'W_LEGACY_BLOCK_TYPE' + | 'I_SCHEDULE_UTC' + | 'E_STORED_VALUE_MISSING' + | 'W_VALUE_KIND' + | 'W_OUT_OF_RANGE' + | 'W_TABLE_FILTER_SHAPE' + | 'W_LITERAL_SECRET' + | 'W_SUBFLOW_COUNT' + | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_JSON_REF_UNTYPED' + | 'E_CODE_FILE_MISSING' + | 'E_CODE_FILE_PATH' + | 'W_CODE_FILE_INLINED' + | 'W_UNRESOLVED_REF' + | 'W_FORWARD_REF_LITERALIZED' + | 'W_COMMENT_MOVED' + | 'W_COMMENT_DROPPED' + | 'E_LOCK_JSON' + | 'E_LOCK_VERSION' + | 'E_LOCK_SHAPE' + | 'E_LOCK_UNKNOWN_FIELD' + | 'E_LOCK_KEY' + | 'E_LOCK_IDENT' + | 'E_LOCK_DUPLICATE_IDENT' + | 'E_LOCK_DUPLICATE_ID' + | 'E_LOCK_PARENT' + | 'E_LOCK_BRANCH' + | 'E_LOCK_CODE_FILE_PATH' + | 'E_SOURCE_META_JSON' + | 'E_SOURCE_META_VERSION' + | 'E_SOURCE_META_SHAPE' + | 'E_SOURCE_META_UNKNOWN_FIELD' + | 'E_SOURCE_META_IDENT' + | 'E_SOURCE_META_DUPLICATE_IDENT' + | 'E_SOURCE_META_ANCHOR' + | 'E_CANON_LEGACY_NAME_COLLISION' + | 'E_CANON_EDGE_SCOPE' + | 'W_CANON_RESERVED_NAME' + | 'W_CANON_DANGLING_EDGE' + | 'W_CANON_DANGLING_PARENT' + | 'W_CANON_RAW_HANDLE' + | 'W_CANON_UNKNOWN_BLOCK_TYPE' + | 'W_CANON_UNRESOLVED_ID' + | 'W_CANON_TITLE_OVERRIDE' + | 'W_CANON_SUBFLOW_REPAIRED' + | 'W_CANON_SUBBLOCK_TYPE_DRIFT' + | 'W_CANON_UNDECODABLE_JSON' + | 'E_MAT_DUPLICATE_LOCK_ID' + | 'E_MAT_UNKNOWN_RESOURCE' + | 'E_MAT_UNKNOWN_VARIABLE' + | 'W_MAT_DELETED_SINCE_PULL' + | 'W_MAT_INFERRED_RENAME' + | 'W_MAT_RETYPE_RECREATED' + | 'W_MAT_LOCK_ID_CLAIMED' + | 'I_MAT_NEEDS_LAYOUT' + | 'E_APPLY_WORKFLOW_MISMATCH' + | 'E_APPLY_LOCKED_BLOCK' + | 'E_APPLY_TYPE_NOT_ADDABLE' + | 'E_APPLY_INVALID_STATE' + | 'E_APPLY_BLOCK_NOT_FOUND' + | 'E_APPLY_INVALID_BLOCK_TYPE' + | 'E_APPLY_BLOCK_NOT_ALLOWED' + | 'E_APPLY_MODEL_NOT_ALLOWED' + | 'E_APPLY_TOOL_NOT_ALLOWED' + | 'E_APPLY_INVALID_EDGE_SOURCE' + | 'E_APPLY_INVALID_EDGE_SCOPE' + | 'E_APPLY_INVALID_SOURCE_HANDLE' + | 'E_APPLY_INVALID_TARGET_HANDLE' + | 'E_APPLY_INVALID_SUBBLOCK_FIELD' + | 'E_APPLY_MISSING_REQUIRED_PARAMS' + | 'E_APPLY_RETRY_NOT_SUPPORTED' + | 'E_APPLY_DUPLICATE_TRIGGER' + | 'E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK' + | 'E_APPLY_DISABLED_ANCESTOR' + | 'E_APPLY_CREDENTIAL_UNREACHABLE' + | 'W_APPLY_CREDENTIAL_KEPT' + | 'E_APPLY_SANDBOX_PLAN_REQUIRED' + | 'W_APPLY_HOSTED_KEY_DROPPED' + | 'W_APPLY_VALUE_NORMALIZED' + | 'W_APPLY_TYPE_CHANGED' + | 'W_APPLY_TRIGGER_REMOVED' + | 'W_APPLY_CATALOG_MOVED' + | 'W_APPLY_PROBABLE_RENAME' + | 'E_APPLY_LINT' + | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'W_APPLY_LINT' + | 'W_TABLE_UNKNOWN_COLUMN' + | 'E_APPLY_INVALID_SCHEDULE' + | 'E_APPLY_BLOCK_DELETE' + | 'E_APPLY_VARIABLE_DELETE' + | 'E_WORKFLOW_META_INVALID' + severity: 'error' | 'warning' | 'info' + message: string + hint?: string + file?: string + line?: number + column?: number + endLine?: number + endColumn?: number + frame?: string + path?: string + kind?: string + key?: string + blockKey?: string + param?: string + }> + } +} + /** `POST /api/v2/organizations/[organizationId]/search/sources/prepare` */ export type PrepareSearchSourcesParams = { organizationId: string @@ -19571,7 +20619,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', }, }, body: { @@ -21228,7 +22276,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Allow the apply to delete blocks the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE` naming them. Ignored when creating a workflow.', + 'Allow the apply to delete blocks and variables the source no longer declares. Without it, an apply that would delete any block is refused with `E_APPLY_BLOCK_DELETE`, and one that would delete any variable with `E_APPLY_VARIABLE_DELETE`, naming them. Ignored when creating a workflow.', }, }, body: { @@ -26496,6 +27544,75 @@ export const V2_OPERATIONS = { }, }, }, + planWorkflowSource: { + method: 'POST', + path: '/api/v2/workflows/[workflowId]/source/plan', + pathParams: ['workflowId'] as const, + pathParamDocs: { workflowId: 'Unique workflow identifier.' }, + responseMode: 'json', + summary: 'Plan workflow source', + workspaceKeyUnsupported: true, + query: { + allowDelete: { + kind: 'boolean', + describe: + 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.', + }, + }, + body: { + files: { + kind: 'object', + required: true, + describe: + 'Relative path → file text: `workflow.ts` plus every function-code file it references (for example `functions/score.js`). At most 2001 files and 4000000 bytes together, for a workflow of at most 2000 blocks.', + }, + lock: { + kind: 'object', + required: true, + describe: + 'Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids.', + }, + base: { + kind: 'object', + required: true, + describe: + 'Where and when the source was read (`.sim/base.json`). A draft that no longer matches `base.fingerprint` is reported as `E_APPLY_STALE` in `diagnostics`.', + }, + }, + }, + planWorkspaceSource: { + method: 'POST', + path: '/api/v2/workspaces/[workspaceId]/source/plan', + pathParams: ['workspaceId'] as const, + pathParamDocs: { workspaceId: 'Workspace to read or apply.' }, + responseMode: 'json', + summary: 'Plan workspace source', + body: { + files: { + kind: 'object', + required: true, + describe: + 'Directory path → text for every managed kind: declarations (`tables/leads.ts`) and workflow folders (`workflows/ingest/workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). A workflow folder sent with only its `.sim/base.json` is unchanged.', + }, + blobs: { + kind: 'array', + describe: + 'Binary files by path, with the SHA-256 and size of their bytes. Their bytes must be staged first: `sim workspaces source apply` stages them, or upload them to `POST /api/v2/workspaces/{workspaceId}/source/blobs` (not available over MCP). An apply with any missing is refused with `E_BLOB_MISSING` and writes nothing.', + }, + base: { + kind: 'object', + describe: + '`.sim/base.json`: per resource, the id and fingerprint the directory was read at. Apply compares it with the server to tell a local edit from a server change.', + }, + kinds: { + kind: 'array', + required: true, + describe: + 'The kind folders the directory holds, empty ones included. A kind is managed only when listed here or when a file of it is sent.', + }, + options: { kind: 'object', describe: 'How far the apply may go.' }, + }, + }, prepareSearchSources: { method: 'POST', path: '/api/v2/organizations/[organizationId]/search/sources/prepare', From 11813e531814e7e49aa74ad2331bd260887e5f31 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:57:41 -0800 Subject: [PATCH 042/104] style(sim-cli): format the written-record write list --- packages/sim-cli/src/commands/protocol/source-dir.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-dir.ts b/packages/sim-cli/src/commands/protocol/source-dir.ts index a31733e3d5f..4ddb7f39967 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir.ts @@ -878,11 +878,7 @@ export async function writeBack( [SOURCE_LOCK_FILE, `${JSON.stringify(answer.lock, null, 2)}\n`], [SOURCE_BASE_FILE, `${JSON.stringify(answer.base, null, 2)}\n`], ] - const write = [ - ...printed, - ...(folder ? [] : writtenFiles(writtenRecord(files))), - ...extra.write, - ] + const write = [...printed, ...(folder ? [] : writtenFiles(writtenRecord(files))), ...extra.write] const orphaned = orphanedCodeFiles(previousLock, answer.lock, Object.keys(answer.files)) const unnamed = await unnamedCodeFiles(dir, previousLock, answer, orphaned) await updateSourceDir(dir, { From 66ccd74e8a2ff1296ec5e7f565f91a8f22c46aff Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:58:42 -0800 Subject: [PATCH 043/104] test(workflow-code): code file tests name paths under functions/, the one code file path rule --- .../workflow-code/src/compile/grammar.test.ts | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index a539801dc5d..493c73a159c 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1725,22 +1725,22 @@ describe('iteration references outside their container', () => { [ START, "const lp = parallel.count('Fan', { count: 2 }, (p) => {", - " const inner = fn('Inner', { code: codeFile('./fns/inner.js') })", + " const inner = fn('Inner', { code: codeFile('./functions/inner.js') })", ' p.to(inner)', '})', - "const after = fn('After', { code: codeFile('./fns/after.js') })", + "const after = fn('After', { code: codeFile('./functions/after.js') })", 'start.to(lp)', 'lp.to(after)', ].join('\n') ), { - 'workflows/fns/inner.js': 'return [$ref.parallel.index, $ref.fan.currentItem]', - 'workflows/fns/after.js': 'return [$ref.loop.index, $ref.fan.index, $ref.fan.results]', + 'workflows/functions/inner.js': 'return [$ref.parallel.index, $ref.fan.currentItem]', + 'workflows/functions/after.js': 'return [$ref.loop.index, $ref.fan.index, $ref.fan.results]', } ) expect(codes(result).map((d) => [d.blockKey, d.span.file])).toEqual([ - ['after', 'workflows/fns/after.js'], - ['after', 'workflows/fns/after.js'], + ['after', 'workflows/functions/after.js'], + ['after', 'workflows/functions/after.js'], ]) }) @@ -1791,10 +1791,10 @@ describe('reference tags written in a code file', () => { it('checks tags in JavaScript strings as it checks $ref chains', () => { const result = run( source( - [START, "const f = fn('F', { code: codeFile('./fns/f.js') })", 'start.to(f)'].join('\n') + [START, "const f = fn('F', { code: codeFile('./functions/f.js') })", 'start.to(f)'].join('\n') ), { - 'workflows/fns/f.js': [ + 'workflows/functions/f.js': [ "const a = ''", 'const b = ``', "const html = '' + a + ''", @@ -1805,12 +1805,12 @@ describe('reference tags written in a code file', () => { expect(unresolved(result)).toEqual([ { message: ' names no block, so it does not resolve at run time.', - file: 'workflows/fns/f.js', + file: 'workflows/functions/f.js', line: 1, }, { message: ': no workflow variable is keyed ghost.', - file: 'workflows/fns/f.js', + file: 'workflows/functions/f.js', line: 2, }, ]) @@ -1821,16 +1821,16 @@ describe('reference tags written in a code file', () => { source( [ START, - "const f = fn('F', { language: 'python', code: codeFile('./fns/f.py') })", + "const f = fn('F', { language: 'python', code: codeFile('./functions/f.py') })", 'start.to(f)', ].join('\n') ), - { 'workflows/fns/f.py': 'q = \nr = \nreturn [q, r]' } + { 'workflows/functions/f.py': 'q = \nr = \nreturn [q, r]' } ) expect(unresolved(result)).toEqual([ { message: ' names no block, so it does not resolve at run time.', - file: 'workflows/fns/f.py', + file: 'workflows/functions/f.py', line: 2, }, ]) @@ -1848,22 +1848,22 @@ describe('$ref and $env in a Python or shell code file', () => { source( [ START, - "const f = fn('F', { language: 'python', code: codeFile('./fns/f.py') })", + "const f = fn('F', { language: 'python', code: codeFile('./functions/f.py') })", 'start.to(f)', ].join('\n') ), - { 'workflows/fns/f.py': "q = $ref.start.q\nkey = $env.API_KEY\nreturn '$5 ok'" } + { 'workflows/functions/f.py': "q = $ref.start.q\nkey = $env.API_KEY\nreturn '$5 ok'" } ) expect(syntax(result)).toEqual([ { hint: 'Python files are saved as written: write .', - file: 'workflows/fns/f.py', + file: 'workflows/functions/f.py', line: 1, column: 5, }, { hint: 'Python files are saved as written: write {{API_KEY}}.', - file: 'workflows/fns/f.py', + file: 'workflows/functions/f.py', line: 2, column: 7, }, @@ -1875,19 +1875,19 @@ describe('$ref and $env in a Python or shell code file', () => { source( [ START, - "const sh = fn('Sh', { language: 'shell', code: codeFile('./fns/s.sh') })", - "const js = fn('Js', { code: codeFile('./fns/j.js') })", + "const sh = fn('Sh', { language: 'shell', code: codeFile('./functions/s.sh') })", + "const js = fn('Js', { code: codeFile('./functions/j.js') })", 'start.to(sh)', 'sh.to(js)', ].join('\n') ), { - 'workflows/fns/s.sh': 'echo "$ref.start.q" "$HOME"', - 'workflows/fns/j.js': 'return $ref.start.q', + 'workflows/functions/s.sh': 'echo "$ref.start.q" "$HOME"', + 'workflows/functions/j.js': 'return $ref.start.q', } ) expect(syntax(result).map((d) => [d.file, d.hint])).toEqual([ - ['workflows/fns/s.sh', 'Shell files are saved as written: write .'], + ['workflows/functions/s.sh', 'Shell files are saved as written: write .'], ]) }) }) From b4bb8e870191287092a7126f2b3921a6617331da Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 22:59:44 -0800 Subject: [PATCH 044/104] test(sim-cli): check refuses an out-of-scope iteration reference on a block the edit changed The integration of the per-block digests (EDITED_ENTRY_REFUSALS) with the out-of-scope refusal maps W_REF_OUT_OF_SCOPE in workflow.ts to E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses it there; a block the lock binds was only refused when moved. A new block now reports the server's code too. --- .../protocol/workflow-source-check.test.ts | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) 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 33b90fc3b4d..c3b83dc9a05 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 @@ -509,7 +509,7 @@ export default workflow('W', {}, () => { await check() expect(scoped()).toEqual([ - expect.objectContaining({ code: 'W_REF_OUT_OF_SCOPE', severity: 'error' }), + expect.objectContaining({ code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' }), ]) writeLock(['start', 'each', 'inner', 'echo'], { inner: 'each', echo: 'each' }) @@ -527,6 +527,52 @@ export default workflow('W', {}, () => { expect(process.exitCode).toBeUndefined() }) + it('fails on an iteration reference an edit types into a block the lock binds outside its loop', async () => { + cacheCatalog() + const source = (code: string) => `// @sim-sdk 1 +import { fn, loop, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', {}) + const each = loop.for('Each', { count: 2 }, (p) => { + const inner = fn('Inner', { code: 'return 1' }) + p.to(inner) + }) + const echo = fn('Echo', { code: '${code}' }) + start.to(each) +}) +` + const lock = { + version: 1, + blocks: { + start: { id: 'id-start', parent: null, ident: 'start', order: 0 }, + each: { id: 'id-each', parent: null, ident: 'each', order: 1 }, + inner: { id: 'id-inner', parent: 'each', ident: 'inner', order: 2 }, + echo: { id: 'id-echo', parent: null, ident: 'echo', order: 3 }, + }, + variables: {}, + } + const printed = source('return 1') + writeFileSync(join(dir, 'workflow.ts'), printed) + writeFileSync(join(dir, '.sim/lock.json'), JSON.stringify(lock)) + const record = storedEdgesWrite( + { files: { 'workflow.ts': printed }, lock, base: { fingerprint: 'sf1:a' } }, + JSON.parse(readFileSync(FIXTURE_CATALOG, 'utf8')) + ) + if (!record) throw new Error('no stored-edges record') + writeFileSync(join(dir, record[0]), record[1]) + writeFileSync(join(dir, 'workflow.ts'), source('return ')) + + await check() + + expect( + ((result().diagnostics ?? []) as Array<{ code: string; severity: string }>).filter( + (finding) => finding.code.includes('OUT_OF_SCOPE') + ) + ).toEqual([expect.objectContaining({ code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' })]) + expect(process.exitCode).toBe(1) + }) + it('fails on $ref in a Python function file, naming the tag the file writes instead', async () => { cacheCatalog() mkdirSync(join(dir, 'functions'), { recursive: true }) From ec0638c0355bc34def573a7f1d270084f2236b43 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:02:55 -0800 Subject: [PATCH 045/104] test(api): list the workspace source plan route among those Copilot is refused --- apps/sim/lib/api/server/routes/copilot-refused-routes.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/sim/lib/api/server/routes/copilot-refused-routes.json b/apps/sim/lib/api/server/routes/copilot-refused-routes.json index 03df5162c99..0c51fe387c2 100644 --- a/apps/sim/lib/api/server/routes/copilot-refused-routes.json +++ b/apps/sim/lib/api/server/routes/copilot-refused-routes.json @@ -343,5 +343,10 @@ "method": "POST", "path": "/api/v2/workspaces/[workspaceId]/source/blobs/missing", "operation": "workspaces.source.blobs.missing" + }, + { + "method": "POST", + "path": "/api/v2/workspaces/[workspaceId]/source/plan", + "operation": "workspaces.source.plan" } ] From b47114c52d9d3f3e1700e3f685b328681ed237eb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:17:02 -0800 Subject: [PATCH 046/104] style(workflow-code): format the code file path tests --- packages/workflow-code/src/compile/grammar.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 493c73a159c..2350506e88d 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1735,7 +1735,8 @@ describe('iteration references outside their container', () => { ), { 'workflows/functions/inner.js': 'return [$ref.parallel.index, $ref.fan.currentItem]', - 'workflows/functions/after.js': 'return [$ref.loop.index, $ref.fan.index, $ref.fan.results]', + 'workflows/functions/after.js': + 'return [$ref.loop.index, $ref.fan.index, $ref.fan.results]', } ) expect(codes(result).map((d) => [d.blockKey, d.span.file])).toEqual([ @@ -1791,7 +1792,9 @@ describe('reference tags written in a code file', () => { it('checks tags in JavaScript strings as it checks $ref chains', () => { const result = run( source( - [START, "const f = fn('F', { code: codeFile('./functions/f.js') })", 'start.to(f)'].join('\n') + [START, "const f = fn('F', { code: codeFile('./functions/f.js') })", 'start.to(f)'].join( + '\n' + ) ), { 'workflows/functions/f.js': [ From 502c0493f16d6b90fa8db427a92297c1f809bd8e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:17:21 -0800 Subject: [PATCH 047/104] style(db): format the 0467 migration snapshot and journal as biome does --- .../db/migrations/meta/0467_snapshot.json | 3588 ++++------------- packages/db/migrations/meta/_journal.json | 2 +- 2 files changed, 861 insertions(+), 2729 deletions(-) diff --git a/packages/db/migrations/meta/0467_snapshot.json b/packages/db/migrations/meta/0467_snapshot.json index 461b514a3b4..c37b324f6a4 100644 --- a/packages/db/migrations/meta/0467_snapshot.json +++ b/packages/db/migrations/meta/0467_snapshot.json @@ -154,12 +154,8 @@ "name": "account_user_id_user_id_fk", "tableFrom": "account", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -252,10 +248,7 @@ "compositePrimaryKeys": { "activity_rollup_dirty_workspace_id_bucket_start_pk": { "name": "activity_rollup_dirty_workspace_id_bucket_start_pk", - "columns": [ - "workspace_id", - "bucket_start" - ] + "columns": ["workspace_id", "bucket_start"] } }, "uniqueConstraints": {}, @@ -314,10 +307,7 @@ "compositePrimaryKeys": { "activity_rollup_inflight_workspace_id_bucket_start_pk": { "name": "activity_rollup_inflight_workspace_id_bucket_start_pk", - "columns": [ - "workspace_id", - "bucket_start" - ] + "columns": ["workspace_id", "bucket_start"] } }, "uniqueConstraints": {}, @@ -559,12 +549,8 @@ "name": "agent_memory_turn_memory_id_memory_id_fk", "tableFrom": "agent_memory_turn", "tableTo": "memory", - "columnsFrom": [ - "memory_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -572,12 +558,8 @@ "name": "agent_memory_turn_workflow_id_workflow_id_fk", "tableFrom": "agent_memory_turn", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -740,12 +722,8 @@ "name": "api_key_user_id_user_id_fk", "tableFrom": "api_key", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -753,12 +731,8 @@ "name": "api_key_workspace_id_workspace_id_fk", "tableFrom": "api_key", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -766,12 +740,8 @@ "name": "api_key_created_by_user_id_fk", "tableFrom": "api_key", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -781,9 +751,7 @@ "api_key_key_unique": { "name": "api_key_key_unique", "nullsNotDistinct": false, - "columns": [ - "key" - ] + "columns": ["key"] } }, "policies": {}, @@ -890,12 +858,8 @@ "name": "assistant_tool_permission_organization_id_organization_id_fk", "tableFrom": "assistant_tool_permission", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -903,12 +867,8 @@ "name": "assistant_tool_permission_user_id_user_id_fk", "tableFrom": "assistant_tool_permission", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -916,12 +876,8 @@ "name": "assistant_tool_permission_credential_id_credential_id_fk", "tableFrom": "assistant_tool_permission", "tableTo": "credential", - "columnsFrom": [ - "credential_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -929,11 +885,7 @@ "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" - ] + "columns": ["organization_id", "user_id", "credential_id"] } }, "uniqueConstraints": {}, @@ -1405,12 +1357,8 @@ "name": "audit_log_workspace_id_workspace_id_fk", "tableFrom": "audit_log", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -1418,12 +1366,8 @@ "name": "audit_log_actor_id_user_id_fk", "tableFrom": "audit_log", "tableTo": "user", - "columnsFrom": [ - "actor_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["actor_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -1720,12 +1664,8 @@ "name": "aws_marketplace_license_organization_id_organization_id_fk", "tableFrom": "aws_marketplace_license", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -1733,12 +1673,8 @@ "name": "aws_marketplace_license_linked_by_user_id_user_id_fk", "tableFrom": "aws_marketplace_license", "tableTo": "user", - "columnsFrom": [ - "linked_by_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["linked_by_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -1906,12 +1842,8 @@ "name": "aws_marketplace_usage_report_organization_id_organization_id_fk", "tableFrom": "aws_marketplace_usage_report", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -1919,12 +1851,8 @@ "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" - ], + "columnsFrom": ["license_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -1989,12 +1917,8 @@ "name": "aws_marketplace_usage_tally_organization_id_organization_id_fk", "tableFrom": "aws_marketplace_usage_tally", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -2002,11 +1926,7 @@ "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" - ] + "columns": ["organization_id", "dimension", "period_start"] } }, "uniqueConstraints": {}, @@ -2168,12 +2088,8 @@ "name": "background_work_status_workspace_id_workspace_id_fk", "tableFrom": "background_work_status", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -2181,12 +2097,8 @@ "name": "background_work_status_workflow_id_workflow_id_fk", "tableFrom": "background_work_status", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -2272,12 +2184,8 @@ "name": "changelog_change_release_id_changelog_release_id_fk", "tableFrom": "changelog_change", "tableTo": "changelog_release", - "columnsFrom": [ - "release_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["release_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -2285,12 +2193,8 @@ "name": "changelog_change_workflow_id_workflow_id_fk", "tableFrom": "changelog_change", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -2298,12 +2202,8 @@ "name": "changelog_change_deployment_version_id_workflow_deployment_version_id_fk", "tableFrom": "changelog_change", "tableTo": "workflow_deployment_version", - "columnsFrom": [ - "deployment_version_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -2311,12 +2211,8 @@ "name": "changelog_change_chat_id_copilot_chats_id_fk", "tableFrom": "changelog_change", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -2502,12 +2398,8 @@ "name": "changelog_release_workspace_id_workspace_id_fk", "tableFrom": "changelog_release", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -2515,12 +2407,8 @@ "name": "changelog_release_body_file_id_workspace_files_id_fk", "tableFrom": "changelog_release", "tableTo": "workspace_files", - "columnsFrom": [ - "body_file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" }, @@ -2528,12 +2416,8 @@ "name": "changelog_release_created_by_user_id_fk", "tableFrom": "changelog_release", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -2541,12 +2425,8 @@ "name": "changelog_release_updated_by_user_id_fk", "tableFrom": "changelog_release", "tableTo": "user", - "columnsFrom": [ - "updated_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -2753,12 +2633,8 @@ "name": "chat_workflow_id_workflow_id_fk", "tableFrom": "chat", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -2766,12 +2642,8 @@ "name": "chat_user_id_user_id_fk", "tableFrom": "chat", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -3152,12 +3024,8 @@ "name": "copilot_async_tool_calls_run_id_copilot_runs_id_fk", "tableFrom": "copilot_async_tool_calls", "tableTo": "copilot_runs", - "columnsFrom": [ - "run_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["run_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -3165,12 +3033,8 @@ "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" - ], + "columnsFrom": ["checkpoint_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -3528,12 +3392,8 @@ "name": "copilot_chats_user_id_user_id_fk", "tableFrom": "copilot_chats", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -3541,12 +3401,8 @@ "name": "copilot_chats_workflow_id_workflow_id_fk", "tableFrom": "copilot_chats", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -3554,12 +3410,8 @@ "name": "copilot_chats_workspace_id_workspace_id_fk", "tableFrom": "copilot_chats", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -3567,12 +3419,8 @@ "name": "copilot_chats_organization_id_organization_id_fk", "tableFrom": "copilot_chats", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -3748,12 +3596,8 @@ "name": "copilot_feedback_user_id_user_id_fk", "tableFrom": "copilot_feedback", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -3761,12 +3605,8 @@ "name": "copilot_feedback_chat_id_copilot_chats_id_fk", "tableFrom": "copilot_feedback", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -3985,12 +3825,8 @@ "name": "copilot_messages_chat_id_copilot_chats_id_fk", "tableFrom": "copilot_messages", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -4037,12 +3873,8 @@ "name": "copilot_organization_request_stops_user_id_user_id_fk", "tableFrom": "copilot_organization_request_stops", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4050,12 +3882,8 @@ "name": "copilot_organization_request_stops_organization_id_organization_id_fk", "tableFrom": "copilot_organization_request_stops", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -4063,11 +3891,7 @@ "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" - ] + "columns": ["user_id", "organization_id", "stream_id"] } }, "uniqueConstraints": {}, @@ -4111,12 +3935,8 @@ "name": "copilot_request_stops_user_id_user_id_fk", "tableFrom": "copilot_request_stops", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4124,12 +3944,8 @@ "name": "copilot_request_stops_workspace_id_workspace_id_fk", "tableFrom": "copilot_request_stops", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -4137,11 +3953,7 @@ "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" - ] + "columns": ["user_id", "workspace_id", "stream_id"] } }, "uniqueConstraints": {}, @@ -4251,12 +4063,8 @@ "name": "copilot_run_checkpoints_run_id_copilot_runs_id_fk", "tableFrom": "copilot_run_checkpoints", "tableTo": "copilot_runs", - "columnsFrom": [ - "run_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["run_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -4606,12 +4414,8 @@ "name": "copilot_runs_chat_id_copilot_chats_id_fk", "tableFrom": "copilot_runs", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4619,12 +4423,8 @@ "name": "copilot_runs_user_id_user_id_fk", "tableFrom": "copilot_runs", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4632,12 +4432,8 @@ "name": "copilot_runs_workflow_id_workflow_id_fk", "tableFrom": "copilot_runs", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4645,12 +4441,8 @@ "name": "copilot_runs_workspace_id_workspace_id_fk", "tableFrom": "copilot_runs", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4658,12 +4450,8 @@ "name": "copilot_runs_organization_id_organization_id_fk", "tableFrom": "copilot_runs", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -4671,12 +4459,8 @@ "name": "copilot_runs_desktop_device_id_desktop_devices_id_fk", "tableFrom": "copilot_runs", "tableTo": "desktop_devices", - "columnsFrom": [ - "desktop_device_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["desktop_device_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -5393,12 +5177,8 @@ "name": "credential_workspace_id_workspace_id_fk", "tableFrom": "credential", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5406,12 +5186,8 @@ "name": "credential_organization_id_organization_id_fk", "tableFrom": "credential", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5419,12 +5195,8 @@ "name": "credential_slack_app_id_slack_app_id_fk", "tableFrom": "credential", "tableTo": "slack_app", - "columnsFrom": [ - "slack_app_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" }, @@ -5432,12 +5204,8 @@ "name": "credential_account_id_account_id_fk", "tableFrom": "credential", "tableTo": "account", - "columnsFrom": [ - "account_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["account_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5445,12 +5213,8 @@ "name": "credential_env_owner_user_id_user_id_fk", "tableFrom": "credential", "tableTo": "user", - "columnsFrom": [ - "env_owner_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["env_owner_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5458,12 +5222,8 @@ "name": "credential_credential_group_enrollment_id_credential_group_enrollment_id_fk", "tableFrom": "credential", "tableTo": "credential_group_enrollment", - "columnsFrom": [ - "credential_group_enrollment_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_group_enrollment_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5471,12 +5231,8 @@ "name": "credential_mcp_server_id_mcp_servers_id_fk", "tableFrom": "credential", "tableTo": "mcp_servers", - "columnsFrom": [ - "mcp_server_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5484,12 +5240,8 @@ "name": "credential_created_by_user_id_fk", "tableFrom": "credential", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -5674,12 +5426,8 @@ "name": "credential_group_workspace_id_workspace_id_fk", "tableFrom": "credential_group", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5687,12 +5435,8 @@ "name": "credential_group_organization_id_organization_id_fk", "tableFrom": "credential_group", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5700,12 +5444,8 @@ "name": "credential_group_created_by_user_id_fk", "tableFrom": "credential_group", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -5948,12 +5688,8 @@ "name": "credential_group_enrollment_credential_group_id_credential_group_id_fk", "tableFrom": "credential_group_enrollment", "tableTo": "credential_group", - "columnsFrom": [ - "credential_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5961,12 +5697,8 @@ "name": "credential_group_enrollment_user_id_user_id_fk", "tableFrom": "credential_group_enrollment", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -5974,12 +5706,8 @@ "name": "credential_group_enrollment_created_by_user_id_fk", "tableFrom": "credential_group_enrollment", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -6137,12 +5865,8 @@ "name": "credential_member_credential_id_credential_id_fk", "tableFrom": "credential_member", "tableTo": "credential", - "columnsFrom": [ - "credential_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6150,12 +5874,8 @@ "name": "credential_member_user_id_user_id_fk", "tableFrom": "credential_member", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6163,12 +5883,8 @@ "name": "credential_member_invited_by_user_id_fk", "tableFrom": "credential_member", "tableTo": "user", - "columnsFrom": [ - "invited_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -6316,12 +6032,8 @@ "name": "custom_block_organization_id_organization_id_fk", "tableFrom": "custom_block", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6329,12 +6041,8 @@ "name": "custom_block_workflow_id_workflow_id_fk", "tableFrom": "custom_block", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6342,12 +6050,8 @@ "name": "custom_block_created_by_user_id_fk", "tableFrom": "custom_block", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -6441,12 +6145,8 @@ "name": "custom_tools_workspace_id_workspace_id_fk", "tableFrom": "custom_tools", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6454,12 +6154,8 @@ "name": "custom_tools_user_id_user_id_fk", "tableFrom": "custom_tools", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -6548,12 +6244,8 @@ "name": "dashboard_workspace_id_workspace_id_fk", "tableFrom": "dashboard", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6561,12 +6253,8 @@ "name": "dashboard_created_by_user_id_fk", "tableFrom": "dashboard", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -6574,12 +6262,8 @@ "name": "dashboard_updated_by_user_id_fk", "tableFrom": "dashboard", "tableTo": "user", - "columnsFrom": [ - "updated_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -6701,12 +6385,8 @@ "name": "data_drain_runs_drain_id_data_drains_id_fk", "tableFrom": "data_drain_runs", "tableTo": "data_drains", - "columnsFrom": [ - "drain_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["drain_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -6867,12 +6547,8 @@ "name": "data_drains_organization_id_organization_id_fk", "tableFrom": "data_drains", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -6880,12 +6556,8 @@ "name": "data_drains_created_by_user_id_fk", "tableFrom": "data_drains", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" } @@ -7055,12 +6727,8 @@ "name": "desktop_devices_user_id_user_id_fk", "tableFrom": "desktop_devices", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -7068,12 +6736,8 @@ "name": "desktop_devices_session_id_session_id_fk", "tableFrom": "desktop_devices", "tableTo": "session", - "columnsFrom": [ - "session_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["session_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -8269,12 +7933,8 @@ "name": "document_knowledge_base_id_knowledge_base_id_fk", "tableFrom": "document", "tableTo": "knowledge_base", - "columnsFrom": [ - "knowledge_base_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -8282,12 +7942,8 @@ "name": "document_connector_id_knowledge_connector_id_fk", "tableFrom": "document", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -8295,12 +7951,8 @@ "name": "document_uploaded_by_user_id_fk", "tableFrom": "document", "tableTo": "user", - "columnsFrom": [ - "uploaded_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -8359,12 +8011,8 @@ "name": "document_secret_provenance_document_id_document_id_fk", "tableFrom": "document_secret_provenance", "tableTo": "document", - "columnsFrom": [ - "document_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["document_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9026,12 +8674,8 @@ "name": "embedding_knowledge_base_id_knowledge_base_id_fk", "tableFrom": "embedding", "tableTo": "knowledge_base", - "columnsFrom": [ - "knowledge_base_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -9039,12 +8683,8 @@ "name": "embedding_document_id_document_id_fk", "tableFrom": "embedding", "tableTo": "document", - "columnsFrom": [ - "document_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["document_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9331,12 +8971,8 @@ "name": "embedding_search_id_embedding_id_fk", "tableFrom": "embedding_search", "tableTo": "embedding", - "columnsFrom": [ - "id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9395,12 +9031,8 @@ "name": "embedding_secret_provenance_embedding_id_embedding_id_fk", "tableFrom": "embedding_secret_provenance", "tableTo": "embedding", - "columnsFrom": [ - "embedding_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["embedding_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9452,12 +9084,8 @@ "name": "environment_user_id_user_id_fk", "tableFrom": "environment", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9467,9 +9095,7 @@ "environment_user_id_unique": { "name": "environment_user_id_unique", "nullsNotDistinct": false, - "columns": [ - "user_id" - ] + "columns": ["user_id"] } }, "policies": {}, @@ -9555,12 +9181,8 @@ "name": "execution_large_value_dependencies_workspace_id_workspace_id_fk", "tableFrom": "execution_large_value_dependencies", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -9568,10 +9190,7 @@ "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" - ] + "columns": ["parent_key", "child_key"] } }, "uniqueConstraints": {}, @@ -9671,12 +9290,8 @@ "name": "execution_large_value_references_workspace_id_workspace_id_fk", "tableFrom": "execution_large_value_references", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -9684,12 +9299,8 @@ "name": "execution_large_value_references_workflow_id_workflow_id_fk", "tableFrom": "execution_large_value_references", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -9697,11 +9308,7 @@ "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" - ] + "columns": ["key", "execution_id", "source"] } }, "uniqueConstraints": {}, @@ -9865,12 +9472,8 @@ "name": "execution_large_values_workspace_id_workspace_id_fk", "tableFrom": "execution_large_values", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -9878,12 +9481,8 @@ "name": "execution_large_values_workflow_id_workflow_id_fk", "tableFrom": "execution_large_values", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -9990,12 +9589,8 @@ "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" - ], + "columnsFrom": ["build_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -10003,10 +9598,7 @@ "compositePrimaryKeys": { "file_search_dependency_build_id_file_id_pk": { "name": "file_search_dependency_build_id_file_id_pk", - "columns": [ - "build_id", - "file_id" - ] + "columns": ["build_id", "file_id"] } }, "uniqueConstraints": {}, @@ -10090,10 +9682,7 @@ "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" - ] + "columns": ["entity_type", "entity_id"] } }, "uniqueConstraints": {}, @@ -10384,12 +9973,8 @@ "name": "folder_project_id_project_id_fk", "tableFrom": "folder", "tableTo": "project", - "columnsFrom": [ - "project_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["project_id"], + "columnsTo": ["id"], "onDelete": "restrict", "onUpdate": "no action" }, @@ -10397,12 +9982,8 @@ "name": "folder_user_id_user_id_fk", "tableFrom": "folder", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -10410,12 +9991,8 @@ "name": "folder_workspace_id_workspace_id_fk", "tableFrom": "folder", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -10423,12 +10000,8 @@ "name": "folder_parent_id_folder_id_fk", "tableFrom": "folder", "tableTo": "folder", - "columnsFrom": [ - "parent_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["parent_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -10436,16 +10009,8 @@ "name": "folder_workspace_parent_owner_fk", "tableFrom": "folder", "tableTo": "folder", - "columnsFrom": [ - "parent_id", - "workspace_id", - "resource_type" - ], - "columnsTo": [ - "id", - "workspace_id", - "resource_type" - ], + "columnsFrom": ["parent_id", "workspace_id", "resource_type"], + "columnsTo": ["id", "workspace_id", "resource_type"], "onDelete": "no action", "onUpdate": "no action" }, @@ -10453,16 +10018,8 @@ "name": "folder_project_parent_owner_fk", "tableFrom": "folder", "tableTo": "folder", - "columnsFrom": [ - "parent_id", - "project_id", - "resource_type" - ], - "columnsTo": [ - "id", - "project_id", - "resource_type" - ], + "columnsFrom": ["parent_id", "project_id", "resource_type"], + "columnsTo": ["id", "project_id", "resource_type"], "onDelete": "no action", "onUpdate": "no action" } @@ -10472,20 +10029,12 @@ "folder_workspace_owner_type_unique": { "name": "folder_workspace_owner_type_unique", "nullsNotDistinct": false, - "columns": [ - "id", - "workspace_id", - "resource_type" - ] + "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" - ] + "columns": ["id", "project_id", "resource_type"] } }, "policies": {}, @@ -10704,12 +10253,8 @@ "name": "invitation_inviter_id_user_id_fk", "tableFrom": "invitation", "tableTo": "user", - "columnsFrom": [ - "inviter_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["inviter_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -10717,12 +10262,8 @@ "name": "invitation_organization_id_organization_id_fk", "tableFrom": "invitation", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -10732,9 +10273,7 @@ "invitation_token_unique": { "name": "invitation_token_unique", "nullsNotDistinct": false, - "columns": [ - "token" - ] + "columns": ["token"] } }, "policies": {}, @@ -10828,12 +10367,8 @@ "name": "invitation_workspace_grant_invitation_id_invitation_id_fk", "tableFrom": "invitation_workspace_grant", "tableTo": "invitation", - "columnsFrom": [ - "invitation_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["invitation_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -10841,12 +10376,8 @@ "name": "invitation_workspace_grant_workspace_id_workspace_id_fk", "tableFrom": "invitation_workspace_grant", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -11105,12 +10636,8 @@ "name": "job_execution_logs_schedule_id_workflow_schedule_id_fk", "tableFrom": "job_execution_logs", "tableTo": "workflow_schedule", - "columnsFrom": [ - "schedule_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["schedule_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -11118,12 +10645,8 @@ "name": "job_execution_logs_workspace_id_workspace_id_fk", "tableFrom": "job_execution_logs", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -11422,12 +10945,8 @@ "name": "knowledge_base_user_id_user_id_fk", "tableFrom": "knowledge_base", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -11435,12 +10954,8 @@ "name": "knowledge_base_workspace_id_workspace_id_fk", "tableFrom": "knowledge_base", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -11448,12 +10963,8 @@ "name": "knowledge_base_organization_id_organization_id_fk", "tableFrom": "knowledge_base", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -11461,12 +10972,8 @@ "name": "knowledge_base_folder_id_folder_id_fk", "tableFrom": "knowledge_base", "tableTo": "folder", - "columnsFrom": [ - "folder_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -11642,12 +11149,8 @@ "name": "knowledge_base_import_workspace_id_workspace_id_fk", "tableFrom": "knowledge_base_import", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -11655,12 +11158,8 @@ "name": "knowledge_base_import_knowledge_base_id_knowledge_base_id_fk", "tableFrom": "knowledge_base_import", "tableTo": "knowledge_base", - "columnsFrom": [ - "knowledge_base_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -11770,12 +11269,8 @@ "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" - ], + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -12157,12 +11652,8 @@ "name": "knowledge_connector_knowledge_base_id_knowledge_base_id_fk", "tableFrom": "knowledge_connector", "tableTo": "knowledge_base", - "columnsFrom": [ - "knowledge_base_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["knowledge_base_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -12170,12 +11661,8 @@ "name": "knowledge_connector_credential_group_id_credential_group_id_fk", "tableFrom": "knowledge_connector", "tableTo": "credential_group", - "columnsFrom": [ - "credential_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -12425,12 +11912,8 @@ "name": "knowledge_connector_member_workspace_id_workspace_id_fk", "tableFrom": "knowledge_connector_member", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -12438,12 +11921,8 @@ "name": "knowledge_connector_member_organization_id_organization_id_fk", "tableFrom": "knowledge_connector_member", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -12451,12 +11930,8 @@ "name": "knowledge_connector_member_connector_id_knowledge_connector_id_fk", "tableFrom": "knowledge_connector_member", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -12464,12 +11939,8 @@ "name": "knowledge_connector_member_credential_id_credential_id_fk", "tableFrom": "knowledge_connector_member", "tableTo": "credential", - "columnsFrom": [ - "credential_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -12709,12 +12180,8 @@ "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" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -12918,12 +12385,8 @@ "name": "knowledge_connector_partition_connector_id_knowledge_connector_id_fk", "tableFrom": "knowledge_connector_partition", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -12931,10 +12394,7 @@ "compositePrimaryKeys": { "kcp_pk": { "name": "kcp_pk", - "columns": [ - "connector_id", - "partition_key" - ] + "columns": ["connector_id", "partition_key"] } }, "uniqueConstraints": {}, @@ -13020,12 +12480,8 @@ "name": "kcpg_snapshot_fk", "tableFrom": "knowledge_connector_permission_grant", "tableTo": "knowledge_connector_permission_snapshot", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "connector_id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["connector_id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13033,11 +12489,7 @@ "compositePrimaryKeys": { "kcpg_pk": { "name": "kcpg_pk", - "columns": [ - "connector_id", - "group_key", - "subject_token" - ] + "columns": ["connector_id", "group_key", "subject_token"] } }, "uniqueConstraints": {}, @@ -13178,12 +12630,8 @@ "name": "knowledge_connector_permission_import_connector_id_knowledge_connector_id_fk", "tableFrom": "knowledge_connector_permission_import", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13262,12 +12710,8 @@ "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" - ], + "columnsFrom": ["import_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13275,11 +12719,7 @@ "compositePrimaryKeys": { "kcpig_pk": { "name": "kcpig_pk", - "columns": [ - "import_id", - "project_path", - "user_id" - ] + "columns": ["import_id", "project_path", "user_id"] } }, "uniqueConstraints": {}, @@ -13338,12 +12778,8 @@ "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" - ], + "columnsFrom": ["import_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13351,10 +12787,7 @@ "compositePrimaryKeys": { "kcpii_pk": { "name": "kcpii_pk", - "columns": [ - "import_id", - "user_id" - ] + "columns": ["import_id", "user_id"] } }, "uniqueConstraints": {}, @@ -13397,12 +12830,8 @@ "name": "kcps_connector_fk", "tableFrom": "knowledge_connector_permission_snapshot", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13574,12 +13003,8 @@ "name": "knowledge_connector_sync_log_connector_id_knowledge_connector_id_fk", "tableFrom": "knowledge_connector_sync_log", "tableTo": "knowledge_connector", - "columnsFrom": [ - "connector_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connector_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13647,12 +13072,8 @@ "name": "knowledge_document_observation_document_id_document_id_fk", "tableFrom": "knowledge_document_observation", "tableTo": "document", - "columnsFrom": [ - "document_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["document_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -13660,12 +13081,8 @@ "name": "knowledge_document_observation_member_id_knowledge_connector_member_id_fk", "tableFrom": "knowledge_document_observation", "tableTo": "knowledge_connector_member", - "columnsFrom": [ - "member_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["member_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -13673,10 +13090,7 @@ "compositePrimaryKeys": { "knowledge_document_observation_document_id_member_id_pk": { "name": "knowledge_document_observation_document_id_member_id_pk", - "columns": [ - "document_id", - "member_id" - ] + "columns": ["document_id", "member_id"] } }, "uniqueConstraints": {}, @@ -13798,12 +13212,8 @@ "name": "knowledge_external_directory_workspace_id_workspace_id_fk", "tableFrom": "knowledge_external_directory", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -13811,12 +13221,8 @@ "name": "knowledge_external_directory_organization_id_organization_id_fk", "tableFrom": "knowledge_external_directory", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14008,12 +13414,8 @@ "name": "knowledge_external_group_organization_id_organization_id_fk", "tableFrom": "knowledge_external_group", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14021,12 +13423,8 @@ "name": "keg_workspace_fk", "tableFrom": "knowledge_external_group", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14088,12 +13486,8 @@ "name": "kegm_group_fk", "tableFrom": "knowledge_external_group_member", "tableTo": "knowledge_external_group", - "columnsFrom": [ - "group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14101,10 +13495,7 @@ "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" - ] + "columns": ["group_id", "subject_token"] } }, "uniqueConstraints": {}, @@ -14166,12 +13557,8 @@ "name": "knowledge_projection_dirty_document_id_document_id_fk", "tableFrom": "knowledge_projection_dirty", "tableTo": "document", - "columnsFrom": [ - "document_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["document_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14304,12 +13691,8 @@ "name": "mcp_server_oauth_mcp_server_id_mcp_servers_id_fk", "tableFrom": "mcp_server_oauth", "tableTo": "mcp_servers", - "columnsFrom": [ - "mcp_server_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["mcp_server_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14317,12 +13700,8 @@ "name": "mcp_server_oauth_user_id_user_id_fk", "tableFrom": "mcp_server_oauth", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -14330,12 +13709,8 @@ "name": "mcp_server_oauth_workspace_id_workspace_id_fk", "tableFrom": "mcp_server_oauth", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14343,12 +13718,8 @@ "name": "mcp_server_oauth_organization_id_organization_id_fk", "tableFrom": "mcp_server_oauth", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14657,12 +14028,8 @@ "name": "mcp_servers_workspace_id_workspace_id_fk", "tableFrom": "mcp_servers", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14670,12 +14037,8 @@ "name": "mcp_servers_organization_id_organization_id_fk", "tableFrom": "mcp_servers", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14683,12 +14046,8 @@ "name": "mcp_servers_credential_group_id_credential_group_id_fk", "tableFrom": "mcp_servers", "tableTo": "credential_group", - "columnsFrom": [ - "credential_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_group_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -14696,12 +14055,8 @@ "name": "mcp_servers_created_by_user_id_fk", "tableFrom": "mcp_servers", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -14802,12 +14157,8 @@ "name": "member_user_id_user_id_fk", "tableFrom": "member", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14815,12 +14166,8 @@ "name": "member_organization_id_organization_id_fk", "tableFrom": "member", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -14922,12 +14269,8 @@ "name": "member_profile_member_id_member_id_fk", "tableFrom": "member_profile", "tableTo": "member", - "columnsFrom": [ - "member_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["member_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -14935,12 +14278,8 @@ "name": "member_profile_manager_member_id_member_id_fk", "tableFrom": "member_profile", "tableTo": "member", - "columnsFrom": [ - "manager_member_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["manager_member_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -14948,12 +14287,8 @@ "name": "member_profile_updated_by_user_id_fk", "tableFrom": "member_profile", "tableTo": "user", - "columnsFrom": [ - "updated_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -15102,12 +14437,8 @@ "name": "memory_workspace_id_workspace_id_fk", "tableFrom": "memory", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15157,12 +14488,8 @@ "name": "memory_artifact_memory_id_memory_id_fk", "tableFrom": "memory_artifact", "tableTo": "memory", - "columnsFrom": [ - "memory_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -15170,12 +14497,8 @@ "name": "memory_artifact_key_execution_large_values_key_fk", "tableFrom": "memory_artifact", "tableTo": "execution_large_values", - "columnsFrom": [ - "key" - ], - "columnsTo": [ - "key" - ], + "columnsFrom": ["key"], + "columnsTo": ["key"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15183,10 +14506,7 @@ "compositePrimaryKeys": { "memory_artifact_memory_id_key_pk": { "name": "memory_artifact_memory_id_key_pk", - "columns": [ - "memory_id", - "key" - ] + "columns": ["memory_id", "key"] } }, "uniqueConstraints": {}, @@ -15327,12 +14647,8 @@ "name": "memory_item_memory_id_memory_id_fk", "tableFrom": "memory_item", "tableTo": "memory", - "columnsFrom": [ - "memory_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15395,12 +14711,8 @@ "name": "memory_secret_provenance_memory_id_memory_id_fk", "tableFrom": "memory_secret_provenance", "tableTo": "memory", - "columnsFrom": [ - "memory_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["memory_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15531,12 +14843,8 @@ "name": "mothership_benchmark_runs_benchmark_id_mothership_benchmarks_id_fk", "tableFrom": "mothership_benchmark_runs", "tableTo": "mothership_benchmarks", - "columnsFrom": [ - "benchmark_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["benchmark_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15713,12 +15021,8 @@ "name": "mothership_benchmarks_organization_id_organization_id_fk", "tableFrom": "mothership_benchmarks", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -15726,12 +15030,8 @@ "name": "mothership_benchmarks_user_id_user_id_fk", "tableFrom": "mothership_benchmarks", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -15739,12 +15039,8 @@ "name": "mothership_benchmarks_run_as_user_id_user_id_fk", "tableFrom": "mothership_benchmarks", "tableTo": "user", - "columnsFrom": [ - "run_as_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["run_as_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -15752,12 +15048,8 @@ "name": "mothership_benchmarks_source_workspace_id_workspace_id_fk", "tableFrom": "mothership_benchmarks", "tableTo": "workspace", - "columnsFrom": [ - "source_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -15847,12 +15139,8 @@ "name": "mothership_inbox_allowed_sender_workspace_id_workspace_id_fk", "tableFrom": "mothership_inbox_allowed_sender", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -15860,12 +15148,8 @@ "name": "mothership_inbox_allowed_sender_added_by_user_id_fk", "tableFrom": "mothership_inbox_allowed_sender", "tableTo": "user", - "columnsFrom": [ - "added_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["added_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16108,12 +15392,8 @@ "name": "mothership_inbox_task_workspace_id_workspace_id_fk", "tableFrom": "mothership_inbox_task", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16121,12 +15401,8 @@ "name": "mothership_inbox_task_chat_id_copilot_chats_id_fk", "tableFrom": "mothership_inbox_task", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -16179,12 +15455,8 @@ "name": "mothership_inbox_webhook_workspace_id_workspace_id_fk", "tableFrom": "mothership_inbox_webhook", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16194,9 +15466,7 @@ "mothership_inbox_webhook_workspace_id_unique": { "name": "mothership_inbox_webhook_workspace_id_unique", "nullsNotDistinct": false, - "columns": [ - "workspace_id" - ] + "columns": ["workspace_id"] } }, "policies": {}, @@ -16232,12 +15502,8 @@ "name": "mothership_memory_selections_user_id_user_id_fk", "tableFrom": "mothership_memory_selections", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16245,12 +15511,8 @@ "name": "mothership_memory_selections_organization_id_organization_id_fk", "tableFrom": "mothership_memory_selections", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16258,12 +15520,8 @@ "name": "mothership_memory_selections_space_id_mothership_memory_spaces_id_fk", "tableFrom": "mothership_memory_selections", "tableTo": "mothership_memory_spaces", - "columnsFrom": [ - "space_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["space_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" } @@ -16271,10 +15529,7 @@ "compositePrimaryKeys": { "mothership_memory_selections_user_id_organization_id_pk": { "name": "mothership_memory_selections_user_id_organization_id_pk", - "columns": [ - "user_id", - "organization_id" - ] + "columns": ["user_id", "organization_id"] } }, "uniqueConstraints": {}, @@ -16346,12 +15601,8 @@ "name": "mothership_memory_spaces_user_id_user_id_fk", "tableFrom": "mothership_memory_spaces", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16359,12 +15610,8 @@ "name": "mothership_memory_spaces_organization_id_organization_id_fk", "tableFrom": "mothership_memory_spaces", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16405,12 +15652,8 @@ "name": "mothership_resource_effects_chat_id_copilot_chats_id_fk", "tableFrom": "mothership_resource_effects", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16418,10 +15661,7 @@ "compositePrimaryKeys": { "mothership_resource_effects_chat_id_effect_id_pk": { "name": "mothership_resource_effects_chat_id_effect_id_pk", - "columns": [ - "chat_id", - "effect_id" - ] + "columns": ["chat_id", "effect_id"] } }, "uniqueConstraints": {}, @@ -16588,12 +15828,8 @@ "name": "oauth_access_token_client_id_oauth_client_client_id_fk", "tableFrom": "oauth_access_token", "tableTo": "oauth_client", - "columnsFrom": [ - "client_id" - ], - "columnsTo": [ - "client_id" - ], + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16601,12 +15837,8 @@ "name": "oauth_access_token_session_id_session_id_fk", "tableFrom": "oauth_access_token", "tableTo": "session", - "columnsFrom": [ - "session_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["session_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -16614,12 +15846,8 @@ "name": "oauth_access_token_user_id_user_id_fk", "tableFrom": "oauth_access_token", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16627,12 +15855,8 @@ "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk", "tableFrom": "oauth_access_token", "tableTo": "oauth_refresh_token", - "columnsFrom": [ - "refresh_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["refresh_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16642,9 +15866,7 @@ "oauth_access_token_token_unique": { "name": "oauth_access_token_token_unique", "nullsNotDistinct": false, - "columns": [ - "token" - ] + "columns": ["token"] } }, "policies": {}, @@ -16864,12 +16086,8 @@ "name": "oauth_client_user_id_user_id_fk", "tableFrom": "oauth_client", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16879,9 +16097,7 @@ "oauth_client_client_id_unique": { "name": "oauth_client_client_id_unique", "nullsNotDistinct": false, - "columns": [ - "client_id" - ] + "columns": ["client_id"] } }, "policies": {}, @@ -16957,12 +16173,8 @@ "name": "oauth_consent_client_id_oauth_client_client_id_fk", "tableFrom": "oauth_consent", "tableTo": "oauth_client", - "columnsFrom": [ - "client_id" - ], - "columnsTo": [ - "client_id" - ], + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -16970,12 +16182,8 @@ "name": "oauth_consent_user_id_user_id_fk", "tableFrom": "oauth_consent", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -16985,11 +16193,7 @@ "oauth_consent_user_client_reference_unique": { "name": "oauth_consent_user_client_reference_unique", "nullsNotDistinct": true, - "columns": [ - "user_id", - "client_id", - "reference_id" - ] + "columns": ["user_id", "client_id", "reference_id"] } }, "policies": {}, @@ -17158,12 +16362,8 @@ "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk", "tableFrom": "oauth_refresh_token", "tableTo": "oauth_client", - "columnsFrom": [ - "client_id" - ], - "columnsTo": [ - "client_id" - ], + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17171,12 +16371,8 @@ "name": "oauth_refresh_token_session_id_session_id_fk", "tableFrom": "oauth_refresh_token", "tableTo": "session", - "columnsFrom": [ - "session_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["session_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -17184,12 +16380,8 @@ "name": "oauth_refresh_token_user_id_user_id_fk", "tableFrom": "oauth_refresh_token", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17197,12 +16389,8 @@ "name": "oauth_refresh_token_family_id_oauth_token_family_id_fk", "tableFrom": "oauth_refresh_token", "tableTo": "oauth_token_family", - "columnsFrom": [ - "family_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["family_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -17212,17 +16400,12 @@ "oauth_refresh_token_token_unique": { "name": "oauth_refresh_token_token_unique", "nullsNotDistinct": false, - "columns": [ - "token" - ] + "columns": ["token"] }, "oauth_refresh_token_family_generation_unique": { "name": "oauth_refresh_token_family_generation_unique", "nullsNotDistinct": false, - "columns": [ - "family_id", - "generation" - ] + "columns": ["family_id", "generation"] } }, "policies": {}, @@ -17386,12 +16569,8 @@ "name": "oauth_token_family_client_id_oauth_client_client_id_fk", "tableFrom": "oauth_token_family", "tableTo": "oauth_client", - "columnsFrom": [ - "client_id" - ], - "columnsTo": [ - "client_id" - ], + "columnsFrom": ["client_id"], + "columnsTo": ["client_id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17399,12 +16578,8 @@ "name": "oauth_token_family_session_id_session_id_fk", "tableFrom": "oauth_token_family", "tableTo": "session", - "columnsFrom": [ - "session_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["session_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -17412,12 +16587,8 @@ "name": "oauth_token_family_user_id_user_id_fk", "tableFrom": "oauth_token_family", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17425,12 +16596,8 @@ "name": "oauth_token_family_consent_id_oauth_consent_id_fk", "tableFrom": "oauth_token_family", "tableTo": "oauth_consent", - "columnsFrom": [ - "consent_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["consent_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -17599,12 +16766,8 @@ "name": "organization_access_request_settings_organization_id_organization_id_fk", "tableFrom": "organization_access_request_settings", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17612,12 +16775,8 @@ "name": "organization_access_request_settings_updated_by_user_id_fk", "tableFrom": "organization_access_request_settings", "tableTo": "user", - "columnsFrom": [ - "updated_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -17711,12 +16870,8 @@ "name": "organization_byok_keys_organization_id_organization_id_fk", "tableFrom": "organization_byok_keys", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17724,12 +16879,8 @@ "name": "organization_byok_keys_created_by_user_id_fk", "tableFrom": "organization_byok_keys", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -17832,12 +16983,8 @@ "name": "organization_member_usage_limit_organization_id_organization_id_fk", "tableFrom": "organization_member_usage_limit", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17845,12 +16992,8 @@ "name": "organization_member_usage_limit_user_id_user_id_fk", "tableFrom": "organization_member_usage_limit", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17858,12 +17001,8 @@ "name": "organization_member_usage_limit_set_by_user_id_fk", "tableFrom": "organization_member_usage_limit", "tableTo": "user", - "columnsFrom": [ - "set_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["set_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -17927,12 +17066,8 @@ "name": "organization_search_history_organization_id_organization_id_fk", "tableFrom": "organization_search_history", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -17940,12 +17075,8 @@ "name": "organization_search_history_user_id_user_id_fk", "tableFrom": "organization_search_history", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -17953,10 +17084,7 @@ "compositePrimaryKeys": { "organization_search_history_organization_id_user_id_pk": { "name": "organization_search_history_organization_id_user_id_pk", - "columns": [ - "organization_id", - "user_id" - ] + "columns": ["organization_id", "user_id"] } }, "uniqueConstraints": {}, @@ -18000,12 +17128,8 @@ "name": "organization_search_integration_organization_id_organization_id_fk", "tableFrom": "organization_search_integration", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -18013,10 +17137,7 @@ "compositePrimaryKeys": { "organization_search_integration_organization_id_connector_type_pk": { "name": "organization_search_integration_organization_id_connector_type_pk", - "columns": [ - "organization_id", - "connector_type" - ] + "columns": ["organization_id", "connector_type"] } }, "uniqueConstraints": {}, @@ -18133,12 +17254,8 @@ "name": "org_search_mcp_invocation_org_fk", "tableFrom": "organization_search_mcp_invocation", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -18146,12 +17263,8 @@ "name": "org_search_mcp_invocation_user_fk", "tableFrom": "organization_search_mcp_invocation", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -18297,12 +17410,8 @@ "name": "organization_secret_source_id_organization_secret_source_id_fk", "tableFrom": "organization_secret", "tableTo": "organization_secret_source", - "columnsFrom": [ - "source_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -18310,12 +17419,8 @@ "name": "organization_secret_owner_user_id_user_id_fk", "tableFrom": "organization_secret", "tableTo": "user", - "columnsFrom": [ - "owner_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["owner_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -18385,12 +17490,8 @@ "name": "organization_secret_source_organization_id_organization_id_fk", "tableFrom": "organization_secret_source", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -18745,12 +17846,8 @@ "name": "paused_executions_workflow_id_workflow_id_fk", "tableFrom": "paused_executions", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -18909,12 +18006,8 @@ "name": "pending_credential_draft_user_id_user_id_fk", "tableFrom": "pending_credential_draft", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -18922,12 +18015,8 @@ "name": "pending_credential_draft_workspace_id_workspace_id_fk", "tableFrom": "pending_credential_draft", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -18935,12 +18024,8 @@ "name": "pending_credential_draft_organization_id_organization_id_fk", "tableFrom": "pending_credential_draft", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -18948,12 +18033,8 @@ "name": "pending_credential_draft_credential_id_credential_id_fk", "tableFrom": "pending_credential_draft", "tableTo": "credential", - "columnsFrom": [ - "credential_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -19111,12 +18192,8 @@ "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" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -19156,12 +18233,8 @@ "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" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -19169,11 +18242,7 @@ "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" - ] + "columns": ["organization_id", "run_id", "page_hash"] } }, "uniqueConstraints": {}, @@ -19227,12 +18296,8 @@ "name": "people_directory_scim_change_organization_id_organization_id_fk", "tableFrom": "people_directory_scim_change", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -19383,12 +18448,8 @@ "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" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["organization_id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -19396,11 +18457,7 @@ "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" - ] + "columns": ["organization_id", "run_id", "external_id"] } }, "uniqueConstraints": {}, @@ -19552,12 +18609,8 @@ "name": "people_directory_sync_organization_id_organization_id_fk", "tableFrom": "people_directory_sync", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -19565,12 +18618,8 @@ "name": "people_directory_sync_configured_by_user_id_fk", "tableFrom": "people_directory_sync", "tableTo": "user", - "columnsFrom": [ - "configured_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["configured_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -19817,12 +18866,8 @@ "name": "permission_access_request_organization_id_organization_id_fk", "tableFrom": "permission_access_request", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -19830,12 +18875,8 @@ "name": "permission_access_request_requester_id_user_id_fk", "tableFrom": "permission_access_request", "tableTo": "user", - "columnsFrom": [ - "requester_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["requester_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -19843,12 +18884,8 @@ "name": "permission_access_request_decided_by_user_id_fk", "tableFrom": "permission_access_request", "tableTo": "user", - "columnsFrom": [ - "decided_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["decided_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -19993,12 +19030,8 @@ "name": "permission_group_organization_id_organization_id_fk", "tableFrom": "permission_group", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20006,12 +19039,8 @@ "name": "permission_group_created_by_user_id_fk", "tableFrom": "permission_group", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -20113,12 +19142,8 @@ "name": "permission_group_member_permission_group_id_permission_group_id_fk", "tableFrom": "permission_group_member", "tableTo": "permission_group", - "columnsFrom": [ - "permission_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20126,12 +19151,8 @@ "name": "permission_group_member_organization_id_organization_id_fk", "tableFrom": "permission_group_member", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20139,12 +19160,8 @@ "name": "permission_group_member_user_id_user_id_fk", "tableFrom": "permission_group_member", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20152,12 +19169,8 @@ "name": "permission_group_member_assigned_by_user_id_fk", "tableFrom": "permission_group_member", "tableTo": "user", - "columnsFrom": [ - "assigned_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["assigned_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -20247,12 +19260,8 @@ "name": "permission_group_workspace_permission_group_id_permission_group_id_fk", "tableFrom": "permission_group_workspace", "tableTo": "permission_group", - "columnsFrom": [ - "permission_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20260,12 +19269,8 @@ "name": "permission_group_workspace_workspace_id_workspace_id_fk", "tableFrom": "permission_group_workspace", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20273,12 +19278,8 @@ "name": "permission_group_workspace_organization_id_organization_id_fk", "tableFrom": "permission_group_workspace", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -20421,12 +19422,8 @@ "name": "permissions_user_id_user_id_fk", "tableFrom": "permissions", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -20555,12 +19552,8 @@ "name": "pinned_item_user_id_user_id_fk", "tableFrom": "pinned_item", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20568,12 +19561,8 @@ "name": "pinned_item_workspace_id_workspace_id_fk", "tableFrom": "pinned_item", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -20704,12 +19693,8 @@ "name": "project_organization_id_organization_id_fk", "tableFrom": "project", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "restrict", "onUpdate": "no action" }, @@ -20717,12 +19702,8 @@ "name": "project_owner_id_user_id_fk", "tableFrom": "project", "tableTo": "user", - "columnsFrom": [ - "owner_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], "onDelete": "restrict", "onUpdate": "no action" } @@ -20732,10 +19713,7 @@ "project_id_organization_scope_unique": { "name": "project_id_organization_scope_unique", "nullsNotDistinct": false, - "columns": [ - "id", - "organization_scope_key" - ] + "columns": ["id", "organization_scope_key"] } }, "policies": {}, @@ -20941,12 +19919,8 @@ "name": "public_share_workspace_id_workspace_id_fk", "tableFrom": "public_share", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -20954,12 +19928,8 @@ "name": "public_share_created_by_user_id_fk", "tableFrom": "public_share", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -21157,12 +20127,8 @@ "name": "resource_policy_workspace_id_workspace_id_fk", "tableFrom": "resource_policy", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -21170,12 +20136,8 @@ "name": "resource_policy_organization_id_organization_id_fk", "tableFrom": "resource_policy", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -21183,12 +20145,8 @@ "name": "resource_policy_created_by_user_id_fk", "tableFrom": "resource_policy", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -21196,12 +20154,8 @@ "name": "resource_policy_updated_by_user_id_fk", "tableFrom": "resource_policy", "tableTo": "user", - "columnsFrom": [ - "updated_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["updated_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -21339,12 +20293,8 @@ "name": "resume_queue_paused_execution_id_paused_executions_id_fk", "tableFrom": "resume_queue", "tableTo": "paused_executions", - "columnsFrom": [ - "paused_execution_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["paused_execution_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -21626,12 +20576,8 @@ "name": "scim_connection_organization_id_organization_id_fk", "tableFrom": "scim_connection", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -21639,12 +20585,8 @@ "name": "scim_connection_created_by_user_id_fk", "tableFrom": "scim_connection", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -21764,12 +20706,8 @@ "name": "scim_credential_connection_id_scim_connection_id_fk", "tableFrom": "scim_credential", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -21777,12 +20715,8 @@ "name": "scim_credential_revoked_by_user_id_fk", "tableFrom": "scim_credential", "tableTo": "user", - "columnsFrom": [ - "revoked_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["revoked_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -21790,12 +20724,8 @@ "name": "scim_credential_created_by_user_id_fk", "tableFrom": "scim_credential", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -21932,12 +20862,8 @@ "name": "scim_group_connection_id_scim_connection_id_fk", "tableFrom": "scim_group", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -22080,12 +21006,8 @@ "name": "scim_group_mapping_group_id_scim_group_id_fk", "tableFrom": "scim_group_mapping", "tableTo": "scim_group", - "columnsFrom": [ - "group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22093,12 +21015,8 @@ "name": "scim_group_mapping_permission_group_id_permission_group_id_fk", "tableFrom": "scim_group_mapping", "tableTo": "permission_group", - "columnsFrom": [ - "permission_group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["permission_group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22106,12 +21024,8 @@ "name": "scim_group_mapping_workspace_id_workspace_id_fk", "tableFrom": "scim_group_mapping", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22119,12 +21033,8 @@ "name": "scim_group_mapping_created_by_user_id_fk", "tableFrom": "scim_group_mapping", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -22213,12 +21123,8 @@ "name": "scim_group_member_group_id_scim_group_id_fk", "tableFrom": "scim_group_member", "tableTo": "scim_group", - "columnsFrom": [ - "group_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["group_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22226,12 +21132,8 @@ "name": "scim_group_member_scim_user_id_scim_user_id_fk", "tableFrom": "scim_group_member", "tableTo": "scim_user", - "columnsFrom": [ - "scim_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -22361,12 +21263,8 @@ "name": "scim_projection_grant_connection_id_scim_connection_id_fk", "tableFrom": "scim_projection_grant", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22374,12 +21272,8 @@ "name": "scim_projection_grant_scim_user_id_scim_user_id_fk", "tableFrom": "scim_projection_grant", "tableTo": "scim_user", - "columnsFrom": [ - "scim_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["scim_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -22490,12 +21384,8 @@ "name": "scim_request_log_connection_id_scim_connection_id_fk", "tableFrom": "scim_request_log", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -22681,12 +21571,8 @@ "name": "scim_user_connection_id_scim_connection_id_fk", "tableFrom": "scim_user", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22694,12 +21580,8 @@ "name": "scim_user_user_id_user_id_fk", "tableFrom": "scim_user", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -22789,12 +21671,8 @@ "name": "scim_user_tombstone_connection_id_scim_connection_id_fk", "tableFrom": "scim_user_tombstone", "tableTo": "scim_connection", - "columnsFrom": [ - "connection_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["connection_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -22802,12 +21680,8 @@ "name": "scim_user_tombstone_user_id_user_id_fk", "tableFrom": "scim_user_tombstone", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -23024,12 +21898,8 @@ "name": "secret_usage_workspace_id_workspace_id_fk", "tableFrom": "secret_usage", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -23127,12 +21997,8 @@ "name": "session_user_id_user_id_fk", "tableFrom": "session", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -23140,12 +22006,8 @@ "name": "session_active_organization_id_organization_id_fk", "tableFrom": "session", "tableTo": "organization", - "columnsFrom": [ - "active_organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["active_organization_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -23155,9 +22017,7 @@ "session_token_unique": { "name": "session_token_unique", "nullsNotDistinct": false, - "columns": [ - "token" - ] + "columns": ["token"] } }, "policies": {}, @@ -23290,12 +22150,8 @@ "name": "settings_user_id_user_id_fk", "tableFrom": "settings", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -23305,9 +22161,7 @@ "settings_user_id_unique": { "name": "settings_user_id_unique", "nullsNotDistinct": false, - "columns": [ - "user_id" - ] + "columns": ["user_id"] } }, "policies": {}, @@ -23451,12 +22305,8 @@ "name": "sim_link_organization_id_organization_id_fk", "tableFrom": "sim_link", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -23464,12 +22314,8 @@ "name": "sim_link_created_by_user_id_fk", "tableFrom": "sim_link", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -23523,12 +22369,8 @@ "name": "sim_trigger_state_workflow_id_workflow_id_fk", "tableFrom": "sim_trigger_state", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -23536,11 +22378,7 @@ "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" - ] + "columns": ["workflow_id", "block_id", "scope_key"] } }, "uniqueConstraints": {}, @@ -23631,12 +22469,8 @@ "name": "skill_workspace_id_workspace_id_fk", "tableFrom": "skill", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -23644,12 +22478,8 @@ "name": "skill_user_id_user_id_fk", "tableFrom": "skill", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -23746,12 +22576,8 @@ "name": "skill_member_skill_id_skill_id_fk", "tableFrom": "skill_member", "tableTo": "skill", - "columnsFrom": [ - "skill_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["skill_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -23759,12 +22585,8 @@ "name": "skill_member_user_id_user_id_fk", "tableFrom": "skill_member", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -23772,12 +22594,8 @@ "name": "skill_member_invited_by_user_id_fk", "tableFrom": "skill_member", "tableTo": "user", - "columnsFrom": [ - "invited_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["invited_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -23855,12 +22673,8 @@ "name": "slack_app_organization_id_organization_id_fk", "tableFrom": "slack_app", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -24058,12 +22872,8 @@ "name": "slack_search_installation_organization_id_organization_id_fk", "tableFrom": "slack_search_installation", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -24071,12 +22881,8 @@ "name": "slack_search_installation_credential_id_credential_id_fk", "tableFrom": "slack_search_installation", "tableTo": "credential", - "columnsFrom": [ - "credential_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["credential_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -24084,12 +22890,8 @@ "name": "slack_search_installation_slack_app_id_slack_app_id_fk", "tableFrom": "slack_search_installation", "tableTo": "slack_app", - "columnsFrom": [ - "slack_app_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["slack_app_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" } @@ -24283,12 +23085,8 @@ "name": "slack_search_turn_installation_id_slack_search_installation_id_fk", "tableFrom": "slack_search_turn", "tableTo": "slack_search_installation", - "columnsFrom": [ - "installation_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["installation_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -24426,12 +23224,8 @@ "name": "sso_domain_organization_id_organization_id_fk", "tableFrom": "sso_domain", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -24439,12 +23233,8 @@ "name": "sso_domain_created_by_user_id_fk", "tableFrom": "sso_domain", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -24589,12 +23379,8 @@ "name": "sso_provider_user_id_user_id_fk", "tableFrom": "sso_provider", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -24602,12 +23388,8 @@ "name": "sso_provider_organization_id_organization_id_fk", "tableFrom": "sso_provider", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -24928,12 +23710,8 @@ "name": "table_jobs_table_id_user_table_definitions_id_fk", "tableFrom": "table_jobs", "tableTo": "user_table_definitions", - "columnsFrom": [ - "table_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -24941,12 +23719,8 @@ "name": "table_jobs_workspace_id_workspace_id_fk", "tableFrom": "table_jobs", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -25115,12 +23889,8 @@ "name": "table_row_executions_table_id_user_table_definitions_id_fk", "tableFrom": "table_row_executions", "tableTo": "user_table_definitions", - "columnsFrom": [ - "table_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25128,12 +23898,8 @@ "name": "table_row_executions_row_id_user_table_rows_id_fk", "tableFrom": "table_row_executions", "tableTo": "user_table_rows", - "columnsFrom": [ - "row_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["row_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25141,12 +23907,8 @@ "name": "table_row_executions_capability_governed_user_id_user_id_fk", "tableFrom": "table_row_executions", "tableTo": "user", - "columnsFrom": [ - "capability_governed_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -25154,10 +23916,7 @@ "compositePrimaryKeys": { "table_row_executions_row_id_group_id_pk": { "name": "table_row_executions_row_id_group_id_pk", - "columns": [ - "row_id", - "group_id" - ] + "columns": ["row_id", "group_id"] } }, "uniqueConstraints": {}, @@ -25348,12 +24107,8 @@ "name": "table_run_dispatches_table_id_user_table_definitions_id_fk", "tableFrom": "table_run_dispatches", "tableTo": "user_table_definitions", - "columnsFrom": [ - "table_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25361,12 +24116,8 @@ "name": "table_run_dispatches_workspace_id_workspace_id_fk", "tableFrom": "table_run_dispatches", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25374,12 +24125,8 @@ "name": "table_run_dispatches_triggered_by_user_id_user_id_fk", "tableFrom": "table_run_dispatches", "tableTo": "user", - "columnsFrom": [ - "triggered_by_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -25387,12 +24134,8 @@ "name": "table_run_dispatches_capability_governed_user_id_user_id_fk", "tableFrom": "table_run_dispatches", "tableTo": "user", - "columnsFrom": [ - "capability_governed_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["capability_governed_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -25537,12 +24280,8 @@ "name": "table_views_table_id_user_table_definitions_id_fk", "tableFrom": "table_views", "tableTo": "user_table_definitions", - "columnsFrom": [ - "table_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25550,12 +24289,8 @@ "name": "table_views_workspace_id_workspace_id_fk", "tableFrom": "table_views", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -25563,12 +24298,8 @@ "name": "table_views_created_by_user_id_fk", "tableFrom": "table_views", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -26181,12 +24912,8 @@ "name": "usage_log_user_id_user_id_fk", "tableFrom": "usage_log", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -26194,12 +24921,8 @@ "name": "usage_log_workspace_id_workspace_id_fk", "tableFrom": "usage_log", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -26207,12 +24930,8 @@ "name": "usage_log_workflow_id_workflow_id_fk", "tableFrom": "usage_log", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -26364,16 +25083,12 @@ "user_email_unique": { "name": "user_email_unique", "nullsNotDistinct": false, - "columns": [ - "email" - ] + "columns": ["email"] }, "user_normalized_email_unique": { "name": "user_normalized_email_unique", "nullsNotDistinct": false, - "columns": [ - "normalized_email" - ] + "columns": ["normalized_email"] } }, "policies": {}, @@ -26480,12 +25195,8 @@ "name": "user_stats_user_id_user_id_fk", "tableFrom": "user_stats", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -26495,9 +25206,7 @@ "user_stats_user_id_unique": { "name": "user_stats_user_id_unique", "nullsNotDistinct": false, - "columns": [ - "user_id" - ] + "columns": ["user_id"] } }, "policies": {}, @@ -26737,12 +25446,8 @@ "name": "user_table_definitions_workspace_id_workspace_id_fk", "tableFrom": "user_table_definitions", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -26750,12 +25455,8 @@ "name": "user_table_definitions_folder_id_folder_id_fk", "tableFrom": "user_table_definitions", "tableTo": "folder", - "columnsFrom": [ - "folder_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -26763,12 +25464,8 @@ "name": "user_table_definitions_created_by_user_id_fk", "tableFrom": "user_table_definitions", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -26835,12 +25532,8 @@ "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" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -26894,12 +25587,8 @@ "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" - ], + "columnsFrom": ["row_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -27146,12 +25835,8 @@ "name": "user_table_rows_table_id_user_table_definitions_id_fk", "tableFrom": "user_table_rows", "tableTo": "user_table_definitions", - "columnsFrom": [ - "table_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["table_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -27159,12 +25844,8 @@ "name": "user_table_rows_workspace_id_workspace_id_fk", "tableFrom": "user_table_rows", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -27172,12 +25853,8 @@ "name": "user_table_rows_created_by_user_id_fk", "tableFrom": "user_table_rows", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -27313,9 +25990,7 @@ "waitlist_email_unique": { "name": "waitlist_email_unique", "nullsNotDistinct": false, - "columns": [ - "email" - ] + "columns": ["email"] } }, "policies": {}, @@ -27658,12 +26333,8 @@ "name": "webhook_workflow_id_workflow_id_fk", "tableFrom": "webhook", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -27671,12 +26342,8 @@ "name": "webhook_deployment_version_id_workflow_deployment_version_id_fk", "tableFrom": "webhook", "tableTo": "workflow_deployment_version", - "columnsFrom": [ - "deployment_version_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -27755,12 +26422,8 @@ "name": "webhook_path_claim_workflow_id_workflow_id_fk", "tableFrom": "webhook_path_claim", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -28065,12 +26728,8 @@ "name": "workflow_user_id_user_id_fk", "tableFrom": "workflow", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28078,12 +26737,8 @@ "name": "workflow_workspace_id_workspace_id_fk", "tableFrom": "workflow", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28091,12 +26746,8 @@ "name": "workflow_folder_id_folder_id_fk", "tableFrom": "workflow", "tableTo": "folder", - "columnsFrom": [ - "folder_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -28281,12 +26932,7 @@ "compositePrimaryKeys": { "workflow_activity_hourly_pk": { "name": "workflow_activity_hourly_pk", - "columns": [ - "workspace_id", - "bucket_start", - "workflow_id", - "trigger" - ] + "columns": ["workspace_id", "bucket_start", "workflow_id", "trigger"] } }, "uniqueConstraints": {}, @@ -28469,12 +27115,8 @@ "name": "workflow_blocks_workflow_id_workflow_id_fk", "tableFrom": "workflow_blocks", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -28656,12 +27298,8 @@ "name": "workflow_checkpoints_user_id_user_id_fk", "tableFrom": "workflow_checkpoints", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28669,12 +27307,8 @@ "name": "workflow_checkpoints_workflow_id_workflow_id_fk", "tableFrom": "workflow_checkpoints", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28682,12 +27316,8 @@ "name": "workflow_checkpoints_chat_id_copilot_chats_id_fk", "tableFrom": "workflow_checkpoints", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -28944,12 +27574,8 @@ "name": "workflow_deployment_operation_workflow_id_workflow_id_fk", "tableFrom": "workflow_deployment_operation", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28957,12 +27583,8 @@ "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" - ], + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -28970,12 +27592,8 @@ "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" - ], + "columnsFrom": ["previous_active_version_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -29128,12 +27746,8 @@ "name": "workflow_deployment_version_workflow_id_workflow_id_fk", "tableFrom": "workflow_deployment_version", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -29271,12 +27885,8 @@ "name": "workflow_edges_workflow_id_workflow_id_fk", "tableFrom": "workflow_edges", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -29284,12 +27894,8 @@ "name": "workflow_edges_source_block_id_workflow_blocks_id_fk", "tableFrom": "workflow_edges", "tableTo": "workflow_blocks", - "columnsFrom": [ - "source_block_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_block_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -29297,12 +27903,8 @@ "name": "workflow_edges_target_block_id_workflow_blocks_id_fk", "tableFrom": "workflow_edges", "tableTo": "workflow_blocks", - "columnsFrom": [ - "target_block_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["target_block_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -29796,12 +28398,8 @@ "name": "workflow_execution_logs_workflow_id_workflow_id_fk", "tableFrom": "workflow_execution_logs", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -29809,12 +28407,8 @@ "name": "workflow_execution_logs_workspace_id_workspace_id_fk", "tableFrom": "workflow_execution_logs", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -29822,12 +28416,8 @@ "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" - ], + "columnsFrom": ["state_snapshot_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" }, @@ -29835,12 +28425,8 @@ "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" - ], + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -29945,12 +28531,8 @@ "name": "workflow_execution_snapshots_workflow_id_workflow_id_fk", "tableFrom": "workflow_execution_snapshots", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -30097,12 +28679,8 @@ "name": "workflow_mcp_server_workspace_id_workspace_id_fk", "tableFrom": "workflow_mcp_server", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -30110,12 +28688,8 @@ "name": "workflow_mcp_server_created_by_user_id_fk", "tableFrom": "workflow_mcp_server", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -30270,12 +28844,8 @@ "name": "workflow_mcp_tool_server_id_workflow_mcp_server_id_fk", "tableFrom": "workflow_mcp_tool", "tableTo": "workflow_mcp_server", - "columnsFrom": [ - "server_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["server_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -30283,12 +28853,8 @@ "name": "workflow_mcp_tool_workflow_id_workflow_id_fk", "tableFrom": "workflow_mcp_tool", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -30692,12 +29258,8 @@ "name": "workflow_schedule_workflow_id_workflow_id_fk", "tableFrom": "workflow_schedule", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -30705,12 +29267,8 @@ "name": "workflow_schedule_deployment_version_id_workflow_deployment_version_id_fk", "tableFrom": "workflow_schedule", "tableTo": "workflow_deployment_version", - "columnsFrom": [ - "deployment_version_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["deployment_version_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -30718,12 +29276,8 @@ "name": "workflow_schedule_deployment_operation_id_workflow_deployment_operation_id_fk", "tableFrom": "workflow_schedule", "tableTo": "workflow_deployment_operation", - "columnsFrom": [ - "deployment_operation_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["deployment_operation_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -30731,12 +29285,8 @@ "name": "workflow_schedule_source_user_id_user_id_fk", "tableFrom": "workflow_schedule", "tableTo": "user", - "columnsFrom": [ - "source_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -30744,12 +29294,8 @@ "name": "workflow_schedule_source_workspace_id_workspace_id_fk", "tableFrom": "workflow_schedule", "tableTo": "workspace", - "columnsFrom": [ - "source_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -30790,12 +29336,8 @@ "name": "workflow_source_meta_workflow_id_workflow_id_fk", "tableFrom": "workflow_source_meta", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -30878,12 +29420,8 @@ "name": "workflow_subflows_workflow_id_workflow_id_fk", "tableFrom": "workflow_subflows", "tableTo": "workflow", - "columnsFrom": [ - "workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -31018,12 +29556,8 @@ "name": "workflow_test_workspace_id_workspace_id_fk", "tableFrom": "workflow_test", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31031,12 +29565,8 @@ "name": "workflow_test_body_file_id_workspace_files_id_fk", "tableFrom": "workflow_test", "tableTo": "workspace_files", - "columnsFrom": [ - "body_file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["body_file_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" }, @@ -31044,12 +29574,8 @@ "name": "workflow_test_created_by_user_id_user_id_fk", "tableFrom": "workflow_test", "tableTo": "user", - "columnsFrom": [ - "created_by_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -31206,12 +29732,8 @@ "name": "workflow_test_run_test_id_workflow_test_id_fk", "tableFrom": "workflow_test_run", "tableTo": "workflow_test", - "columnsFrom": [ - "test_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["test_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31219,12 +29741,8 @@ "name": "workflow_test_run_workspace_id_workspace_id_fk", "tableFrom": "workflow_test_run", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31232,12 +29750,8 @@ "name": "workflow_test_run_triggered_by_user_id_user_id_fk", "tableFrom": "workflow_test_run", "tableTo": "user", - "columnsFrom": [ - "triggered_by_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["triggered_by_user_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -31379,12 +29893,8 @@ "name": "workload_identity_pending_subject_workspace_id_workspace_id_fk", "tableFrom": "workload_identity_pending_subject", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31392,12 +29902,8 @@ "name": "workload_identity_pending_subject_user_id_user_id_fk", "tableFrom": "workload_identity_pending_subject", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -31685,12 +30191,8 @@ "name": "workspace_owner_id_user_id_fk", "tableFrom": "workspace", "tableTo": "user", - "columnsFrom": [ - "owner_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["owner_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31698,12 +30200,8 @@ "name": "workspace_organization_id_organization_id_fk", "tableFrom": "workspace", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -31711,12 +30209,8 @@ "name": "workspace_project_id_project_id_fk", "tableFrom": "workspace", "tableTo": "project", - "columnsFrom": [ - "project_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["project_id"], + "columnsTo": ["id"], "onDelete": "restrict", "onUpdate": "no action" }, @@ -31724,12 +30218,8 @@ "name": "workspace_billed_account_user_id_user_id_fk", "tableFrom": "workspace", "tableTo": "user", - "columnsFrom": [ - "billed_account_user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["billed_account_user_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" }, @@ -31737,12 +30227,8 @@ "name": "workspace_forked_from_workspace_id_workspace_id_fk", "tableFrom": "workspace", "tableTo": "workspace", - "columnsFrom": [ - "forked_from_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["forked_from_workspace_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -31750,14 +30236,8 @@ "name": "workspace_project_organization_fk", "tableFrom": "workspace", "tableTo": "project", - "columnsFrom": [ - "project_id", - "organization_scope_key" - ], - "columnsTo": [ - "id", - "organization_scope_key" - ], + "columnsFrom": ["project_id", "organization_scope_key"], + "columnsTo": ["id", "organization_scope_key"], "onDelete": "no action", "onUpdate": "no action" }, @@ -31765,14 +30245,8 @@ "name": "workspace_fork_project_fk", "tableFrom": "workspace", "tableTo": "workspace", - "columnsFrom": [ - "forked_from_workspace_id", - "project_id" - ], - "columnsTo": [ - "id", - "project_id" - ], + "columnsFrom": ["forked_from_workspace_id", "project_id"], + "columnsTo": ["id", "project_id"], "onDelete": "no action", "onUpdate": "no action" } @@ -31782,10 +30256,7 @@ "workspace_id_project_unique": { "name": "workspace_id_project_unique", "nullsNotDistinct": false, - "columns": [ - "id", - "project_id" - ] + "columns": ["id", "project_id"] } }, "policies": {}, @@ -31880,12 +30351,8 @@ "name": "workspace_byok_keys_workspace_id_workspace_id_fk", "tableFrom": "workspace_byok_keys", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -31893,12 +30360,8 @@ "name": "workspace_byok_keys_created_by_user_id_fk", "tableFrom": "workspace_byok_keys", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -31969,12 +30432,8 @@ "name": "workspace_environment_workspace_id_workspace_id_fk", "tableFrom": "workspace_environment", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -32119,12 +30578,8 @@ "name": "workspace_file_workspace_id_workspace_id_fk", "tableFrom": "workspace_file", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -32132,12 +30587,8 @@ "name": "workspace_file_uploaded_by_user_id_fk", "tableFrom": "workspace_file", "tableTo": "user", - "columnsFrom": [ - "uploaded_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["uploaded_by"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -32147,9 +30598,7 @@ "workspace_file_key_unique": { "name": "workspace_file_key_unique", "nullsNotDistinct": false, - "columns": [ - "key" - ] + "columns": ["key"] } }, "policies": {}, @@ -32192,12 +30641,8 @@ "name": "workspace_file_collab_state_file_id_workspace_files_id_fk", "tableFrom": "workspace_file_collab_state", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -32527,12 +30972,8 @@ "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" - ], + "columnsFrom": ["build_id"], + "columnsTo": ["id"], "onDelete": "no action", "onUpdate": "no action" } @@ -32540,10 +30981,7 @@ "compositePrimaryKeys": { "workspace_file_search_chunk_pk": { "name": "workspace_file_search_chunk_pk", - "columns": [ - "build_id", - "ordinal" - ] + "columns": ["build_id", "ordinal"] } }, "uniqueConstraints": {}, @@ -32629,12 +31067,8 @@ "name": "workspace_file_search_queue_workspace_fk", "tableFrom": "workspace_file_search_dispatch_queue", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -32813,12 +31247,8 @@ "name": "workspace_file_search_index_file_fk", "tableFrom": "workspace_file_search_index", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -32826,12 +31256,8 @@ "name": "workspace_file_search_index_workspace_fk", "tableFrom": "workspace_file_search_index", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -32839,10 +31265,7 @@ "compositePrimaryKeys": { "workspace_file_search_index_pk": { "name": "workspace_file_search_index_pk", - "columns": [ - "file_id", - "source_content_updated_at" - ] + "columns": ["file_id", "source_content_updated_at"] } }, "uniqueConstraints": {}, @@ -33117,12 +31540,8 @@ "name": "workspace_file_search_revision_file_id_workspace_files_id_fk", "tableFrom": "workspace_file_search_revision", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -33130,12 +31549,8 @@ "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" - ], + "columnsFrom": ["build_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -33261,12 +31676,8 @@ "name": "workspace_file_search_segment_file_fk", "tableFrom": "workspace_file_search_segment", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -33274,12 +31685,8 @@ "name": "workspace_file_search_segment_workspace_fk", "tableFrom": "workspace_file_search_segment", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -33287,12 +31694,7 @@ "compositePrimaryKeys": { "workspace_file_search_segment_pk": { "name": "workspace_file_search_segment_pk", - "columns": [ - "file_id", - "source_content_updated_at", - "line_number", - "segment_number" - ] + "columns": ["file_id", "source_content_updated_at", "line_number", "segment_number"] } }, "uniqueConstraints": {}, @@ -33343,12 +31745,8 @@ "name": "workspace_file_secret_provenance_file_id_workspace_files_id_fk", "tableFrom": "workspace_file_secret_provenance", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -33556,12 +31954,8 @@ "name": "workspace_file_version_file_id_workspace_files_id_fk", "tableFrom": "workspace_file_version", "tableTo": "workspace_files", - "columnsFrom": [ - "file_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["file_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -33569,12 +31963,8 @@ "name": "workspace_file_version_workspace_id_workspace_id_fk", "tableFrom": "workspace_file_version", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -34176,12 +32566,8 @@ "name": "workspace_files_project_id_project_id_fk", "tableFrom": "workspace_files", "tableTo": "project", - "columnsFrom": [ - "project_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["project_id"], + "columnsTo": ["id"], "onDelete": "restrict", "onUpdate": "no action" }, @@ -34189,12 +32575,8 @@ "name": "workspace_files_user_id_user_id_fk", "tableFrom": "workspace_files", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -34202,12 +32584,8 @@ "name": "workspace_files_workspace_id_workspace_id_fk", "tableFrom": "workspace_files", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -34215,12 +32593,8 @@ "name": "workspace_files_organization_id_organization_id_fk", "tableFrom": "workspace_files", "tableTo": "organization", - "columnsFrom": [ - "organization_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["organization_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -34228,12 +32602,8 @@ "name": "workspace_files_folder_id_folder_id_fk", "tableFrom": "workspace_files", "tableTo": "folder", - "columnsFrom": [ - "folder_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["folder_id"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" }, @@ -34241,12 +32611,8 @@ "name": "workspace_files_chat_id_copilot_chats_id_fk", "tableFrom": "workspace_files", "tableTo": "copilot_chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["chat_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -34420,12 +32786,8 @@ "name": "workspace_fork_block_map_child_workspace_id_workspace_id_fk", "tableFrom": "workspace_fork_block_map", "tableTo": "workspace", - "columnsFrom": [ - "child_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -34531,12 +32893,8 @@ "name": "workspace_fork_dependent_value_child_workspace_id_workspace_id_fk", "tableFrom": "workspace_fork_dependent_value", "tableTo": "workspace", - "columnsFrom": [ - "child_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -34645,12 +33003,8 @@ "name": "workspace_fork_promote_run_child_workspace_id_workspace_id_fk", "tableFrom": "workspace_fork_promote_run", "tableTo": "workspace", - "columnsFrom": [ - "child_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -34658,12 +33012,8 @@ "name": "workspace_fork_promote_run_created_by_user_id_fk", "tableFrom": "workspace_fork_promote_run", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -34764,12 +33114,8 @@ "name": "workspace_fork_resource_map_child_workspace_id_workspace_id_fk", "tableFrom": "workspace_fork_resource_map", "tableTo": "workspace", - "columnsFrom": [ - "child_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -34777,12 +33123,8 @@ "name": "workspace_fork_resource_map_created_by_user_id_fk", "tableFrom": "workspace_fork_resource_map", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -34992,12 +33334,8 @@ "name": "workspace_fork_workflow_sync_child_workspace_id_workspace_id_fk", "tableFrom": "workspace_fork_workflow_sync", "tableTo": "workspace", - "columnsFrom": [ - "child_workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["child_workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -35005,12 +33343,8 @@ "name": "workspace_fork_workflow_sync_source_workflow_id_workflow_id_fk", "tableFrom": "workspace_fork_workflow_sync", "tableTo": "workflow", - "columnsFrom": [ - "source_workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["source_workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -35018,12 +33352,8 @@ "name": "workspace_fork_workflow_sync_target_workflow_id_workflow_id_fk", "tableFrom": "workspace_fork_workflow_sync", "tableTo": "workflow", - "columnsFrom": [ - "target_workflow_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["target_workflow_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -35144,12 +33474,8 @@ "name": "workspace_operation_receipt_workspace_id_workspace_id_fk", "tableFrom": "workspace_operation_receipt", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -35283,12 +33609,8 @@ "name": "workspace_resource_key_workspace_id_workspace_id_fk", "tableFrom": "workspace_resource_key", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -35296,12 +33618,8 @@ "name": "workspace_resource_key_created_by_user_id_fk", "tableFrom": "workspace_resource_key", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -35441,12 +33759,8 @@ "name": "workspace_sandbox_workspace_id_workspace_id_fk", "tableFrom": "workspace_sandbox", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -35454,12 +33768,8 @@ "name": "workspace_sandbox_created_by_user_id_fk", "tableFrom": "workspace_sandbox", "tableTo": "user", - "columnsFrom": [ - "created_by" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["created_by"], + "columnsTo": ["id"], "onDelete": "set null", "onUpdate": "no action" } @@ -35506,12 +33816,8 @@ "name": "workspace_source_apply_lease_workspace_id_workspace_id_fk", "tableFrom": "workspace_source_apply_lease", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -35625,12 +33931,8 @@ "name": "workspace_source_staged_blob_workspace_id_workspace_id_fk", "tableFrom": "workspace_source_staged_blob", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -35687,12 +33989,8 @@ "name": "workspace_visit_user_id_user_id_fk", "tableFrom": "workspace_visit", "tableTo": "user", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["user_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" }, @@ -35700,12 +33998,8 @@ "name": "workspace_visit_workspace_id_workspace_id_fk", "tableFrom": "workspace_visit", "tableTo": "workspace", - "columnsFrom": [ - "workspace_id" - ], - "columnsTo": [ - "id" - ], + "columnsFrom": ["workspace_id"], + "columnsTo": ["id"], "onDelete": "cascade", "onUpdate": "no action" } @@ -35713,10 +34007,7 @@ "compositePrimaryKeys": { "workspace_visit_user_id_workspace_id_pk": { "name": "workspace_visit_user_id_workspace_id_pk", - "columns": [ - "user_id", - "workspace_id" - ] + "columns": ["user_id", "workspace_id"] } }, "uniqueConstraints": {}, @@ -35729,143 +34020,77 @@ "public.api_key_access": { "name": "api_key_access", "schema": "public", - "values": [ - "read", - "write" - ] + "values": ["read", "write"] }, "public.aws_marketplace_license_status": { "name": "aws_marketplace_license_status", "schema": "public", - "values": [ - "pending", - "active", - "inactive" - ] + "values": ["pending", "active", "inactive"] }, "public.aws_marketplace_usage_report_status": { "name": "aws_marketplace_usage_report_status", "schema": "public", - "values": [ - "pending", - "reported", - "rejected" - ] + "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" - ] + "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" - ] + "values": ["pending", "processing", "completed", "completed_with_warnings", "failed"] }, "public.billing_blocked_reason": { "name": "billing_blocked_reason", "schema": "public", - "values": [ - "payment_failed", - "dispute" - ] + "values": ["payment_failed", "dispute"] }, "public.billing_entity_type": { "name": "billing_entity_type", "schema": "public", - "values": [ - "user", - "organization" - ] + "values": ["user", "organization"] }, "public.chat_type": { "name": "chat_type", "schema": "public", - "values": [ - "mothership", - "copilot" - ] + "values": ["mothership", "copilot"] }, "public.copilot_async_tool_status": { "name": "copilot_async_tool_status", "schema": "public", - "values": [ - "pending", - "running", - "completed", - "failed", - "cancelled", - "delivered" - ] + "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" - ] + "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" - ] + "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" - ] + "values": ["invited", "delivery_failed", "in_progress", "completed", "revoked"] }, "public.credential_group_status": { "name": "credential_group_status", "schema": "public", - "values": [ - "active", - "disabled" - ] + "values": ["active", "disabled"] }, "public.credential_member_role": { "name": "credential_member_role", "schema": "public", - "values": [ - "admin", - "member" - ] + "values": ["admin", "member"] }, "public.credential_member_status": { "name": "credential_member_status", "schema": "public", - "values": [ - "active", - "pending", - "revoked" - ] + "values": ["active", "pending", "revoked"] }, "public.credential_type": { "name": "credential_type", @@ -35883,10 +34108,7 @@ "public.data_drain_cadence": { "name": "data_drain_cadence", "schema": "public", - "values": [ - "hourly", - "daily" - ] + "values": ["hourly", "daily"] }, "public.data_drain_destination": { "name": "data_drain_destination", @@ -35905,146 +34127,82 @@ "public.data_drain_run_status": { "name": "data_drain_run_status", "schema": "public", - "values": [ - "running", - "success", - "failed" - ] + "values": ["running", "success", "failed"] }, "public.data_drain_run_trigger": { "name": "data_drain_run_trigger", "schema": "public", - "values": [ - "cron", - "manual" - ] + "values": ["cron", "manual"] }, "public.data_drain_source": { "name": "data_drain_source", "schema": "public", - "values": [ - "workflow_logs", - "job_logs", - "audit_logs", - "copilot_chats", - "copilot_runs" - ] + "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" - ] + "values": ["execution_log", "paused_snapshot"] }, "public.folder_resource_type": { "name": "folder_resource_type", "schema": "public", - "values": [ - "workflow", - "file", - "knowledge_base", - "table" - ] + "values": ["workflow", "file", "knowledge_base", "table"] }, "public.invitation_kind": { "name": "invitation_kind", "schema": "public", - "values": [ - "organization", - "workspace" - ] + "values": ["organization", "workspace"] }, "public.invitation_membership_intent": { "name": "invitation_membership_intent", "schema": "public", - "values": [ - "internal", - "external" - ] + "values": ["internal", "external"] }, "public.invitation_status": { "name": "invitation_status", "schema": "public", - "values": [ - "pending", - "accepted", - "rejected", - "cancelled", - "expired" - ] + "values": ["pending", "accepted", "rejected", "cancelled", "expired"] }, "public.managed_oauth_credential_status": { "name": "managed_oauth_credential_status", "schema": "public", - "values": [ - "active", - "needs_reauth", - "revoked" - ] + "values": ["active", "needs_reauth", "revoked"] }, "public.permission_type": { "name": "permission_type", "schema": "public", - "values": [ - "admin", - "write", - "read" - ] + "values": ["admin", "write", "read"] }, "public.sandbox_image_status": { "name": "sandbox_image_status", "schema": "public", - "values": [ - "pending", - "building", - "ready", - "failed" - ] + "values": ["pending", "building", "ready", "failed"] }, "public.sandbox_language": { "name": "sandbox_language", "schema": "public", - "values": [ - "javascript", - "python" - ] + "values": ["javascript", "python"] }, "public.secret_usage_scope": { "name": "secret_usage_scope", "schema": "public", - "values": [ - "workspace", - "personal" - ] + "values": ["workspace", "personal"] }, "public.secret_usage_source": { "name": "secret_usage_source", "schema": "public", - "values": [ - "workflow", - "copilot", - "mcp" - ] + "values": ["workflow", "copilot", "mcp"] }, "public.upload_session_method": { "name": "upload_session_method", "schema": "public", - "values": [ - "put", - "multipart" - ] + "values": ["put", "multipart"] }, "public.upload_session_provider": { "name": "upload_session_provider", "schema": "public", - "values": [ - "local", - "s3", - "blob", - "gcs" - ] + "values": ["local", "s3", "blob", "gcs"] }, "public.upload_session_purpose": { "name": "upload_session_purpose", @@ -36079,12 +34237,7 @@ "public.usage_log_category": { "name": "usage_log_category", "schema": "public", - "values": [ - "model", - "fixed", - "tool", - "model_unbilled" - ] + "values": ["model", "fixed", "tool", "model_unbilled"] }, "public.usage_log_source": { "name": "usage_log_source", @@ -36107,34 +34260,17 @@ "public.workspace_file_search_index_status": { "name": "workspace_file_search_index_status", "schema": "public", - "values": [ - "pending", - "ready", - "skipped", - "failed" - ] + "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" - ] + "values": ["upload", "user", "api", "copilot", "workflow", "collab", "revert", "unknown"] }, "public.workspace_fork_promote_direction": { "name": "workspace_fork_promote_direction", "schema": "public", - "values": [ - "push", - "pull" - ] + "values": ["push", "pull"] }, "public.workspace_fork_resource_type": { "name": "workspace_fork_resource_type", @@ -36160,11 +34296,7 @@ "public.workspace_mode": { "name": "workspace_mode", "schema": "public", - "values": [ - "personal", - "organization", - "grandfathered_shared" - ] + "values": ["personal", "organization", "grandfathered_shared"] }, "public.workspace_resource_kind": { "name": "workspace_resource_kind", @@ -36206,4 +34338,4 @@ "schemas": {}, "tables": {} } -} \ No newline at end of file +} diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index de42422c078..a7db62ed789 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -3272,4 +3272,4 @@ "breakpoints": true } ] -} \ No newline at end of file +} From 1bf4d57ed0153e7b40ba73d62d3aa22b37207b7c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:50:23 -0800 Subject: [PATCH 048/104] fix(workspace-source): judge an MCP header env-only with the shared auth scheme list concealHeaderValues kept its own scheme list without digest and key, so a reader saw Authorization: Digest {{TOKEN}} as stored() instead of as written. It now strips the scheme with withoutAuthScheme, the list workflows and workspace declarations share. --- .../lib/workspace-source/application/kinds/mcp/stored.ts | 6 +++--- .../sim/lib/workspace-source/application/mcp.integration.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts index 522df815d40..22f9f6d6713 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts @@ -5,6 +5,7 @@ * be guessed from. */ import { hmacSha256Hex } from '@sim/security/hmac' +import { withoutAuthScheme } from '@sim/workflow-code' import { fingerprintOf, type ResourceFingerprint } from '@sim/workspace-code' import { holdsLiteralSecret, @@ -75,13 +76,12 @@ export function declOf(row: McpServerRow): McpServerDecl { } } -/** `{{NAME}}` env references, and the auth scheme word a header value may open with. */ +/** `{{NAME}}` env references. */ const ENV_REFERENCES = /\{\{[A-Za-z_][A-Za-z0-9_]*\}\}/g -const LEADING_AUTH_SCHEME = /^\s*(?:bearer|basic|token|bot|apikey)\s+/i /** Whether a header value is only env references (after an optional auth scheme word). */ function isEnvReferenceOnly(value: string): boolean { - return value.replace(LEADING_AUTH_SCHEME, '').replace(ENV_REFERENCES, '').trim() === '' + return withoutAuthScheme(value).replace(ENV_REFERENCES, '').trim() === '' } /** diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index 08907ef7914..b4db3c69938 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -712,7 +712,7 @@ describe('MCP servers as workspace source', () => { workspaceId, name: 'Tenant', url, - headers: { 'X-Tenant': tenant, Authorization: 'Bearer {{GH_TOKEN}}' }, + headers: { 'X-Tenant': tenant, Authorization: 'Digest {{GH_TOKEN}}' }, authType: 'headers', }, }) @@ -724,7 +724,7 @@ describe('MCP servers as workspace source', () => { const read = await runner.get(workspaceId, reader) expect(JSON.stringify(read)).not.toContain(tenant) expect(read.files[path]).toContain("'X-Tenant': stored()") - expect(read.files[path]).toContain('Bearer {{GH_TOKEN}}') + expect(read.files[path]).toContain('Digest {{GH_TOKEN}}') const address: `mcp-server:${string}` = `mcp-server:${path.slice(4, -3)}` expect(read.base.resources[address]).toEqual(written.base.resources[address]) @@ -741,7 +741,7 @@ describe('MCP servers as workspace source', () => { ) expect(renamed.applied).toMatchObject([{ action: 'update', fields: ['name'] }]) expect((await liveServers(workspaceId)).map((server) => server.headers)).toEqual([ - { 'X-Tenant': tenant, Authorization: 'Bearer {{GH_TOKEN}}' }, + { 'X-Tenant': tenant, Authorization: 'Digest {{GH_TOKEN}}' }, ]) } ) From ebfa029cc059452bd614c02262c0bc87d7553d0b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:51:35 -0800 Subject: [PATCH 049/104] fix(workspace-source): never compare an MCP header value with one hidden from the caller A read member's plan compared a literal header value they wrote with the stored one their get printed as stored(): a right guess planned a no-op, a wrong one an update, so the read-role plan confirmed guesses of values like X-Tenant. A caller who may not see header values now gets E_APPLY_FORBIDDEN for any literal text on a header whose value is hidden, matching or not. --- .../application/kinds/mcp/adapter.ts | 16 ++++- .../application/kinds/mcp/stored.ts | 14 +++++ .../application/mcp.integration.ts | 61 ++++++++++++++++++- 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index 1da05bb6174..f3d54a5ac2b 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -69,6 +69,7 @@ import { concealHeaderValues, declOf, headersToWrite, + hiddenHeadersWritten, holdsDeclaration, keepsStoredHeaders, resolveStoredHeaders, @@ -166,7 +167,20 @@ async function planServer( const bound = stored.bound.get(key) const adoptable = stored.unbound.find((record) => record.id === id) - const { decl, missing } = resolveStoredHeaders(declared, (bound ?? adoptable)?.state) + const target = bound ?? adoptable + // A caller who cannot see a header's stored value may only keep it: comparing text they wrote + // with the hidden value would tell them whether they guessed it. + if (target && (await revealsHeaderValues(ctx)) !== true) { + for (const header of hiddenHeadersWritten(declared, target.state)) { + finding( + 'E_APPLY_FORBIDDEN', + `Header "${header}" holds a value you cannot see, so it can only be kept as \`stored()\`.`, + 'Writing a header value the MCP server hides needs permission to update the server.' + ) + } + if (change.diagnostics.length > 0) return change + } + const { decl, missing } = resolveStoredHeaders(declared, target?.state) change.decl = decl // A server the base records that the server deleted since: its `stored()` headers have nothing // to keep, and the declaration cannot be compared with the base, so it stays deleted. diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts index 22f9f6d6713..46394551084 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/stored.ts @@ -84,6 +84,20 @@ function isEnvReferenceOnly(value: string): boolean { return withoutAuthScheme(value).replace(ENV_REFERENCES, '').trim() === '' } +/** + * The headers `decl` writes as literal text where `row` stores a value {@link concealHeaderValues} + * hides: a reader who cannot see that value may keep it (`stored()`) or replace it with env + * references, never compare text of their own with it. + */ +export function hiddenHeadersWritten(decl: McpServerDecl, row: McpServerRow): string[] { + const stored = storedHeaders(row) + return Object.entries(decl.headers ?? {}).flatMap(([name, header]) => { + const value = stored[name] + const hidden = value !== undefined && !isEnvReferenceOnly(value) + return hidden && !isStoredHeader(header) && !isEnvReferenceOnly(header) ? [name] : [] + }) +} + /** * `decl` (as {@link declOf} printed `row`) for a reader who may not see header values, as the MCP * server list withholds them from anyone who cannot rewrite them: every header holding literal diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index b4db3c69938..8b4be7cc35d 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -29,9 +29,13 @@ import { updateMcpServerUseCase, } from '@/lib/mcp/application/use-cases' import { generateMcpServerId } from '@/lib/mcp/utils' +import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' import { readSourceResources } from '@/lib/workflows/application/read-source-resources' import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' -import type { ApplyWorkspaceSourceInput } from '@/lib/workspace-source/application/apply-workspace-source' +import { + type ApplyWorkspaceSourceInput, + readWorkspaceSourcePlan, +} from '@/lib/workspace-source/application/apply-workspace-source' import { failKeyClaims, refusal, @@ -746,6 +750,61 @@ describe('MCP servers as workspace source', () => { } ) + check( + 'never tells a read-only member whether a header value they wrote matches the one hidden from them', + async () => { + const workspaceId = await newWorkspace() + await createMcpServerUseCase.execute({ + principal: owner, + input: { + workspaceId, + name: 'Tenant', + url, + headers: { 'X-Tenant': 'acme' }, + authType: 'headers', + }, + }) + const read = await runner.get(workspaceId, reader) + const [path] = Object.keys(read.files) + expect(read.files[path]).toContain("'X-Tenant': stored()") + + const planWith = async (guess: string) => { + const plan = await withPermissionGroupScope(() => + readWorkspaceSourcePlan.execute({ + principal: reader, + input: { + workspaceId, + kinds: ['mcp-server', 'workflow'], + files: { [path]: read.files[path].replace('stored()', `'${guess}'`) }, + base: read.base, + }, + }) + ) + return { plan: plan.plan, diagnostics: plan.diagnostics } + } + const right = await planWith('acme') + const wrong = await planWith('other') + + expect(right).toEqual(wrong) + expect(findings(right.diagnostics, 'error')).toEqual([ + `E_APPLY_FORBIDDEN mcp-server:${path.slice(4, -3)}`, + ]) + // Keeping the value it cannot see stays a no-op. + const kept = await withPermissionGroupScope(() => + readWorkspaceSourcePlan.execute({ + principal: reader, + input: { + workspaceId, + kinds: ['mcp-server', 'workflow'], + files: read.files, + base: read.base, + }, + }) + ) + expect(kept.plan.map((change) => change.action)).toEqual(['noop']) + } + ) + check( 'refuses a replace that carries stored() header values to a new URL unless an admin applies it', async () => { From 83a64b5563c713cf60a6042ee36671179de0dc92 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:53:04 -0800 Subject: [PATCH 050/104] fix(workspace-source): check an MCP server URL only after the caller may write the server An in-place URL change ran the allowlist, egress and DNS check before the update role check, so a read member's plan learned how a URL fared. The URL check now runs after every role check, on the create, replace and update branches alike. --- .../application/kinds/mcp/adapter.ts | 16 ++--- .../application/mcp.integration.ts | 61 ++++++++++++------- 2 files changed, 47 insertions(+), 30 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index f3d54a5ac2b..3df129e919e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -548,24 +548,24 @@ export const mcpAdapter: KindAdapter<'mcp-server', McpServerRow> = { input: { workspaceId, name: decl.name, url: decl.url }, }) } - // The URL is checked as the write checks it (allowlist, egress policy, DNS), so a URL the - // write would refuse refuses the plan, not the apply after other resources were written. - if (decl && (createsServer || change.detail?.changed.includes('url'))) { - await assertMcpServerUrlAccepted(decl.url) - } await authorizeCarriedHeaders(change, ctx) - if (!change.storedId) return - if (change.action === 'delete' || change.detail?.replace) { + if (change.storedId && (change.action === 'delete' || change.detail?.replace)) { await deleteMcpServerUseCase.authorize({ principal, input: { workspaceId, serverId: change.storedId }, }) - } else if (change.action !== 'create') { + } else if (change.storedId && change.action !== 'create') { await updateUseCaseOf(change.detail?.changed ?? []).authorize({ principal, input: { workspaceId, serverId: change.storedId }, }) } + // The URL is checked as the write checks it (allowlist, egress policy, DNS), so a URL the + // write would refuse refuses the plan, not the apply after other resources were written. It + // runs last, so only a caller who may write the server learns how its URL fares. + if (decl && (createsServer || change.detail?.changed.includes('url'))) { + await assertMcpServerUrlAccepted(decl.url) + } }, async storedFingerprintNow(change, ctx) { diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index 8b4be7cc35d..cae5fa3ba5c 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -139,6 +139,21 @@ function apply(workspaceId: string, files: Record, options: Appl return runner.apply(workspaceId, { files, ...options }) } +/** What an apply of `files` would do, as `principal` reads it with the read-role plan. */ +function planAs( + principal: Principal, + workspaceId: string, + files: Record, + base: ApplyOptions['base'] +) { + return withPermissionGroupScope(() => + readWorkspaceSourcePlan.execute({ + principal, + input: { workspaceId, kinds: ['mcp-server', 'workflow'], files, ...(base ? { base } : {}) }, + }) + ) +} + function findings( diagnostics: ReadonlyArray<{ code: string; severity: string; kind?: string; key?: string }>, severity: string @@ -548,6 +563,27 @@ describe('MCP servers as workspace source', () => { } ) + check('checks a changed server URL only for a caller who may write the server', async () => { + const workspaceId = await newWorkspace() + const unresolvable = 'http://mcp-gone.invalid/mcp' + await db.insert(mcpServers).values({ + id: generateMcpServerId(workspaceId, unresolvable), + workspaceId, + name: 'Gone', + transport: 'streamable-http', + url: unresolvable, + }) + const read = await runner.get(workspaceId, reader) + const [path] = Object.keys(read.files) + const requery = { [path]: read.files[path].replace(unresolvable, `${unresolvable}?v=2`) } + + const plan = await planAs(reader, workspaceId, requery, read.base) + expect(findings(plan.diagnostics, 'error')).toEqual([ + `E_APPLY_FORBIDDEN mcp-server:${path.slice(4, -3)}`, + ]) + expect(JSON.stringify(plan.diagnostics)).not.toContain('resolve') + }) + check( 'a re-run that adopts a stopped replace carrying stored() headers still needs an admin', async () => { @@ -769,17 +805,8 @@ describe('MCP servers as workspace source', () => { expect(read.files[path]).toContain("'X-Tenant': stored()") const planWith = async (guess: string) => { - const plan = await withPermissionGroupScope(() => - readWorkspaceSourcePlan.execute({ - principal: reader, - input: { - workspaceId, - kinds: ['mcp-server', 'workflow'], - files: { [path]: read.files[path].replace('stored()', `'${guess}'`) }, - base: read.base, - }, - }) - ) + const files = { [path]: read.files[path].replace('stored()', `'${guess}'`) } + const plan = await planAs(reader, workspaceId, files, read.base) return { plan: plan.plan, diagnostics: plan.diagnostics } } const right = await planWith('acme') @@ -790,17 +817,7 @@ describe('MCP servers as workspace source', () => { `E_APPLY_FORBIDDEN mcp-server:${path.slice(4, -3)}`, ]) // Keeping the value it cannot see stays a no-op. - const kept = await withPermissionGroupScope(() => - readWorkspaceSourcePlan.execute({ - principal: reader, - input: { - workspaceId, - kinds: ['mcp-server', 'workflow'], - files: read.files, - base: read.base, - }, - }) - ) + const kept = await planAs(reader, workspaceId, read.files, read.base) expect(kept.plan.map((change) => change.action)).toEqual(['noop']) } ) From 4e254bdc810d5a3c4069b68f46923ad5e693367a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:57:38 -0800 Subject: [PATCH 051/104] fix(api): give source plans their own budget and slots, charged per evaluated workflow The workflow plan ran the whole apply pipeline at the read role on the generic per-plan budget with no concurrency slot, and the workspace plan cost one source-read unit for up to a hundred workflow evaluations while holding the apply lane. Both now draw on a source-plan bucket (the workspace plan charged per evaluated folder, as workspaceApplyRateCost charges an apply) and run in a plan lane of their own, so a status loop never spends the write budget or blocks an apply. The slot machinery moves to lib/workflows/api so the workflow route can render its 429 too. --- apps/docs/openapi-v2-workflows.json | 4 +- .../[workflowId]/source/plan/route.ts | 11 +-- .../[workflowId]/source/route.test.ts | 63 ++++++++++++++ .../[workspaceId]/source/plan/route.test.ts | 86 +++++++++++++++++++ .../[workspaceId]/source/plan/route.ts | 15 ++-- .../workspaces/[workspaceId]/source/route.ts | 2 +- .../contracts/v2/openapi/workflow-source.ts | 2 +- .../contracts/v2/openapi/workspace-source.ts | 2 +- .../lib/api/mcp/generated/v2-operations.ts | 4 +- .../lib/api/server/routes/v2-json-route.ts | 19 ++++ apps/sim/lib/workflows/api/index.ts | 1 + apps/sim/lib/workflows/api/route-policies.ts | 6 +- .../api/source-slots.test.ts} | 25 ++++-- apps/sim/lib/workflows/api/source-slots.ts | 62 +++++++++++++ .../workspace-source/api/route-policies.ts | 61 +------------ 15 files changed, 281 insertions(+), 82 deletions(-) create mode 100644 apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts rename apps/sim/lib/{workspace-source/api/route-policies.test.ts => workflows/api/source-slots.test.ts} (65%) create mode 100644 apps/sim/lib/workflows/api/source-slots.ts diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index e6152101193..f76b52e4fc1 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6241,7 +6241,7 @@ "post": { "operationId": "planWorkflowSource", "summary": "Plan workflow source", - "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", "x-sim-operation": "workflows.source.plan", "x-oauth-scope": "api:read", "tags": ["Workflows"], @@ -9051,7 +9051,7 @@ "post": { "operationId": "planWorkspaceSource", "summary": "Plan workspace source", - "description": "Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.", + "description": "Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws on the source-plan budget, one unit per workflow folder it evaluates as an apply does, takes no apply lease or apply slot and records no audit event, so `sim workspaces source status` never spends the source-write budget or holds up an apply. A server already running as many plans as it allows answers `429`. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.", "x-sim-operation": "workspaces.source.plan", "x-oauth-scope": "api:read", "tags": ["Workflows"], diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts index 47f5b083a4e..6031ead11b6 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/plan/route.ts @@ -1,7 +1,7 @@ import { SOURCE_REQUEST_MAX_BYTES } from '@sim/workflow-code/limits' import { v2PlanWorkflowSourceContract } from '@/lib/api/contracts/v2/workflow-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { v2WorkflowErrorPolicies, withSourceSlot } from '@/lib/workflows/api' import { planWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { workflowOperations } from '@/lib/workflows/application/operations' @@ -11,14 +11,15 @@ export const revalidate = 0 /** * POST /api/v2/workflows/[workflowId]/source/plan — what applying the submitted source would do, * without writing: the dry run `sim workflows source status` reads. A read at the `read` role on - * the generic budget, so asking for a status never spends the source-write budget an apply - * needs. Answers 403 while the `workflow-code` flag is off. + * the source-plan budget (`v2RateLimits.sourcePlan`), so asking for a status never spends the + * source-write budget an apply needs; a server already running as many plans as it allows + * answers 429. Answers 403 while the `workflow-code` flag is off. */ export const POST = defineV2JsonRoute({ contract: v2PlanWorkflowSourceContract, auth: v2ApiKeyAuth, operation: workflowOperations.planSource, - rateLimit: v2RateLimits.publicApi, + rateLimit: v2RateLimits.sourcePlan, errorPolicy: v2WorkflowErrorPolicies.concealWorkflowGraphAuthorization, parseOptions: { maxBodyBytes: SOURCE_REQUEST_MAX_BYTES }, mapInput: ({ params, query, body }) => ({ @@ -28,6 +29,6 @@ export const POST = defineV2JsonRoute({ base: body.base, ...(query.allowDelete !== undefined ? { allowDelete: query.allowDelete } : {}), }), - useCase: planWorkflowSource, + useCase: withSourceSlot(planWorkflowSource, 'plan'), present: (result) => ({ data: result }), }) 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 741d8ffe85e..d2aecd7a517 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 @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ authorizeRead: vi.fn(), apply: vi.fn(), create: vi.fn(), + plan: vi.fn(), })) vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => v2ApiKeyAuthModuleMock) @@ -34,6 +35,10 @@ vi.mock('@/lib/workflows/application/apply-workflow-source', () => ({ operation: { id: 'workflows.source.create' }, execute: mocks.create, }, + planWorkflowSource: { + operation: { id: 'workflows.source.plan' }, + execute: mocks.plan, + }, })) import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -42,6 +47,7 @@ import { WorkflowSourceRejectedError, WorkflowSourceStaleError, } from '@/lib/workflows/application/source-error' +import { POST as PLAN } from '@/app/api/v2/workflows/[workflowId]/source/plan/route' import { GET, POST } from '@/app/api/v2/workflows/[workflowId]/source/route' import { POST as CREATE } from '@/app/api/v2/workspaces/[workspaceId]/workflows/source/route' @@ -378,3 +384,60 @@ describe('source write rate limit', () => { expect(mocks.create).not.toHaveBeenCalled() }) }) + +describe('source plan budget', () => { + const person = { + ...auth, + principal: { + kind: 'personal_api_key' as const, + userId: 'user-1', + keyId: 'key-2', + access: 'write' as const, + }, + rateLimitSubjectIds: ['api-key:key-2', 'user:user-1'] as const, + keyType: 'personal' as const, + } + const plan = () => + PLAN( + new NextRequest(`http://localhost:3000/api/v2/workflows/${WORKFLOW_ID}/source/plan`, { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, + body: JSON.stringify(applyBody), + }), + context + ) + + beforeEach(() => { + v2RouteMocks.authenticate.mockResolvedValue(person) + v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) + meterOperationBuckets() + mocks.plan.mockResolvedValue({ ...applied, dryRun: true, applied: false }) + 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 () => { + 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) + }) + + it('answers 429 with Retry-After to a plan past the plans this server runs at once', async () => { + const finish: Array<() => void> = [] + mocks.plan.mockImplementation( + () => new Promise((resolve) => finish.push(() => resolve({ ...applied, dryRun: true }))) + ) + const running = Array.from({ length: 4 }, () => plan()) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + const refused = await plan() + expect(refused.status).toBe(429) + expect(refused.headers.get('Retry-After')).toBe('5') + + 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/v2/workspaces/[workspaceId]/source/plan/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts new file mode 100644 index 00000000000..211c21b8dee --- /dev/null +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts @@ -0,0 +1,86 @@ +import { + V2_PREAUTH_RATE_LIMIT_ALLOWED, + v2ApiKeyAuthModuleMock, + v2RateLimiterModuleMock, + v2RouteMocks, +} from '@sim/testing' +import { NextRequest } from 'next/server' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ plan: vi.fn() })) + +vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => v2ApiKeyAuthModuleMock) +vi.mock('@/lib/core/rate-limiter', () => v2RateLimiterModuleMock) +vi.mock('@/lib/workspace-source/application/apply-workspace-source', () => ({ + readWorkspaceSourcePlan: { operation: { id: 'workspaces.source.plan' }, execute: mocks.plan }, +})) + +import { POST } from '@/app/api/v2/workspaces/[workspaceId]/source/plan/route' + +const WORKSPACE_ID = '11111111-2222-4333-8444-555555555555' + +const auth = { + principal: { + kind: 'workspace_api_key' as const, + workspaceId: WORKSPACE_ID, + keyId: 'key-1', + access: 'read' as const, + }, + rateLimitSubjectIds: ['api-key:key-1', `workspace:${WORKSPACE_ID}`] as const, + rateLimitSubscription: null, + keyType: 'workspace' as const, +} + +const WORKFLOW = "// @sim-sdk 1\nexport default workflow('W', () => {})\n" + +/** Units each limiter key was charged. */ +const charged = new Map() + +function plan(files: Record) { + return POST( + new NextRequest(`http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/source/plan`, { + method: 'POST', + headers: { 'x-api-key': 'key', 'content-type': 'application/json' }, + body: JSON.stringify({ files, kinds: ['workflow'] }), + }), + { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) } + ) +} + +describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => { + beforeEach(() => { + charged.clear() + v2RouteMocks.authenticate.mockResolvedValue(auth) + v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) + v2RouteMocks.operationRate.mockImplementation(async (key: string, _config, cost = 1) => { + charged.set(key, (charged.get(key) ?? 0) + cost) + return { + allowed: true, + remaining: 1, + resetAt: new Date('2026-01-01T01:00:00.000Z'), + retryAfterMs: 0, + } + }) + mocks.plan.mockResolvedValue({ + workspaceId: WORKSPACE_ID, + dryRun: true, + plan: [], + applied: [], + needBlobs: [], + files: {}, + base: { version: 1, workspaceId: WORKSPACE_ID, resources: {} }, + diagnostics: [], + }) + }) + + it('charges a plan one unit per workflow folder it evaluates, as an apply is charged', async () => { + const response = await plan({ + 'workflows/a/workflow.ts': WORKFLOW, + 'workflows/b/workflow.ts': WORKFLOW, + 'workflows/c/workflow.ts': WORKFLOW, + }) + + expect(response.status).toBe(200) + expect(Math.max(...charged.values())).toBe(3) + }) +}) diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts index 1c41c1a9026..e185e8494e7 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts @@ -1,9 +1,10 @@ import { WORKSPACE_SOURCE_REQUEST_MAX_BYTES } from '@sim/workspace-code/limits' import { v2PlanWorkspaceSourceContract } from '@/lib/api/contracts/v2/workspace-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { withSourceSlot } from '@/lib/workflows/api' import { v2WorkspaceSourceErrorPolicy, - withSourceSlot, + workspaceApplyRateCost, } from '@/lib/workspace-source/api/route-policies' import { readWorkspaceSourcePlan } from '@/lib/workspace-source/application/apply-workspace-source' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' @@ -13,16 +14,17 @@ export const revalidate = 0 /** * POST /api/v2/workspaces/[workspaceId]/source/plan — what applying the submitted directory would - * do, without writing: the dry run `sim workspaces source status` reads. One unit of the - * source-read budget whatever the directory holds, so a status never spends the source-write - * budget an apply needs. A server already running as many applies as it allows answers 429. + * do, without writing: the dry run `sim workspaces source status` reads. Charged to the + * source-plan budget as an apply is to the write budget (see `workspaceApplyRateCost`), so a + * status never spends the source-write budget an apply needs. Plans run in their own slots: a + * server already running as many plans as it allows answers 429, and applies never wait on them. * Answers 403 while the `workflow-code` flag is off. */ export const POST = defineV2JsonRoute({ contract: v2PlanWorkspaceSourceContract, auth: v2ApiKeyAuth, operation: workspaceSourceOperations.plan, - rateLimit: v2RateLimits.sourceRead, + rateLimit: v2RateLimits.sourcePlan, errorPolicy: v2WorkspaceSourceErrorPolicy, parseOptions: { maxBodyBytes: WORKSPACE_SOURCE_REQUEST_MAX_BYTES }, mapInput: ({ params, body }) => ({ @@ -34,6 +36,7 @@ export const POST = defineV2JsonRoute({ ...(body.options?.only ? { only: body.options.only } : {}), ...(body.options?.allowDelete !== undefined ? { allowDelete: body.options.allowDelete } : {}), }), - useCase: withSourceSlot(readWorkspaceSourcePlan, 'apply'), + rateLimitCost: (input) => workspaceApplyRateCost(input.files, input.blobs), + useCase: withSourceSlot(readWorkspaceSourcePlan, 'plan'), present: (result) => ({ data: result }), }) 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 681a3c871dc..f61927065ff 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts @@ -4,9 +4,9 @@ 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 { v2WorkspaceSourceErrorPolicy, - withSourceSlot, workspaceApplyRateCost, } from '@/lib/workspace-source/api/route-policies' import { applyWorkspaceSource } from '@/lib/workspace-source/application/apply-workspace-source' diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts index fe285191073..d71d6f5e918 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts @@ -142,7 +142,7 @@ export const workflowSourceOpenApiRoutes = [ applicationOperation: workflowOperations.planSource, operationId: 'planWorkflowSource', summary: 'Plan workflow source', - description: `Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since \`base\` (\`E_APPLY_STALE\`), the diff, and every finding, exactly as \`dryRun=true\` reports them, with \`200\`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so \`sim workflows source status\` never spends what an apply needs. \`allowDelete=true\` plans block deletes instead of reporting \`E_APPLY_BLOCK_DELETE\`. Returns \`403\` while workflows as code is not enabled. ${WORKSPACE_API_KEY_DENIED}`, + description: `Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since \`base\` (\`E_APPLY_STALE\`), the diff, and every finding, exactly as \`dryRun=true\` reports them, with \`200\`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers \`429\`), and records no audit or analytics event, so \`sim workflows source status\` never spends what an apply needs. \`allowDelete=true\` plans block deletes instead of reporting \`E_APPLY_BLOCK_DELETE\`. Returns \`403\` while workflows as code is not enabled. ${WORKSPACE_API_KEY_DENIED}`, tags: ['Workflows'], errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'], success: { description: 'The evaluated source.', headers: RATE_LIMIT_HEADERS }, 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 d40dc84fca5..796a7bf60ea 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workspace-source.ts @@ -157,7 +157,7 @@ export const workspaceSourceOpenApiRoutes = [ operationId: 'planWorkspaceSource', summary: 'Plan workspace source', description: - 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.', + 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws on the source-plan budget, one unit per workflow folder it evaluates as an apply does, takes no apply lease or apply slot and records no audit event, so `sim workspaces source status` never spends the source-write budget or holds up an apply. A server already running as many plans as it allows answers `429`. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.', tags: ['Workflows'], errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'], success: { description: 'The planned changes.', headers: RATE_LIMIT_HEADERS }, diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 430638b669d..a1edd7d0eaa 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -2485,7 +2485,7 @@ export const V2_MCP_OPERATIONS = { contract: v2PlanWorkflowSourceContract, summary: 'Plan workflow source', description: - 'Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the generic API budget rather than the source-write budget, and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', + 'Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/workflows/[workflowId]/source/plan/route').then((route) => route.POST), @@ -2494,7 +2494,7 @@ export const V2_MCP_OPERATIONS = { contract: v2PlanWorkspaceSourceContract, summary: 'Plan workspace source', description: - 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws one unit of the source-read budget whatever the directory holds, takes no apply lease and records no audit event, so `sim workspaces source status` never spends the source-write budget. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.', + 'Report what Apply Workspace Source would do with this directory, without writing: every planned change and finding, exactly as `dryRun=true` reports them (a resource changed on the server since the directory was read included). A read: it needs only workspace read access, draws on the source-plan budget, one unit per workflow folder it evaluates as an apply does, takes no apply lease or apply slot and records no audit event, so `sim workspaces source status` never spends the source-write budget or holds up an apply. A server already running as many plans as it allows answers `429`. Each change is still checked by the operation that owns it, so a change the caller may not write is reported as refused. The body is an apply body without `provenance`. Returns `403` while workflows as code is not enabled.\n\nOAuth scope: `api:read`.', handler: () => import('@/app/api/v2/workspaces/[workspaceId]/source/plan/route').then((route) => route.POST), }, 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 adbc0f3d670..dee705ef039 100644 --- a/apps/sim/lib/api/server/routes/v2-json-route.ts +++ b/apps/sim/lib/api/server/routes/v2-json-route.ts @@ -183,6 +183,18 @@ const V2_SOURCE_READ_RATE_LIMIT: TokenBucketConfig = { refillIntervalMs: 60_000, } +/** + * Planning source (`sim workflows source status`, `sim workspaces source status`): a plan runs + * the apply's whole pipeline without writing, so it is charged like one, one unit per workflow it + * evaluates, on a bucket of its own so a status loop never spends the write budget an apply needs + * and never runs at the generic budget's rate. + */ +const V2_SOURCE_PLAN_RATE_LIMIT: TokenBucketConfig = { + maxTokens: 60, + refillRate: 30, + refillIntervalMs: 60_000, +} + /** * Staging the binary files of a workspace source apply: each request carries up to 24 MB, so a * 1 GB directory stages in about 45 requests. Its own bucket, so staging never spends the @@ -224,6 +236,13 @@ export const v2RateLimits = { return enforceV2Buckets(request, auth, 'workspaces.source.read', V2_SOURCE_READ_RATE_LIMIT, 1) }, } satisfies V2RateLimitPolicy, + /** {@link V2_SOURCE_PLAN_RATE_LIMIT}, one bucket shared by workflow and workspace plans. */ + sourcePlan: { + maxCost: V2_SOURCE_PLAN_RATE_LIMIT.maxTokens, + async enforce(request, auth, _operation, cost = 1) { + return enforceV2Buckets(request, auth, 'source.plan', V2_SOURCE_PLAN_RATE_LIMIT, cost) + }, + } satisfies V2RateLimitPolicy, /** {@link V2_SOURCE_BLOB_STAGE_RATE_LIMIT}, shared by staging and asking what is staged. */ sourceBlobStage: { async enforce(request, auth) { diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 15fb042b55a..3c1075f5b02 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -7,6 +7,7 @@ export { v2WorkflowErrorPolicies, WORKFLOW_NOT_FOUND_MESSAGE, } from '@/lib/workflows/api/route-policies' +export { renderSourceSlotBusy, withSourceSlot } from '@/lib/workflows/api/source-slots' export { presentV2WorkflowTrigger, presentV2WorkspaceSchedule, diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index 2374689ba77..90f207b9237 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -23,6 +23,7 @@ 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 { WORKFLOW_DELEGATION_AUDIENCE } from '@/lib/workflows/application/authorization' import { WorkflowImportError } from '@/lib/workflows/application/import-error' import { WorkflowOperationsNotAppliedError } from '@/lib/workflows/application/operations-error' @@ -79,11 +80,14 @@ export const v2WorkflowErrorPolicies = { * diagnostics, stale * source answers `409` with the current fingerprint, and a source rename onto * a name taken meanwhile answers `409` with `SOURCE_NAME_TAKEN`, so a pipeline - * can act on each without a second request. + * can act on each without a second request. A source plan refused for want of a + * slot answers `429` with `Retry-After`. */ concealWorkflowGraphAuthorization: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workflow not found', render(error) { + const busy = renderSourceSlotBusy(error) + if (busy) return busy if (error instanceof WorkflowOperationsNotAppliedError) { return v2ErrorForOrchestration(error.code, error.message, { code: 'OPERATIONS_NOT_APPLIED', diff --git a/apps/sim/lib/workspace-source/api/route-policies.test.ts b/apps/sim/lib/workflows/api/source-slots.test.ts similarity index 65% rename from apps/sim/lib/workspace-source/api/route-policies.test.ts rename to apps/sim/lib/workflows/api/source-slots.test.ts index 07bb9c33ebd..c6adeeb88cd 100644 --- a/apps/sim/lib/workspace-source/api/route-policies.test.ts +++ b/apps/sim/lib/workflows/api/source-slots.test.ts @@ -4,15 +4,12 @@ import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' import { generateId } from '@sim/utils/id' import { describe, expect, it } from 'vitest' -import { - v2WorkspaceSourceErrorPolicy, - withSourceSlot, -} from '@/lib/workspace-source/api/route-policies' +import { renderSourceSlotBusy, withSourceSlot } from '@/lib/workflows/api/source-slots' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' const principal = createSessionPrincipal({ userId: generateId(), sessionId: generateId() }) -/** A source use case whose every run waits until `finish` is called. */ +/** A source use case whose every run waits until `finishOne` is called. */ function blockingUseCase() { const waiting: Array<() => void> = [] const useCase = { @@ -34,7 +31,7 @@ async function refusalOf(run: Promise) { () => null, (caught: unknown) => caught ) - return v2WorkspaceSourceErrorPolicy.render(error) + return renderSourceSlotBusy(error) } describe('withSourceSlot', () => { @@ -60,4 +57,20 @@ describe('withSourceSlot', () => { for (let finished = 0; finished < 4; finished += 1) applies.finishOne() await expect(Promise.all([...running, admitted])).resolves.toHaveLength(5) }) + + it('runs plans in slots of their own: never in an apply’s, and never past their own cap', async () => { + const plans = blockingUseCase() + const plan = withSourceSlot(plans.useCase, 'plan') + const applies = blockingUseCase() + const apply = withSourceSlot(applies.useCase, 'apply') + const planning = Array.from({ length: 4 }, () => plan.execute({ principal, input: {} })) + + expect((await refusalOf(plan.execute({ principal, input: {} })))?.status).toBe(429) + const applying = Array.from({ length: 4 }, () => apply.execute({ principal, input: {} })) + for (let finished = 0; finished < 4; finished += 1) applies.finishOne() + await expect(Promise.all(applying)).resolves.toHaveLength(4) + + for (let finished = 0; finished < 4; finished += 1) plans.finishOne() + await expect(Promise.all(planning)).resolves.toHaveLength(4) + }) }) diff --git a/apps/sim/lib/workflows/api/source-slots.ts b/apps/sim/lib/workflows/api/source-slots.ts new file mode 100644 index 00000000000..96d64e605b9 --- /dev/null +++ b/apps/sim/lib/workflows/api/source-slots.ts @@ -0,0 +1,62 @@ +import type { NextResponse } from 'next/server' +import type { ApplicationOperation, AuthorizingUseCase } from '@/lib/core/application' +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. + */ +const MAX_CONCURRENT_SOURCE_REQUESTS = { read: 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 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 + +/** A source request refused because this process already runs as many as it may. */ +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.name = 'SourceSlotBusyError' + } +} + +/** + * `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 + * {@link MAX_CONCURRENT_SOURCE_REQUESTS} of them, so a burst cannot run the process out of memory. + */ +export function withSourceSlot( + useCase: AuthorizingUseCase, + lane: SourceLane +): AuthorizingUseCase { + return { + ...useCase, + async execute(args) { + if (runningSourceRequests[lane] >= MAX_CONCURRENT_SOURCE_REQUESTS[lane]) { + throw new SourceSlotBusyError(lane) + } + runningSourceRequests[lane] += 1 + try { + return await useCase.execute(args) + } finally { + runningSourceRequests[lane] -= 1 + } + }, + } +} + +/** 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) }, + }) +} diff --git a/apps/sim/lib/workspace-source/api/route-policies.ts b/apps/sim/lib/workspace-source/api/route-policies.ts index ca9dfc24e18..a30b6d5cc0b 100644 --- a/apps/sim/lib/workspace-source/api/route-policies.ts +++ b/apps/sim/lib/workspace-source/api/route-policies.ts @@ -6,61 +6,11 @@ import { workflowCodec, workflowFolder } from '@sim/workspace-code/kinds/workflo import { kindOfPath } from '@sim/workspace-code/layout' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { createV2ResourceConcealmentPolicy } from '@/lib/api/server/routes' -import type { ApplicationOperation, AuthorizingUseCase } from '@/lib/core/application' +import { renderSourceSlotBusy } from '@/lib/workflows/api/source-slots' import { WorkspaceSourceRejectedError } from '@/lib/workspace-source/application/errors' import { WorkspaceSourceBusyError } from '@/lib/workspace-source/lease/store' import { SourceStagingFullError } from '@/lib/workspace-source/staging/store' -import { - v2CaughtOrchestrationError, - v2Error, - v2ErrorForOrchestration, -} from '@/app/api/v2/lib/response' - -/** Workspace source requests of one lane this server process runs at once. */ -const MAX_CONCURRENT_SOURCE_REQUESTS = { read: 4, apply: 4 } as const - -type SourceLane = keyof typeof MAX_CONCURRENT_SOURCE_REQUESTS - -const runningSourceRequests: Record = { read: 0, apply: 0 } - -/** Seconds a request refused for want of a slot is told to wait. */ -const SOURCE_BUSY_RETRY_AFTER_SECONDS = 5 - -/** A workspace source request refused because this process already runs as many as it may. */ -class SourceSlotBusyError extends Error { - constructor(readonly lane: SourceLane) { - super( - `This server is already running ${MAX_CONCURRENT_SOURCE_REQUESTS[lane]} workspace source ${lane === 'read' ? 'gets' : 'applies'}; retry shortly.` - ) - this.name = 'SourceSlotBusyError' - } -} - -/** - * `useCase`, run in one of its lane's slots: a get or an apply (each holds a directory's worth of - * text, stored state and canonical forms in memory) waits for nothing, and is refused with - * {@link SourceSlotBusyError} (`429` with `Retry-After`) 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 -): AuthorizingUseCase { - return { - ...useCase, - async execute(args) { - if (runningSourceRequests[lane] >= MAX_CONCURRENT_SOURCE_REQUESTS[lane]) { - throw new SourceSlotBusyError(lane) - } - runningSourceRequests[lane] += 1 - try { - return await useCase.execute(args) - } finally { - runningSourceRequests[lane] -= 1 - } - }, - } -} +import { v2CaughtOrchestrationError, v2ErrorForOrchestration } from '@/app/api/v2/lib/response' /** * Workspace source routes conceal an unreachable workspace as absent. A refused apply answers its @@ -73,11 +23,8 @@ export function withSourceSlot( export const v2WorkspaceSourceErrorPolicy = createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workspace not found', render(error) { - if (error instanceof SourceSlotBusyError) { - return v2Error('RATE_LIMITED', error.message, { - headers: { 'Retry-After': String(SOURCE_BUSY_RETRY_AFTER_SECONDS) }, - }) - } + const busy = renderSourceSlotBusy(error) + if (busy) return busy if (error instanceof WorkspaceSourceRejectedError) { return v2ErrorForOrchestration(error.code, error.message, { code: error.stale ? 'SOURCE_STALE' : 'SOURCE_REJECTED', From 69bbe902f3957e6da0f2893c38fcb8366baeff36 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 19 Nov 2026 23:58:28 -0800 Subject: [PATCH 052/104] fix(api): judge a provenance repo's credentials by parsing it carriesCredentials matched one regex shape, so a leading space, a git+https user, a query-string token or a slash inside the userinfo slipped a token into the audit log. It now refuses whitespace and control characters, parses scheme URLs (refusing an unparsable one, a query, a password, or any user on an HTTP(S) transport) and refuses an scp-style address whose user holds a password. --- .../[workflowId]/source/route.test.ts | 34 +++++++++++++++++++ .../lib/api/contracts/v2/workflow-source.ts | 23 ++++++++++--- 2 files changed, 52 insertions(+), 5 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 d2aecd7a517..7439d86e380 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 @@ -255,6 +255,40 @@ describe('POST /api/v2/workflows/{workflowId}/source', () => { expect(mocks.apply).not.toHaveBeenCalled() }) + it('refuses a provenance repo carrying credentials in any form before applying, so none reaches the audit log', async () => { + const credentialed = [ + 'https://x-access-token:ghp_x@github.com/a/b.git', + 'https://ghp_x@github.com/a/b.git', + ' https://ghp_x@github.com/a/b.git', + '\thttps://ghp_x@github.com/a/b.git', + 'git+https://ghp_x@github.com/a/b.git', + 'https://github.com/a/b.git?access_token=ghp_x', + 'https://u:pa/ss@github.com/a/b.git', + 'ssh://git:secret@github.com/a/b.git', + 'user:secret@github.com:a/b.git', + ] + for (const repo of credentialed) { + const response = await POST( + applyRequest({ ...applyBody, provenance: { client: 'cli', repo } }), + context + ) + expect({ repo, status: response.status }).toEqual({ repo, status: 400 }) + } + expect(mocks.apply).not.toHaveBeenCalled() + + for (const repo of [ + 'https://github.com/a/b.git', + 'ssh://git@github.com/a/b.git', + 'git@github.com:a/b.git', + ]) { + const response = await POST( + applyRequest({ ...applyBody, provenance: { client: 'cli', repo } }), + context + ) + expect({ repo, status: response.status }).toEqual({ repo, status: 200 }) + } + }) + it('passes x- extension fields on the lock, its blocks and their layout through to apply', async () => { const lock = { ...source.lock, diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 4814ad729e7..2beff33b588 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -66,11 +66,24 @@ const sourceFilesSchema = z `Relative path → file text: \`workflow.ts\` plus every function-code file it references (for example \`functions/score.js\`). At most ${SOURCE_LIMITS.maxFiles} files and ${SOURCE_LIMITS.maxTotalBytes} bytes together, for a workflow of at most ${SOURCE_LIMITS.maxBlocks} blocks.` ) -/** Whether a repository URL carries credentials: any user in an `http(s)` URL, or a password. */ +/** + * Whether a repository address carries credentials, judged by parsing it rather than matching + * one shape: a URL (`scheme://…`) that does not parse, holds a query, a password, or any user + * on an HTTP(S) transport (`git+https://token@…` included); or an scp-style address + * (`user@host:path`) whose user holds a password. Whitespace and control characters are refused + * outright, so no padding hides the address from the parser. + */ function carriesCredentials(repo: string): boolean { - const userinfo = /^([a-z][a-z0-9+.-]*):\/\/([^/@]*)@/i.exec(repo) - if (!userinfo) return false - return /^https?$/i.test(userinfo[1]) || userinfo[2].includes(':') + if (/[\s\p{Cc}]/u.test(repo)) return true + if (!repo.includes('://')) return repo.includes('?') || /^[^@/]*:[^@/]*@/.test(repo) + let url: URL + try { + url = new URL(repo) + } catch { + return true + } + if (url.password !== '' || url.search !== '') return true + return url.username !== '' && /(^|\+)https?:$/i.test(url.protocol) } /** `provenance.repo`: the repository a source or directory was taken from, never with credentials. */ @@ -80,7 +93,7 @@ export const provenanceRepoSchema = z .max(512, 'provenance.repo is too long') .refine((repo) => !carriesCredentials(repo), { message: - 'provenance.repo must not carry credentials: send the URL without its user and password', + 'provenance.repo must not carry credentials: send the URL without its user, password and query', }) .describe('The repository the source was taken from (its remote URL); recorded in the audit log.') From 05b2fa76704e32fa3ec1651aac2022d39192dfe5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:13:58 -0800 Subject: [PATCH 053/104] fix(workflow-code): one refusal decision for the apply and the offline check The server's three refusal passes and the CLI's editedRefusal chain decided the same thing four ways and had drifted: check refused x.error and undeclared start inputs the server keeps, the server refused an out-of-scope read in an unedited code file of a changed block that check passed, --no-strict exempted a refusal the server makes regardless, and the per-code warning cap could hide a refusable finding from both. refuseEditedFindings (packages/workflow-code/src/diagnostics/refusals.ts) is now the one rule. Given a compile and what the edit changed, it raises W_REF_OUT_OF_SCOPE on a changed block (any file), W_UNKNOWN_OUTPUT_PATH in workflow.ts on a changed block, and W_UNRESOLVED_REF and W_CODE_FILE_REF_SYNTAX in an edited code file. The server's evaluation and checkWorkflowDir both call it. The compile keeps one of each refusable code, block and file a cap leaves out (CompileResult.withheld), so caps only shape the listing. A path the run may still resolve, an input the start does not declare or x.error with no error edge, is its own code, W_OUTPUT_PATH_UNDECLARED, which is never refused, so the server no longer needs its lint to confirm an entry reference. The iteration-scope walk lives once, in readsIterationOutOfScope; the lint calls it for editor and Copilot edits and a source apply turns it off, so no finding is told apart by a reason prefix any more. A check compares block digests only when the catalog the source was printed with is cached, preferring a warning to a refusal the server would not make. Also files W_CODE_FILE_REF_SYNTAX with the code-file codes, drops the dead W_UNRESOLVED_REF entry of the workflow.ts table, and puts checkLiteralRefs' orphaned TSDoc back on it. --- apps/docs/content/docs/cli/reference.mdx | 8 +- apps/docs/content/docs/cli/workflows.mdx | 4 +- apps/docs/content/docs/cli/workspaces.mdx | 4 +- apps/docs/openapi-v2-workflows.json | 27 ++- .../apply-workflow-source.integration.ts | 37 +++ .../workflows/application/source-evaluate.ts | 220 ++++-------------- .../workflows/editing/dangling-refs.test.ts | 6 +- apps/sim/lib/workflows/editing/lint-report.ts | 7 +- apps/sim/lib/workflows/editing/lint.ts | 78 +++---- .../protocol/workflow-source-check.test.ts | 42 +++- .../protocol/workflow-source-check.ts | 113 ++++----- .../commands/protocol/workflow-source-get.ts | 2 +- packages/sim-cli/src/generated/v2-api.ts | 27 ++- packages/workflow-code/src/compile/SYNTAX.md | 12 +- .../workflow-code/src/compile/checks.test.ts | 12 +- .../workflow-code/src/compile/grammar.test.ts | 2 +- packages/workflow-code/src/compile/index.ts | 14 +- packages/workflow-code/src/compile/report.ts | 57 ++++- packages/workflow-code/src/compile/values.ts | 56 ++--- .../workflow-code/src/diagnostics/codes.ts | 47 ++-- .../src/diagnostics/refusals.test.ts | 109 +++++++++ .../workflow-code/src/diagnostics/refusals.ts | 131 +++++++++++ packages/workflow-code/src/index.ts | 8 +- packages/workflow-code/src/iteration-scope.ts | 54 +++++ 24 files changed, 677 insertions(+), 400 deletions(-) create mode 100644 packages/workflow-code/src/diagnostics/refusals.test.ts create mode 100644 packages/workflow-code/src/diagnostics/refusals.ts create mode 100644 packages/workflow-code/src/iteration-scope.ts diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index a9a19b587cc..8154355dadb 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8632,7 +8632,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. | +| `--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). | @@ -8641,7 +8641,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -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. | +| `--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). | @@ -10019,7 +10019,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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). 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index e6c6a16dea1..8473f3cd48b 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1436,7 +1436,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. | +| `--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). | @@ -1445,7 +1445,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 6a60ac84c57..98d9c078037 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -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. | +| `--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). | @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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 a function file changed since the get, W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE, W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in every mode, as the server refuses it; so is W_REF_OUT_OF_SCOPE (E_APPLY_REF_OUT_OF_SCOPE) on a block the source moved into another container. In workflow.ts, W_UNKNOWN_OUTPUT_PATH, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE are the error E_APPLY_UNRESOLVED_REF, E_APPLY_REF_OUT_OF_SCOPE on a block the edit added or changed, as the server refuses them there (not with --no-strict). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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). 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. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index f76b52e4fc1..f7e065f599b 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -19176,7 +19176,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19210,10 +19209,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -19626,7 +19627,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -19660,10 +19660,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -20593,7 +20595,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -20627,10 +20628,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -21536,7 +21539,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -21570,10 +21572,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -26589,7 +26593,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -26623,10 +26626,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -27165,7 +27170,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -27199,10 +27203,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -27584,7 +27590,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -27618,10 +27623,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -28449,7 +28456,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -28483,10 +28489,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", @@ -28868,7 +28876,6 @@ "W_REF_NOT_NORMALIZED", "E_REF_UNREPRESENTABLE", "W_REF_OUT_OF_SCOPE", - "W_CODE_FILE_REF_SYNTAX", "E_EDGE_SCOPE", "E_EDGE_NOTE", "E_TARGET_TRIGGER", @@ -28902,10 +28909,12 @@ "W_LITERAL_SECRET", "W_SUBFLOW_COUNT", "W_UNKNOWN_OUTPUT_PATH", + "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", + "W_CODE_FILE_REF_SYNTAX", "W_UNRESOLVED_REF", "W_FORWARD_REF_LITERALIZED", "W_COMMENT_MOVED", 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 be4ffda675c..6ec74a3e98e 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2750,6 +2750,43 @@ describe('renames in source', () => { } ) + check( + 'refuses every edited Python file holding a $ref, however many the compile lists of that code', + async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + // More of one code than a compile lists, so the second file's are all left out of the listing. + const refs = Array.from({ length: 120 }, (_, i) => `v${i} = $ref.start.v${i}`) + const entry = source.files['workflow.ts'] + .replace( + /fn\('Boom', \{.*\}\)/, + "fn('Boom', { language: 'python', code: codeFile('./functions/boom.py') })" + ) + .replace( + /fn\('Tally', \{.*\}\)/, + "fn('Tally', { language: 'python', code: codeFile('./functions/tally.py') })" + ) + const files = { + ...omit(source.files, ['functions/boom.js', 'functions/tally.js']), + 'workflow.ts': entry, + 'functions/boom.py': refs.join('\n'), + 'functions/tally.py': refs.join('\n'), + } + + const dryRun = await apply(source, files, { dryRun: true }) + + expect( + [ + ...new Set( + dryRun.diagnostics + .filter((d) => d.code === 'E_APPLY_CODE_FILE_REF_SYNTAX') + .map((d) => d.file) + ), + ].sort() + ).toEqual(['functions/boom.py', 'functions/tally.py']) + } + ) + check( 'a dangling reference the stored code already holds stays a warning, whatever else the apply changes', async () => { diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 9b735317d0b..a7d9177ad0f 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -13,7 +13,6 @@ import { compileWorkflow, type Diagnostic, diffCanonical, - EDITED_CODE_FILE_REFUSALS, encodeAnchor, getOwn, type LocatedDiagnostic, @@ -23,6 +22,7 @@ import { parseWorkflowLock, type ResourceKeyResolver, type ResourceKind, + refuseEditedFindings, renamesBetween, replacedBetween, type SourceBase, @@ -67,11 +67,10 @@ import type { StoredSource } from '@/lib/workflows/code/print-stored' import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workflows/code/resources' import { mergeSourceMetaFromLock } from '@/lib/workflows/code/source-lock' import type { StoredCanonical } from '@/lib/workflows/code/stored-canonical' -import { - isIterationScopeFinding, - type WorkflowLintReport, - type WorkflowLintTableSchema, - type WorkflowLintUnresolvedReference, +import type { + WorkflowLintReport, + WorkflowLintTableSchema, + WorkflowLintUnresolvedReference, } from '@/lib/workflows/editing/lint' import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' import { workflowNameExistsInFolder } from '@/lib/workflows/orchestration' @@ -243,36 +242,35 @@ function withoutPendingReferences( } /** - * `lint` without the block-output references compile already reported in a function's code - * file (`W_UNRESOLVED_REF`, or `E_APPLY_UNRESOLVED_REF` on code the edit changed, on that block, - * located at the file line): the same dangling `$ref` is one finding there, as an offline check - * reports it, not also a lint finding on the `codeFile()` call. + * `lint` without the block-output findings compile already reported at their source line, so a + * dangling reference is one finding, as an offline check reports it: on a block whose + * `workflow.ts` reads a path no output has (`W_UNKNOWN_OUTPUT_PATH`, or its refusal), every + * block-output finding; on a block whose code file `$ref` names nothing (`W_UNRESOLVED_REF`, or + * its refusal), the one on its code. */ -function withoutCodeFileReferences( +function withoutCompiledReferences( lint: WorkflowLintReport, compiled: readonly LocatedDiagnostic[], keyOf: (id: string) => string | undefined ): WorkflowLintReport { - const reported = new Set( - compiled.flatMap((diagnostic) => - (diagnostic.code === 'W_UNRESOLVED_REF' || diagnostic.code === 'E_APPLY_UNRESOLVED_REF') && - diagnostic.blockKey !== undefined && - diagnostic.span.file !== SOURCE_ENTRY_FILE - ? [diagnostic.blockKey] - : [] - ) - ) - if (reported.size === 0) return lint + const inEntry = new Set() + const inCode = new Set() + for (const { code, blockKey, span } of compiled) { + if (blockKey === undefined) continue + if (span.file === SOURCE_ENTRY_FILE) { + if (code === 'W_UNKNOWN_OUTPUT_PATH' || code === 'E_APPLY_UNRESOLVED_REF') + inEntry.add(blockKey) + } else if (code === 'W_UNRESOLVED_REF' || code === 'E_APPLY_UNRESOLVED_REF') { + inCode.add(blockKey) + } + } + if (inEntry.size === 0 && inCode.size === 0) return lint return { ...lint, unresolvedReferences: lint.unresolvedReferences.filter((reference) => { const key = keyOf(reference.blockId) - return !( - reference.kind === 'block-output' && - reference.field === 'code' && - key !== undefined && - reported.has(key) - ) + if (reference.kind !== 'block-output' || key === undefined) return true + return !inEntry.has(key) && !(reference.field === 'code' && inCode.has(key)) }), } } @@ -294,131 +292,22 @@ const RENAME_SETTLED_CODES: ReadonlySet = new Set([ * a finding stays only where that compile still reports it. */ function withoutRenameSettledFindings( - diagnostics: CompileResult['diagnostics'], + compiled: Pick, renames: ReadonlyMap, recompile: () => CompileResult -): CompileResult['diagnostics'] { - if (renames.size === 0 || !diagnostics.some((d) => RENAME_SETTLED_CODES.has(d.code))) { - return diagnostics +): Pick { + const settles = (d: CompileResult['diagnostics'][number]) => RENAME_SETTLED_CODES.has(d.code) + if (renames.size === 0 || ![...compiled.diagnostics, ...compiled.withheld].some(settles)) { + return compiled } const at = (d: CompileResult['diagnostics'][number]) => `${d.code}@${d.span.file}:${d.span.line}:${d.span.column}` - const still = new Set( - recompile() - .diagnostics.filter((d) => RENAME_SETTLED_CODES.has(d.code)) - .map(at) - ) - return diagnostics.filter((d) => !RENAME_SETTLED_CODES.has(d.code) || still.has(at(d))) -} - -/** - * `diagnostics` with each function code file finding of {@link EDITED_CODE_FILE_REFUSALS} on a - * block whose code the source changed (`codeChanged`, by block key) refused under its error code: - * a `$ref` naming no block, a `$ref` in a Python file, fail at run time. On code the stored - * workflow already holds it stays a warning, so a workflow saved with one still applies unchanged. - */ -function withEditedCodeFileRefsRefused( - diagnostics: CompileResult['diagnostics'], - codeChanged: (blockKey: string) => boolean -): LocatedDiagnostic[] { - return diagnostics.map((diagnostic): LocatedDiagnostic => { - const refusal = EDITED_CODE_FILE_REFUSALS.get(diagnostic.code) - if ( - refusal === undefined || - diagnostic.span.file === SOURCE_ENTRY_FILE || - diagnostic.blockKey === undefined || - !codeChanged(diagnostic.blockKey) - ) { - return diagnostic - } - return { ...diagnostic, code: refusal, severity: 'error' } - }) -} - -/** - * The apply's handling of compile's `W_REF_OUT_OF_SCOPE`, an iteration field read from outside - * its container: refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the write adds, changes or - * moves (`changed`, by block key), which would fail at run time (a code file the edit changed - * already refused it); a warning on a block the stored workflow already holds as it is, so such a - * workflow still applies unchanged. The lint's finding for the same block is dropped from `lint`, - * as compile's is the one located at the source line. - */ -function withOutOfScopeRefsRefused( - diagnostics: readonly LocatedDiagnostic[], - lint: WorkflowLintReport, - changed: (blockKey: string) => boolean, - keyOf: (id: string) => string | undefined -): { diagnostics: LocatedDiagnostic[]; lint: WorkflowLintReport } { - const reported = new Set() - const refused = diagnostics.map((diagnostic): LocatedDiagnostic => { - const scoped = - diagnostic.code === 'W_REF_OUT_OF_SCOPE' || diagnostic.code === 'E_APPLY_REF_OUT_OF_SCOPE' - if (!scoped || diagnostic.blockKey === undefined) return diagnostic - reported.add(diagnostic.blockKey) - return diagnostic.code === 'W_REF_OUT_OF_SCOPE' && changed(diagnostic.blockKey) - ? { ...diagnostic, code: 'E_APPLY_REF_OUT_OF_SCOPE', severity: 'error' } - : diagnostic - }) - if (reported.size === 0) return { diagnostics: refused, lint } - return { - diagnostics: refused, - lint: { - ...lint, - unresolvedReferences: lint.unresolvedReferences.filter((reference) => { - const key = keyOf(reference.blockId) - return !(isIterationScopeFinding(reference) && key !== undefined && reported.has(key)) - }), - }, - } -} - -/** Compile findings of a reference in the entry file to an output or block that does not exist. */ -const ENTRY_REF_CODES: ReadonlySet = new Set(['W_UNKNOWN_OUTPUT_PATH', 'W_UNRESOLVED_REF']) - -/** - * One finding per dangling reference in the entry file, in the vocabulary an offline check uses. - * Compile reports such a reference at its line (`W_UNKNOWN_OUTPUT_PATH`, `W_UNRESOLVED_REF`), and - * the lint reports the same one again on the whole block, refusing it (`E_APPLY_LINT`) on a block - * this apply adds or changes (`changed`, by block key). So the lint's block-output finding on a - * block compile already reported one for is dropped, and where the lint would have refused it, - * compile's finding is the refusal instead: `E_APPLY_UNRESOLVED_REF`, located at the reference. - */ -function withEntryRefsDeduplicated( - diagnostics: LocatedDiagnostic[], - lint: WorkflowLintReport, - changed: ReadonlySet, - keyOf: (id: string) => string | undefined -): { diagnostics: LocatedDiagnostic[]; lint: WorkflowLintReport } { - const reported = new Set( - diagnostics.flatMap((diagnostic) => - ENTRY_REF_CODES.has(diagnostic.code) && - diagnostic.blockKey !== undefined && - diagnostic.span.file === SOURCE_ENTRY_FILE - ? [diagnostic.blockKey] - : [] - ) - ) - if (reported.size === 0) return { diagnostics, lint } - const refused = new Set() - const unresolvedReferences = lint.unresolvedReferences.filter((reference) => { - const key = keyOf(reference.blockId) - if (reference.kind !== 'block-output' || key === undefined || !reported.has(key)) return true - if (changed.has(reference.blockId)) refused.add(key) - return false - }) + const again = recompile() + const still = new Set([...again.diagnostics, ...again.withheld].filter(settles).map(at)) + const kept = (d: CompileResult['diagnostics'][number]) => !settles(d) || still.has(at(d)) return { - lint: { ...lint, unresolvedReferences }, - diagnostics: diagnostics.map((diagnostic): LocatedDiagnostic => { - if ( - !ENTRY_REF_CODES.has(diagnostic.code) || - diagnostic.span.file !== SOURCE_ENTRY_FILE || - diagnostic.blockKey === undefined || - !refused.has(diagnostic.blockKey) - ) { - return diagnostic - } - return { ...diagnostic, code: 'E_APPLY_UNRESOLVED_REF', severity: 'error' } - }), + diagnostics: compiled.diagnostics.filter(kept), + withheld: compiled.withheld.filter(kept), } } @@ -891,15 +780,13 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise - compileWorkflow({ ...compileInput, stored: compiled.stored, renamedKeys }) - ), - (key) => { - const compiledBlock = getOwn(compiledWorkflow.blocks, key) - return !isEqual(compiledBlock && getOwn(compiledBlock.params, 'code'), storedCode(key)) - } + const compileFindings = withoutRenameSettledFindings(compiled, renamedKeys, () => + compileWorkflow({ ...compileInput, stored: compiled.stored, renamedKeys }) ) + const codeEdited = (key: string) => { + const compiledBlock = getOwn(compiledWorkflow.blocks, key) + return !isEqual(compiledBlock && getOwn(compiledBlock.params, 'code'), storedCode(key)) + } const sourceRefusals: Diagnostic[] = [] const headerSpan = compiled.spans[encodeAnchor({ kind: 'header' })] /** Where a finding about the workflow itself points: the field it names, else the name. */ @@ -1032,25 +919,18 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise m.id)]) const changedKeys = new Set([...changedIds].flatMap((id) => keyById.get(id) ?? [])) const keyOfId = (id: string) => keyById.get(id) - const scoped = withOutOfScopeRefsRefused( + const compileDiagnostics = refuseEditedFindings(compileFindings, { + changed: (key) => changedKeys.has(key), + codeEdited, + }) + const compiledLint = withoutCompiledReferences( + withoutPendingReferences(lint, input.pendingResources ?? []), compileDiagnostics, - lint, - (key) => changedKeys.has(key), - keyOfId - ) - const entryRefs = withEntryRefsDeduplicated( - scoped.diagnostics, - withoutCodeFileReferences( - withoutPendingReferences(scoped.lint, input.pendingResources ?? []), - compileDiagnostics, - keyOfId - ), - changedIds, keyOfId ) const foreignIds = await foreignResourceRefusals({ @@ -1061,13 +941,13 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise { field: 'code', value: ['', ''], }) - expect(isIterationScopeFinding(findings[0])).toBe(true) }) it('ignores non-reference angle text (Slack links, comparisons, bare tags)', () => { diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index bc976f664b9..a0fa196628d 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -101,6 +101,11 @@ interface WorkflowLintReportOptions extends AgentToolReferenceValidationOptions * (a workspace source apply's dry run): they stand in for the stored schema. */ declaredTables?: ReadonlyMap + /** + * `false` leaves out the iteration-scope check, for a caller whose compile reports it at the + * source line (a source apply). + */ + iterationScope?: boolean } /** @@ -164,7 +169,7 @@ export async function buildWorkflowLintReport( // do not fail loudly (API bodies, agent prompts), and an unquoted string // reference makes a JSON field unparseable only once the block runs. unresolvedReferences.push( - ...collectDanglingBlockOutputReferences(graph), + ...collectDanglingBlockOutputReferences(graph, { iterationScope: options.iterationScope }), ...collectUnquotedJsonStringReferences(graph) ) diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index 732de92cf7d..d5b54b4de15 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -1,6 +1,6 @@ import { toRecordOrNull } from '@sim/utils/object' import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' -import { didYouMean, LOOP_PROPERTIES, PARALLEL_PROPERTIES } from '@sim/workflow-code' +import { didYouMean, readsIterationOutOfScope, type ScopeNode } from '@sim/workflow-code' import type { CanonicalModeOverrides } from '@sim/workflow-code/catalog/canonical-index' import { MCP_STRUCTURED_CONTENT_OUTPUT } from '@/lib/mcp/output-schema' import { @@ -857,63 +857,45 @@ function referenceTarget( return targetByKey.get(head) ?? targetByKey.get(normalizeName(head)) ?? null } -/** The iteration fields each container type exposes only to the blocks inside it. */ -const ITERATION_FIELDS: Readonly> = { - loop: LOOP_PROPERTIES, - parallel: PARALLEL_PROPERTIES, -} - -/** How an iteration-scope finding's reason starts, so a caller can tell it from the others. */ -const OUT_OF_SCOPE_REASON = 'out-of-scope:' - -/** - * The containers whose iteration fields `blockId` reads at run time: itself when it is one (a - * while condition reads ``), then each enclosing one, innermost first. - */ -function iterationScopeIds(blocks: Record, blockId: string): string[] { - const scopes: string[] = [] - const seen = new Set() - let id: string | undefined = blockId - while (id !== undefined && !seen.has(id)) { - seen.add(id) - const block: BlockState | undefined = blocks[id] - if (block?.type && Object.hasOwn(ITERATION_FIELDS, block.type)) scopes.push(id) - const parentId: unknown = block?.data?.parentId - id = typeof parentId === 'string' && parentId.length > 0 ? parentId : undefined +/** A block of the graph as the shared iteration-scope rule reads it. */ +function scopeNodeOf(blocks: Record, id: string): ScopeNode | undefined { + const block = blocks[id] + if (!block) return undefined + const parentId: unknown = block.data?.parentId + return { + kind: block.type === 'loop' || block.type === 'parallel' ? block.type : null, + parent: typeof parentId === 'string' && parentId.length > 0 ? parentId : null, } - return scopes } /** - * Whether a `head.path` token read from `blockId` is an iteration field (`index`, `currentItem`, - * `items`, …) of a container the block is not inside: a named loop or parallel (`targetId`), - * whose fields the executor refuses outside it, or the bare `loop`/`parallel` prefix in a block - * with no container of that kind, which resolves to nothing. + * Whether a `head.path` token read from `blockId` is an iteration field of a container the block + * is not inside: a named loop or parallel (`targetId`), or the bare `loop`/`parallel` prefix. */ -function readsIterationOutOfScope( +function readsTokenOutOfScope( blocks: Record, blockId: string, token: string, targetId: string | undefined ): boolean { const [head = '', field = ''] = token.split('.') - const kind = targetId === undefined ? head : blocks[targetId]?.type - const fields = - kind !== undefined && Object.hasOwn(ITERATION_FIELDS, kind) ? ITERATION_FIELDS[kind] : undefined - if (!fields?.includes(splitLeadingBracketPath(field).property)) return false - const scopes = iterationScopeIds(blocks, blockId) - return targetId === undefined - ? !scopes.some((id) => blocks[id]?.type === kind) - : !scopes.includes(targetId) -} - -/** Whether a lint reference finding is one {@link readsIterationOutOfScope} reported. */ -export function isIterationScopeFinding(reference: WorkflowLintUnresolvedReference): boolean { - return reference.kind === 'block-output' && reference.reason.startsWith(OUT_OF_SCOPE_REASON) + if (targetId === undefined && head !== 'loop' && head !== 'parallel') return false + return readsIterationOutOfScope( + blockId, + targetId === undefined ? (head as 'loop' | 'parallel') : { key: targetId }, + splitLeadingBracketPath(field).property, + (id) => scopeNodeOf(blocks, id) + ) } +/** + * Dangling, unknown and out-of-scope block-output references. `iterationScope: false` leaves the + * iteration-scope rule to a caller that reports it itself (a source apply, whose compile reports + * it at the source line). + */ export function collectDanglingBlockOutputReferences( - workflowState: Pick + workflowState: Pick, + { iterationScope = true }: { iterationScope?: boolean } = {} ): WorkflowLintUnresolvedReference[] { const blocks = (workflowState.blocks || {}) as Record const targetByKey = referenceTargetIndex(blocks) @@ -940,7 +922,11 @@ export function collectDanglingBlockOutputReferences( for (const token of referenceCandidates(leaf, subBlockId === 'code')) { if (!token || !REF_TOKEN_SHAPE.test(token)) continue const targetId = referenceTarget(token, targetByKey) - if (targetId !== null && readsIterationOutOfScope(blocks, blockId, token, targetId)) { + if ( + iterationScope && + targetId !== null && + readsTokenOutOfScope(blocks, blockId, token, targetId) + ) { outOfScope.add(`<${token}>`) continue } @@ -984,7 +970,7 @@ export function collectDanglingBlockOutputReferences( field: subBlockId, value: [...outOfScope], kind: 'block-output', - reason: `${OUT_OF_SCOPE_REASON} reads a loop or parallel's iteration fields (index, currentItem, items) from outside that container — the run fails or reads nothing. Move the block into the container, or read the container's results after it finishes.`, + reason: `Reads a loop or parallel's iteration fields (index, currentItem, items) from outside that container — the run fails or reads nothing. Move the block into the container, or read the container's results after it finishes.`, }) } for (const [targetId, group] of unknownByTarget) { 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 c3b83dc9a05..0756a33b170 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 @@ -39,6 +39,19 @@ function cacheCatalog(): void { cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, readFileSync(FIXTURE_CATALOG, 'utf8')) } +/** Records in `.sim/base.json` that the source was printed with the fixture catalog, as a get does. */ +function printedWithFixture(): void { + writeFileSync( + join(dir, '.sim/base.json'), + JSON.stringify({ + workflowId: 'wf', + workspaceId: WORKSPACE_ID, + fingerprint: 'sf1:a', + catalogHash: 'fixture', + }) + ) +} + function result(): Record { return JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') } @@ -553,6 +566,7 @@ export default workflow('W', {}, () => { variables: {}, } const printed = source('return 1') + printedWithFixture() writeFileSync(join(dir, 'workflow.ts'), printed) writeFileSync(join(dir, '.sim/lock.json'), JSON.stringify(lock)) const record = storedEdgesWrite( @@ -742,6 +756,7 @@ export default workflow('W', {}, () => { ), variables: {}, } + printedWithFixture() writeFileSync(join(dir, 'workflow.ts'), printed) writeFileSync(join(dir, '.sim/lock.json'), JSON.stringify(lock)) const record = storedEdgesWrite( @@ -770,19 +785,44 @@ export default workflow('W', {}, () => { expect(process.exitCode).toBe(1) }) - it('stays a warning on a block the stored workflow already holds that way, and with --no-strict', async () => { + it('stays a warning on a block the stored workflow already holds that way', async () => { cacheCatalog() writePrinted(reads('dataa')) await check() expect(findings()).toEqual(['warning W_UNKNOWN_OUTPUT_PATH']) expect(process.exitCode).toBeUndefined() + }) + it('fails with --no-strict too, as the server refuses it whatever the client asks', async () => { + cacheCatalog() writePrinted(reads('data')) writeFileSync(join(dir, 'workflow.ts'), reads('dataa')) await checkIn(dir, '--no-strict') + expect(findings()).toEqual(['error E_APPLY_UNRESOLVED_REF']) + expect(process.exitCode).toBe(1) + }) + + it('claims no refusal when the catalog the source was printed with is not cached', async () => { + cacheCatalog() + writePrinted(reads('data')) + writeFileSync( + join(dir, '.sim/base.json'), + JSON.stringify({ workflowId: 'wf', workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a' }) + ) + writeFileSync(join(dir, 'workflow.ts'), reads('dataa')) + await check() expect(findings()).toEqual(['warning W_UNKNOWN_OUTPUT_PATH']) expect(process.exitCode).toBeUndefined() }) + + it('keeps x.error on a block with no error edge a warning, which the server never refuses', async () => { + cacheCatalog() + writePrinted(reads('data')) + writeFileSync(join(dir, 'workflow.ts'), reads('error')) + await check() + expect(findings()).toEqual(['warning W_OUTPUT_PATH_UNDECLARED']) + expect(process.exitCode).toBeUndefined() + }) }) it('fails on a bound block with --strict and on nothing with --no-strict', async () => { 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 92cad8b88b7..4f377d6a416 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -7,11 +7,13 @@ import { codePointLabel, compileWorkflow, didYouMean, - EDITED_CODE_FILE_REFUSALS, + EDIT_REFUSALS, encodeAnchor, getOwn, parseJsonField, parseWorkflowLock, + raisedMessage, + refuseEditedFindings, scriptName, startInputs, type Value, @@ -94,29 +96,6 @@ const STORED_EXEMPT_CODES: ReadonlySet = new Set(['W_BRANCH_UNWIRED']) */ const EDIT_SCOPED_CODES: ReadonlySet = new Set(['W_JSON_REF_UNTYPED']) -/** - * Warnings a check refuses under the server's error code, whatever the strict mode, on a block the - * lock binds that the source moved into another container: the server refuses them on any block - * the edit changed. `W_REF_OUT_OF_SCOPE`, an iteration field the move left outside its container. - */ -const MOVED_BLOCK_REFUSALS: ReadonlyMap = new Map([ - ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], -]) - -/** - * Warnings in `workflow.ts` a check refuses under the server's error code on a block the edit - * added or changed, in the default and strict modes: a reference to an output or block that does - * not exist (`E_APPLY_UNRESOLVED_REF`, at the reference), or an iteration field read outside its - * container (`E_APPLY_REF_OUT_OF_SCOPE`), which the server refuses on such a block and keeps as a warning only on a block the stored workflow already holds. A block counts as - * changed when the lock does not bind it, 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). - */ -const EDITED_ENTRY_REFUSALS: ReadonlyMap = new Map([ - ['W_UNKNOWN_OUTPUT_PATH', 'E_APPLY_UNRESOLVED_REF'], - ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], - ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], -]) - /** * Which {@link STRICT_CODES} warnings fail a check: `new` those on a block the lock does not bind * (one added since the get, or every block of a workflow that has no lock yet), `all` every one, @@ -125,12 +104,6 @@ const EDITED_ENTRY_REFUSALS: ReadonlyMap = new Map */ type StrictMode = 'new' | 'all' | 'off' -/** - * The clause a warning ends with to say an apply saves the value anyway (`; it is kept as - * written.`), dropped from a warning a check raises to an error, which nothing saves. - */ -const KEPT_AS_WRITTEN = /[;,] (?:it|the value|the text) is kept as written\.$/ - /** One finding of a check, as the write commands print theirs. */ export type CheckFinding = Diagnostic @@ -145,6 +118,13 @@ export function strictMode(options: StrictOptions): StrictMode { return options.strict ? 'all' : 'off' } +/** Where each kind of edit refusal applies, as the help says it. */ +const REFUSAL_WHERE: Record<(typeof EDIT_REFUSALS)[number]['where'], string> = { + 'changed block': 'in any file of a block the edit added or changed', + 'workflow.ts': 'in workflow.ts on a block the edit added or changed', + 'edited code file': 'in a function file changed since the get', +} + /** Help shared by both check commands: what fails, and the strict flags. */ export const STRICT_HELP = `Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists @@ -155,23 +135,19 @@ does not bind (a block added since the get, or every block of a new workflow): ${[...STRICT_CODES].map((code) => ` ${code}`).join(',\n')}. --strict fails on them in every block, except ${[...STORED_EXEMPT_CODES].join(', ')} 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 a function file changed since the get, ${[...EDITED_CODE_FILE_REFUSALS] - .map(([warning, refusal]) => `${warning} is the error ${refusal}`) - .join(', ')} in every mode, as the server refuses it; so is ${[...MOVED_BLOCK_REFUSALS] - .map(([warning, refusal]) => `${warning} (${refusal})`) - .join(', ')} on a block the source moved into another container. In workflow.ts, ${[ - ...EDITED_ENTRY_REFUSALS.keys(), -].join(', ')} are the error ${[...new Set(EDITED_ENTRY_REFUSALS.values())].join( - ', ' -)} on a block the edit added or changed, as the server refuses them there (not with ---no-strict). ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not -bind, and with --strict on every block.` +on none of them. In every mode, as the server refuses them: ${EDIT_REFUSALS.map( + ({ warning, refusal, where }) => `${warning} is the error ${refusal} ${REFUSAL_WHERE[where]}` +).join('; ')}. 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). +${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not bind, and with +--strict on every block.` /** Adds the `--strict` / `--no-strict` pair to a check command. */ export function strictFlags(command: Command): Command { return command .option('--strict', 'Fail on the warnings listed below in every block, not only new ones') - .option('--no-strict', 'Never fail on a warning') + .option('--no-strict', 'Never fail on a warning an apply saves') } const CHECK_HELP = ` @@ -432,7 +408,7 @@ async function compileWorkflowDir( ...(storedEdges ? { storedUnreadEdges: storedEdges } : {}), ...(envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}), }) - return { lock, files, compiled, storedBlocks } + return { lock, files, compiled, storedBlocks, printedWith } } /** @@ -479,7 +455,7 @@ export async function checkWorkflowDir( catalog: BlockCatalog, options: { declarations?: WorkspaceDeclarations; strict: StrictMode; prefix?: string } ): Promise<{ findings: CheckFinding[]; entry: string }> { - const { lock, files, compiled, storedBlocks } = await compileWorkflowDir( + const { lock, files, compiled, storedBlocks, printedWith } = await compileWorkflowDir( dir, catalog, options.declarations @@ -535,34 +511,22 @@ export async function checkWorkflowDir( : undefined return previousFile === undefined || written.digests[previousFile] !== textDigest } - const moved = (blockKey: string | undefined) => { - const held = blockKey === undefined || !lock ? undefined : getOwn(lock.blocks, blockKey) - const block = - blockKey === undefined || !compiled.workflow - ? undefined - : getOwn(compiled.workflow.blocks, blockKey) + const moved = (blockKey: string) => { + const held = lock ? getOwn(lock.blocks, blockKey) : undefined + const block = compiled.workflow ? getOwn(compiled.workflow.blocks, blockKey) : undefined return held !== undefined && block !== undefined && held.parent !== block.parent } - /** Whether the edit added or changed the block: see {@link EDITED_ENTRY_REFUSALS}. */ - const changed = (blockKey: string | undefined) => { - if (!bound(blockKey)) return true - const block = blockKey === undefined ? undefined : compiled.workflow?.blocks[blockKey] - const printed = blockKey === undefined ? undefined : storedBlocks?.get(blockKey) + /** + * Whether the edit added, moved or changed the block. A block's digest is compared only when + * the catalog it was printed with is cached: against another catalog every block may compile + * differently, and a check prefers a warning to a refusal the server would not make. + */ + const changed = (blockKey: string) => { + if (!bound(blockKey) || moved(blockKey)) return true + const block = compiled.workflow?.blocks[blockKey] + const printed = printedWith ? storedBlocks?.get(blockKey) : undefined return block !== undefined && printed !== undefined && blockDigest(block) !== printed } - const editedRefusal = (code: string, file: string | undefined, blockKey: string | undefined) => { - const refusal = - file === undefined - ? undefined - : file !== SOURCE_ENTRY_FILE - ? edited(file, blockKey) - ? EDITED_CODE_FILE_REFUSALS.get(code) - : undefined - : options.strict !== 'off' && changed(blockKey) - ? EDITED_ENTRY_REFUSALS.get(code) - : undefined - return refusal ?? (moved(blockKey) ? MOVED_BLOCK_REFUSALS.get(code) : undefined) - } const fails = (code: string, blockKey: string | undefined) => STRICT_CODES.has(code) && !(STORED_EXEMPT_CODES.has(code) && bound(blockKey)) && @@ -571,16 +535,19 @@ export async function checkWorkflowDir( const reported = (code: string, blockKey: string | undefined) => !SERVER_ONLY_CODES.has(code) && !(EDIT_SCOPED_CODES.has(code) && options.strict !== 'all' && bound(blockKey)) + const refused = refuseEditedFindings(compiled, { + changed, + codeEdited: (blockKey, file) => edited(file, blockKey), + }) const findings = [ - ...compiled.diagnostics.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)), + ...refused.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)), ...declared, ].map(({ code, severity, message, hint, frame, span, blockKey }): CheckFinding => { - const refusal = severity === 'warning' ? editedRefusal(code, span?.file, blockKey) : undefined - const raised = refusal !== undefined || (severity === 'warning' && fails(code, blockKey)) + const raised = severity === 'warning' && fails(code, blockKey) return { - code: refusal ?? code, + code, severity: raised ? 'error' : severity, - message: raised ? message.replace(KEPT_AS_WRITTEN, '.') : message, + message: raised ? raisedMessage(message) : message, ...(hint !== undefined ? { hint } : {}), ...(frame !== undefined ? { frame } : {}), ...(span ? { file: `${prefix}${span.file}`, line: span.line, column: span.column } : {}), 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 eafc0bd1d5c..1a8d25ac105 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -130,7 +130,7 @@ The \`// @sim-sdk 1\` header must be the first line, and the file has exactly on ## Diagnostics and exit codes -Findings print as \`file:line:column severity CODE: message\`, then the code frame and a hint. \`E_*\` refuses the whole apply; \`W_*\` is saved as written and names a real problem. \`check\` prints the \`W_*\` codes it fails on as \`error\` on a block you added; the apply still saves them as warnings. A reference to an output or block that does not exist, in a block you added or changed, is the error \`E_APPLY_UNRESOLVED_REF\` in both. Exit codes of every \`workflows source\` command: +Findings print as \`file:line:column severity CODE: message\`, then the code frame and a hint. \`E_*\` refuses the whole apply; \`W_*\` is saved as written and names a real problem. \`check\` prints the \`W_*\` codes it fails on as \`error\` on a block you added; the apply still saves them as warnings. A path no output has (\`W_UNKNOWN_OUTPUT_PATH\`), in a block you added or changed, is the error \`E_APPLY_UNRESOLVED_REF\` in both, whatever \`--strict\` says; a path the run may still resolve (\`W_OUTPUT_PATH_UNDECLARED\`: an input the start does not declare, \`x.error\` with no error edge) stays a warning. Exit codes of every \`workflows source\` command: ${sourceExitCodesTable('sim workflows source')} diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 3efe7c0150a..82aa2ebd0de 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -845,7 +845,6 @@ export type ApplyWorkflowSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -879,10 +878,12 @@ export type ApplyWorkflowSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -1343,7 +1344,6 @@ export type ApplyWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1377,10 +1377,12 @@ export type ApplyWorkspaceSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -1634,7 +1636,6 @@ export type ApplyWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -1668,10 +1669,12 @@ export type ApplyWorkspaceSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -5300,7 +5303,6 @@ export type CreateWorkflowFromSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -5334,10 +5336,12 @@ export type CreateWorkflowFromSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -10402,7 +10406,6 @@ export type GetWorkflowSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -10436,10 +10439,12 @@ export type GetWorkflowSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -11094,7 +11099,6 @@ export type GetWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -11128,10 +11132,12 @@ export type GetWorkspaceSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -14416,7 +14422,6 @@ export type PlanWorkflowSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -14450,10 +14455,12 @@ export type PlanWorkflowSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -14869,7 +14876,6 @@ export type PlanWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -14903,10 +14909,12 @@ export type PlanWorkspaceSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' @@ -15160,7 +15168,6 @@ export type PlanWorkspaceSourceResponse = { | 'W_REF_NOT_NORMALIZED' | 'E_REF_UNREPRESENTABLE' | 'W_REF_OUT_OF_SCOPE' - | 'W_CODE_FILE_REF_SYNTAX' | 'E_EDGE_SCOPE' | 'E_EDGE_NOTE' | 'E_TARGET_TRIGGER' @@ -15194,10 +15201,12 @@ export type PlanWorkspaceSourceResponse = { | 'W_LITERAL_SECRET' | 'W_SUBFLOW_COUNT' | 'W_UNKNOWN_OUTPUT_PATH' + | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' + | 'W_CODE_FILE_REF_SYNTAX' | 'W_UNRESOLVED_REF' | 'W_FORWARD_REF_LITERALIZED' | 'W_COMMENT_MOVED' diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 365af9c60ea..285331073d7 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -191,10 +191,13 @@ reordered tool never takes another tool's secret. - `blk.a.b` → ``, `blk['x-y']` → ``, `blk.items[0]` → ``, `blk.items['0']` → ``. Paths are typed from the block's outputs; a path no output - has is `W_UNKNOWN_OUTPUT_PATH`. For an agent with a `responseFormat`, its declared fields count - beside the static outputs (skipped when the format holds references); for a Start, API or Input - trigger its declared `inputFormat` inputs do, so `start.nope`, or a reference to an input since - removed, warns at the reference; other dynamic outputs skip the check. + has is `W_UNKNOWN_OUTPUT_PATH` (the apply refuses it on a block the edit changed). For an agent + with a `responseFormat`, its declared fields count beside the static outputs (skipped when the + format holds references); for a Start, API or Input trigger its declared `inputFormat` inputs + do, so `start.nope`, or a reference to an input since removed, is `W_OUTPUT_PATH_UNDECLARED` + at the reference (a caller may still pass it, so it is never refused); other dynamic outputs + skip the check. `x.error` on a block with no error edge reads nothing: + `W_OUTPUT_PATH_UNDECLARED`. - A ref to a block declared later is `W_FORWARD_REF`; it still resolves. A ref into a sibling subflow's child is `E_OUT_OF_SCOPE`. An unknown identifier is `E_UNKNOWN_IDENTIFIER` with a did-you-mean. Wiring resolves its identifiers the same way. @@ -437,6 +440,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. For a literal token in a credential field, the hint says `credential('')`. | | `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. | | `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. | +| `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | | `W_JSON_REF_UNTYPED` | A bare ref in a JSON literal whose type nothing declares. | | `E_CODE_FILE_MISSING` | `codeFile()` names a file the request did not send. | | `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 4f76c5cd78b..c4e5829f4b4 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -116,7 +116,7 @@ describe("references into a start trigger's declared inputs", () => { 'start.to(next)', ].join('\n') ), - 'W_UNKNOWN_OUTPUT_PATH' + 'W_OUTPUT_PATH_UNDECLARED' ) it('warns on an input the start does not declare, at the reference', () => { @@ -665,7 +665,7 @@ describe('hints that name the fix', () => { expect(unknown?.hint).toBe('Did you mean data?') }) - it('reads x.error in the handler of an error edge, and refuses it on a block without one', () => { + it('reads x.error in the handler of an error edge, and warns that it reads nothing on a block without one', () => { const body = (wiring: string) => [ START, @@ -674,8 +674,8 @@ describe('hints that name the fix', () => { 'start.to(call)', wiring, ].join('\n') - expect(findings(run(body('call.onError(failed)')), 'W_UNKNOWN_OUTPUT_PATH')).toEqual([]) - const [unknown] = findings(run(body('call.to(failed)')), 'W_UNKNOWN_OUTPUT_PATH') + expect(findings(run(body('call.onError(failed)')), 'W_OUTPUT_PATH_UNDECLARED')).toEqual([]) + const [unknown] = findings(run(body('call.to(failed)')), 'W_OUTPUT_PATH_UNDECLARED') expect(unknown?.message).toBe( 'Call has no output error: only a block with an error edge outputs its failure message.' ) @@ -709,8 +709,8 @@ describe('hints that name the fix', () => { 'start.to(classify)', wiring, ].join('\n') - expect(findings(run(body('classify.onError(failed)')), 'W_UNKNOWN_OUTPUT_PATH')).toEqual([]) - expect(findings(run(body('classify.to(failed)')), 'W_UNKNOWN_OUTPUT_PATH')).toHaveLength(1) + expect(findings(run(body('classify.onError(failed)')), 'W_OUTPUT_PATH_UNDECLARED')).toEqual([]) + expect(findings(run(body('classify.to(failed)')), 'W_OUTPUT_PATH_UNDECLARED')).toHaveLength(1) }) it('lists the outputs when no output is close to an unknown path', () => { diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 2350506e88d..2bd53501f8b 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1917,7 +1917,7 @@ describe('reference-shaped text that floods the warnings', () => { { length: 120 }, (_, i) => `const a${i} = api('A${i}', { url: t\`\` })` ) - const later = "const later = api('Later', { url: t`${start.missing}` })" + const later = "const later = api('Later', { url: t`${a0.missing}` })" const result = run(source([START, ...flood, later].join('\n'))) expect(result.diagnostics.filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH')).toHaveLength(1) expect(result.diagnostics.filter((d) => d.code === 'W_TOO_MANY_WARNINGS')).toHaveLength(1) diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 2f58b44c7b4..17a3ea7c2c1 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -110,6 +110,11 @@ export interface CompileResult { workflow: CanonicalWorkflow | null /** Spans into the entry count from after a leading byte order mark (see `compileWorkflow`). */ diagnostics: LocatedDiagnostic[] + /** + * Refusable warnings the warning caps left out of `diagnostics`, one per code, block and file: + * what `refuseEditedFindings` reads beside `diagnostics`, so a cap never hides a refusal. + */ + withheld: LocatedDiagnostic[] /** Where each anchor sits, to map later server findings back to lines. */ spans: Partial> /** @@ -422,6 +427,7 @@ function emptyResult(reporter: Reporter, sdkMajor: number | null): CompileResult return { workflow: null, diagnostics: reporter.diagnostics, + withheld: reporter.withheld, spans: {}, metaSpans: {}, hints: { blocks: {} }, @@ -743,7 +749,12 @@ function compileEntry( // break the JSON is moot until the path is fixed. const unknownAt = new Set( reporter.diagnostics - .filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH' || d.code === 'W_UNRESOLVED_REF') + .filter( + (d) => + d.code === 'W_UNKNOWN_OUTPUT_PATH' || + d.code === 'W_OUTPUT_PATH_UNDECLARED' || + d.code === 'W_UNRESOLVED_REF' + ) .map((d) => `${d.span.file}:${d.span.start}`) ) for (const ref of untyped) { @@ -782,6 +793,7 @@ function compileEntry( return { workflow, diagnostics: reporter.diagnostics, + withheld: reporter.withheld, spans, metaSpans: ctx.metaSpans, hints, diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index 887cc6353b7..1f606c519bf 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -7,6 +7,7 @@ import { type SourceSpan, splitLines, } from '../diagnostics/frame' +import { REFUSABLE_WARNING_CODES } from '../diagnostics/refusals' import type { BlockKey, SubBlockId } from '../model' /** Babel's line terminators, so lines agree with Babel `loc`. */ @@ -107,6 +108,14 @@ function capLength(text: string): string { */ export class Reporter { readonly diagnostics: LocatedDiagnostic[] = [] + /** + * The first of each {@link REFUSABLE_WARNING_CODES} code, block and file a warning cap left out + * of {@link diagnostics}, so an apply's refusals are decided on every finding (see + * `refuseEditedFindings`) while the listing stays capped. + */ + readonly withheld: LocatedDiagnostic[] = [] + /** The code, block and file of each refusable warning listed or withheld. */ + private readonly refusableHeld = new Set() private readonly indexes = new Map() private errorCount = 0 private warningCount = 0 @@ -166,6 +175,7 @@ export class Reporter { } else if (severity === 'info') { if (this.infoCount >= MAX_INFOS) return } else if (this.warningCount >= MAX_WARNINGS) { + this.withhold(code, message, at, extras) if (this.warningCount === MAX_WARNINGS) { this.record( 'W_TOO_MANY_WARNINGS', @@ -180,6 +190,7 @@ export class Reporter { const ofCode = this.warningsByCode.get(code) ?? 0 this.warningsByCode.set(code, ofCode + 1) if (ofCode >= MAX_WARNINGS_PER_CODE) { + this.withhold(code, message, at, extras) if (ofCode === MAX_WARNINGS_PER_CODE) { this.record( 'W_TOO_MANY_WARNINGS', @@ -192,9 +203,27 @@ export class Reporter { return } } + const held = refusableKey(code, at, extras) + if (held !== undefined) this.refusableHeld.add(held) this.record(code, message, at, extras, framesSource(code)) } + /** + * Keeps a refusable warning a cap left out in {@link withheld}, unless one of its code, block + * and file is already listed or withheld. + */ + private withhold( + code: CompileDiagnosticCode, + message: string, + at: Range, + extras: ReportExtras + ): void { + const held = refusableKey(code, at, extras) + if (held === undefined || this.refusableHeld.has(held)) return + this.refusableHeld.add(held) + this.withheld.push(this.build(code, message, at, extras, framesSource(code))) + } + /** Records one diagnostic; `framed` is false when the finding at `at` is about a literal secret. */ private record( code: CompileDiagnosticCode, @@ -203,14 +232,25 @@ export class Reporter { extras: ReportExtras, framed: boolean ): void { - const span = this.span(at) - const lines = this.indexes.get(at.file)?.lines ?? [''] const severity = severityOf(code) if (severity === 'error') this.errorCount++ else if (severity === 'info') this.infoCount++ else this.warningCount++ + this.diagnostics.push(this.build(code, message, at, extras, framed)) + } + + private build( + code: CompileDiagnosticCode, + message: string, + at: Range, + extras: ReportExtras, + framed: boolean + ): LocatedDiagnostic { + const span = this.span(at) + const lines = this.indexes.get(at.file)?.lines ?? [''] + const severity = severityOf(code) const hint = typeof extras.hint === 'function' ? extras.hint() : extras.hint - const diagnostic = { + return { code, severity, message: capLength(message), @@ -226,6 +266,15 @@ export class Reporter { })), }), } as LocatedDiagnostic - this.diagnostics.push(diagnostic) } } + +/** The code, block and file a refusable warning is withheld by; none for any other finding. */ +function refusableKey( + code: CompileDiagnosticCode, + at: Range, + extras: ReportExtras +): string | undefined { + if (!REFUSABLE_WARNING_CODES.has(code) || extras.blockKey === undefined) return undefined + return `${code}\u0000${extras.blockKey}\u0000${at.file}` +} diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 800501d410c..ebaafb374a1 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -27,6 +27,7 @@ import { type RefSegment, } from '../code-files/ref-path' import { REF_ROOT } from '../code-files/to-file' +import { type ContainerKind, readsIterationOutOfScope, type ScopeNode } from '../iteration-scope' import { JsonRef, type JsonTree, @@ -179,56 +180,44 @@ export function objectEntries( return entries } -/** - * `W_REF_NOT_NORMALIZED` for each hand-written `` in literal text whose head is not a - * normalized block key, or names no declared block. Such text is kept verbatim, so a rename in the - * same apply never rewrites it; the block's ident is the reference that follows the block. - */ -/** - * The containers whose iteration fields a block reads at run time: those enclosing it, and the - * block itself when it is one (a while condition reads ``). - */ -function iterationScopes(decl: BlockDecl): BlockDecl[] { - const enclosing = enclosingContainers(decl) - return containerKindOf(decl) ? [decl, ...enclosing] : enclosing +/** A declared block as the iteration-scope rule reads it. */ +function scopeNodeOf(ctx: CompileContext, key: BlockKey): ScopeNode | undefined { + const decl = ctx.declsByKey.get(key) + return decl && { kind: containerKindOf(decl), parent: decl.parent?.key ?? null } } /** * Reports `W_REF_OUT_OF_SCOPE` when block `siteKey` reads iteration field `property` of a - * container it is not inside: `container` is a declared loop or parallel (`lp.index`, - * `$ref.lp.index`), or the kind whose innermost enclosing container `` names. Outside - * the container the executor refuses a named iteration field and finds no scope for a bare one. - * A container output (`results`) and a property no container has are not this check's. + * container it is not inside (see {@link readsIterationOutOfScope}): `container` is a declared + * loop or parallel (`lp.index`, `$ref.lp.index`), or the kind whose innermost enclosing container + * `` names. */ function checkIterationScope( ctx: CompileContext, at: Range, siteKey: BlockKey, - container: BlockDecl | 'loop' | 'parallel', + container: BlockDecl | ContainerKind, property: string ): void { const site = ctx.declsByKey.get(siteKey) - const kind = typeof container === 'string' ? container : containerKindOf(container) - if (!site || !kind) return - if (!(kind === 'loop' ? LOOP_PROPERTIES : PARALLEL_PROPERTIES).includes(property)) return - const scopes = iterationScopes(site) + if (!site) return + const nodeOf = (key: BlockKey) => scopeNodeOf(ctx, key) + if (!readsIterationOutOfScope(siteKey, container, property, nodeOf)) return if (typeof container === 'string') { - if (scopes.some((decl) => containerKindOf(decl) === kind)) return ctx.reporter.report( 'W_REF_OUT_OF_SCOPE', - `${site.name} reads the enclosing ${kind}'s ${property}, but it sits in no ${kind}, so the reference resolves to nothing at run time.`, + `${site.name} reads the enclosing ${container}'s ${property}, but it sits in no ${container}, so the reference resolves to nothing at run time.`, at, { - hint: `Move ${site.name} into a ${kind}'s body, or read a ${kind}'s results after it finishes.`, + hint: `Move ${site.name} into a ${container}'s body, or read a ${container}'s results after it finishes.`, blockKey: siteKey, } ) return } - if (scopes.includes(container)) return ctx.reporter.report( 'W_REF_OUT_OF_SCOPE', - `${site.name} reads ${container.name}'s ${property}, but it is not inside ${container.name}; outside it a ${kind} outputs only results, so the run fails.`, + `${site.name} reads ${container.name}'s ${property}, but it is not inside ${container.name}; outside it a ${containerKindOf(container)} outputs only results, so the run fails.`, at, { hint: `Move ${site.name} into ${container.name}'s body, or read ${container.ident ?? container.key}.results after it finishes.`, @@ -257,6 +246,11 @@ function checkIterationTag( if (target) checkIterationScope(ctx, at, siteKey, target, property.name) } +/** + * `W_REF_NOT_NORMALIZED` for each hand-written `` in literal text whose head is not a + * normalized block key, or names no declared block. Such text is kept verbatim, so a rename in the + * same apply never rewrites it; the block's ident is the reference that follows the block. + */ function checkLiteralRefs(ctx: CompileContext, node: Node, text: string, site: ValueSite): void { // A note never runs, so nothing in it resolves: `` in its markdown is text, not a reference. if (catalogBlockOf(site.decl)?.graph.annotationOnly) return @@ -817,13 +811,13 @@ function isErrorOutput(segments: RefSegment[]): boolean { /** * Checks each `x.error` reference once the edges are known: `x` must have an error edge - * (`x.onError(...)`), else the path is unknown (`W_UNKNOWN_OUTPUT_PATH`). + * (`x.onError(...)`), else the path reads nothing (`W_OUTPUT_PATH_UNDECLARED`). */ export function checkErrorOutputRefs(ctx: CompileContext, erroring: ReadonlySet): void { for (const { at, target, blockKey } of ctx.errorOutputRefs) { if (erroring.has(target.key)) continue ctx.reporter.report( - 'W_UNKNOWN_OUTPUT_PATH', + 'W_OUTPUT_PATH_UNDECLARED', `${target.name} has no output error: only a block with an error edge outputs its failure message.`, at, { @@ -872,8 +866,8 @@ function declaredOutputFields( * Checks each reference into a block whose outputs a param declares (an agent's * `responseFormat`, an input trigger's `inputFormat`), once every block is compiled: the first * path segment must be a declared field or one of the block's static outputs - * (`W_UNKNOWN_OUTPUT_PATH` otherwise). A warning, as for any unknown output path: a caller may - * still pass an undeclared input, which the unified Start passes through. A param the compiler + * (`W_UNKNOWN_OUTPUT_PATH` otherwise, `W_OUTPUT_PATH_UNDECLARED` for an input trigger: a caller + * may still pass an undeclared input, which the unified Start passes through). A param the compiler * cannot read (not JSON, or holding references) leaves every path allowed; an absent one leaves * the static outputs. */ @@ -901,7 +895,7 @@ export function checkDynamicOutputRefs( const path = formatStoredPath(segments) if (dynamic.source === 'inputFormat') { ctx.reporter.report( - 'W_UNKNOWN_OUTPUT_PATH', + 'W_OUTPUT_PATH_UNDECLARED', fields.length > 0 ? `${target.name} declares no input ${first.name}: its inputFormat declares ${fields.join(', ')}.` : `${target.name} declares no input ${first.name}: its inputFormat declares none.`, diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 1b8e8d6eda0..a34113dddef 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -119,13 +119,6 @@ const COMPILE_SCOPE_CODES = [ * `E_APPLY_REF_OUT_OF_SCOPE`. */ 'W_REF_OUT_OF_SCOPE', - /** - * `$ref.key.path` or `$env.NAME` in a Python or shell code file, which is saved as written (only - * JavaScript files are rewritten), so the run reads it as text; `hint` names the `` or - * `{{NAME}}` form those files take. A warning so stored code that holds the text still - * round-trips; refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. - */ - 'W_CODE_FILE_REF_SYNTAX', ] as const /** Wiring. */ @@ -238,8 +231,18 @@ const COMPILE_CATALOG_CODES = [ * round-trip. */ 'W_SUBFLOW_COUNT', - /** Skipped when the block's outputs are dynamic. */ + /** + * A path the referenced block's outputs do not have, which fails the run when it resolves. + * Skipped when the block's outputs are dynamic and cannot be read. Refused as + * `E_APPLY_UNRESOLVED_REF` in `workflow.ts` on a block the edit added or changed. + */ 'W_UNKNOWN_OUTPUT_PATH', + /** + * A path the referenced block does not declare that the run still accepts: an input its + * `inputFormat` does not declare (a caller may pass it), or `x.error` on a block with no error + * edge (it reads nothing). Never refused, unlike `W_UNKNOWN_OUTPUT_PATH`. + */ + 'W_OUTPUT_PATH_UNDECLARED', /** * A bare reference in a JSON field literal whose output type nothing declares: it is stored bare * (typed), so a string value would break the JSON (`json-fields.ts`). @@ -258,6 +261,13 @@ const CODE_FILE_CODES = [ 'E_CODE_FILE_PATH', /** The printer's bijection self-check failed; the code was printed inline as `js```. */ 'W_CODE_FILE_INLINED', + /** + * `$ref.key.path` or `$env.NAME` in a Python or shell code file, which is saved as written (only + * JavaScript files are rewritten), so the run reads it as text; `hint` names the `` or + * `{{NAME}}` form those files take. A warning so stored code that holds the text still + * round-trips; refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. + */ + 'W_CODE_FILE_REF_SYNTAX', ] as const /** References and comments, shared by compile and print. */ @@ -532,27 +542,6 @@ export const DIAGNOSTIC_CODES = [ ] as const export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number] -/** The error codes {@link EDITED_CODE_FILE_REFUSALS} refuses a code file warning under. */ -type EditedCodeFileRefusal = - | 'E_APPLY_UNRESOLVED_REF' - | 'E_APPLY_REF_OUT_OF_SCOPE' - | 'E_APPLY_CODE_FILE_REF_SYNTAX' - -/** - * Code file warnings refused under an error code in a function code file the edit changed: the - * server refuses them on a block whose code the source changed, and an offline check in a file - * changed since the get wrote it. On code the stored workflow already holds they stay warnings, so - * a workflow saved with one still applies unchanged. - */ -export const EDITED_CODE_FILE_REFUSALS: ReadonlyMap = new Map< - CompileDiagnosticCode, - EditedCodeFileRefusal ->([ - ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], - ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], - ['W_CODE_FILE_REF_SYNTAX', 'E_APPLY_CODE_FILE_REF_SYNTAX'], -]) - /** * Whether a finding with `code` may carry a code frame. A finding about a literal secret in * source carries its span only, so the frame never echoes the secret over the API into logs or diff --git a/packages/workflow-code/src/diagnostics/refusals.test.ts b/packages/workflow-code/src/diagnostics/refusals.test.ts new file mode 100644 index 00000000000..755438c539e --- /dev/null +++ b/packages/workflow-code/src/diagnostics/refusals.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest' +import { TEST_CATALOG } from '../compile/catalog.test-helpers' +import { compileWorkflow } from '../compile/index' +import { MAX_WARNINGS_PER_CODE } from '../compile/report' +import { type EditedBlocks, refuseEditedFindings } from './refusals' + +const IMPORTS = "import { api, codeFile, fn, loop, t, trigger, workflow } from '@sim/workflow-sdk'" + +function compile(body: string[], files: Record = {}) { + const text = `// @sim-sdk 1\n${IMPORTS}\n\nexport default workflow('Test', () => {\n${body.map((line) => ` ${line}`).join('\n')}\n})\n` + return compileWorkflow({ + entry: { path: 'workflow.ts', text }, + files: new Map(Object.entries(files)), + catalog: TEST_CATALOG, + sdkMajor: 1, + }) +} + +/** An edit that changed exactly `keys`, code files included. */ +function edited(...keys: string[]): EditedBlocks { + return { changed: (key) => keys.includes(key), codeEdited: (key) => keys.includes(key) } +} + +function errors(findings: ReadonlyArray<{ code: string; severity: string; blockKey?: string }>) { + return findings + .filter((finding) => finding.severity === 'error') + .map((finding) => `${finding.code} ${finding.blockKey}`) +} + +const START = "const start = trigger.start('Start')" + +describe('refuseEditedFindings', () => { + it('refuses an edited block’s warning that the per-code cap left out of the listing', () => { + const flood = Array.from( + { length: MAX_WARNINGS_PER_CODE }, + (_, i) => `q${i} = $ref.start.q${i}` + ) + const compiled = compile( + [ + START, + "const a = fn('A', { language: 'python', code: codeFile('./functions/a.py') })", + "const b = fn('B', { language: 'python', code: codeFile('./functions/b.py') })", + 'start.to(a)', + 'a.to(b)', + ], + { 'functions/a.py': flood.join('\n'), 'functions/b.py': 'y = $ref.a.result' } + ) + expect( + compiled.diagnostics.filter((d) => d.code === 'W_CODE_FILE_REF_SYNTAX' && d.blockKey === 'b') + ).toEqual([]) + + expect(errors(refuseEditedFindings(compiled, edited('b')))).toEqual([ + 'E_APPLY_CODE_FILE_REF_SYNTAX b', + ]) + expect(errors(refuseEditedFindings(compiled, edited()))).toEqual([]) + }) + + it('keeps x.error on a block with no error edge a warning, as the run reads nothing there', () => { + const compiled = compile([ + START, + "const call = api('Call', { url: 'https://x' })", + "const next = api('Next', { url: t`${call.error}` })", + 'start.to(call)', + 'call.to(next)', + ]) + + expect(errors(refuseEditedFindings(compiled, edited('next')))).toEqual([]) + }) + + it('refuses a path no output has in workflow.ts on a changed block only', () => { + const compiled = compile([ + START, + "const call = api('Call', { url: 'https://x' })", + "const next = api('Next', { url: t`${call.dat}` })", + 'start.to(call)', + 'call.to(next)', + ]) + + expect(errors(refuseEditedFindings(compiled, edited('next')))).toEqual([ + 'E_APPLY_UNRESOLVED_REF next', + ]) + expect(errors(refuseEditedFindings(compiled, edited('call')))).toEqual([]) + }) + + it('refuses an iteration field read outside its container in an unedited code file of a changed block', () => { + const compiled = compile( + [ + START, + "const lp = loop.forEach('Each', { collection: '[1]' }, (body) => {", + " const inner = fn('Inner', { code: 'return 1' })", + ' body.to(inner)', + '})', + "const after = fn('After', { code: codeFile('./functions/after.js') })", + 'start.to(lp)', + 'lp.to(after)', + ], + { 'functions/after.js': 'return $ref.each.index' } + ) + const changedOnly: EditedBlocks = { + changed: (key) => key === 'after', + codeEdited: () => false, + } + + expect(errors(refuseEditedFindings(compiled, changedOnly))).toEqual([ + 'E_APPLY_REF_OUT_OF_SCOPE after', + ]) + expect(errors(refuseEditedFindings(compiled, edited()))).toEqual([]) + }) +}) diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts new file mode 100644 index 00000000000..f33fb0134c3 --- /dev/null +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -0,0 +1,131 @@ +/** + * Which compile warnings an apply refuses on the blocks an edit wrote. A warning stays a warning + * on what the stored workflow already holds, so a workflow saved with one still applies + * unchanged; on a block the edit added or changed it fails at run time, so the apply refuses it + * under an `E_APPLY_*` code. The server's source evaluation and the CLI's offline check both call + * {@link refuseEditedFindings} with what each knows the edit changed, so they cannot disagree. + */ +import { SOURCE_ENTRY_FILE } from '../limits' +import type { CompileDiagnosticCode } from './codes' +import type { LocatedDiagnostic } from './frame' + +/** The error codes an edited block's warning is refused under. */ +export type EditRefusalCode = + | 'E_APPLY_UNRESOLVED_REF' + | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_CODE_FILE_REF_SYNTAX' + +/** What an edit changed, as the caller can tell it. */ +export interface EditedBlocks { + /** Whether the edit added the block or changed it in any way, a move included. */ + changed(blockKey: string): boolean + /** Whether the edit changed the text of the block's function code file `file`. */ + codeEdited(blockKey: string, file: string): boolean +} + +/** + * An iteration field read outside its container (`W_REF_OUT_OF_SCOPE`), refused in any file on a + * block the edit changed, or in a code file the edit changed. + */ +const CHANGED_BLOCK_REFUSALS: ReadonlyMap = new Map([ + ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], +]) + +/** In `workflow.ts` on a block the edit changed: a path no output of the block has. */ +const ENTRY_REFUSALS: ReadonlyMap = new Map([ + ['W_UNKNOWN_OUTPUT_PATH', 'E_APPLY_UNRESOLVED_REF'], +]) + +/** + * In a function code file whose text the edit changed: a `$ref` naming no block or variable, or a + * `$ref`/`$env` in a Python or shell file, which runs as text. + */ +const CODE_FILE_REFUSALS: ReadonlyMap = new Map([ + ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], + ['W_CODE_FILE_REF_SYNTAX', 'E_APPLY_CODE_FILE_REF_SYNTAX'], +]) + +/** + * Every warning code {@link refuseEditedFindings} may refuse: the compile keeps one of each code, + * block and file that its caps leave out (`CompileResult.withheld`), so a cap never hides a + * refusal. + */ +export const REFUSABLE_WARNING_CODES: ReadonlySet = new Set([ + 'W_REF_OUT_OF_SCOPE', + 'W_UNKNOWN_OUTPUT_PATH', + 'W_UNRESOLVED_REF', + 'W_CODE_FILE_REF_SYNTAX', +]) + +/** The rules' error codes with the warning each refuses, for help text. */ +export const EDIT_REFUSALS: ReadonlyArray<{ + warning: string + refusal: EditRefusalCode + where: 'changed block' | 'workflow.ts' | 'edited code file' +}> = [ + ...[...CHANGED_BLOCK_REFUSALS].map(([warning, refusal]) => ({ + warning, + refusal, + where: 'changed block' as const, + })), + ...[...ENTRY_REFUSALS].map(([warning, refusal]) => ({ + warning, + refusal, + where: 'workflow.ts' as const, + })), + ...[...CODE_FILE_REFUSALS].map(([warning, refusal]) => ({ + warning, + refusal, + where: 'edited code file' as const, + })), +] + +/** + * The clause a warning ends with to say an apply saves the value anyway (`; it is kept as + * written.`), dropped from a warning raised to an error, which nothing saves. + */ +const KEPT_AS_WRITTEN = /[;,] (?:it|the value|the text) is kept as written\.$/ + +/** `message` without its {@link KEPT_AS_WRITTEN} clause, for a warning raised to an error. */ +export function raisedMessage(message: string): string { + return message.replace(KEPT_AS_WRITTEN, '.') +} + +/** The code the apply refuses `finding` under, given what the edit changed; none when it stays. */ +function refusalOf(finding: LocatedDiagnostic, edit: EditedBlocks): EditRefusalCode | undefined { + if (finding.severity !== 'warning' || finding.blockKey === undefined) return undefined + const { blockKey, span } = finding + const inEntryFile = span.file === SOURCE_ENTRY_FILE + const onChanged = CHANGED_BLOCK_REFUSALS.get(finding.code) + if (onChanged) { + const edited = edit.changed(blockKey) || (!inEntryFile && edit.codeEdited(blockKey, span.file)) + return edited ? onChanged : undefined + } + if (inEntryFile) { + const inEntry = ENTRY_REFUSALS.get(finding.code) + return inEntry && edit.changed(blockKey) ? inEntry : undefined + } + const inCode = CODE_FILE_REFUSALS.get(finding.code) + return inCode && edit.codeEdited(blockKey, span.file) ? inCode : undefined +} + +/** + * A compile's findings with every warning the apply refuses on an edited block raised to its + * error code (see the module doc). `withheld`, the refusable warnings the compile's caps left + * out, join the result only when refused, so a refusal never depends on where a cap fell. + */ +export function refuseEditedFindings( + compiled: { diagnostics: readonly D[]; withheld: readonly D[] }, + edit: EditedBlocks +): Array { + const refused = (finding: D): LocatedDiagnostic | undefined => { + const code = refusalOf(finding, edit) + return code === undefined + ? undefined + : { ...finding, code, severity: 'error', message: raisedMessage(finding.message) } + } + return [ + ...compiled.diagnostics.map((finding) => refused(finding) ?? finding), + ...compiled.withheld.flatMap((finding) => refused(finding) ?? []), + ] +} diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index b7a567196a0..746ce8622ec 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -52,7 +52,6 @@ export { type ApplyDiagnosticCode, type DiagnosticCode, type DiagnosticSeverity, - EDITED_CODE_FILE_REFUSALS, framesSource, } from './diagnostics/codes' export { @@ -63,6 +62,12 @@ export { type SourceSpan, splitLines, } from './diagnostics/frame' +export { + EDIT_REFUSALS, + type EditedBlocks, + raisedMessage, + refuseEditedFindings, +} from './diagnostics/refusals' export { type CanonicalDiff, diffCanonical, renamesBetween, replacedBetween } from './diff' export { canonicalDigests, @@ -72,6 +77,7 @@ export { } from './equivalence' export { executableView } from './equivalence/executable' export { sha256Hex, stableStringify } from './hash' +export { readsIterationOutOfScope, type ScopeNode } from './iteration-scope' export { parseJsonField } from './json-fields' export { type DefinedField, diff --git a/packages/workflow-code/src/iteration-scope.ts b/packages/workflow-code/src/iteration-scope.ts new file mode 100644 index 00000000000..f77237e4445 --- /dev/null +++ b/packages/workflow-code/src/iteration-scope.ts @@ -0,0 +1,54 @@ +/** + * The iteration-scope rule: a loop's or parallel's iteration fields (`index`, `currentItem`, + * `items`, …) resolve only inside that container. Outside it the executor refuses a named + * container's field and finds no scope for the bare `` prefix. Compile reports a + * violation at its source line; the workflow lint reports it for edits made without source. Both + * walk the graph through {@link readsIterationOutOfScope}, so they cannot disagree. + */ +import { LOOP_PROPERTIES, PARALLEL_PROPERTIES } from './code-files' + +/** The kind of iteration container. */ +export type ContainerKind = 'loop' | 'parallel' + +/** One block as the rule reads it: its container kind (`null` for any other block) and parent. */ +export interface ScopeNode { + kind: ContainerKind | null + parent: string | null +} + +/** + * The containers whose iteration fields `site` reads at run time: itself when it is one (a while + * condition reads ``), then each enclosing one, innermost first. + */ +function iterationScopes(site: string, nodeOf: (key: string) => ScopeNode | undefined): string[] { + const scopes: string[] = [] + const seen = new Set() + for (let key: string | null = site; key !== null && !seen.has(key); ) { + seen.add(key) + const node = nodeOf(key) + if (node?.kind) scopes.push(key) + key = node?.parent ?? null + } + return scopes +} + +/** + * Whether block `site` reading iteration field `property` of `container` is out of scope: + * `container` is a container block's key, or the bare `loop`/`parallel` prefix (``), + * which names the innermost enclosing container of that kind. A property no container of the kind + * has (a container output such as `results`) is not this rule's. + */ +export function readsIterationOutOfScope( + site: string, + container: { key: string } | ContainerKind, + property: string, + nodeOf: (key: string) => ScopeNode | undefined +): boolean { + const kind = typeof container === 'string' ? container : nodeOf(container.key)?.kind + if (!kind) return false + if (!(kind === 'loop' ? LOOP_PROPERTIES : PARALLEL_PROPERTIES).includes(property)) return false + const scopes = iterationScopes(site, nodeOf) + return typeof container === 'string' + ? !scopes.some((key) => nodeOf(key)?.kind === kind) + : !scopes.includes(container.key) +} From 75d6c3452d7469c8e3ff376b01fac529611ba51f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:18:39 -0800 Subject: [PATCH 054/104] fix(workflow-code): infer a variable or input rename only with evidence beyond its type A lone same-type pair was taken as a rename, so removing apiKey: string and adding region: string kept the id, skipped E_APPLY_VARIABLE_DELETE and still printed a removal. A rename now needs one item without an id, one id without its key, and a shared non-empty value (or, for an input field, a description); otherwise it is a delete and an add, which needs --allow-delete. The branch, input field and variable writers share soleRename and sharesEvidence instead of three copies, and the plan reports an inferred variable rename as diff.variables.renamed rather than a removal. --- apps/docs/openapi-v2-workflows.json | 72 ++++++++++++++++++- .../[workflowId]/source/route.test.ts | 2 +- .../workflows/source/route.test.ts | 2 +- .../contracts/v2/openapi/workflow-source.ts | 6 +- .../lib/api/contracts/v2/workflow-source.ts | 10 +++ .../apply-workflow-source.integration.ts | 22 ++++++ .../lib/workflows/application/source-diff.ts | 52 +++++++++++--- .../protocol/source-apply-interrupt.test.ts | 2 +- .../protocol/workflow-source-apply.ts | 23 ++++-- .../workflow-source-roundtrip.test.ts | 2 +- .../protocol/workflow-source-status.test.ts | 2 +- packages/sim-cli/src/generated/v2-api.ts | 12 ++++ .../workflow-code/src/materialize/branches.ts | 26 +++---- .../src/materialize/index.test.ts | 21 ++++-- .../workflow-code/src/materialize/index.ts | 32 +++++---- .../workflow-code/src/materialize/rename.ts | 38 ++++++++++ .../src/structured/input-format.ts | 57 ++++++++------- 17 files changed, 303 insertions(+), 78 deletions(-) create mode 100644 packages/workflow-code/src/materialize/rename.ts diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index f7e065f599b..81b96cece92 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6165,6 +6165,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, @@ -6360,6 +6361,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, @@ -6547,6 +6549,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, @@ -19568,6 +19571,26 @@ }, "description": "Variable keys removed." }, + "renamed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Former key." + }, + "to": { + "type": "string", + "description": "New key." + } + }, + "required": ["from", "to"], + "additionalProperties": false, + "description": "A renamed variable." + }, + "description": "Variables renamed; each keeps its id, so none is deleted." + }, "modified": { "type": "array", "items": { @@ -19576,7 +19599,7 @@ "description": "Variable keys changed." } }, - "required": ["added", "removed", "modified"], + "required": ["added", "removed", "renamed", "modified"], "additionalProperties": false, "description": "Variable changes." } @@ -20071,6 +20094,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, @@ -20536,6 +20560,26 @@ }, "description": "Variable keys removed." }, + "renamed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Former key." + }, + "to": { + "type": "string", + "description": "New key." + } + }, + "required": ["from", "to"], + "additionalProperties": false, + "description": "A renamed variable." + }, + "description": "Variables renamed; each keeps its id, so none is deleted." + }, "modified": { "type": "array", "items": { @@ -20544,7 +20588,7 @@ "description": "Variable keys changed." } }, - "required": ["added", "removed", "modified"], + "required": ["added", "removed", "renamed", "modified"], "additionalProperties": false, "description": "Variable changes." } @@ -21039,6 +21083,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, @@ -21480,6 +21525,26 @@ }, "description": "Variable keys removed." }, + "renamed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Former key." + }, + "to": { + "type": "string", + "description": "New key." + } + }, + "required": ["from", "to"], + "additionalProperties": false, + "description": "A renamed variable." + }, + "description": "Variables renamed; each keeps its id, so none is deleted." + }, "modified": { "type": "array", "items": { @@ -21488,7 +21553,7 @@ "description": "Variable keys changed." } }, - "required": ["added", "removed", "modified"], + "required": ["added", "removed", "renamed", "modified"], "additionalProperties": false, "description": "Variable changes." } @@ -21989,6 +22054,7 @@ "variables": { "added": [], "removed": [], + "renamed": [], "modified": [] } }, 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 7439d86e380..cc742967047 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 @@ -180,7 +180,7 @@ const applied = { modified: [{ id: 'b-1', key: 'start', fields: ['name'] }], }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files: source.files, 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 f82f20c20d1..c527917f2f1 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 @@ -56,7 +56,7 @@ const created = { modified: [], }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files, diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts index d71d6f5e918..da125d95b86 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts @@ -121,7 +121,7 @@ export const workflowSourceOpenApiRoutes = [ noop: true, blocks: { added: [], removed: [], renamed: [], modified: [] }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files: WORKFLOW_SOURCE_EXAMPLE.files, @@ -184,7 +184,7 @@ export const workflowSourceOpenApiRoutes = [ noop: true, blocks: { added: [], removed: [], renamed: [], modified: [] }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files: WORKFLOW_SOURCE_EXAMPLE.files, @@ -251,7 +251,7 @@ export const workflowSourceOpenApiRoutes = [ modified: [], }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files: WORKFLOW_SOURCE_EXAMPLE.files, diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 2beff33b588..66194535f67 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -199,6 +199,16 @@ const sourceDiffSchema = z .object({ added: z.array(z.string()).describe('Variable keys added.'), removed: z.array(z.string()).describe('Variable keys removed.'), + renamed: z + .array( + z + .object({ + from: z.string().describe('Former key.'), + to: z.string().describe('New key.'), + }) + .describe('A renamed variable.') + ) + .describe('Variables renamed; each keeps its id, so none is deleted.'), modified: z.array(z.string()).describe('Variable keys changed.'), }) .describe('Variable changes.'), 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 6ec74a3e98e..068d677bb73 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2933,6 +2933,11 @@ describe('workflow variables in source', () => { ) expect(result.applied).toBe(true) + expect(result.diff.variables).toMatchObject({ + added: [], + removed: [], + renamed: [{ from: 'threshold', to: 'limit' }], + }) const [row] = await db .select({ variables: workflow.variables }) .from(workflow) @@ -2940,6 +2945,23 @@ describe('workflow variables in source', () => { expect(Object.keys(row.variables as Record)).toEqual([seeded.variableId]) }) + check( + 'an unrelated variable of the same type replacing one is a delete, refused without allowDelete', + async () => { + const seeded = await seedWorkflow() + const source = await getSource(seeded.workflowId) + const files = withVariables(source.files, "{ retries: { type: 'number', value: 5 } }") + + await expectRejected(apply(source, files), 'E_APPLY_VARIABLE_DELETE') + const allowed = await apply(source, files, { allowDelete: true, dryRun: true }) + expect(allowed.diff.variables).toMatchObject({ + added: ['retries'], + removed: ['threshold'], + renamed: [], + }) + } + ) + 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-diff.ts b/apps/sim/lib/workflows/application/source-diff.ts index 7ba815b8cb2..bd9bdbcd926 100644 --- a/apps/sim/lib/workflows/application/source-diff.ts +++ b/apps/sim/lib/workflows/application/source-diff.ts @@ -1,4 +1,9 @@ -import type { CanonicalDiff, CanonicalWorkflow, LockIdentity } from '@sim/workflow-code' +import { + type CanonicalDiff, + type CanonicalWorkflow, + getOwn, + type LockIdentity, +} from '@sim/workflow-code' interface SourceBlockRef { id: string @@ -20,7 +25,13 @@ export interface SourceDiffSummary { modified: Array } edges: { added: number; removed: number } - variables: { added: string[]; removed: string[]; modified: string[] } + variables: { + added: string[] + removed: string[] + /** Keys renamed with their id kept (an inferred lone rename), not added and removed. */ + renamed: Array<{ from: string; to: string }> + modified: string[] + } /** The workflow's name and description fields the source changes (a stored workflow's). */ meta?: Array<'name' | 'description'> } @@ -73,11 +84,36 @@ export function summarizeDiff( }), }, edges: { added: diff.edges.added.length, removed: diff.edges.removed.length }, - variables: { - added: diff.variables.added, - removed: diff.variables.removed, - modified: diff.variables.modified, - }, + variables: variableChanges(diff, base.identity, target.identity), + } +} + +/** + * The variable changes, a removed key whose id an added key kept reported as a rename: the apply + * keeps that variable, so it is neither deleted nor needs `allowDelete`. + */ +function variableChanges( + diff: CanonicalDiff, + base: LockIdentity, + target: LockIdentity +): SourceDiffSummary['variables'] { + const addedById = new Map( + diff.variables.added.flatMap((key) => { + const id = getOwn(target.variables, key) + return id === undefined ? [] : [[id, key] as const] + }) + ) + const renamed = diff.variables.removed.flatMap((from) => { + const id = getOwn(base.variables, from) + const to = id === undefined ? undefined : addedById.get(id) + return to === undefined ? [] : [{ from, to }] + }) + const moved = new Set(renamed.flatMap(({ from, to }) => [from, to])) + return { + added: diff.variables.added.filter((key) => !moved.has(key)), + removed: diff.variables.removed.filter((key) => !moved.has(key)), + renamed, + modified: diff.variables.modified, } } @@ -90,6 +126,6 @@ export function emptyDiffSummary(): SourceDiffSummary { noop: false, blocks: { added: [], removed: [], renamed: [], modified: [] }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, } } diff --git a/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts b/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts index b3a2fd47a1e..ee5a49fda00 100644 --- a/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts @@ -30,7 +30,7 @@ function applied() { noop: false, blocks: { added: [{ id: 'b-1', key: 'start' }], removed: [], renamed: [], modified: [] }, edges: { added: 1, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files: { 'workflow.ts': `${ENTRY}// stored\n` }, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 8dc745a54ae..c1f436a9563 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -165,9 +165,12 @@ function diffSummary(data: SourceApplyData): string { `${blocks.renamed.length} renamed`, `${blocks.modified.length} modified`, ] - const variableChanges = (['added', 'removed', 'modified'] as const).flatMap((change) => - variables[change].length > 0 ? [`${change} ${variables[change].join(', ')}`] : [] - ) + const variableChanges = [ + ...(['added', 'removed', 'modified'] as const).flatMap((change) => + variables[change].length > 0 ? [`${change} ${variables[change].join(', ')}`] : [] + ), + ...renamedVariables(variables).map(({ from, to }) => `renamed ${from} → ${to}`), + ] const modified = blocks.modified.map(({ key, fields }) => `${key} (${fields.join(', ')})`) const typed = (list: ReadonlyArray<{ key: string; type: string }>) => list.map(({ key, type }) => `${key} (${type})`).join('; ') @@ -621,9 +624,21 @@ export function attachWorkflowSourceCreate(source: Command): void { ) } +/** The variables a diff renames, none when the answer lists none. */ +function renamedVariables( + variables: SourceApplyData['diff']['variables'] +): ReadonlyArray<{ from: string; to: string }> { + return variables.renamed ?? [] +} + /** Whether a diff adds, removes or changes any workflow variable. */ function variablesChanged(variables: SourceApplyData['diff']['variables']): boolean { - return variables.added.length > 0 || variables.removed.length > 0 || variables.modified.length > 0 + return ( + variables.added.length > 0 || + variables.removed.length > 0 || + renamedVariables(variables).length > 0 || + variables.modified.length > 0 + ) } /** The create command for `dir` in `workspaceId`, as the next step a starter prints. */ diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 2f443403952..94d6fd1d2e4 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -116,7 +116,7 @@ function appliedResponse( noop: false, blocks: { added: [], removed: [], renamed: [], modified: [] }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics: [], files, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index 6c3f9f79f4e..d52c9873ef8 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -84,7 +84,7 @@ function dryRun(diagnostics: Array> = [], modified = 0) })), }, edges: { added: 0, removed: 0 }, - variables: { added: [], removed: [], modified: [] }, + variables: { added: [], removed: [], renamed: [], modified: [] }, }, diagnostics, files: GOT, diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 82aa2ebd0de..d5af8090d59 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -806,6 +806,10 @@ export type ApplyWorkflowSourceResponse = { variables: { added: Array removed: Array + renamed: Array<{ + from: string + to: string + }> modified: Array } } @@ -5264,6 +5268,10 @@ export type CreateWorkflowFromSourceResponse = { variables: { added: Array removed: Array + renamed: Array<{ + from: string + to: string + }> modified: Array } } @@ -14383,6 +14391,10 @@ export type PlanWorkflowSourceResponse = { variables: { added: Array removed: Array + renamed: Array<{ + from: string + to: string + }> modified: Array } } diff --git a/packages/workflow-code/src/materialize/branches.ts b/packages/workflow-code/src/materialize/branches.ts index 940320f8c48..8d4b7831c24 100644 --- a/packages/workflow-code/src/materialize/branches.ts +++ b/packages/workflow-code/src/materialize/branches.ts @@ -1,7 +1,8 @@ import { positionalKeys, positionalTitle } from '../canonicalize/branches' import type { BranchKey, CanonicalBranches, CanonicalBranchRow } from '../model' -import { deepEqual, getOwn, setOwn } from '../records' +import { getOwn, setOwn } from '../records' import type { MaterializeContext } from './context' +import { sharesEvidence, soleRename } from './rename' interface BranchWrite { /** The stored subBlock value: JSON text, or `null` for never-persisted rows. */ @@ -59,9 +60,8 @@ export function writeBranches( } /** - * The one row a branch rename left without a known id, with the one known id whose key no row - * holds any more, when the prev row under that key held the same expression; `null` unless there - * is exactly one of each, as a single key rename leaves. + * The one row a lone branch key rename left without a known id, with its id, when the prev row + * under the former key held the same expression (see {@link soleRename}). */ function renamedRowId( rows: readonly CanonicalBranchRow[], @@ -70,8 +70,6 @@ function renamedRowId( prevRows: readonly CanonicalBranchRow[], used: ReadonlySet ): { index: number; id: string } | null { - const unmatched = knownRowIds.flatMap((id, index) => (id === undefined ? [index] : [])) - if (unmatched.length !== 1) return null const keys = new Set(rows.map((row) => row.key)) const orphans = new Map() for (const source of knownIds) { @@ -79,10 +77,14 @@ function renamedRowId( if (!keys.has(key) && !used.has(id)) orphans.set(id, key) } } - const [index] = unmatched - const [orphan] = orphans - if (orphans.size !== 1 || index === undefined || orphan === undefined) return null - const [id, formerKey] = orphan - const former = prevRows.find((row) => row.key === formerKey) - return former && deepEqual(former.value, rows[index]?.value) ? { index, id } : null + const renamed = soleRename( + knownRowIds.flatMap((id, index) => (id === undefined ? [index] : [])), + [...orphans], + (index, formerKey) => { + const former = prevRows.find((row) => row.key === formerKey) + const row = rows[index] + return former !== undefined && row !== undefined && sharesEvidence(former, row, ['value']) + } + ) + return renamed && { index: renamed.item, id: renamed.id } } diff --git a/packages/workflow-code/src/materialize/index.test.ts b/packages/workflow-code/src/materialize/index.test.ts index c61457429ff..93129215d40 100644 --- a/packages/workflow-code/src/materialize/index.test.ts +++ b/packages/workflow-code/src/materialize/index.test.ts @@ -897,20 +897,20 @@ describe('materialize: identity', () => { }) }) - it('keeps the id of the one inputFormat field renamed to a field of the same type', () => { + it('keeps the id of the one inputFormat field renamed with its type and description', () => { const prev = workflowState([ blockState('start', 'start_trigger', 'Start', { inputFormat: [ - { id: 'f-n', name: 'n', type: 'number' }, + { id: 'f-n', name: 'n', type: 'number', description: 'How many' }, { id: 'f-q', name: 'q', type: 'string' }, ], }), ]) - const renamed = (to: string, type: string) => + const renamed = (to: string, type: string, description = 'How many') => edit(canonical(prev).workflow, (draft) => { const inputFormat = draft.blocks.start.params.inputFormat if (inputFormat.kind === 'value' && Array.isArray(inputFormat.value)) { - inputFormat.value[0] = { name: to, type } + inputFormat.value[0] = { name: to, type, description } } }) const ids = (workflow: CanonicalWorkflow) => @@ -922,6 +922,8 @@ describe('materialize: identity', () => { expect(ids(renamed('num', 'number'))).toEqual(['f-n', 'f-q']) expect(ids(renamed('label', 'string'))).toEqual(['new-1', 'f-q']) + // A shared type alone ties nothing: another field of that type is a delete and an add. + expect(ids(renamed('count', 'number', 'Rows to fetch'))).toEqual(['new-1', 'f-q']) }) it('keeps the id of the one variable renamed to a key of the same type', () => { @@ -939,6 +941,17 @@ describe('materialize: identity', () => { expect(ids(renamed('plain'))).toEqual(['new-1']) }) + it('treats an unrelated variable of the same type added beside a removed one as a delete and an add', () => { + const pulled = base() + const replaced = edit(canonical(pulled).workflow, (draft) => { + draft.variables = { region: { key: 'region', name: 'Region', type: 'number', value: 42 } } + }) + + expect(Object.keys(run(replaced, null, { prev: pulled }).state.variables ?? {})).toEqual([ + 'new-1', + ]) + }) + it('leaves an inputFormat id two fields share out of the identity items', () => { const prev = workflowState([ blockState('start', 'start_trigger', 'Start', { diff --git a/packages/workflow-code/src/materialize/index.ts b/packages/workflow-code/src/materialize/index.ts index 335d65561a7..d06ab4b50e2 100644 --- a/packages/workflow-code/src/materialize/index.ts +++ b/packages/workflow-code/src/materialize/index.ts @@ -26,6 +26,7 @@ import type { MaterializeContext, MaterializeHooks } from './context' import { type BranchHandles, writeEdges } from './edges' import { type IdentityEntry, type LockFreshness, resolveIdentity } from './identity' import { restorePreserved } from './preserve' +import { sharesEvidence, soleRename } from './rename' import { loopEntry, parallelEntry } from './subflows' import { rewriteRenamedReferences, rewriteStoredBlockReferences } from './values' @@ -98,11 +99,7 @@ function writeVariables( return { variables, idByKey } } -/** - * The one variable a rename left without a known id, with the one prev variable whose key the - * workflow no longer holds, when both have the same type; `null` unless there is exactly one of - * each, as a single key rename leaves. - */ +/** The one variable a lone key rename left without a known id, with its id (see {@link soleRename}). */ function renamedVariable( workflow: CanonicalWorkflow, knownIds: ReadonlyMap, @@ -110,16 +107,23 @@ function renamedVariable( used: ReadonlySet ): { key: VarKey; id: string } | null { if (!prevCanonical) return null - const unmatched = Object.keys(workflow.variables).filter((key) => !knownIds.has(key)) - const orphans = Object.entries(prevCanonical.identity.variables).filter( - ([key, id]) => !Object.hasOwn(workflow.variables, key) && !used.has(id) + const renamed = soleRename( + Object.keys(workflow.variables).filter((key) => !knownIds.has(key)), + Object.entries(prevCanonical.identity.variables).flatMap(([key, id]) => + !Object.hasOwn(workflow.variables, key) && !used.has(id) ? [[id, key] as const] : [] + ), + (key, formerKey) => { + const former = getOwn(prevCanonical.workflow.variables, formerKey) + const variable = getOwn(workflow.variables, key) + return ( + former !== undefined && + variable !== undefined && + former.type === variable.type && + sharesEvidence(former, variable, ['value']) + ) + } ) - const [key] = unmatched - const [orphan] = orphans - if (unmatched.length !== 1 || orphans.length !== 1 || key === undefined || !orphan) return null - const [formerKey, id] = orphan - const former = getOwn(prevCanonical.workflow.variables, formerKey) - return former?.type === getOwn(workflow.variables, key)?.type ? { key, id } : null + return renamed && { key: renamed.item, id: renamed.id } } /** diff --git a/packages/workflow-code/src/materialize/rename.ts b/packages/workflow-code/src/materialize/rename.ts new file mode 100644 index 00000000000..ca1b5dcfb1e --- /dev/null +++ b/packages/workflow-code/src/materialize/rename.ts @@ -0,0 +1,38 @@ +import { deepEqual } from '../records' + +/** + * The id a lone key rename carries over to the item it renamed: exactly one item has no known id, + * exactly one known id lost its key, and `continues(item, formerKey)` ties the two beyond their + * type (see {@link sharesEvidence}). `null` otherwise, so an unrelated delete and add in one edit + * stay a delete and an add, which the apply refuses without `allowDelete`. + */ +export function soleRename( + unmatched: readonly I[], + orphans: ReadonlyArray, + continues: (item: I, formerKey: K) => boolean +): { item: I; id: string } | null { + if (unmatched.length !== 1 || orphans.length !== 1) return null + const [item] = unmatched + const [[id, formerKey]] = orphans + return continues(item, formerKey) ? { item, id } : null +} + +/** Whether `value` says something about the item that holds it: not absent, empty or blank. */ +function isEvidence(value: unknown): boolean { + if (value === undefined || value === null) return false + if (typeof value === 'string') return value.trim() !== '' + if (Array.isArray(value)) return value.length > 0 + if (typeof value === 'object') return Object.keys(value).length > 0 + return true +} + +/** + * Whether two items (of one type: the caller checks it) are the same item under a new key: some + * field of `fields` holds a value in either, and every such field is equal in both. A shared type + * alone, or two empty values, ties nothing: `apiKey: string` removed and `region: string` added + * are a delete and an add. + */ +export function sharesEvidence(before: T, after: T, fields: ReadonlyArray): boolean { + const held = fields.filter((field) => isEvidence(before[field]) || isEvidence(after[field])) + return held.length > 0 && held.every((field) => deepEqual(before[field], after[field])) +} diff --git a/packages/workflow-code/src/structured/input-format.ts b/packages/workflow-code/src/structured/input-format.ts index 6cafc1389a2..0216cc4d007 100644 --- a/packages/workflow-code/src/structured/input-format.ts +++ b/packages/workflow-code/src/structured/input-format.ts @@ -12,6 +12,7 @@ import { unsupported } from '../compile/context' import { isJson, type LockItem } from '../lock' import type { MaterializeContext } from '../materialize/context' import type { ParamSite } from '../materialize/params' +import { sharesEvidence, soleRename } from '../materialize/rename' import { type BlockKey, isPlainRecord, type Value } from '../model' import { printKey } from '../print/strings' import { objectExpr, type Property } from '../print/syntax' @@ -212,9 +213,9 @@ function restoreInputFormatIds(list: unknown[], site: ParamSite, context: Materi } /** - * The one field a rename left without a known id, with the one known id whose name no field holds - * any more, when prev stored that id with the same type; `null` unless there is exactly one of - * each, as a single field rename leaves. + * The one field a lone rename left without a known id, with the id prev stored under the former + * name, when prev's field shares its type and its default value or description (see + * {@link soleRename}). */ function renamedFieldId( list: readonly unknown[], @@ -224,30 +225,36 @@ function renamedFieldId( prevById: ReadonlyMap>, used: ReadonlySet ): { index: number; id: string } | null { - const unmatched = list.flatMap((item, index) => - isRecordLike(item) && - item.id === undefined && - typeof item.name === 'string' && - unique.has(item.name) && - known[index] === undefined - ? [index] - : [] - ) - if (unmatched.length !== 1) return null const names = new Set(list.flatMap((item) => (isRecordLike(item) ? [item.name] : []))) - const orphans = new Set( - itemIds - .filter((entry) => !names.has(entry.name) && !used.has(entry.id)) - .map((entry) => entry.id) + const renamed = soleRename( + list.flatMap((item, index) => + isRecordLike(item) && + item.id === undefined && + typeof item.name === 'string' && + unique.has(item.name) && + known[index] === undefined + ? [index] + : [] + ), + [ + ...new Set( + itemIds + .filter((entry) => !names.has(entry.name) && !used.has(entry.id)) + .map((entry) => entry.id) + ), + ].map((id) => [id, id] as const), + (index, id) => { + const field = list[index] + const former = prevById.get(id) + return ( + isRecordLike(field) && + former !== undefined && + former.type === field.type && + sharesEvidence>(former, field, ['value', 'description']) + ) + } ) - const [index] = unmatched - const [id] = orphans - if (orphans.size !== 1 || index === undefined || id === undefined) return null - const field = list[index] - const former = prevById.get(id) - return isRecordLike(field) && former !== undefined && former.type === field.type - ? { index, id } - : null + return renamed && { index: renamed.item, id: renamed.id } } /** The record sugar as source: `name: 'type'`, or `name: { type, value?, description?, required? }`. */ From 24193a72fc5acdd9f5f4c8bbae483152871f677a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:19:28 -0800 Subject: [PATCH 055/104] fix(workflow-code): report $ref in a Python or shell file only when it names a reference A shell variable named ref or env before a dot (echo $ref.txt) was a W_CODE_FILE_REF_SYNTAX, which an edited file refuses, so a valid script could not be applied. A $ref now needs a path under a declared block (by key or const), loop, parallel or variable, and an $env a name the workspace declares when its names are known. --- packages/workflow-code/src/compile/blocks.ts | 21 +++++++++++++++++++ .../workflow-code/src/compile/grammar.test.ts | 21 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 445bdbf3c41..ae9b77c2e0d 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -459,6 +459,26 @@ const SCRIPT_LANGUAGE_LABEL: Record, str shell: 'Shell', } +/** + * Whether a `$ref`/`$env` match in a Python or shell file is a reference rather than the + * language's own text (a shell variable `$ref` before `.txt`): `$ref` needs a path under a block, + * `loop`, `parallel` or `variable`, and `$env` a name the workspace declares, when its names are + * known. + */ +function isScriptRef(ctx: CompileContext, root: string, names: readonly string[]): boolean { + const [head] = names + if (head === undefined) return false + if (root === 'env') return !ctx.envNames || ctx.envNames.has(head) + if (names.length < 2) return false + return ( + ctx.declsByKey.has(head) || + ctx.declsByIdent.has(head) || + head === 'loop' || + head === 'parallel' || + head === 'variable' + ) +} + /** * `W_CODE_FILE_REF_SYNTAX` on each `$ref.key.path` and `$env.NAME` in a Python or shell file: * only JavaScript files are rewritten, so these reach the run as text and break the code. The @@ -476,6 +496,7 @@ function reportScriptRefSyntax( for (const match of text.matchAll(SCRIPT_REF)) { const [written, root, members] = match const names = members.slice(1).split('.') + if (!isScriptRef(ctx, root, names)) continue const form = root === 'env' ? `{{${names[0]}}}` : `<${names.join('.')}>` ctx.reporter.report( 'W_CODE_FILE_REF_SYNTAX', diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 2bd53501f8b..d2e433b3e94 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1893,6 +1893,27 @@ describe('$ref and $env in a Python or shell code file', () => { ['workflows/functions/s.sh', 'Shell files are saved as written: write .'], ]) }) + + it('leaves a shell variable named ref or env alone when no block or env name follows it', () => { + const result = compileWorkflow({ + entry: { + path: ENTRY, + text: source( + [ + START, + "const sh = fn('Sh', { language: 'shell', code: codeFile('./functions/s.sh') })", + ].join('\n') + ), + }, + files: new Map([ + ['workflows/functions/s.sh', 'ref=out; env=dev\necho $ref.txt $ref.start $env.lower'], + ]), + catalog: TEST_CATALOG, + sdkMajor: 1, + envNames: new Set(['API_KEY']), + }) + expect(syntax(result)).toEqual([]) + }) }) describe('reference-shaped text that floods the warnings', () => { From cba4928001cf5da1ab537d28e29b9af12fe9bbab Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:21:48 -0800 Subject: [PATCH 056/104] docs(sim-cli): say the primer's run command runs the deployed version, and name both delete refusals The primer's run-and-debug step ran the deployed version, so an agent following the edit loop tested a stale deployment (or got not deployed) after each apply. It now says to apply --deploy first. The delete rule names E_APPLY_VARIABLE_DELETE beside E_APPLY_BLOCK_DELETE, a credential key points at sim workflows source resources, and the results line names the container's .results instead of an undefined lp. --- .../sim-cli/src/commands/protocol/source-primer.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index cbc004865dd..89664fbeaef 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -36,11 +36,11 @@ 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: the block keeps its id. 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, \`lp.results\`. A rename rewrites every \`$ref.\` in the function files to the new key. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). + 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\`). - **Look up a builder**: \`${PARAMS_COMMAND} \` (\`agent\`, \`trigger.schedule\`; a namespace like \`gmail\` lists its builders), offline. -- **Credentials**: \`sim credentials connect --name ""\`, give its link to the account owner, then name it \`credential('')\`. -- **Run and debug**: \`sim workflows run --input '{…}'\`; a failed run: \`sim logs get --trace --no-include-workflow-state\` (spans show resolved inputs). +- **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). - **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}\`.` } @@ -50,7 +50,7 @@ const WORKFLOW_PRIMER = `# Sim workflow source: primer **Edit loop**: edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`) → \`sim workflows source check --dir .\` (offline; it also adds new blocks to \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workflows source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. -- **Deletes**: removing a block's declaration deletes the block only with \`apply --allow-delete\`; without it the apply is refused (\`E_APPLY_BLOCK_DELETE\`); so does removing a variable. +- **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`). - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. ${sharedRules('sim workflows source')} ` From bb6245cb7fdaf760a923cc7e425a04365f45cdf4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:29:49 -0800 Subject: [PATCH 057/104] fix(workspace-source): vouch a deployment's draft by fingerprint alone, so a plan writes nothing A workspace plan read each deployment's draft with readWorkflowSource: it printed the whole source (refusing a first deploy over the print limits for every deployment in the directory), recorded a source-read analytics event per deployment and could allocate resource keys. The deployment adapter now asks readDraftFingerprint, which hashes the stored draft through the same canonicalization a read prints (withStoredCanonical) without printing, recording or allocating. draftSourceFingerprint and every dry run resolve only keys already bound (allocate: false), so the plan and dry-run docs that say they write nothing are now true. --- .../application/apply-workflow-source.ts | 1 + .../application/read-workflow-source.ts | 121 +++++++++++------- apps/sim/lib/workflows/code/resources.ts | 4 +- .../lib/workflows/code/stored-canonical.ts | 17 ++- .../application/deployments.integration.ts | 36 +++++- .../application/kinds/deployment/adapter.ts | 16 +-- .../workspaces/resource-keys.integration.ts | 23 ++++ apps/sim/lib/workspaces/resource-keys.ts | 4 +- 8 files changed, 165 insertions(+), 57 deletions(-) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index fcb0ec7574c..3152ae07bf8 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -479,6 +479,7 @@ async function runSourceApply( workflowId: context.workflowId, workspaceId: context.workspaceId, createdBy, + allocate: !dryRun, }), (shared.envNames ??= loadEnvNames(context.workspaceId, subjectUserId)), ]) diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index a9b0f9fcaf9..ab821839f34 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -50,6 +50,7 @@ import { type PrefetchedStoredResources, prefetchStoredResources, prefetchStoredResourcesFor, + type StoredCanonical, } from '@/lib/workflows/code/stored-canonical' import { parseWorkflowVariables } from '@/lib/workflows/variables/parse' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' @@ -154,11 +155,38 @@ export async function loadStoredSource( } } +/** + * Runs `use` on `stored` canonicalized against its source catalog and resource keys, inside the + * gate's custom block scope: the one canonicalization a source read prints and a fingerprint check + * hashes, so the two cannot disagree. + */ +function withStoredCanonical( + loaded: { + organizationId: string | null + gate: CatalogGate + prefetched: PrefetchedStoredResources + stored: StoredSource + }, + use: (canonical: StoredCanonical, catalog: ReturnType) => Promise +): Promise { + const { gate, prefetched, stored } = loaded + return withCatalogBlockScope(gate, async () => { + const catalog = buildSourceCatalog({ + gate, + organizationId: loaded.organizationId, + storedTypes: storedCatalogTypes(Object.values(stored.state.blocks)), + }) + const canonical = await canonicalizeStored({ prefetched, ...stored, catalog }) + return use(canonical, catalog) + }) +} + /** * The `sf1:` fingerprint a source read of `draft` would report as `base.fingerprint`: `draft` is a * graph of the workflow in `context` as the normalized tables load it (a deploy's snapshot), read * under the workflow's current name and description. A caller holding the fingerprint an apply - * answered with tells from it whether `draft` is still the draft that apply wrote. + * answered with tells from it whether `draft` is still the draft that apply wrote. Writes nothing: + * a resource with no key yet stays unkeyed (a draft holding one is not the draft any read printed). */ export async function draftSourceFingerprint( principal: Principal, @@ -171,6 +199,7 @@ export async function draftSourceFingerprint( workflowId: context.workflowId, workspaceId: context.workspaceId, createdBy: resolvePrincipalSubjectUserId(principal) ?? null, + allocate: false, }), ]) const state = { @@ -181,15 +210,10 @@ export async function draftSourceFingerprint( variables: parseWorkflowVariables(draft.variables) ?? {}, } const meta = { name: context.workflow.name, description: context.workflow.description ?? null } - return withCatalogBlockScope(gate, async () => { - const catalog = buildSourceCatalog({ - gate, - organizationId: context.workspaceOrganizationId, - storedTypes: storedCatalogTypes(Object.values(state.blocks)), - }) - const { canonical, resources } = await canonicalizeStored({ prefetched, state, meta, catalog }) - return storedSourceFingerprint(canonical, resources) - }) + return withStoredCanonical( + { organizationId: context.workspaceOrganizationId, gate, prefetched, stored: { state, meta } }, + async ({ canonical, resources }) => storedSourceFingerprint(canonical, resources) + ) } /** Everything one workflow's source read prints from, loaded by a single or a batched read. */ @@ -213,42 +237,39 @@ async function printLoadedSource( const { state, meta } = loaded.stored const counts = { blocks: Object.keys(state.blocks).length, edges: state.edges.length } assertFitsSourceLimits({ files: {}, entryDepth: 0 }, counts) - return withCatalogBlockScope(gate, async () => { - const catalog = buildSourceCatalog({ - gate, - organizationId: scope.workspaceOrganizationId, - storedTypes: storedCatalogTypes(Object.values(state.blocks)), - }) - const { canonical, resources } = await canonicalizeStored({ prefetched, state, meta, catalog }) - const canonicalHash = storedCanonicalHash(canonical, resources) - const printed = printStoredSource({ - state, - meta, - catalog, - resources, - sourceMeta, - functionCode, - lockless: canonical, - }) - assertFitsSourceLimits(printed, counts) - return { - workflowId: scope.workflowId, - workspaceId: scope.workspaceId, - files: printed.files, - lock: printed.lock, - base: { - version: 1, + return withStoredCanonical( + { organizationId: scope.workspaceOrganizationId, gate, prefetched, stored: loaded.stored }, + async ({ canonical, resources }, catalog) => { + const canonicalHash = storedCanonicalHash(canonical, resources) + const printed = printStoredSource({ + state, + meta, + catalog, + resources, + sourceMeta, + functionCode, + lockless: canonical, + }) + assertFitsSourceLimits(printed, counts) + return { workflowId: scope.workflowId, workspaceId: scope.workspaceId, - fingerprint: printed.fingerprint, - catalogHash: catalog.hash, - }, - canonicalHash, - sdkMajor: catalog.sdkMajor, - blockTypes: usedBlockTypes(canonical.workflow), - diagnostics: [...canonical.diagnostics, ...printed.diagnostics].map(toReadDiagnostic), + files: printed.files, + lock: printed.lock, + base: { + version: 1, + workflowId: scope.workflowId, + workspaceId: scope.workspaceId, + fingerprint: printed.fingerprint, + catalogHash: catalog.hash, + }, + canonicalHash, + sdkMajor: catalog.sdkMajor, + blockTypes: usedBlockTypes(canonical.workflow), + diagnostics: [...canonical.diagnostics, ...printed.diagnostics].map(toReadDiagnostic), + } } - }) + ) } /** @@ -284,6 +305,20 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ }, }) +/** + * The `sf1:` fingerprint of the workflow's stored draft ({@link draftSourceFingerprint}), for a + * caller that needs only to tell whether the draft is one it vouches for (a workspace plan's + * deployment). Prints nothing, so no source limit applies, and records and writes nothing. + */ +export const readDraftFingerprint = defineAuthorizedWorkflowUseCase({ + operation: workflowOperations.readSource, + resolveContext: resolvePrincipalWorkflowContext<{ workflowId: string }>, + async execute({ principal, context }): Promise { + const { state } = await loadStoredSource(context) + return draftSourceFingerprint(principal, context, state) + }, +}) + interface ReadWorkflowSourcesInput { workspaceId: string /** Workflows of the workspace to read; one archived or in another workspace reads as missing. */ diff --git a/apps/sim/lib/workflows/code/resources.ts b/apps/sim/lib/workflows/code/resources.ts index 245f6dd5c83..6e4f452296f 100644 --- a/apps/sim/lib/workflows/code/resources.ts +++ b/apps/sim/lib/workflows/code/resources.ts @@ -140,6 +140,8 @@ interface LoadResourceKeyResolverOptions { * which sees the shared credentials only. */ actorUserId: string | null + /** `false` resolves only the keys already bound, allocating none (a plan writes nothing). */ + allocate?: boolean } /** @@ -164,7 +166,7 @@ export async function loadResourceKeyResolver( resolveKeys( workspaceId, idRefs.filter((ref) => ref.kind !== 'credential' || !hiddenRefIds.has(ref.id)), - { createdBy: options.actorUserId } + { createdBy: options.actorUserId, allocate: options.allocate } ), withoutHiddenCredentials(workspaceId, actorUserId, boundIdsByKey), ]) diff --git a/apps/sim/lib/workflows/code/stored-canonical.ts b/apps/sim/lib/workflows/code/stored-canonical.ts index 6579c00ffb3..f24b2cd5eb1 100644 --- a/apps/sim/lib/workflows/code/stored-canonical.ts +++ b/apps/sim/lib/workflows/code/stored-canonical.ts @@ -40,6 +40,11 @@ interface StoredResourceScope { * credential access bounds which credentials print by key. `null` for an actorless caller. */ createdBy: string | null + /** + * `false` resolves only the resource keys already bound, allocating none, so a plan or a + * fingerprint check writes nothing. + */ + allocate?: boolean } /** The resolver for a workflow's remembered references, loaded before its graph is. */ @@ -58,6 +63,7 @@ export async function prefetchStoredResources( const loaded = referencesByWorkflow.get(scope.workflowId) ?? { ids: [], keys: [] } const resources = await loadResourceKeyResolver(scope.workspaceId, loaded, { actorUserId: scope.createdBy, + allocate: scope.allocate, }) return { ...scope, loaded, resources } } @@ -78,6 +84,7 @@ export async function prefetchStoredResourcesFor( } const resources = await loadResourceKeyResolver(scope.workspaceId, loaded, { actorUserId: scope.createdBy, + allocate: scope.allocate, }) return { ...scope, loaded, resources } } @@ -112,11 +119,12 @@ function unionReferences(base: ResourceReferences, extra: ResourceReferences): R * Canonicalizes the stored graph with its resource keys, normally in one pass. The result equals * a recording pass followed by a pass over a resolver for exactly the recorded references. This is * the single entry point for canonicalizing a stored workflow with resources: keys come only from - * the workspace's persisted resource keys (`resolveKeys` / `resolveIds`), allocated on first reference. + * the workspace's persisted resource keys (`resolveKeys` / `resolveIds`), allocated on first reference + * unless the prefetch was made with `allocate: false`. */ export async function canonicalizeStored(input: StoredCanonicalInput): Promise { const { state, meta, catalog } = input - const { workflowId, workspaceId, createdBy } = input.prefetched + const { workflowId, workspaceId, createdBy, allocate } = input.prefetched let { loaded, resources } = input.prefetched for (;;) { const referenced: ResourceReferences = { ids: [], keys: [] } @@ -147,6 +155,9 @@ export async function canonicalizeStored(input: StoredCanonicalInput): Promise { expect(result.base.resources['deployment:nightly']?.id).toBe(await workflowId(workspaceId)) }) + check( + 'plans a redeploy of a draft the directory vouches for without recording a source read', + async () => { + const workspaceId = await workspaces.create({ name: 'Plan vouches quietly', ownerId }) + const created = await apply(workspaceId, { [WORKFLOW]: NIGHTLY, [DEPLOYMENT]: DRAFT }) + expect(created.failed).toBeUndefined() + const { [DEPLOYMENT]: _deployment, ...workflowFiles } = created.files + const edited = await apply( + workspaceId, + { ...workflowFiles, [WORKFLOW]: created.files[WORKFLOW].replace("'02:00'", "'03:00'") }, + { kinds: ['workflow'], base: created.base } + ) + expect(edited.failed).toBeUndefined() + const read = await getAll(workspaceId, ['workflow', 'deployment']) + posthogServerMockFns.mockCaptureServerEvent.mockClear() + + const plan = await apply( + workspaceId, + { ...read.files, [DEPLOYMENT]: DRAFT }, + { + base: read.base, + dryRun: true, + principal: createPersonalApiKeyPrincipal({ userId: ownerId, keyId: generateId() }), + } + ) + + expect(actions(plan.plan)).toContain('update deployment:nightly') + expect( + posthogServerMockFns.mockCaptureServerEvent.mock.calls.map(([, event]) => event) + ).not.toContain('workflow_source_read') + } + ) + check( 'a get prints a deployment for each deployed workflow and applies back as a no-op', async () => { diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 37346edc310..f2ca11cb726 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -58,7 +58,7 @@ import { } from '@/lib/workflows/application/deployments' import { listWorkflows } from '@/lib/workflows/application/list-workflows' import { workflowOperations } from '@/lib/workflows/application/operations' -import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' +import { readDraftFingerprint } from '@/lib/workflows/application/read-workflow-source' import { updateWorkflowPublicApi } from '@/lib/workflows/application/update-workflow-deployment-settings' import { ResourceChangedError, @@ -399,11 +399,10 @@ async function vouchedDraft( if (!workflowId) return undefined const base = folder?.decl ? workflowSourceBase(folder.decl) : null if (!base && (folder || !options.firstDeploy)) return undefined - const read = await readWorkflowSource.execute({ + const fingerprint = await readDraftFingerprint.execute({ principal: ctx.principal, input: { workflowId }, }) - const fingerprint = read.base.fingerprint if (base && (base.workflowId !== workflowId || base.fingerprint !== fingerprint)) return undefined return { fingerprint } } @@ -593,11 +592,12 @@ async function planDeployment( // A chat write redeploys a draft that differs from the live version: it may publish only the // draft the plan vouched for, or else the one it saw, never one edited since. if (writesChat && !detail.draft && workflowId) { - const seen = await readWorkflowSource.execute({ - principal: ctx.principal, - input: { workflowId }, - }) - detail.draft = { fingerprint: seen.base.fingerprint } + detail.draft = { + fingerprint: await readDraftFingerprint.execute({ + principal: ctx.principal, + input: { workflowId }, + }), + } } // A chat the apply keeps goes live with the edited draft all the same. const publishesEditedDraft = detail.deploy && draftEdited diff --git a/apps/sim/lib/workspaces/resource-keys.integration.ts b/apps/sim/lib/workspaces/resource-keys.integration.ts index c8a575ef7d7..9a95fc5604a 100644 --- a/apps/sim/lib/workspaces/resource-keys.integration.ts +++ b/apps/sim/lib/workspaces/resource-keys.integration.ts @@ -350,6 +350,29 @@ describe('workspace resource keys against PostgreSQL', () => { expect(await keyRows(workspaceId, 'table', foreign)).toEqual([]) }) + it('resolves only bound keys and allocates none when a read asks it not to', async () => { + const bound = generateId() + const unbound = generateId() + await insertTable(bound, workspaceId, 'Bound', at(35)) + await insertTable(unbound, workspaceId, 'Unbound', at(36)) + expect(await keyOf('table', bound)).toBe('bound') + + const resolver = await loadResourceKeyResolver( + workspaceId, + { + ids: [ + { kind: 'table', id: bound }, + { kind: 'table', id: unbound }, + ], + }, + { actorUserId: userId, allocate: false } + ) + + expect(resolver.toKey('table', bound)).toBe('bound') + expect(resolver.toKey('table', unbound)).toBeNull() + expect(await keyRows(workspaceId, 'table', unbound)).toEqual([]) + }) + it('allocates inside the caller’s transaction and rolls back with it', async () => { const id = generateId() await insertTable(id, workspaceId, 'Rollback', at(40)) diff --git a/apps/sim/lib/workspaces/resource-keys.ts b/apps/sim/lib/workspaces/resource-keys.ts index 39d3117cef3..c2a4ce40495 100644 --- a/apps/sim/lib/workspaces/resource-keys.ts +++ b/apps/sim/lib/workspaces/resource-keys.ts @@ -194,6 +194,8 @@ interface ResourceKeyOptions { interface ResolveKeysOptions extends ResourceKeyOptions { /** The human the allocation is attributed to; `null` for an actorless caller. */ createdBy?: string | null + /** `false` leaves a resource with no key out instead of allocating it one (a read that writes nothing). */ + allocate?: boolean } function trimKey(value: string, maxLength: number): string { @@ -397,7 +399,7 @@ export async function resolveKeys( live.map((row) => row.id) ) const unbound = live.filter((row) => !keys.has(row.id)) - if (unbound.length > 0) { + if (unbound.length > 0 && options.allocate !== false) { const allocated = await allocateKeys( executor, workspaceId, From cae3e4de1c5baa259731f1bdc626d18d8b84293d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:31:39 -0800 Subject: [PATCH 058/104] fix(workflow-persistence): refuse an edge to a block the saved state does not hold The diff-based save kept an unchanged edge and then deleted the block it named, whose cascade dropped the edge while the save reported success; the full replace it replaced refused such a state with a foreign-key violation. The save now refuses it before writing anything. The property test now applies one to five edits per save, including a retype under the same id, and the suite covers an edge id another workflow owns and a stored edge id repeated in one state (the unique violation, not 21000), each leaving the graph as it was. --- .../normalized-save.integration.ts | 100 +++++++++++++++++- packages/workflow-persistence/src/save.ts | 15 ++- 2 files changed, 110 insertions(+), 5 deletions(-) diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts index 2354fd84143..337692b89b8 100644 --- a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -4,7 +4,8 @@ * random edit sequences (add, remove, modify, move into a subflow, retarget and drop edges, replace a block * under the edges it keeps) are * saved both ways and the rows compared. A one-field edit rewrites one row, and an id owned by another - * workflow is still refused with the unique violation callers map to a conflict. + * workflow is still refused with the unique violation callers map to a conflict, as are an edge id + * repeated in one state and an edge to a block the state does not hold. */ import { db } from '@sim/db' import { user, workflow, workflowBlocks, workflowEdges, workflowSubflows } from '@sim/db/schema' @@ -124,7 +125,10 @@ async function fullReplaceRows(workflowId: string, state: WorkflowState) { }) } -/** One random edit of the kinds a source apply, operations apply or Copilot edit makes. */ +/** + * One random edit of the kinds a source apply, operations apply or Copilot edit makes, a retype + * under the same id included. + */ function mutate(state: WorkflowState, random: () => number): WorkflowState { const blocks = Object.values(state.blocks).map((block) => structuredClone(block)) let edges = state.edges.map((edge) => ({ ...edge })) @@ -161,7 +165,13 @@ function mutate(state: WorkflowState, random: () => number): WorkflowState { } } else if (edit === 2) { const target = pick(functions) - if (target) target.subBlocks.code = { id: 'code', type: 'code', value: `return ${random()}` } + if (!target) return stateOf(blocks, edges) + if (random() < 0.5) { + target.subBlocks.code = { id: 'code', type: 'code', value: `return ${random()}` } + } else { + target.type = 'api' + target.subBlocks = { url: { id: 'url', type: 'short-input', value: 'https://example.com' } } + } } else if (edit === 3) { const target = pick(blocks) if (target) target.position = { x: Math.floor(random() * 2000), y: Math.floor(random() * 900) } @@ -238,7 +248,9 @@ describe('saveWorkflowToNormalizedTables', () => { expect(await saveWorkflowToNormalizedTables(workflowId, state)).toEqual({ success: true }) for (let step = 0; step < 40; step++) { - state = mutate(state, random) + // Real applies batch edits, and the risky orderings come from combinations of them. + const edits = 1 + Math.floor(random() * 5) + for (let applied = 0; applied < edits; applied++) state = mutate(state, random) expect(await saveWorkflowToNormalizedTables(workflowId, state)).toEqual({ success: true }) const diffed = await storedRows(db, workflowId) expect(diffed, `seed ${seed} step ${step}`).toEqual( @@ -296,4 +308,84 @@ describe('saveWorkflowToNormalizedTables', () => { expect(await storedRows(db, workflowId)).toEqual(before) expect((await storedRows(db, owner)).blocks.map((block) => block.name)).toEqual(['Claimed']) }) + + it('refuses an edge id another workflow owns and leaves the stored graph as it was', async () => { + const owner = await insertWorkflow() + const workflowId = await insertWorkflow() + const [a, b] = [functionBlock(generateId(), 'A', 0), functionBlock(generateId(), 'B', 100)] + const [c, d] = [functionBlock(generateId(), 'C', 0), functionBlock(generateId(), 'D', 100)] + const edgeId = generateId() + await saveWorkflowToNormalizedTables( + owner, + stateOf([a, b], [{ id: edgeId, source: a.id, target: b.id }]) + ) + await saveWorkflowToNormalizedTables(workflowId, stateOf([c, d], [])) + const before = await storedRows(db, workflowId) + + const refused = await db + .transaction((tx) => + saveWorkflowToNormalizedTables( + workflowId, + stateOf([c, d], [{ id: edgeId, source: c.id, target: d.id }]), + tx + ) + ) + .then( + () => undefined, + (error: unknown) => error + ) + + expect(getPostgresErrorCode(refused)).toBe('23505') + expect(await storedRows(db, workflowId)).toEqual(before) + }) + + it('refuses a state repeating a stored edge id, with the unique violation and nothing written', async () => { + const workflowId = await insertWorkflow() + const [a, b, c] = ['A', 'B', 'C'].map((name, index) => + functionBlock(generateId(), name, index * 100) + ) + const edgeId = generateId() + await saveWorkflowToNormalizedTables( + workflowId, + stateOf([a, b, c], [{ id: edgeId, source: a.id, target: b.id }]) + ) + const before = await storedRows(db, workflowId) + + const refused = await db + .transaction((tx) => + saveWorkflowToNormalizedTables( + workflowId, + stateOf( + [a, b, c], + [ + { id: edgeId, source: a.id, target: b.id }, + { id: edgeId, source: b.id, target: c.id }, + ] + ), + tx + ) + ) + .then( + () => undefined, + (error: unknown) => error + ) + + expect(getPostgresErrorCode(refused)).toBe('23505') + expect(await storedRows(db, workflowId)).toEqual(before) + }) + + it('refuses an edge to a block the state removes, as a full replace did, and writes nothing', async () => { + const workflowId = await insertWorkflow() + const [a, b] = [functionBlock(generateId(), 'A', 0), functionBlock(generateId(), 'B', 100)] + const edges = [{ id: generateId(), source: a.id, target: b.id }] + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf([a, b], edges))).toEqual({ + success: true, + }) + const before = await storedRows(db, workflowId) + + const saved = await saveWorkflowToNormalizedTables(workflowId, stateOf([a], edges)) + + expect(saved.success).toBe(false) + expect(await storedRows(db, workflowId)).toEqual(before) + }) }) diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index 5d1096ffb2d..ffcdad3faa6 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -195,7 +195,8 @@ async function deleteRows( /** * Makes the workflow's normalized block, edge and subflow rows match `state`, leaving the rows a - * delete-all and re-insert would leave. Only the difference is written: rows whose stored columns + * delete-all and re-insert would leave; a state with an edge to a block it does not hold is + * refused before anything is written, as that re-insert's foreign keys refused it. Only the difference is written: 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. * @@ -219,8 +220,20 @@ export async function saveWorkflowToNormalizedTables( targetHandle: normalizeWorkflowEdgeTargetHandle(edge.targetHandle) ?? null, })) const desiredSubflows = toSubflowRows(workflowId, blockRecords) + const desiredBlockIds = new Set(desiredBlocks.map((block) => block.id)) + const dangling = desiredEdges.find( + (edge) => !desiredBlockIds.has(edge.sourceBlockId) || !desiredBlockIds.has(edge.targetBlockId) + ) const execute = async (tx: DbOrTx) => { + // The diff keeps an unchanged edge and deletes the block it names, whose cascade would then + // drop it silently; a full replace refused such a state with a foreign-key violation, so this + // refuses it before writing anything. + if (dangling) { + throw new Error( + `Edge ${dangling.id} connects a block the saved state does not hold (${dangling.sourceBlockId} → ${dangling.targetBlockId})` + ) + } const [storedBlocks, storedEdges, storedSubflows] = await Promise.all([ tx .select() From d3dddcc7fa84946139ce02a14bd795fe04903054 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:32:39 -0800 Subject: [PATCH 059/104] fix(workflow-code): keep the did-you-mean for a handle typo that names an SDK export Reading api.result beside a block const named api1, with api not imported, reported only that api is not imported, and following that advice led to api being an SDK function. A read of an unimported SDK name now leads with the did-you-mean over visible names when one is close, and names the import second; with no near name it still names the import. --- .../workflow-code/src/compile/checks.test.ts | 23 +++++++++++++++++++ packages/workflow-code/src/compile/context.ts | 20 ++++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index c4e5829f4b4..33af4dea231 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -522,6 +522,29 @@ describe('an SDK export the file did not import', () => { })) ) }) + + it('suggests the block handle a read of an unimported SDK name is close to, before the import', () => { + const result = compileWith( + 'fn, js, trigger, workflow', + [ + START, + "const api1 = fn('Api', { code: 'return 1' })", + "const next = fn('Next', { code: js`return ${api.result}` })", + 'start.to(api1)', + 'api1.to(next)', + ].join('\n') + ) + expect( + result.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ message: d.message, hint: d.hint })) + ).toEqual([ + { + message: 'api is not defined.', + hint: "Did you mean api1? (api is also an SDK export, which needs adding to the import from '@sim/workflow-sdk'.)", + }, + ]) + }) }) describe('a misspelled required param', () => { diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 52acc1cbc45..f65afe14229 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -288,7 +288,8 @@ export function reportNotImported( /** * Reports an identifier `scope` does not bind: `E_OUT_OF_SCOPE` when a block inside another loop or - * parallel holds the name, else `E_UNKNOWN_IDENTIFIER` with a did-you-mean over the visible names. + * parallel holds the name, else `E_UNKNOWN_IDENTIFIER` with a did-you-mean over the visible names + * (an SDK export not imported names the import, after any did-you-mean). * `at` is what the out-of-scope error covers (a whole member chain for a reference). Returns `null`. */ export function reportUnresolvedIdentifier( @@ -311,7 +312,22 @@ export function reportUnresolvedIdentifier( return null } if (isSdkImportable(ctx, identifier.name)) { - return reportNotImported(ctx, 'E_UNKNOWN_IDENTIFIER', identifier.name, identifier, blockKey) + // A read of `agent` beside a block named agent1 is a typo of the handle more often than a + // missing import: the did-you-mean leads, and the import is the second clause. + const near = didYouMean(identifier.name, visibleNames(scope)) + if (!near) { + return reportNotImported(ctx, 'E_UNKNOWN_IDENTIFIER', identifier.name, identifier, blockKey) + } + ctx.reporter.report( + 'E_UNKNOWN_IDENTIFIER', + `${identifier.name} is not defined.`, + rangeOf(ctx, identifier), + { + hint: `${near} (${identifier.name} is also an SDK export, which needs adding to the import from '${SDK_MODULE}'.)`, + blockKey, + } + ) + return null } ctx.reporter.report( 'E_UNKNOWN_IDENTIFIER', From f8d024cf44e0baef0e76e14f1aa0f131a3215290 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:34:26 -0800 Subject: [PATCH 060/104] fix(sim-cli): never refresh workspace types on a dry run, nor wait on a 429 for them apply --dry-run, whose help says it writes no files, rewrote .sim/sdk/workspace.d.ts and the manifest, and the optional resource listing behind that refresh was resent up to six times on a 429, holding up the apply about a minute. A dry run now skips the refresh, and the refresh sends its listing with retryRateLimited: false, which the client now honours for a GET too. --- .../src/commands/protocol/source-tree.ts | 13 +++++++++---- .../protocol/workflow-source-apply.test.ts | 18 +++++++++++++++++- .../commands/protocol/workflow-source-apply.ts | 6 ++++-- .../protocol/workflow-source-roundtrip.test.ts | 4 ++-- packages/sim-cli/src/http/client.test.ts | 15 +++++++++++++++ packages/sim-cli/src/http/client.ts | 5 +++-- 6 files changed, 50 insertions(+), 11 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index f7874c01973..4fae7aecd3b 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -353,11 +353,13 @@ function workspaceTypesFrom( export async function loadWorkspaceTypes( client: OperationClient<'getSourceResources'>, workspaceId: string, - local: LocalDeclarations = {} + local: LocalDeclarations = {}, + options: { optional?: boolean } = {} ): Promise { try { const { data } = await client.request('getSourceResources', { params: { workspaceId }, + ...(options.optional ? { retryRateLimited: false } : {}), }) return workspaceTypesFrom(workspaceManifestFrom(data), local) } catch (error) { @@ -396,11 +398,12 @@ export async function refreshWorkspaceTypes(dir: string, local: LocalDeclaration * Re-reads the workspace's resources into a workflow directory's `workspace.d.ts` and the manifest * kept beside it, so `tsc` types a resource created since the last get (a child workflow, a table, * a credential) instead of refusing its key, and stops accepting one deleted since. The commands - * that already talk to the server (apply, its dry run and plan, create, status) call it; an offline + * that already talk to the server (apply, create, status) call it; an offline * check cannot. Only a directory holding types the CLI wrote is touched (a workflow folder of a * workspace directory types its workflows at the root, which the workspace commands refresh), only * a file whose text changes is rewritten, and a failure to list the resources (a rate limit, a - * dropped connection) leaves the files as they are: the types are a convenience, never the write. + * dropped connection) leaves the files as they are: the types are a convenience, never the write, + * so a rate-limited listing is not resent. A dry run, which writes no files, does not call it. */ export async function refreshWorkflowWorkspaceTypes( client: OperationClient<'getSourceResources'>, @@ -412,7 +415,9 @@ export async function refreshWorkflowWorkspaceTypes( readSourceText(dir, WORKSPACE_MANIFEST_FILE), ]) if (types === null || manifest === null) return - const fresh = await loadWorkspaceTypes(client, workspaceId).catch(() => null) + const fresh = await loadWorkspaceTypes(client, workspaceId, {}, { optional: true }).catch( + () => null + ) if (!fresh?.stored) return const stored = `${JSON.stringify(fresh.stored, null, 2)}\n` const write = [ 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 5fb19ca9ec2..a9a2aa94613 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 @@ -11,7 +11,7 @@ import { buildGeneratedCommands } from '../../runtime/build' import { cacheCatalogText } from '../../test/catalog-cache' import { contextMockFns, contextMockState } from '../../test/context-mock' import { digest } from './source-dir' -import { TSCONFIG_MARKER } from './source-tree' +import { TSCONFIG_MARKER, WORKSPACE_TYPES_FILE } from './source-tree' import { attachWorkflowSourceApply, attachWorkflowSourceCreate } from './workflow-source-apply' const prompt = vi.hoisted(() => ({ @@ -314,6 +314,22 @@ describe('sim workflows source apply', () => { expect(readFileSync(join(dir, 'workflow.ts'), 'utf8')).toBe(ENTRY) }) + it('neither reads nor rewrites the workspace types on a dry run', async () => { + mkdirSync(join(dir, '.sim/sdk'), { recursive: true }) + writeFileSync(join(dir, WORKSPACE_TYPES_FILE), '// types the last get wrote\n') + writeFileSync(join(dir, '.sim/sdk/workspace.manifest.json'), '{}\n') + request.mockResolvedValue(outcome({ dryRun: true })) + + await apply(WORKFLOW_ID, '--dir', dir, '--dry-run') + + expect(request.mock.calls.map((call) => call[0])).not.toContainEqual( + expect.stringContaining('/source/resources') + ) + expect(readFileSync(join(dir, WORKSPACE_TYPES_FILE), 'utf8')).toBe( + '// types the last get wrote\n' + ) + }) + it('at a terminal, shows the dry run and applies once the person confirms', async () => { setTerminal(true) request.mockImplementation(async (_path: string, options: { query?: { dryRun?: boolean } }) => 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 c1f436a9563..d50d78befbc 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -501,7 +501,9 @@ export function attachWorkflowSourceApply(source: Command): void { const base = await readBase(options.dir, named) const workflowId = base.workflowId const files = await readSourceFiles(options.dir, lock) - await refreshWorkflowWorkspaceTypes(client, options.dir, base.workspaceId) + if (!options.dryRun) { + await refreshWorkflowWorkspaceTypes(client, options.dir, base.workspaceId) + } await runSourceWrite<'applyWorkflowSource'>({ options, creating: false, @@ -598,7 +600,7 @@ export function attachWorkflowSourceCreate(source: Command): void { profile.sources.workspaceId === 'flag' ? null : await readStarterWorkspace(options.dir) const workspaceId = client.requireWorkspace(starterWorkspace ?? undefined) const files = await readSourceFiles(options.dir, null) - await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) + if (!options.dryRun) await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) await runSourceWrite<'createWorkflowFromSource'>({ options, creating: true, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 94d6fd1d2e4..4a2d98d4f40 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -487,13 +487,13 @@ describe('the workspace-scoped source reads', () => { }) describe('catalog and declarations', () => { - it('types a workflow created since the get once an apply or its dry run talks to the server', async () => { + it('types a workflow created since the get once an apply talks to the server', async () => { await get() expect(read('.sim/sdk/workspace.d.ts')).not.toContain("'handbook-answer'") const child = { key: 'handbook-answer', id: 'wf-child', name: 'Handbook Answer', inputs: [] } server.manifest = () => json({ data: { ...MANIFEST, workflows: [child] } }) - await sim('workflows', 'source', 'apply', WORKFLOW_ID, '--dir', dir, '--dry-run') + await sim('workflows', 'source', 'apply', WORKFLOW_ID, '--dir', dir, '--yes') expect(read('.sim/sdk/workspace.d.ts')).toContain("'handbook-answer'") expect(JSON.parse(read('.sim/sdk/workspace.manifest.json')).workflows).toHaveProperty( diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index cd84dc5496f..ee04ffdb25c 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -551,6 +551,21 @@ describe('rate limiting', () => { ).rejects.toMatchObject({ status: 429, retryAfterMs: 30_000 }) }) + it('never resends a GET whose caller opted out, so an optional read never waits on a limit', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const fetch = vi.fn().mockResolvedValue(limited()) + vi.stubGlobal('fetch', fetch) + + const outcome = await settle( + client().request('/api/v2/workspaces/ws_1/workflows/source/resources', { + retryRateLimited: false, + }) + ) + + expect(outcome.status).toBe('rejected') + expect(fetch).toHaveBeenCalledTimes(1) + }) + it('resends a write that declared itself safe to resend after a 429', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) const fetch = vi diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 8f80810cb14..1e50672c1c2 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -74,7 +74,8 @@ export interface RequestOptions { /** * Resend a write the server answered `429`, as every GET is. Only for a route that rate limits * before it acts: a v2 route charges its bucket at admission, ahead of the use case, so the - * refused request did nothing and sending it again is sending it for the first time. + * refused request did nothing and sending it again is sending it for the first time. `false` + * never resends, a GET included: for an optional read a caller would rather skip than wait on. */ retryRateLimited?: boolean } @@ -393,7 +394,7 @@ const RATE_LIMIT_RETRY_AFTER_MAX_MS = 60_000 /** Whether a request answered `429` may be sent again: a GET, or a write that opted in. */ function resendsRateLimited(method: string, options: RequestOptions): boolean { - return method === 'GET' || options.retryRateLimited === true + return options.retryRateLimited ?? method === 'GET' } /** The rate-limit refusal a command exits with, saying what to do about it. */ From 8f877955ba0d258f6cb461e2d02bbf3c60f34e96 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:40:03 -0800 Subject: [PATCH 061/104] refactor: settle the wave-1 cleanliness polish items - Puts the WorkflowBlockHandler and deployDraft TSDoc back above their declarations. - compileConfig looks a config key up once. - The plan route, its OpenAPI text and PlanWorkflowSourceInput say allowDelete plans block and variable deletes (E_APPLY_VARIABLE_DELETE too). - WORKFLOW_CODE_FEATURE lives with isWorkflowCodeEnabled, which reads its flag name, and both operations modules import it from there. - provenanceGitShaSchema and sourceFingerprintSchema replace the copied gitSha and sf1 regexes. - The workspace plan use case is planWorkspaceSource, matching the workflow side and the operationId; the internal planner is buildWorkspacePlan; the CLI status aliases are PlanData. --- apps/docs/openapi-v2-workflows.json | 6 +++--- .../[workspaceId]/source/plan/route.test.ts | 2 +- .../workspaces/[workspaceId]/source/plan/route.ts | 4 ++-- apps/sim/executor/handlers/workflow/handler.ts | 8 ++++---- .../api/contracts/v2/openapi/workflow-source.ts | 4 ++-- apps/sim/lib/api/contracts/v2/workflow-source.ts | 11 +++++++---- apps/sim/lib/api/contracts/v2/workflows.ts | 8 ++------ apps/sim/lib/api/contracts/v2/workspace-source.ts | 5 ++--- apps/sim/lib/api/contracts/workflow-source.ts | 7 +++++++ apps/sim/lib/api/mcp/generated/v2-operations.ts | 2 +- .../application/apply-workflow-source.ts | 2 +- .../workflows/application/code-availability.ts | 2 +- apps/sim/lib/workflows/application/operations.ts | 11 +---------- apps/sim/lib/workflows/code/feature-flag.ts | 15 +++++++++++++-- .../application/apply-workspace-source.ts | 12 ++++++------ .../application/kinds/deployment/adapter.ts | 8 ++++---- .../application/mcp.integration.ts | 4 ++-- .../workspace-source/application/operations.ts | 2 +- apps/sim/lib/workspace-source/application/plan.ts | 2 +- .../application/status.integration.ts | 4 ++-- .../commands/protocol/workflow-source-status.ts | 8 ++++---- .../commands/protocol/workspace-source-status.ts | 14 +++++++------- packages/sim-cli/src/generated/v2-api.ts | 2 +- packages/workflow-code/src/compile/blocks.ts | 3 +-- 24 files changed, 76 insertions(+), 70 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 81b96cece92..d1b9e6b6b43 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6242,7 +6242,7 @@ "post": { "operationId": "planWorkflowSource", "summary": "Plan workflow source", - "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "description": "Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block and variable deletes instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", "x-sim-operation": "workflows.source.plan", "x-oauth-scope": "api:read", "tags": ["Workflows"], @@ -6271,9 +6271,9 @@ "name": "allowDelete", "in": "query", "required": false, - "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "description": "Plan the deletes of blocks and variables the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`.", "schema": { - "description": "Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.", + "description": "Plan the deletes of blocks and variables the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`.", "type": "boolean" } } diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts index 211c21b8dee..1c6df0fab07 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts @@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({ plan: vi.fn() })) vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => v2ApiKeyAuthModuleMock) vi.mock('@/lib/core/rate-limiter', () => v2RateLimiterModuleMock) vi.mock('@/lib/workspace-source/application/apply-workspace-source', () => ({ - readWorkspaceSourcePlan: { operation: { id: 'workspaces.source.plan' }, execute: mocks.plan }, + planWorkspaceSource: { operation: { id: 'workspaces.source.plan' }, execute: mocks.plan }, })) import { POST } from '@/app/api/v2/workspaces/[workspaceId]/source/plan/route' diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts index e185e8494e7..39f2fcf1e15 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts @@ -6,7 +6,7 @@ import { v2WorkspaceSourceErrorPolicy, workspaceApplyRateCost, } from '@/lib/workspace-source/api/route-policies' -import { readWorkspaceSourcePlan } from '@/lib/workspace-source/application/apply-workspace-source' +import { planWorkspaceSource } from '@/lib/workspace-source/application/apply-workspace-source' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' export const dynamic = 'force-dynamic' @@ -37,6 +37,6 @@ export const POST = defineV2JsonRoute({ ...(body.options?.allowDelete !== undefined ? { allowDelete: body.options.allowDelete } : {}), }), rateLimitCost: (input) => workspaceApplyRateCost(input.files, input.blobs), - useCase: withSourceSlot(readWorkspaceSourcePlan, 'plan'), + useCase: withSourceSlot(planWorkspaceSource, 'plan'), present: (result) => ({ data: result }), }) diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index 361c4afbc15..47cbc594aba 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -190,10 +190,6 @@ type WorkflowTraceSpan = TraceSpan & { output?: (Record & { childTraceSpans?: WorkflowTraceSpan[] }) | null } -/** - * Handler for workflow blocks that execute other workflows inline. - * Creates sub-execution contexts and manages data flow between parent and child workflows. - */ /** * A child workflow read refused because the run's delegation does not reach it, named for what * that almost always means: the workflow block names a workflow of another workspace (a raw id @@ -206,6 +202,10 @@ function childReadError(error: unknown, workflowId: string): unknown { ) } +/** + * Handler for workflow blocks that execute other workflows inline. + * Creates sub-execution contexts and manages data flow between parent and child workflows. + */ export class WorkflowBlockHandler implements BlockHandler { private serializer = new Serializer() diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts index da125d95b86..25ca2eb1e1e 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflow-source.ts @@ -142,7 +142,7 @@ export const workflowSourceOpenApiRoutes = [ applicationOperation: workflowOperations.planSource, operationId: 'planWorkflowSource', summary: 'Plan workflow source', - description: `Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since \`base\` (\`E_APPLY_STALE\`), the diff, and every finding, exactly as \`dryRun=true\` reports them, with \`200\`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers \`429\`), and records no audit or analytics event, so \`sim workflows source status\` never spends what an apply needs. \`allowDelete=true\` plans block deletes instead of reporting \`E_APPLY_BLOCK_DELETE\`. Returns \`403\` while workflows as code is not enabled. ${WORKSPACE_API_KEY_DENIED}`, + description: `Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since \`base\` (\`E_APPLY_STALE\`), the diff, and every finding, exactly as \`dryRun=true\` reports them, with \`200\`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers \`429\`), and records no audit or analytics event, so \`sim workflows source status\` never spends what an apply needs. \`allowDelete=true\` plans block and variable deletes instead of reporting \`E_APPLY_BLOCK_DELETE\` or \`E_APPLY_VARIABLE_DELETE\`. Returns \`403\` while workflows as code is not enabled. ${WORKSPACE_API_KEY_DENIED}`, tags: ['Workflows'], errors: [...RESOURCE_ERRORS, 'PayloadTooLarge'], success: { description: 'The evaluated source.', headers: RATE_LIMIT_HEADERS }, @@ -153,7 +153,7 @@ export const workflowSourceOpenApiRoutes = [ v2PlanWorkflowSourceContract.query, 'PlanWorkflowSourceQuery', 'Plan workflow source query', - 'Whether to plan block deletes.' + 'Whether to plan block and variable deletes.' ), body: documentedSchema( v2PlanWorkflowSourceContract.body, diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 66194535f67..21ce8d8d635 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -86,6 +86,11 @@ function carriesCredentials(repo: string): boolean { return url.username !== '' && /(^|\+)https?:$/i.test(url.protocol) } +/** `provenance.gitSha`: the commit a source or directory was taken from. */ +export const provenanceGitShaSchema = z + .string() + .regex(/^[0-9a-f]{7,64}$/, 'provenance.gitSha must be a hexadecimal commit hash') + /** `provenance.repo`: the repository a source or directory was taken from, never with credentials. */ export const provenanceRepoSchema = z .string() @@ -104,9 +109,7 @@ const provenanceSchema = z error: 'provenance.client: expected one of "cli" | "copilot" | "canvas" | "api"', }) .describe('What submitted the source.'), - gitSha: z - .string() - .regex(/^[0-9a-f]{7,64}$/, 'provenance.gitSha must be a hexadecimal commit hash') + gitSha: provenanceGitShaSchema .optional() .describe('The commit the source was taken from; recorded in the audit log.'), repo: provenanceRepoSchema.optional(), @@ -263,7 +266,7 @@ const planWorkflowSourceQuerySchema = z allowDelete: booleanQueryFlagSchema .optional() .describe( - 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.' + 'Plan the deletes of blocks and variables the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`.' ), }) .strict() diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index a4c7f272a36..3cab387eba2 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -60,6 +60,7 @@ import { referenceOccurrenceSchema, workflowReferenceManifestSchema, } from '@/lib/api/contracts/workflow-references' +import { sourceFingerprintSchema } from '@/lib/api/contracts/workflow-source' import { cancelWorkflowExecutionReasonSchema, workflowExecutionPausedDetailSchema, @@ -1078,12 +1079,7 @@ export const v2DeployWorkflowContract = defineRouteContract({ description: v1DeployWorkflowBodySchema.shape.description.describe( 'Optional release note for the deployment version.' ), - expectedDraftFingerprint: z - .string() - .regex( - /^sf1:[0-9a-f]{64}$/, - 'expectedDraftFingerprint must be a source fingerprint (sf1: and 64 hex digits)' - ) + expectedDraftFingerprint: sourceFingerprintSchema('expectedDraftFingerprint') .optional() .describe( 'Deploy only this draft: the `sf1:` fingerprint a source apply answered with (`base.fingerprint`). When the draft changed since, the deploy answers `409` and publishes nothing.' diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index 509a8c5ffa3..e948df35730 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -12,6 +12,7 @@ import { import { defineRouteContract } from '@/lib/api/contracts/types' import { v2DataResponse } from '@/lib/api/contracts/v2/shared' import { + provenanceGitShaSchema, provenanceRepoSchema, SOURCE_PATH_MAX_LENGTH, } from '@/lib/api/contracts/v2/workflow-source' @@ -284,9 +285,7 @@ const applyBodySchema = z provenance: z .object({ client: z.enum(['cli', 'api']).describe('What submitted the directory.'), - gitSha: z - .string() - .regex(/^[0-9a-f]{7,64}$/, 'provenance.gitSha must be a hexadecimal commit hash') + gitSha: provenanceGitShaSchema .optional() .describe('The commit the directory was taken from; recorded in the audit log.'), repo: provenanceRepoSchema.optional(), diff --git a/apps/sim/lib/api/contracts/workflow-source.ts b/apps/sim/lib/api/contracts/workflow-source.ts index 76ac10975b4..720ad00ad6f 100644 --- a/apps/sim/lib/api/contracts/workflow-source.ts +++ b/apps/sim/lib/api/contracts/workflow-source.ts @@ -113,6 +113,13 @@ export const workflowLockSchema = withExtensions({ 'Identity sidecar (`.sim/lock.json`): binds the keys in the source to stored ids.' ) +/** The `sf1:` fingerprint a source read or apply reports as `base.fingerprint`, by `field`. */ +export function sourceFingerprintSchema(field: string) { + return z + .string() + .regex(/^sf1:[0-9a-f]{64}$/, `${field} must be a source fingerprint (sf1: and 64 hex digits)`) +} + export const sourceBaseSchema = withExtensions({ version: z .literal(1) diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index a1edd7d0eaa..a2d923769f9 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -2485,7 +2485,7 @@ export const V2_MCP_OPERATIONS = { contract: v2PlanWorkflowSourceContract, summary: 'Plan workflow source', description: - 'Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block deletes instead of reporting `E_APPLY_BLOCK_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', + 'Report what Apply Workflow Source would do with this source, without writing: whether the draft changed since `base` (`E_APPLY_STALE`), the diff, and every finding, exactly as `dryRun=true` reports them, with `200`. A read: it needs only workspace read access, draws on the source-plan budget rather than the source-write budget (a server already running as many plans as it allows answers `429`), and records no audit or analytics event, so `sim workflows source status` never spends what an apply needs. `allowDelete=true` plans block and variable deletes instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`. Returns `403` while workflows as code is not enabled. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/workflows/[workflowId]/source/plan/route').then((route) => route.POST), diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 3152ae07bf8..532c489df76 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -303,7 +303,7 @@ export interface PlanWorkflowSourceInput { files: Record lock: WorkflowLockV1 base: SourceBase - /** Plan block deletes as allowed, so the plan names them instead of refusing. */ + /** Plan block and variable deletes as allowed, so the plan names them instead of refusing. */ allowDelete?: boolean } diff --git a/apps/sim/lib/workflows/application/code-availability.ts b/apps/sim/lib/workflows/application/code-availability.ts index 4e33eb848ee..2dce91c11ec 100644 --- a/apps/sim/lib/workflows/application/code-availability.ts +++ b/apps/sim/lib/workflows/application/code-availability.ts @@ -3,7 +3,7 @@ import { defineWorkspaceOperation, isOperationFeatureEnabled, } from '@/lib/core/application' -import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/application/operations' +import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/code/feature-flag' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' /** permission-group-exempt: reports rollout availability only; source operations enforce their own policies. */ diff --git a/apps/sim/lib/workflows/application/operations.ts b/apps/sim/lib/workflows/application/operations.ts index 6b70b15d895..b5d84ea73b6 100644 --- a/apps/sim/lib/workflows/application/operations.ts +++ b/apps/sim/lib/workflows/application/operations.ts @@ -1,14 +1,5 @@ -import type { OperationFeature } from '@/lib/core/application/feature-availability' import { defineWorkspaceOperation } from '@/lib/core/application/workspace-operation' - -/** - * Workflows and workspaces as code (the source catalog and resources, workflow and workspace - * source read and apply) ship behind the `workflow-code` flag; every source operation declares it. - */ -export const WORKFLOW_CODE_FEATURE = { - flag: 'workflow-code', - unavailableMessage: 'Workflows as code is in preview and not enabled for this workspace', -} as const satisfies OperationFeature +import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/code/feature-flag' const ALL_WORKFLOW_PRINCIPAL_POLICY = { principalKinds: [ diff --git a/apps/sim/lib/workflows/code/feature-flag.ts b/apps/sim/lib/workflows/code/feature-flag.ts index d419691d3cf..38b4c145af6 100644 --- a/apps/sim/lib/workflows/code/feature-flag.ts +++ b/apps/sim/lib/workflows/code/feature-flag.ts @@ -1,5 +1,15 @@ +import type { OperationFeature } from '@/lib/core/application/feature-availability' import { isFeatureEnabled } from '@/lib/core/config/feature-flags' +/** + * Workflows and workspaces as code (the source catalog and resources, workflow and workspace + * source read and apply) ship behind the `workflow-code` flag; every source operation declares it. + */ +export const WORKFLOW_CODE_FEATURE = { + flag: 'workflow-code', + unavailableMessage: 'Workflows as code is in preview and not enabled for this workspace', +} as const satisfies OperationFeature + /** * Where a workflows-as-code surface runs: the workspace, its organization (null for a personal * workspace) and the acting user, each matched against its allowlist in the `workflow-code` flag. @@ -15,8 +25,9 @@ export interface WorkflowCodeScope { * Workflows and workspaces as code (the SDK block catalog and resources, workflow source and * workspace source read and apply, the Code tab) ship behind one `workflow-code` flag, rolled out * globally or by organization, workspace or user. Source operations declare it as - * `WORKFLOW_CODE_FEATURE`; surfaces outside an operation (the Code tab, Copilot entitlements) ask here. + * {@link WORKFLOW_CODE_FEATURE}; surfaces outside an operation (the Code tab, Copilot entitlements) + * ask here. */ export function isWorkflowCodeEnabled(scope: WorkflowCodeScope): Promise { - return isFeatureEnabled('workflow-code', scope) + return isFeatureEnabled(WORKFLOW_CODE_FEATURE.flag, scope) } 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 f03ebff47f0..7b92a8a36b0 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -23,7 +23,7 @@ import { finding, GET_HINT } from '@/lib/workspace-source/application/findings' import { claimKey } from '@/lib/workspace-source/application/keys' import { workspaceSourceOperations } from '@/lib/workspace-source/application/operations' import { - planWorkspaceSource, + buildWorkspacePlan, type WorkspacePlan, type WorkspaceSourceSubmission, } from '@/lib/workspace-source/application/plan' @@ -264,7 +264,7 @@ function planned( } } -/** What {@link readWorkspaceSourcePlan} reads: a directory as an apply sends it, without its knobs. */ +/** What {@link planWorkspaceSource} reads: a directory as an apply sends it, without its knobs. */ export type PlanWorkspaceSourceInput = Omit /** @@ -272,13 +272,13 @@ export type PlanWorkspaceSourceInput = Omit resolveActiveWorkspaceApplicationContext(input.workspaceId), authorizationOptions: {}, async execute({ principal, input, context }): Promise { - const plan = await planWorkspaceSource(input, sourceContext(principal, context)) + const plan = await buildWorkspacePlan(input, sourceContext(principal, context)) return planned(plan, context.workspaceId, true) }, }) @@ -305,7 +305,7 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ ...(input.provenance ? { provenance: input.provenance } : {}), } if (input.dryRun === true) { - return planned(await planWorkspaceSource(input, ctx), context.workspaceId, true) + return planned(await buildWorkspacePlan(input, ctx), context.workspaceId, true) } const facts = { principal, @@ -323,7 +323,7 @@ export const applyWorkspaceSource = defineAuthorizedWorkspaceUseCase({ throw error }) try { - const plan = await planWorkspaceSource(input, ctx, { requireBlobs: true }) + const plan = await buildWorkspacePlan(input, ctx, { requireBlobs: true }) if (plan.refusing.length > 0) { recordWorkspaceSourceApplied(facts, plan.changes, { refused: 'rejected' }) throw new WorkspaceSourceRejectedError(plan.diagnostics, plan.refusing) diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index f2ca11cb726..513c5dff9af 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -619,10 +619,6 @@ function idempotencyKey(decl: DeploymentDecl, workflowId: string, live: string | return `workspace-source:${sha256Hex(JSON.stringify([workflowId, local, live]))}` } -/** - * Deploys the draft unless it already is the live version: a re-run after a deploy that - * succeeded finds nothing to publish, and one after a deploy that failed replays the same key. - */ /** * The `sf1:` fingerprint of the draft change `change` may publish on workflow `workflowId`, or * `undefined` when its plan vouched for none (a chat write on a workflow this apply creates). @@ -646,6 +642,10 @@ async function publishing(change: DeploymentChange, publish: () => Promise - readWorkspaceSourcePlan.execute({ + planWorkspaceSource.execute({ principal, input: { workspaceId, kinds: ['mcp-server', 'workflow'], files, ...(base ? { base } : {}) }, }) diff --git a/apps/sim/lib/workspace-source/application/operations.ts b/apps/sim/lib/workspace-source/application/operations.ts index 0e35ae96400..38b2d61528a 100644 --- a/apps/sim/lib/workspace-source/application/operations.ts +++ b/apps/sim/lib/workspace-source/application/operations.ts @@ -1,5 +1,5 @@ import { defineWorkspaceOperation } from '@/lib/core/application/workspace-operation' -import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/application/operations' +import { WORKFLOW_CODE_FEATURE } from '@/lib/workflows/code/feature-flag' const SOURCE_OPERATION_POLICY = { principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'workspace_api_key'], diff --git a/apps/sim/lib/workspace-source/application/plan.ts b/apps/sim/lib/workspace-source/application/plan.ts index 7fa84b773dc..a309d3f20fb 100644 --- a/apps/sim/lib/workspace-source/application/plan.ts +++ b/apps/sim/lib/workspace-source/application/plan.ts @@ -306,7 +306,7 @@ function checkLimits( * Plans `submission`. With `requireBlobs` (an apply that writes), a blob a write needs that is not * staged refuses the apply; a dry run lists such blobs in `needBlobs` instead. */ -export async function planWorkspaceSource( +export async function buildWorkspacePlan( submission: WorkspaceSourceSubmission, ctx: SourceContext, options: { requireBlobs?: boolean } = {} diff --git a/apps/sim/lib/workspace-source/application/status.integration.ts b/apps/sim/lib/workspace-source/application/status.integration.ts index 55046e68aaa..6121d653a6f 100644 --- a/apps/sim/lib/workspace-source/application/status.integration.ts +++ b/apps/sim/lib/workspace-source/application/status.integration.ts @@ -25,7 +25,7 @@ import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope. import * as tableUseCases from '@/lib/table/application/tables' import { applyWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' -import { readWorkspaceSourcePlan } from '@/lib/workspace-source/application/apply-workspace-source' +import { planWorkspaceSource } from '@/lib/workspace-source/application/apply-workspace-source' import { sourceChecks, sourceRunner, @@ -114,7 +114,7 @@ async function statusOf(read: ReadDirectory, local: Record, whol ) ) const plan = await withPermissionGroupScope(() => - readWorkspaceSourcePlan.execute({ + planWorkspaceSource.execute({ principal: owner, input: { workspaceId: read.workspaceId, 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 a7550314650..5bcda703e6b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -53,7 +53,7 @@ import { refreshWorkflowWorkspaceTypes, withSourceExitCode } from './source-tree import type { Diagnostic } from './source-ui' import { readBase, readLock, readSourceFiles } from './workflow-source-apply' -type ApplyData = PlanWorkflowSourceResponse['data'] +type PlanData = PlanWorkflowSourceResponse['data'] const PREFIX = 'sim workflows source' @@ -107,11 +107,11 @@ interface WorkflowPlanSummary { } /** The dry run's findings the plan counts: all but `E_APPLY_STALE`, which the status lists. */ -function workflowPlanFindings(data: ApplyData): Diagnostic[] { +function workflowPlanFindings(data: PlanData): Diagnostic[] { return planFindings(data.diagnostics, (code) => code === 'E_APPLY_STALE') } -function planSummary(data: ApplyData): WorkflowPlanSummary { +function planSummary(data: PlanData): WorkflowPlanSummary { const planned = workflowPlanFindings(data) const findings = (severity: string) => planned.filter((finding) => finding.severity === severity).length @@ -172,7 +172,7 @@ export function attachWorkflowSourceStatus(source: Command): void { : [] let server: ServerCheck = options.offline ? 'offline' : 'checked' let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined - let data: ApplyData | null = null + let data: PlanData | null = null let serverChanges: ServerResourceChange[] = [] let login: string | null = null if (!options.offline) { 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 56e91ecfaa1..15c1875646c 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -2,8 +2,8 @@ * `sim workspaces source status` and `sim workspaces source diff`: what changed in a workspace * source directory since it was read, on either side, without applying anything. Local changes * come from the file digests `.sim/written.json` records; the server's come from the plan read - * (`planWorkspaceSource`: a dry run on the source-read budget, one unit whatever the directory - * holds) of the directory (its findings name every resource changed since the base), and the base text a + * (`planWorkspaceSource`: a dry run on the source-plan budget, charged per workflow it + * evaluates) of the directory (its findings name every resource changed since the base), and the base text a * diff shows from the server's current source where it still prints what the directory was read * at. */ @@ -76,7 +76,7 @@ import { } from './workspace-source-dir' import { ONLY_KINDS_HELP, parseKinds } from './workspace-source-get' -type ApplyData = PlanWorkspaceSourceResponse['data'] +type PlanData = PlanWorkspaceSourceResponse['data'] type ServerSource = GetWorkspaceSourceResponse['data'] const PREFIX = 'sim workspaces source' @@ -197,7 +197,7 @@ interface WorkspacePlanSummary { warnings: number } -type PlannedChange = ApplyData['plan'][number] +type PlannedChange = PlanData['plan'][number] /** * The dry run's plan as an apply to `target` would make it. The status sends every workflow folder @@ -225,11 +225,11 @@ function planAsApplied( } /** The dry run's findings the plan counts: all but the server changes the status lists. */ -function workspacePlanFindings(data: ApplyData): Diagnostic[] { +function workspacePlanFindings(data: PlanData): Diagnostic[] { return planFindings(data.diagnostics, isServerChangeFinding) } -function planSummary(data: ApplyData, plan: readonly PlannedChange[]): WorkspacePlanSummary { +function planSummary(data: PlanData, plan: readonly PlannedChange[]): WorkspacePlanSummary { const count = (...actions: string[]) => plan.filter((change) => actions.includes(change.action)).length const planned = workspacePlanFindings(data) @@ -326,7 +326,7 @@ export function attachWorkspaceSourceStatus(source: Command): void { const locals = localResourceChanges(local.changed) let server: ServerCheck = options.offline ? 'offline' : 'checked' let note: string | undefined = options.offline ? 'Skipped with --offline.' : undefined - let data: ApplyData | null = null + let data: PlanData | null = null let applyPlan: PlannedChange[] = [] let workspaceId = local.readFrom // The scope every recommended command carries, so it acts on what this status showed. diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index d5af8090d59..e0c4cb5b9dd 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -27577,7 +27577,7 @@ export const V2_OPERATIONS = { allowDelete: { kind: 'boolean', describe: - 'Plan the deletes of blocks the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE`.', + 'Plan the deletes of blocks and variables the source no longer declares as an apply with `allowDelete` would, listing them in the diff, instead of reporting `E_APPLY_BLOCK_DELETE` or `E_APPLY_VARIABLE_DELETE`.', }, }, body: { diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index ae9b77c2e0d..322f5bc4860 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1756,8 +1756,6 @@ function compileConfig( const written = new Map, ObjectProperty>() if (!configNode) return { fields, written } for (const [key, property] of objectEntries(ctx, configNode)) { - const known = getOwn(form, key) - if (known) written.set(known.field, property) const entry = getOwn(form, key) if (!entry) { ctx.reporter.report( @@ -1768,6 +1766,7 @@ function compileConfig( ) continue } + written.set(entry.field, property) const node = property.value const field = String(entry.field) if (entry.kind === 'number') { From 347aae3a6906f842ab4b7cd36ad03112fa67acae Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:41:48 -0800 Subject: [PATCH 062/104] refactor(workspace-source): tell an adopt's additive changes by a list, not a label suffix refuseUnreadAdopt's callers kept only the plan labels that did not end in ' (add)', so rewording a label would have turned every additive adopt into a refusal with no type error. The table and knowledge base diffs now list the labels that only add (a new column, a new document) in additions, and the adopt guard filters on that list. --- .../application/kinds/knowledge/adapter.ts | 2 +- .../workspace-source/application/kinds/knowledge/diff.ts | 7 ++++++- .../workspace-source/application/kinds/table/adapter.ts | 2 +- .../lib/workspace-source/application/kinds/table/diff.ts | 7 ++++++- 4 files changed, 14 insertions(+), 4 deletions(-) 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 36c40d06f83..d8c3381edff 100644 --- a/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/knowledge/adapter.ts @@ -311,7 +311,7 @@ async function planKnowledgeBase( const refused = refuseUnreadAdopt( change, resource, - changes.fields.filter((field) => !field.endsWith(' (add)')) + changes.fields.filter((field) => !changes.additions.includes(field)) ) if (refused) return refused } diff --git a/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts b/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts index 3a82b53167e..dd0d9cd2837 100644 --- a/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts +++ b/apps/sim/lib/workspace-source/application/kinds/knowledge/diff.ts @@ -71,6 +71,8 @@ export interface KnowledgeChanges { /** Replacements a stopped replace left that this apply does not finish: deleted. */ discards: StoredDoc[] fields: string[] + /** The `fields` that only add to what the knowledge base holds, which an adopt may write. */ + additions: string[] diagnostics: WorkspaceSourceDiagnostic[] } @@ -244,6 +246,7 @@ export async function diffKnowledgeBase(input: { renames: [], discards: [], fields: [], + additions: [], diagnostics: [], } if (decl.name !== knowledgeBase.name) { @@ -291,8 +294,10 @@ export async function diffKnowledgeBase(input: { } const current = byName.get(name) if (!current) { + const label = `docs/${name} (add)` changes.uploads.push({ name, doc }) - changes.fields.push(`docs/${name} (add)`) + changes.fields.push(label) + changes.additions.push(label) continue } if (unchecked.has(current.id)) { 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 0c048c49637..1b07e4359c8 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/adapter.ts @@ -529,7 +529,7 @@ function changedOnAdopt( rows: RowsOutcome, state: StoredTableState ): string[] { - const fields = changes.fields.filter((field) => !field.endsWith(' (add)')) + const fields = changes.fields.filter((field) => !changes.additions.includes(field)) const rowsChanged = rows.plan !== undefined && state.table.rowCount > 0 && diff --git a/apps/sim/lib/workspace-source/application/kinds/table/diff.ts b/apps/sim/lib/workspace-source/application/kinds/table/diff.ts index 6f53119171f..6fe74d96f5e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/diff.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/diff.ts @@ -66,6 +66,8 @@ export interface TableChanges { columns: ColumnChange[] /** Fields that change, for the plan display. */ fields: string[] + /** The `fields` that only add to what the table holds (a new column), which an adopt may write. */ + additions: string[] /** Stored columns this update renames, old name → new name. */ renamedColumns: Array<{ from: string; to: string }> /** Every column name the table holds after the update, in declaration order. */ @@ -253,6 +255,7 @@ export async function diffTable( table: {}, columns: [], fields: [], + additions: [], renamedColumns: [], columnNames: Object.entries(decl.columns).map(([columnKey, column]) => columnName(columnKey, column) @@ -309,8 +312,10 @@ export async function diffTable( decl.rows.data.every((row) => !isEmptyCell(row[columnKey])) && unkeyedRows.every((row) => current !== undefined && !isEmptyCell(row[getColumnId(current)])) if (!current) { + const label = `columns.${columnKey} (add)` changes.columns.push({ op: 'add', key: columnKey, column: target }) - changes.fields.push(`columns.${columnKey} (add)`) + changes.fields.push(label) + changes.additions.push(label) // A new column is empty in every row, so a required one would hold rows that break it, // unless managed rows fill it. if (target.required && table.rowCount > 0 && !filled) { From f363244d571417dd5128ef822a822f44befb2dd8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:43:18 -0800 Subject: [PATCH 063/104] refactor(sim-cli): report a promotion's target deletes once, and re-hint findings in one place A promotion printed a stderr line counting the target-only deletes on top of one W_PROMOTE_DELETES_TARGET_ONLY warning per delete; the line is gone. printPlan's special loop for W_PROMOTE_TARGET_DELETED is replaced by listing that code among the server-change findings in workspace-code's status. promotionDiagnostics and the refusal path share withPromotionHint, and the refusal is re-hinted into a new error instead of mutating the caller's. --- .../protocol/workspace-source-apply.test.ts | 6 +- .../protocol/workspace-source-apply.ts | 79 ++++++++++--------- packages/workspace-code/src/status.ts | 1 + 3 files changed, 45 insertions(+), 41 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 990314b7a7b..b5bd4fa7fb0 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 @@ -548,9 +548,9 @@ describe('workspaces source apply', () => { const [stale] = byCode('E_APPLY_STALE') expect(stale.hint).toContain('.sim/targets/ws_prod.json') expect(stale.hint).not.toContain('fresh directory') - expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toContain( - 'deletes 1 resource(s) that only workspace ws_prod holds' - ) + const stderr = vi.mocked(console.error).mock.calls.flat().join('\n') + expect(stderr).toContain(' ! gone (deleted on the server; kept as the server has it)') + expect(stderr).not.toContain('resource(s) that only workspace ws_prod holds') }) it('refuses --to naming the workspace the directory was read from', async () => { 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 537c3838a7b..a259d59429d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -197,12 +197,6 @@ function printPlan( .filter((change) => change.server !== 'added') .map((change) => [`${change.kind}:${change.key}`, change.server]) ) - // A promotion reports the target's delete as W_PROMOTE_TARGET_DELETED in place of the server's W_SERVER_DELETED. - for (const finding of diagnostics) { - if (finding.code === 'W_PROMOTE_TARGET_DELETED' && finding.kind && finding.key) { - drifted.set(`${finding.kind}:${finding.key}`, 'deleted') - } - } const driftOf = (change: Change) => change.action === 'noop' ? drifted.get(`${change.kind}:${change.key}`) : undefined for (const kind of APPLY_ORDER) { @@ -248,19 +242,6 @@ function printPlan( } } -/** - * Says loudly, below a promotion's plan, how many resources `--allow-delete` deletes that only the - * target holds: a promotion deletes everything the directory does not declare. - */ -function printTargetOnlyDeletes(promotion: Promotion | null, plan: readonly Change[]): void { - if (!promotion) return - const deletes = plan.filter((change) => change.action === 'delete') - if (deletes.length === 0) return - printError( - `--allow-delete with --to: this promotion deletes ${deletes.length} resource(s) that only workspace ${promotion.target} holds: ${deletes.map((change) => resourceWhere(change.kind, change.key)).join(', ')}.` - ) -} - /** The changes that delete something (a resource, rows, documents, columns, a deployment). */ export function destructiveChanges(changes: readonly Change[]): number { return changes.filter((change) => change.action === 'delete' || change.destructive !== undefined) @@ -556,6 +537,16 @@ function promotionHint(code: string, target: string): string | undefined { return undefined } +/** `finding` with the hint a promotion to `target` gives its code, when it gives one. */ +function withPromotionHint( + finding: F, + code: string, + target: string +): F { + const hint = promotionHint(code, target) + return hint === undefined ? finding : { ...finding, hint } +} + /** * The server's findings as a promotion reports them: refusals carry the promotion's hint, and the * server's `W_SERVER_DELETED` for a resource the promotion warns about itself @@ -563,13 +554,11 @@ function promotionHint(code: string, target: string): string | undefined { */ function promotionDiagnostics(diagnostics: readonly Finding[], promotion: Promotion): Finding[] { const warned = new Set(promotion.deletedInTarget) - return diagnostics.flatMap((finding) => { - if (finding.code === 'W_SERVER_DELETED' && warned.has(`${finding.kind}:${finding.key}`)) { - return [] - } - const hint = promotionHint(finding.code, promotion.target) - return [hint === undefined ? finding : { ...finding, hint }] - }) + return diagnostics.flatMap((finding) => + finding.code === 'W_SERVER_DELETED' && warned.has(`${finding.kind}:${finding.key}`) + ? [] + : [withPromotionHint(finding, finding.code, promotion.target)] + ) } /** @@ -608,16 +597,32 @@ function promotionWarnings(promotion: Promotion, plan: readonly Change[]): Findi return [...deleted, ...targetOnly] } -/** A refusal's findings as a promotion reports them (see {@link promotionDiagnostics}). */ -function rehintRefusal(refusal: unknown, promotion: Promotion): void { - if (!(refusal instanceof SimApiError) || !isRecordLike(refusal.details)) return +/** + * `refusal` with its findings as a promotion reports them (see {@link promotionDiagnostics}): a + * new error, the caller's left as it was. + */ +function rehinted(refusal: unknown, promotion: Promotion): unknown { + if (!(refusal instanceof SimApiError) || !isRecordLike(refusal.details)) return refusal const { diagnostics } = refusal.details - if (!Array.isArray(diagnostics)) return - refusal.details.diagnostics = diagnostics.map((finding) => { - if (!isRecordLike(finding) || typeof finding.code !== 'string') return finding - const hint = promotionHint(finding.code, promotion.target) - return hint === undefined ? finding : { ...finding, hint } - }) + if (!Array.isArray(diagnostics)) return refusal + const details = { + ...refusal.details, + diagnostics: diagnostics.map((finding) => + isRecordLike(finding) && typeof finding.code === 'string' + ? withPromotionHint(finding, finding.code, promotion.target) + : finding + ), + } + const copy = new SimApiError( + refusal.message, + refusal.status, + refusal.code, + details, + refusal.exitCode, + refusal.requestId + ) + copy.retryAfterMs = refusal.retryAfterMs + return copy } /** @@ -728,8 +733,7 @@ export function attachWorkspaceSourceApply(source: Command): void { refusal = error } } - if (promotion) rehintRefusal(refusal, promotion) - return printRefusal(refusal, profile.output, { + return printRefusal(promotion ? rehinted(refusal, promotion) : refusal, profile.output, { ...(dryRun ? {} : { ifAnswerLost: answerLostHint(options.dir) }), verbose: options.verbose === true, }) @@ -779,7 +783,6 @@ export function attachWorkspaceSourceApply(source: Command): void { if (mode !== 'write') { preview = reported(await send(submission, true)) printPlan(preview.plan, preview.diagnostics) - printTargetOnlyDeletes(promotion, preview.plan) findings.print(preview.diagnostics) const errors = preview.diagnostics.some((finding) => finding.severity === 'error') if (errors) setSoftExitCode(refusedExitCode(preview.diagnostics)) diff --git a/packages/workspace-code/src/status.ts b/packages/workspace-code/src/status.ts index ff009660297..49cabfa88c4 100644 --- a/packages/workspace-code/src/status.ts +++ b/packages/workspace-code/src/status.ts @@ -136,6 +136,7 @@ const SERVER_FINDINGS: ReadonlyMap = new Map( W_SERVER_CHANGED: 'changed', W_SERVER_DELETED: 'deleted', W_SERVER_MOVED: 'moved', + W_PROMOTE_TARGET_DELETED: 'deleted', E_APPLY_STALE: 'changed', W_UNDECLARED: 'added', E_APPLY_NO_BASE: 'added', From 2c97f77ed0e596ca909add05e2befedce97ff184 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:45:03 -0800 Subject: [PATCH 064/104] refactor: split planDeployment's live-draft branch and the variable delete refusal out planDeployment's live: 'draft' branch nested the vouch, the chat refusals and the pinned case three deep; it is now planLiveDraft. evaluateSource's inline variable delete refusal is variableDeleteRefusal beside blockDeleteRefusal. --- .../workflows/application/source-evaluate.ts | 19 +-- .../application/kinds/deployment/adapter.ts | 113 +++++++++++------- 2 files changed, 80 insertions(+), 52 deletions(-) diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index a7d9177ad0f..70e3d2ea418 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -322,6 +322,17 @@ function listNames(names: readonly string[]): string { return names.length > 10 ? `${shown}, and ${names.length - 10} more` : shown } +/** `E_APPLY_VARIABLE_DELETE` for the stored variables an apply removes, by name. */ +function variableDeleteRefusal(names: readonly string[], span: SourceSpan | undefined): Diagnostic { + return { + code: 'E_APPLY_VARIABLE_DELETE', + severity: 'error', + message: `This apply deletes ${names.length} variable${names.length === 1 ? '' : 's'} the source no longer declares: ${listNames(names)}.`, + hint: 'Pass --allow-delete (allowDelete=true) to delete them, or declare them again in workflow(name, { variables }) to keep them.', + ...withSpan(span), + } +} + /** * `E_APPLY_BLOCK_DELETE` for the stored blocks an apply removes. When the source adds blocks of * a removed block's type, they may be renames whose name and const both changed with no identity @@ -836,13 +847,7 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise 0 && !input.allowDelete) { - sourceRefusals.push({ - code: 'E_APPLY_VARIABLE_DELETE', - severity: 'error', - message: `This apply deletes ${removedVariables.length} variable${removedVariables.length === 1 ? '' : 's'} the source no longer declares: ${listNames(removedVariables)}.`, - hint: 'Pass --allow-delete (allowDelete=true) to delete them, or declare them again in workflow(name, { variables }) to keep them.', - ...withSpan(metaSpan()), - }) + sourceRefusals.push(variableDeleteRefusal(removedVariables, metaSpan())) } const renameWarnings = input.allowDelete ? probableRenames(removedBlocks, addedBlocks).map( diff --git a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts index 513c5dff9af..523d3877984 100644 --- a/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/deployment/adapter.ts @@ -421,6 +421,72 @@ function draftNotSourceFinding(key: string, declared: boolean) { ) } +/** + * The deployment `next` of a workflow whose draft differs from its live version: `live: 'draft'` + * deploys the draft the directory vouches for (`W_DEPLOY_DRAFT_NOT_SOURCE` when it vouches for + * none, refusing a chat write that would deploy it), and `live: 'pinned'` keeps the live version + * (refusing a chat write, which would deploy the draft). + */ +async function planLiveDraft( + next: DeploymentChange, + detail: DeploymentPlan, + decl: DeploymentDecl, + ctx: PlanContext, + facts: { + key: string + workflowId: string | undefined + draftEdited: boolean + workflowChange: PlannedChange<'workflow'> | undefined + } +): Promise { + const { key, workflowChange } = facts + if (decl.live !== 'draft') { + next.diagnostics.push( + deploymentFinding( + key, + 'I_DEPLOY_DRAFT_NOT_LIVE', + `${where('workflow', key)}'s draft differs from its live version, which keeps running: the deployment is pinned.`, + "Set `live: 'draft'` to deploy the draft with this apply." + ) + ) + if (detail.chat === 'replace') { + next.diagnostics.push( + deploymentFinding( + key, + 'E_DEPLOY_PINNED_CHAT', + 'Writing the chat deploys the draft, which this pinned deployment keeps out of the live version.', + "Set `live: 'draft'`, or leave the chat as it is until the draft should go live." + ) + ) + } + return + } + const draft = await vouchedDraft(ctx, { + workflowId: facts.workflowId, + draftEdited: facts.draftEdited, + folder: workflowChange, + firstDeploy: false, + }) + if (draft) { + detail.deploy = true + detail.draft = draft + next.action = 'update' + next.fields = ['live version', ...(next.fields ?? [])] + return + } + next.diagnostics.push(draftNotSourceFinding(key, workflowChange !== undefined)) + if (detail.chat === 'replace') { + next.diagnostics.push( + deploymentFinding( + key, + 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT', + 'Writing the chat deploys the draft, which holds edits this directory does not declare.', + `Get those edits into ${workflowFolder(key)}/ first, or leave the chat as it is.` + ) + ) + } +} + /** Plans one declared deployment against the workflow under the same key. */ async function planDeployment( key: string, @@ -527,51 +593,8 @@ async function planDeployment( ) ) if (Object.keys(plannedOutputNames).length > 0) detail.plannedOutputNames = plannedOutputNames - const draftDiffers = state.needsRedeployment || draftEdited - if (draftDiffers && decl.live === 'draft') { - const draft = await vouchedDraft(ctx, { - workflowId, - draftEdited, - folder: workflowChange, - firstDeploy: false, - }) - if (draft) { - detail.deploy = true - detail.draft = draft - next.action = 'update' - next.fields = ['live version', ...(next.fields ?? [])] - } else { - next.diagnostics.push(draftNotSourceFinding(key, workflowChange !== undefined)) - if (detail.chat === 'replace') { - next.diagnostics.push( - deploymentFinding( - key, - 'E_DEPLOY_DRAFT_NOT_SOURCE_CHAT', - 'Writing the chat deploys the draft, which holds edits this directory does not declare.', - `Get those edits into ${workflowFolder(key)}/ first, or leave the chat as it is.` - ) - ) - } - } - } else if (draftDiffers) { - next.diagnostics.push( - deploymentFinding( - key, - 'I_DEPLOY_DRAFT_NOT_LIVE', - `${where('workflow', key)}'s draft differs from its live version, which keeps running: the deployment is pinned.`, - "Set `live: 'draft'` to deploy the draft with this apply." - ) - ) - if (detail.chat === 'replace') { - next.diagnostics.push( - deploymentFinding( - key, - 'E_DEPLOY_PINNED_CHAT', - 'Writing the chat deploys the draft, which this pinned deployment keeps out of the live version.', - "Set `live: 'draft'`, or leave the chat as it is until the draft should go live." - ) - ) - } + if (state.needsRedeployment || draftEdited) { + await planLiveDraft(next, detail, decl, ctx, { key, workflowId, draftEdited, workflowChange }) } } if (next.action === 'noop') return next From 2bbf25070be24fda47d565233a7d499a7f714044 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:45:42 -0800 Subject: [PATCH 065/104] test(workflow-code): time hostile scans with the shared scaling helper, and fill the cap whatever its ratios hostile.test kept its own growth(): 4x scale against a threshold of 9, all large timings before all small ones, and the input built inside the timed region. Both scans now use scaling.test-helpers' growth and MAX_GROWTH. The secret-framing case filled the total warning cap with five codes, which only worked while MAX_WARNINGS / MAX_WARNINGS_PER_CODE was 5; it now fills each code to its own cap in turn from a list long enough for any ratio. --- .../workflow-code/src/compile/hostile.test.ts | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 29ed24e2043..e0f764c86ca 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { codeFileReferences } from '../code-files/references' +import { growth, MAX_GROWTH } from '../scaling.test-helpers' import { TEST_CATALOG } from './catalog.test-helpers' import type { CompileResult } from './index' import { compileWorkflow } from './index' @@ -19,28 +20,6 @@ function wrap(body: string, options = '{}'): string { return `${HEADER}export default workflow('Hostile', ${options}, () => {\n${body}\n})\n` } -/** - * How many times longer `work` takes at four times the size `size`, the fastest of three timings - * each: about 4 for linear work and about 16 for quadratic, on a slow machine as on a fast one. - * A wall-clock budget instead fails on a loaded runner and passes a quadratic scan on a fast one. - * The work repeats until one timing at `size` spans 25 ms, so the clock's millisecond steps are - * small beside it. - */ -function growth(work: (size: number) => void, size: number): number { - let repeats = 1 - const time = (at: number) => { - const started = Date.now() - for (let repeat = 0; repeat < repeats; repeat += 1) work(at) - return Date.now() - started - } - while (time(size) < 25 && repeats < 1_024) repeats *= 2 - const fastest = (at: number) => Math.min(time(at), time(at), time(at)) - return fastest(size * 4) / Math.max(1, fastest(size)) -} - -/** The {@link growth} under which work counts as linear: well short of quadratic's 16. */ -const LINEAR_GROWTH = 9 - function run( text: string, limits?: CompileLimits, @@ -174,7 +153,11 @@ describe('hostile sources produce diagnostics only', () => { it('scans a 400 KB value of overlapping token prefixes for secrets in linear time', () => { const source = (repeats: number) => wrap(`const a = api('A', { url: 'https://x', body: '${'-eyJ'.repeat(repeats)}' })`) - expect(growth((repeats) => run(source(repeats)), 25_000)).toBeLessThan(LINEAR_GROWTH) + const scan = (repeats: number) => { + const text = source(repeats) + return () => run(text) + } + expect(growth(scan, 12_500)).toBeLessThan(MAX_GROWTH) const result = run(source(100_000)) expect(result.workflow).not.toBeNull() expect(codes(result)).not.toContain('W_LITERAL_SECRET') @@ -195,14 +178,26 @@ describe('hostile sources produce diagnostics only', () => { const reporter = new Reporter() reporter.addFile('w.ts', `body: '${jwt}'`) const at = { file: 'w.ts', start: 7, end: 7 + jwt.length } + // Enough codes, each filled to its own cap in turn, that the warnings reach the total cap + // whatever the two caps are. const fillers = [ 'W_SUBFLOW_COUNT', 'W_FORWARD_REF', 'W_VALUE_KIND', 'W_OUT_OF_RANGE', 'W_UNKNOWN_OPTION', + 'W_REQUIRED_MISSING', + 'W_ENV_UNKNOWN', + 'W_REF_NOT_NORMALIZED', + 'W_JSON_REF_UNTYPED', + 'W_COMMENT_MOVED', + 'W_COMMENT_DROPPED', + 'W_FIELD_NOT_APPLICABLE', ] as const - for (let i = 0; i < MAX_WARNINGS; i++) reporter.report(fillers[i % fillers.length], `x${i}`, at) + expect(fillers.length * MAX_WARNINGS_PER_CODE).toBeGreaterThanOrEqual(MAX_WARNINGS) + for (let i = 0; i < MAX_WARNINGS; i++) { + reporter.report(fillers[Math.floor(i / MAX_WARNINGS_PER_CODE)], `x${i}`, at) + } reporter.report('W_LITERAL_SECRET', 'body holds a literal secret', at) const capped = reporter.diagnostics.at(-1) expect(capped?.code).toBe('W_TOO_MANY_WARNINGS') @@ -212,7 +207,11 @@ describe('hostile sources produce diagnostics only', () => { it('checks the precision of a 100 KB numeric literal in linear time', () => { const source = (zeros: number) => wrap(`const a = api('A', { url: 'x', timeout: 0.1${'0'.repeat(zeros)}1 })`) - expect(growth((zeros) => run(source(zeros)), 25_000)).toBeLessThan(LINEAR_GROWTH) + const check = (zeros: number) => { + const text = source(zeros) + return () => run(text) + } + expect(growth(check, 12_500)).toBeLessThan(MAX_GROWTH) expect(codes(run(source(100_000)))).toContain('W_NUMBER_PRECISION') }) From d2ba434fcd0c1483e059dac318af1ee63a276647 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:47:10 -0800 Subject: [PATCH 066/104] test(workflows): check the workflow-code gate on every source use case The gate test listed five read use cases, so dropping feature: from a plan, apply, create or staging operation (the bug 1bc0a1a5be fixed for the plans) passed CI. The concealment and FEATURE_NOT_ENABLED checks now run over a table of every workflow and workspace source use case. --- .../source-feature-gate.integration.ts | 157 ++++++++++++++---- 1 file changed, 123 insertions(+), 34 deletions(-) diff --git a/apps/sim/lib/workflows/application/source-feature-gate.integration.ts b/apps/sim/lib/workflows/application/source-feature-gate.integration.ts index 8d136214719..dac9db8815a 100644 --- a/apps/sim/lib/workflows/application/source-feature-gate.integration.ts +++ b/apps/sim/lib/workflows/application/source-feature-gate.integration.ts @@ -3,9 +3,12 @@ * gate answers only after authorization, so with the flag off a caller who cannot reach the * workspace sees the same concealed not-found for a real workflow or workspace as for a made-up * one (no existence or rollout oracle), and a member who can reach it is told the feature is off - * with `FEATURE_NOT_ENABLED`, on `authorize` (what a `HEAD` runs) as on `execute`. + * with `FEATURE_NOT_ENABLED`, on `authorize` (what a `HEAD` runs) as on `execute`. Every source use + * case is checked, the plans, applies, create and blob staging included, so an operation that + * loses its `feature` declaration fails here. */ +import type { Principal } from '@sim/auth/principal' import { db } from '@sim/db' import { permissions, user, workflow, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' @@ -17,13 +20,27 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites import { concealCrossTenantResourceError } from '@/lib/api/server/routes/resource-concealment' import { forbiddenErrorDetails } from '@/lib/core/application/forbidden' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { + applyWorkflowSource, + createWorkflowFromSource, + planWorkflowSource, +} from '@/lib/workflows/application/apply-workflow-source' import { readSourceCatalog } from '@/lib/workflows/application/read-source-catalog' import { readSourceResources } from '@/lib/workflows/application/read-source-resources' import { readWorkflowSource, readWorkflowSources, } from '@/lib/workflows/application/read-workflow-source' +import { + applyWorkspaceSource, + planWorkspaceSource, +} from '@/lib/workspace-source/application/apply-workspace-source' import { readWorkspaceSource } from '@/lib/workspace-source/application/read-workspace-source' +import { + admitSourceBlobStage, + findMissingSourceBlobs, + stageSourceBlobs, +} from '@/lib/workspace-source/application/stage-blobs' vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) @@ -46,6 +63,88 @@ async function answer(run: Promise) { throw new Error('Expected the operation to be refused') } +/** A source use case, run on the workflow (or workspace) with id `id`. */ +interface GatedUseCase { + name: string + execute(principal: Principal, id: string): Promise + authorize(principal: Principal, id: string): Promise +} + +/** A use case whose input names the workflow it acts on. */ +function onWorkflow( + name: string, + useCase: { + execute(args: { principal: Principal; input: I }): Promise + authorize(args: { principal: Principal; input: I }): Promise + }, + input: (workflowId: string) => I +): GatedUseCase { + return { + name, + execute: (principal, id) => useCase.execute({ principal, input: input(id) }), + authorize: (principal, id) => useCase.authorize({ principal, input: input(id) }), + } +} + +const onWorkspace = onWorkflow + +const SUBMISSION = { + files: {}, + lock: { version: 1 as const, blocks: {}, variables: {} }, +} + +/** Every source use case that acts on one workflow. */ +const WORKFLOW_USE_CASES: GatedUseCase[] = [ + onWorkflow('readWorkflowSource', readWorkflowSource, (id) => ({ workflowId: id })), + ...[ + ['applyWorkflowSource', applyWorkflowSource], + ['planWorkflowSource', planWorkflowSource], + ].map(([name, useCase]) => + onWorkflow(String(name), useCase as typeof applyWorkflowSource, (id) => ({ + workflowId: id, + ...SUBMISSION, + base: { + version: 1 as const, + workflowId: id, + workspaceId, + fingerprint: 'sf1:x', + catalogHash: 'h', + }, + })) + ), +] + +/** Every source use case that acts on a workspace. */ +const WORKSPACE_USE_CASES: GatedUseCase[] = [ + onWorkspace('readSourceResources', readSourceResources, (id) => ({ workspaceId: id })), + onWorkspace('readSourceCatalog', readSourceCatalog, (id) => ({ workspaceId: id })), + onWorkspace('readWorkspaceSource', readWorkspaceSource, (id) => ({ workspaceId: id })), + onWorkspace('readWorkflowSources', readWorkflowSources, (id) => ({ + workspaceId: id, + workflowIds: [workflowId], + })), + onWorkspace('createWorkflowFromSource', createWorkflowFromSource, (id) => ({ + workspaceId: id, + files: {}, + })), + onWorkspace('planWorkspaceSource', planWorkspaceSource, (id) => ({ + workspaceId: id, + files: {}, + kinds: [], + })), + onWorkspace('applyWorkspaceSource', applyWorkspaceSource, (id) => ({ + workspaceId: id, + files: {}, + kinds: [], + })), + onWorkspace('admitSourceBlobStage', admitSourceBlobStage, (id) => ({ workspaceId: id })), + onWorkspace('stageSourceBlobs', stageSourceBlobs, (id) => ({ workspaceId: id, blobs: [] })), + onWorkspace('findMissingSourceBlobs', findMissingSourceBlobs, (id) => ({ + workspaceId: id, + blobs: [], + })), +] + const NOT_FOUND = { code: 'not_found', details: undefined } const FEATURE_OFF = { code: 'forbidden', details: { code: 'FEATURE_NOT_ENABLED' } } @@ -95,43 +194,33 @@ afterAll(async () => { }) describe('workflow-code gate with the flag off', () => { - it('conceals a real workflow from an outsider exactly as a made-up one', async () => { - const real = await answer( - readWorkflowSource.execute({ principal: outsider, input: { workflowId } }) - ) - const fake = await answer( - readWorkflowSource.execute({ principal: outsider, input: { workflowId: generateId() } }) - ) - expect(real).toEqual(NOT_FOUND) - expect(fake).toEqual(NOT_FOUND) - }) - - it('conceals a real workspace from an outsider exactly as a made-up one', async () => { - for (const useCase of [readSourceResources, readSourceCatalog, readWorkspaceSource]) { - const real = await answer(useCase.execute({ principal: outsider, input: { workspaceId } })) - const fake = await answer( - useCase.execute({ principal: outsider, input: { workspaceId: generateId() } }) - ) - expect(real).toEqual(NOT_FOUND) - expect(fake).toEqual(NOT_FOUND) - } - const real = await answer( - readWorkflowSources.execute({ - principal: outsider, - input: { workspaceId, workflowIds: [workflowId] }, + it('conceals a real workflow or workspace from an outsider exactly as a made-up one', async () => { + const cases = [ + ...WORKFLOW_USE_CASES.map((useCase) => ({ useCase, id: workflowId })), + ...WORKSPACE_USE_CASES.map((useCase) => ({ useCase, id: workspaceId })), + ] + for (const { useCase, id } of cases) { + const real = await answer(useCase.execute(outsider, id)) + const fake = await answer(useCase.execute(outsider, generateId())) + expect({ name: useCase.name, real, fake }).toEqual({ + name: useCase.name, + real: NOT_FOUND, + fake: NOT_FOUND, }) - ) - expect(real).toEqual(NOT_FOUND) + } }) it('tells a member the feature is off with FEATURE_NOT_ENABLED on authorize and execute', async () => { - const workflowInput = { principal: member, input: { workflowId } } - const workspaceInput = { principal: member, input: { workspaceId } } - expect(await answer(readWorkflowSource.execute(workflowInput))).toEqual(FEATURE_OFF) - expect(await answer(readWorkflowSource.authorize(workflowInput))).toEqual(FEATURE_OFF) - for (const useCase of [readSourceResources, readSourceCatalog, readWorkspaceSource]) { - expect(await answer(useCase.execute(workspaceInput))).toEqual(FEATURE_OFF) - expect(await answer(useCase.authorize(workspaceInput))).toEqual(FEATURE_OFF) + const cases = [ + ...WORKFLOW_USE_CASES.map((useCase) => ({ useCase, id: workflowId })), + ...WORKSPACE_USE_CASES.map((useCase) => ({ useCase, id: workspaceId })), + ] + for (const { useCase, id } of cases) { + expect({ + name: useCase.name, + execute: await answer(useCase.execute(member, id)), + authorize: await answer(useCase.authorize(member, id)), + }).toEqual({ name: useCase.name, execute: FEATURE_OFF, authorize: FEATURE_OFF }) } }) From 236674e397d3382ddce8beff539d562e557c464a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:48:32 -0800 Subject: [PATCH 067/104] test(realtime): assert each keystroke race exactly, against the real locked save The race assertions were disjunctive, so a flush that never wrote passed all four, and the writer model hand-ran a delete-all and re-insert no production writer does any more. The locking writer is now a transaction that locks the workflow row and calls the real diff save, renaming the block, with the keystroke interleaved after the lock and after the save: each must be confirmed with both the keystroke and the rename kept. The unlocked delete-and-reinsert stays as the case the flush's rows-affected check guards, and must report failure with the old value; the variable race must confirm and keep both values. untilSettledOrBlocked says which happened and fails the test when neither does instead of quietly running the interleave late. --- .../graph-replace-race.integration.ts | 158 +++++++++++++----- 1 file changed, 114 insertions(+), 44 deletions(-) diff --git a/apps/realtime/src/handlers/graph-replace-race.integration.ts b/apps/realtime/src/handlers/graph-replace-race.integration.ts index 11028e19119..58fc33f4872 100644 --- a/apps/realtime/src/handlers/graph-replace-race.integration.ts +++ b/apps/realtime/src/handlers/graph-replace-race.integration.ts @@ -1,20 +1,24 @@ /** - * Real PostgreSQL coverage for a canvas keystroke racing a whole-graph replace. A source apply - * locks the workflow row, re-reads the graph, then deletes and re-inserts every block from what it - * read; a revert to a deployed version deletes and re-inserts without the lock. A keystroke flushed - * inside either window must survive the replace or be reported to its sender as failed (the client - * retries a retryable failure): it may never be confirmed and then vanish. A variable keystroke - * racing an apply that rewrites the variables must not revert the apply's own change either. + * Real PostgreSQL coverage for a canvas keystroke racing a whole-graph write. Every production + * graph writer (a source apply, a revert to a deployed version, a normalized-state replace) locks + * the workflow row and then saves through `saveWorkflowToNormalizedTables`, which rewrites only the + * rows that changed. A keystroke flushed inside that window waits for the row lock and then lands + * on the saved graph, so it is confirmed and kept. A writer that skipped the lock and deleted the + * block under the flush (none does in production) must still never see a keystroke confirmed and + * then lost: the flush reports it failed, which the client retries. A variable keystroke racing an + * apply that rewrites the variables must not revert the apply's own change either. * - * Drives the real `subblock-update` and `variable-update` handlers (real permission checks and flush) with only the - * socket and the room manager stood in, and runs the replace's SQL sequence by hand at each - * interleaving point. + * Drives the real `subblock-update` and `variable-update` handlers (real permission checks and + * flush) with only the socket and the room manager stood in, and interleaves the keystroke at each + * point of the writer's transaction. Each interleaving has one correct outcome, asserted exactly. */ import { db, runOutsideTransactionContext } from '@sim/db' import { permissions, user, workflow, workflowBlocks, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState } from '@sim/workflow-types/workflow' import { and, eq, isNull, sql } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import { setupSubblocksHandlers } from '@/handlers/subblocks' @@ -80,48 +84,88 @@ async function storedValue(): Promise { return subBlocks?.code?.value } -/** Resolves once `settled` resolves or another session is waiting on a lock. */ -async function untilSettledOrBlocked(settled: Promise): Promise { +async function storedName(): Promise { + const [row] = await db + .select({ name: workflowBlocks.name }) + .from(workflowBlocks) + .where(eq(workflowBlocks.id, blockId)) + return row?.name +} + +/** + * Waits until `settled` resolves (`settled`) or another session waits on a lock (`blocked`), and + * fails the test when neither happens: an interleave that silently ran after the writer instead + * would pass for a broken flush as for a sound one. + */ +async function untilSettledOrBlocked(settled: Promise): Promise<'settled' | 'blocked'> { let done = false void settled.then(() => { done = true }) - for (let attempt = 0; attempt < 200 && !done; attempt++) { + for (let attempt = 0; attempt < 500; attempt++) { + if (done) return 'settled' const [{ waiting }] = await db.execute<{ waiting: number }>( sql`select count(*)::int as waiting from pg_stat_activity where datname = current_database() and wait_event_type = 'Lock'` ) - if (waiting > 0) return + if (waiting > 0) return 'blocked' await sleep(10) } + throw new Error('The keystroke neither settled nor waited on a lock') +} + +const RENAMED = 'Function 1 (applied)' + +/** The block as the writer saves it: the code it read, under a new name. */ +function savedBlock(): BlockState { + return { + id: blockId, + type: 'function', + name: RENAMED, + position: { x: 0, y: 0 }, + subBlocks: { code: { id: 'code', type: 'code', value: BEFORE } }, + outputs: {}, + enabled: true, + } } -type Writer = 'locking' | 'blind' -type Point = 'after-reread' | 'after-delete' +type Point = 'after-lock' | 'after-save' /** - * A whole-graph replace, statement for statement: a `locking` writer (a source apply) locks the - * live workflow row and re-reads the blocks first, a `blind` one (a revert to a deployed version) - * does not; both then delete every block and re-insert the graph they started from. `interleave` - * runs at `point` inside it, on its own connections, as the realtime server's flush would. + * A production graph write: lock the live workflow row, then save the graph through the real + * diff save, renaming the block from what it read. `interleave` runs at `point` inside the + * transaction, on its own connections, as the realtime server's flush would. */ -async function replaceGraph(writer: Writer, point: Point, interleave: () => Promise) { +async function lockedSave(point: Point, interleave: () => Promise) { + await db.transaction(async (tx) => { + await tx + .select({ id: workflow.id }) + .from(workflow) + .where(and(eq(workflow.id, workflowId), isNull(workflow.archivedAt))) + .limit(1) + .for('update') + if (point === 'after-lock') await runOutsideTransactionContext(interleave) + await saveWorkflowToNormalizedTables( + workflowId, + { blocks: { [blockId]: savedBlock() }, edges: [], loops: {}, parallels: {} }, + tx + ) + if (point === 'after-save') await runOutsideTransactionContext(interleave) + }) +} + +/** + * A writer that skips the workflow row lock and deletes every block before re-inserting what it + * read: no production writer does, but it is the case the flush's rows-affected check exists for. + */ +async function unlockedReplace(interleave: () => Promise) { await db.transaction(async (tx) => { - if (writer === 'locking') { - await tx - .select({ id: workflow.id }) - .from(workflow) - .where(and(eq(workflow.id, workflowId), isNull(workflow.archivedAt))) - .limit(1) - .for('update') - } const read = await tx .select() .from(workflowBlocks) .where(eq(workflowBlocks.workflowId, workflowId)) - if (point === 'after-reread') await runOutsideTransactionContext(interleave) await tx.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) - if (point === 'after-delete') await runOutsideTransactionContext(interleave) + await runOutsideTransactionContext(interleave) await tx.insert(workflowBlocks).values(read) }) } @@ -179,13 +223,35 @@ describe('subblock flush racing a whole-graph replace', () => { }) }) - it.each<[Writer, Point]>([ - ['locking', 'after-reread'], - ['locking', 'after-delete'], - ['blind', 'after-delete'], - ])('never confirms a keystroke a %s replace then loses (keystroke %s)', async (writer, point) => { + const keystroke = (handlers: Record, outcome: Promise) => async () => { + await handlers['subblock-update']({ + workflowId, + blockId, + subblockId: 'code', + value: TYPED, + timestamp: Date.now(), + operationId: generateId(), + }) + expect(await untilSettledOrBlocked(outcome)).toBe('blocked') + } + + it.each(['after-lock', 'after-save'])( + 'keeps a keystroke flushed inside a locked save (%s), and the save’s own change', + async (point) => { + const { handlers, outcome } = connect() + await lockedSave(point, keystroke(handlers, outcome)) + + expect({ + reported: await outcome, + code: await storedValue(), + name: await storedName(), + }).toEqual({ reported: 'operation-confirmed', code: TYPED, name: RENAMED }) + } + ) + + it('reports a keystroke an unlocked replace deletes the block under as failed, never confirmed', async () => { const { handlers, outcome } = connect() - await replaceGraph(writer, point, async () => { + await unlockedReplace(async () => { await handlers['subblock-update']({ workflowId, blockId, @@ -194,12 +260,13 @@ describe('subblock flush racing a whole-graph replace', () => { timestamp: Date.now(), operationId: generateId(), }) - await untilSettledOrBlocked(outcome) + expect(await untilSettledOrBlocked(outcome)).toBe('blocked') + }) + + expect({ reported: await outcome, code: await storedValue() }).toEqual({ + reported: 'operation-failed', + code: BEFORE, }) - const reported = await outcome - const stored = await storedValue() - expect({ reported, stored }).not.toEqual({ reported: 'operation-confirmed', stored: BEFORE }) - if (reported === 'operation-confirmed') expect(stored).toBe(TYPED) }) }) @@ -237,7 +304,7 @@ describe('variable flush racing an apply that rewrites the variables', () => { timestamp: Date.now(), operationId: generateId(), }) - await untilSettledOrBlocked(outcome) + expect(await untilSettledOrBlocked(outcome)).toBe('blocked') }) const read = locked.variables as Record> await tx @@ -251,7 +318,10 @@ describe('variable flush racing an apply that rewrites the variables', () => { .from(workflow) .where(eq(workflow.id, workflowId)) const stored = row.variables as Record - expect(stored[otherVariableId].value).toBe(APPLIED) - if (reported === 'operation-confirmed') expect(stored[variableId].value).toBe(TYPED) + expect({ + reported, + typed: stored[variableId].value, + applied: stored[otherVariableId].value, + }).toEqual({ reported: 'operation-confirmed', typed: TYPED, applied: APPLIED }) }) }) From c231bdc8818fa63dbb5a3316bef99686dd844071 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:49:48 -0800 Subject: [PATCH 068/104] test(workflows): cover the other-workspace id check for every kind and edge of it The tenant-isolation guard was covered for one table-and-workflow probe. foreignResourceRefusals now runs against real Postgres for each kind it names (table, child workflow, knowledge base): another workspace's id and an archived own one refuse, an own one and one the enclosing apply creates first are accepted, every id of a comma-separated value is checked, and a field the edit leaves alone is never checked. --- .../source-resource-scope.integration.ts | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 apps/sim/lib/workflows/application/source-resource-scope.integration.ts diff --git a/apps/sim/lib/workflows/application/source-resource-scope.integration.ts b/apps/sim/lib/workflows/application/source-resource-scope.integration.ts new file mode 100644 index 00000000000..ebd7f4c2e30 --- /dev/null +++ b/apps/sim/lib/workflows/application/source-resource-scope.integration.ts @@ -0,0 +1,179 @@ +/** + * Real PostgreSQL coverage for the check that refuses a resource id an edit writes verbatim when + * the workflow's own workspace does not hold it live: for each kind it names (table, child + * workflow, knowledge base), an id of another workspace and an archived one of the same workspace + * refuse, one of the same workspace or one the enclosing apply creates first is accepted, every id + * of a comma-separated value is checked, and a field the edit leaves alone is never checked. + */ +import { db } from '@sim/db' +import { knowledgeBase, user, userTableDefinitions, workflow, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { generateId } from '@sim/utils/id' +import type { BlockState } from '@sim/workflow-types/workflow' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { foreignResourceRefusals } from '@/lib/workflows/application/source-resource-scope' +import type { GraphDiff } from '@/lib/workflows/code/apply/graph-diff' +import { getBlock } from '@/blocks/registry' + +const ownerId = generateId() +const ownWorkspace = generateId() +const otherWorkspace = generateId() + +/** The block type and the field id that names each kind by id. */ +const KINDS = { + table: { blockType: 'table', selector: 'table-selector' }, + workflow: { blockType: 'workflow', selector: 'workflow-selector' }, + 'knowledge base': { blockType: 'knowledge', selector: 'knowledge-base-selector' }, +} as const + +type Kind = keyof typeof KINDS + +function fieldOf(kind: Kind): string { + const { blockType, selector } = KINDS[kind] + const field = getBlock(blockType)?.subBlocks.find((subBlock) => subBlock.type === selector) + if (!field) throw new Error(`${blockType} has no ${selector}`) + return field.id +} + +/** A live resource of `kind` in `workspaceId`, archived when asked; returns its id. */ +async function insertResource(kind: Kind, workspaceId: string, archived = false): Promise { + const id = generateId() + const now = new Date() + if (kind === 'table') { + await db.insert(userTableDefinitions).values({ + id, + workspaceId, + name: `t_${id.slice(0, 8)}`, + createdBy: ownerId, + schema: { columns: [] }, + ...(archived ? { archivedAt: now } : {}), + }) + } else if (kind === 'workflow') { + await db.insert(workflow).values({ + id, + workspaceId, + userId: ownerId, + name: `w ${id.slice(0, 8)}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + ...(archived ? { archivedAt: now } : {}), + }) + } else { + await db.insert(knowledgeBase).values({ + id, + workspaceId, + userId: ownerId, + name: `kb ${id.slice(0, 8)}`, + ...(archived ? { deletedAt: now } : {}), + }) + } + return id +} + +function blockNaming(kind: Kind, value: string): BlockState { + const field = fieldOf(kind) + return { + id: generateId(), + type: KINDS[kind].blockType, + name: `Uses ${kind}`, + position: { x: 0, y: 0 }, + subBlocks: { [field]: { id: field, type: KINDS[kind].selector, value } }, + outputs: {}, + enabled: true, + } +} + +/** The ids `refusals` name, by the block they are on. */ +async function refusedIds( + blocks: BlockState[], + diff: Pick, + pendingIds: string[] = [] +): Promise { + const refusals = await foreignResourceRefusals({ + blocks: Object.fromEntries(blocks.map((block) => [block.id, block])), + diff: { removed: [], edgesAdded: [], edgesRemoved: [], ...diff }, + workspaceId: ownWorkspace, + pendingIds: new Set(pendingIds), + keyOf: () => undefined, + }) + expect(refusals.every((refusal) => refusal.code === 'E_MAT_UNKNOWN_RESOURCE')).toBe(true) + return refusals.map((refusal) => /"([^"]+)"/.exec(refusal.message)?.[1] ?? '') +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Resource scope fixture', + email: `${ownerId}@resource-scope.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + for (const id of [ownWorkspace, otherWorkspace]) { + await insertWorkspaceFixture(db, { + id, + name: 'Resource scope', + ownerId, + billedAccountUserId: ownerId, + }) + } +}) + +afterAll(async () => { + await deleteWorkspaceFixture(db, inArray(workspace.id, [ownWorkspace, otherWorkspace])) + await db.delete(user).where(eq(user.id, ownerId)) +}) + +describe('foreignResourceRefusals', () => { + it.each(Object.keys(KINDS) as Kind[])( + 'refuses a %s of another workspace or an archived one, and accepts its own or a pending one', + async (kind) => { + const own = await insertResource(kind, ownWorkspace) + const foreign = await insertResource(kind, otherWorkspace) + const archived = await insertResource(kind, ownWorkspace, true) + const pending = generateId() + const blocks = [own, foreign, archived, pending].map((id) => blockNaming(kind, id)) + + const refused = await refusedIds( + blocks, + { added: blocks.map((block) => block.id), modified: [] }, + [pending] + ) + + expect(refused.sort()).toEqual([foreign, archived].sort()) + } + ) + + it('checks every id of a comma-separated value', async () => { + const own = await insertResource('table', ownWorkspace) + const foreign = await insertResource('table', otherWorkspace) + const block = blockNaming('table', `${own}, ${foreign}`) + + expect(await refusedIds([block], { added: [block.id], modified: [] })).toEqual([foreign]) + }) + + it('never checks a field the edit leaves alone, so a stored dangling id refuses nothing', async () => { + const foreign = await insertResource('table', otherWorkspace) + const block = blockNaming('table', foreign) + const modified = { + id: block.id, + subBlocks: ['code'], + attributes: ['name'], + typeChanged: false, + parentChanged: false, + lockedChanged: false, + enabledChanged: false, + } + + expect(await refusedIds([block], { added: [], modified: [modified] })).toEqual([]) + expect( + await refusedIds([block], { + added: [], + modified: [{ ...modified, subBlocks: [fieldOf('table')] }], + }) + ).toEqual([foreign]) + }) +}) From 7d5124e48eb8faafc8a056d9e7f8df24234d295b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 00:51:25 -0800 Subject: [PATCH 069/104] test: keep one owner for each duplicated assertion - The Python $ref hint is the compile tests'; the CLI check and the server integration assert only the refusal code and file. - The swap and retype integrations keep what the diff unit tests cannot see (stored ids, edges), not the modified-field shape those tests own. - Drops the executor case that mapped a mocked DelegatedWorkspaceAuthorizationError to text; the apply-time refusal is the real guard. - The unresolvable MCP host case asserts the refusal code, not resolver message text that varies without a resolver. - The write-back traversal cases assert the warning that says a stored file was not written. --- .../handlers/workflow/handler.test.ts | 13 ----- .../apply-workflow-source.integration.ts | 55 +++++++------------ .../application/mcp.integration.ts | 3 - .../protocol/workflow-source-check.test.ts | 1 - .../workflow-source-roundtrip.test.ts | 4 ++ 5 files changed, 24 insertions(+), 52 deletions(-) diff --git a/apps/sim/executor/handlers/workflow/handler.test.ts b/apps/sim/executor/handlers/workflow/handler.test.ts index 58a1034a4df..140bad47f89 100644 --- a/apps/sim/executor/handlers/workflow/handler.test.ts +++ b/apps/sim/executor/handlers/workflow/handler.test.ts @@ -19,7 +19,6 @@ import { import { permissionsMock } from '@sim/testing/mocks/permissions.mock' import { usersQueriesMock, usersQueriesMockFns } from '@sim/testing/mocks/users-queries.mock' import { afterAll, beforeAll, beforeEach, describe, expect, it, type Mock, vi } from 'vitest' -import { DelegatedWorkspaceAuthorizationError } from '@/lib/core/application' import { classifyFailure, logFailureOnce } from '@/lib/core/errors/failure-log' import { createTimeoutAbortController, getExecutionDeadlineAt } from '@/lib/core/execution-limits' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -373,18 +372,6 @@ describe('WorkflowBlockHandler', () => { ) }) - it('names a child the run cannot read through its delegation as a workflow of another workspace', async () => { - const ctx = { ...mockContext, workspaceId: 'workspace-parent' } - mockReadWorkflowDefinitionAsExecutor.mockRejectedValueOnce( - new DelegatedWorkspaceAuthorizationError() - ) - - await expect(handler.execute(ctx, mockBlock, inputs)).rejects.toThrow( - 'Child workflow child-workflow-id is not in this workspace' - ) - expect(mockExecutorExecute).not.toHaveBeenCalled() - }) - it('leaves an internal child load fault for the block executor to log with the run identity', async () => { mockReadWorkflowDefinitionAsExecutor.mockRejectedValueOnce( new TypeError('definition is undefined') 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 068d677bb73..dbe89bffa5a 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2436,11 +2436,6 @@ describe('renames in source', () => { { id: seeded.ids.boom, from: 'boom', to: 'tally' }, { id: seeded.ids.tally, from: 'tally', to: 'boom' }, ]) - expect( - result.diff.blocks.modified - .filter((block) => block.id === seeded.ids.boom || block.id === seeded.ids.tally) - .map((block) => block.fields) - ).toEqual([['name'], ['name']]) expect(result.diff.edges).toEqual({ added: 0, removed: 0 }) }) @@ -2466,7 +2461,6 @@ describe('renames in source', () => { expect(result.diff.blocks.added).toEqual([ expect.objectContaining({ key: 'tally', type: 'api' }), ]) - expect(result.diff.blocks.modified.map((block) => block.key)).not.toContain('tally') expect(result.diff.edges).toEqual({ added: 2, removed: 2 }) }) @@ -2718,37 +2712,28 @@ describe('renames in source', () => { } ) - check( - 'a $ref the edit wrote into a Python function file is refused, naming the tag', - async () => { - const seeded = await seedChain() - const source = await getSource(seeded.workflowId) - const entry = source.files['workflow.ts'].replace( - /fn\('Boom', \{.*\}\)/, - "fn('Boom', { language: 'python', code: codeFile('./functions/boom.py') })" - ) - expect(entry).toContain('boom.py') - const files = { - ...omit(source.files, ['functions/boom.js']), - 'workflow.ts': entry, - 'functions/boom.py': 'return $ref.start.value\n', - } + check('a $ref the edit wrote into a Python function file is refused', async () => { + const seeded = await seedChain() + const source = await getSource(seeded.workflowId) + const entry = source.files['workflow.ts'].replace( + /fn\('Boom', \{.*\}\)/, + "fn('Boom', { language: 'python', code: codeFile('./functions/boom.py') })" + ) + expect(entry).toContain('boom.py') + const files = { + ...omit(source.files, ['functions/boom.js']), + 'workflow.ts': entry, + 'functions/boom.py': 'return $ref.start.value\n', + } - const dryRun = await apply(source, files, { dryRun: true }) + const dryRun = await apply(source, files, { dryRun: true }) - expect( - dryRun.diagnostics - .filter((d) => d.severity === 'error') - .map((d) => ({ code: d.code, file: d.file, hint: d.hint })) - ).toEqual([ - { - code: 'E_APPLY_CODE_FILE_REF_SYNTAX', - file: 'functions/boom.py', - hint: 'Python files are saved as written: write .', - }, - ]) - } - ) + expect( + dryRun.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ code: d.code, file: d.file })) + ).toEqual([{ code: 'E_APPLY_CODE_FILE_REF_SYNTAX', file: 'functions/boom.py' }]) + }) check( 'refuses every edited Python file holding a $ref, however many the compile lists of that code', diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index 88249e3374f..e15d84a2019 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -252,9 +252,6 @@ describe('MCP servers as workspace source', () => { const dryRun = await apply(workspaceId, files, { dryRun: true }) expect(findings(dryRun.diagnostics, 'error')).toEqual(['E_APPLY_REFUSED mcp-server:bad']) - expect(dryRun.diagnostics.find((finding) => finding.key === 'bad')?.message).toContain( - 'could not be resolved' - ) const refused = await refusal(apply(workspaceId, files)) expect(findings(refused.diagnostics, 'error')).toEqual(['E_APPLY_REFUSED mcp-server:bad']) 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 0756a33b170..ecba07cac65 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 @@ -611,7 +611,6 @@ export default workflow('W', {}, () => { severity: 'error', file: 'functions/total.py', line: 1, - hint: 'Python files are saved as written: write .', }) ) expect(process.exitCode).toBe(1) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 4a2d98d4f40..1fabd5501e3 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -358,6 +358,7 @@ describe('the source directory never reaches outside --dir', () => { expect(existsSync(join(root, 'escape.js'))).toBe(false) expect(read('workflow.ts')).toBe('// changed\n') expect(JSON.parse(read('.sim/base.json')).fingerprint).not.toBe(FIRST) + expect(stderr.join('\n')).toContain('the answer named ../escape.js, which the CLI never writes') }) it.each([ @@ -436,6 +437,9 @@ describe('the files a server answer may write', () => { expect(existsSync(join(dir, '.git'))).toBe(false) expect(JSON.parse(read('.sim/base.json')).fingerprint).not.toBe(FIRST) + expect(stderr.join('\n')).toContain( + 'the answer named .git/hooks/pre-commit, which the CLI never writes' + ) }) }) From 71e5baa993ae8b036c07b80a6c9064b33534c38f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:05:25 -0800 Subject: [PATCH 070/104] test(workflows): compare a fidelity snapshot's edges by id The normalized loader reads edges in no particular order, and the diff save updates rows in place, so a no-op apply's before and after snapshots could list the same edges in another order and fail about one run in three. The snapshot now sorts them by id. --- .../application/apply-workflow-source.fidelity.integration.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.fidelity.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.fidelity.integration.ts index 83472ee5cbf..9a61f35bc8d 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.fidelity.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.fidelity.integration.ts @@ -152,7 +152,9 @@ async function snapshot(workflowId: string) { updatedAt: row.updatedAt.getTime(), graph: { blocks: graph.blocks, - edges: graph.edges, + // The loader reads edges in no particular order, and a save that updates rows in place + // moves them in the heap, so they compare by id. + edges: [...graph.edges].sort((a, b) => compareStrings(a.id, b.id)), loops: sortedNodes(graph.loops), parallels: sortedNodes(graph.parallels), variables: graph.variables, From 50c49f7fc1ab349ad905114102d765d3a2d91aac Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:18:14 -0800 Subject: [PATCH 071/104] refactor: drop the exports the refusal and slot moves left unused LOOP_PROPERTIES and PARALLEL_PROPERTIES left the workflow-code entry once the lint read the iteration-scope rule instead, EditedBlocks is only refuseEditedFindings' parameter type, and renderSourceSlotBusy is imported from its module, not the barrel. --- apps/sim/lib/workflows/api/index.ts | 2 +- packages/workflow-code/src/index.ts | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 3c1075f5b02..d87ea6cedd8 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -7,7 +7,7 @@ export { v2WorkflowErrorPolicies, WORKFLOW_NOT_FOUND_MESSAGE, } from '@/lib/workflows/api/route-policies' -export { renderSourceSlotBusy, withSourceSlot } from '@/lib/workflows/api/source-slots' +export { withSourceSlot } from '@/lib/workflows/api/source-slots' export { presentV2WorkflowTrigger, presentV2WorkspaceSchedule, diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 746ce8622ec..b9bd87b7774 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -35,8 +35,6 @@ export { createJsContextScanner, fromCodeFile, isIdentifierName, - LOOP_PROPERTIES, - PARALLEL_PROPERTIES, } from './code-files' export { type CompileResult, compileWorkflow, type StoredEdgeRef } from './compile' export { codePointLabel, scriptName } from './compile/characters' @@ -64,7 +62,6 @@ export { } from './diagnostics/frame' export { EDIT_REFUSALS, - type EditedBlocks, raisedMessage, refuseEditedFindings, } from './diagnostics/refusals' From 52981e4343ad66766bf317f0fe5d15b0cc66999a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:48:14 -0800 Subject: [PATCH 072/104] fix(workflow-code): cap refused withheld findings at the error budget An apply refusing many edited blocks listed every refused withheld finding, past MAX_ERRORS. List them up to what remains of the cap and count the rest in one E_TOO_MANY_ERRORS, so the response stays bounded and still refuses. --- .../workflow-code/src/compile/hostile.test.ts | 3 +- packages/workflow-code/src/compile/report.ts | 4 +-- .../workflow-code/src/diagnostics/codes.ts | 3 ++ .../src/diagnostics/refusals.test.ts | 24 ++++++++++++++ .../workflow-code/src/diagnostics/refusals.ts | 32 +++++++++++++++---- 5 files changed, 56 insertions(+), 10 deletions(-) diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index e0f764c86ca..6a761e4f8e4 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -1,11 +1,12 @@ import { afterEach, describe, expect, it } from 'vitest' import { codeFileReferences } from '../code-files/references' +import { MAX_ERRORS } from '../diagnostics/codes' import { growth, MAX_GROWTH } from '../scaling.test-helpers' import { TEST_CATALOG } from './catalog.test-helpers' import type { CompileResult } from './index' import { compileWorkflow } from './index' import { type CompileLimits, sourceDepthOverflow } from './parse' -import { MAX_ERRORS, MAX_INFOS, MAX_WARNINGS, MAX_WARNINGS_PER_CODE, Reporter } from './report' +import { MAX_INFOS, MAX_WARNINGS, MAX_WARNINGS_PER_CODE, Reporter } from './report' /** * Hostile sources: compile never executes anything and never throws. Each input must come diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index 1f606c519bf..2c588ec96df 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -1,5 +1,5 @@ import { truncateAtCodePoint } from '@sim/utils/string' -import { type CompileDiagnosticCode, framesSource } from '../diagnostics/codes' +import { type CompileDiagnosticCode, framesSource, MAX_ERRORS } from '../diagnostics/codes' import { codeFrame, LINE_BREAK, @@ -69,8 +69,6 @@ function severityOf(code: CompileDiagnosticCode): SeverityOfCode { return code.startsWith('I_') ? 'info' : 'warning' } -/** Errors one compile lists before it stops with `E_TOO_MANY_ERRORS`. */ -export const MAX_ERRORS = 100 /** Warnings one compile lists before the rest are omitted with `W_TOO_MANY_WARNINGS`. */ export const MAX_WARNINGS = 100 /** diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index a34113dddef..a80c749a0da 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -293,6 +293,9 @@ const COMPILE_DIAGNOSTIC_CODES = [ ...CODE_FILE_CODES, ...REFERENCE_CODES, ] as const +/** Errors one compile lists before it stops with `E_TOO_MANY_ERRORS`. */ +export const MAX_ERRORS = 100 + export type CompileDiagnosticCode = (typeof COMPILE_DIAGNOSTIC_CODES)[number] /** diff --git a/packages/workflow-code/src/diagnostics/refusals.test.ts b/packages/workflow-code/src/diagnostics/refusals.test.ts index 755438c539e..c53fa5ea888 100644 --- a/packages/workflow-code/src/diagnostics/refusals.test.ts +++ b/packages/workflow-code/src/diagnostics/refusals.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { TEST_CATALOG } from '../compile/catalog.test-helpers' import { compileWorkflow } from '../compile/index' import { MAX_WARNINGS_PER_CODE } from '../compile/report' +import { MAX_ERRORS } from './codes' import { type EditedBlocks, refuseEditedFindings } from './refusals' const IMPORTS = "import { api, codeFile, fn, loop, t, trigger, workflow } from '@sim/workflow-sdk'" @@ -106,4 +107,27 @@ describe('refuseEditedFindings', () => { ]) expect(errors(refuseEditedFindings(compiled, edited()))).toEqual([]) }) + + it('lists refused withheld findings only up to the error cap, then one summary error', () => { + const count = MAX_ERRORS + 30 + const keys = Array.from({ length: count }, (_, i) => `f${i}`) + const compiled = compile( + [ + START, + ...keys.map( + (key) => + `const ${key} = fn('${key}', { language: 'python', code: codeFile('./functions/${key}.py') })` + ), + ...keys.map((key) => `start.to(${key})`), + ], + Object.fromEntries(keys.map((key) => [`functions/${key}.py`, 'x = $ref.start.input'])) + ) + const refused = errors(refuseEditedFindings(compiled, edited(...keys))) + + expect(refused).toHaveLength(MAX_ERRORS + 1) + expect(refused.at(-1)).toMatch(/^E_TOO_MANY_ERRORS /) + expect( + refused.slice(0, -1).every((line) => line.startsWith('E_APPLY_CODE_FILE_REF_SYNTAX')) + ).toBe(true) + }) }) diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index f33fb0134c3..814ceaaafa5 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -6,7 +6,7 @@ * {@link refuseEditedFindings} with what each knows the edit changed, so they cannot disagree. */ import { SOURCE_ENTRY_FILE } from '../limits' -import type { CompileDiagnosticCode } from './codes' +import { type CompileDiagnosticCode, MAX_ERRORS } from './codes' import type { LocatedDiagnostic } from './frame' /** The error codes an edited block's warning is refused under. */ @@ -112,7 +112,10 @@ function refusalOf(finding: LocatedDiagnostic, edit: EditedBlocks): EditRefusalC /** * A compile's findings with every warning the apply refuses on an edited block raised to its * error code (see the module doc). `withheld`, the refusable warnings the compile's caps left - * out, join the result only when refused, so a refusal never depends on where a cap fell. + * out, join the result only when refused, so a refusal never depends on where a cap fell. They + * are listed only up to what remains of {@link MAX_ERRORS}; the rest are counted in one + * `E_TOO_MANY_ERRORS`, so the result keeps the compile's error bound and still holds an error + * whenever any finding is refused. */ export function refuseEditedFindings( compiled: { diagnostics: readonly D[]; withheld: readonly D[] }, @@ -124,8 +127,25 @@ export function refuseEditedFindings( ? undefined : { ...finding, code, severity: 'error', message: raisedMessage(finding.message) } } - return [ - ...compiled.diagnostics.map((finding) => refused(finding) ?? finding), - ...compiled.withheld.flatMap((finding) => refused(finding) ?? []), - ] + const listed: Array = compiled.diagnostics.map( + (finding) => refused(finding) ?? finding + ) + const extra = compiled.withheld.flatMap((finding) => refused(finding) ?? []) + const budget = Math.max( + 0, + MAX_ERRORS - listed.filter((finding) => finding.severity === 'error').length + ) + if (extra.length <= budget) return [...listed, ...extra] + const [first] = extra.slice(budget) + const omitted = extra.length - budget + const summary: LocatedDiagnostic<'E_TOO_MANY_ERRORS'> = { + code: 'E_TOO_MANY_ERRORS', + severity: 'error', + message: `${omitted} more edited ${omitted === 1 ? 'finding is' : 'findings are'} refused, as the ones listed are. The next: ${first.message}`, + hint: 'Fix the errors listed and check again to see the rest.', + span: first.span, + ...(first.frame === undefined ? {} : { frame: first.frame }), + ...(first.blockKey === undefined ? {} : { blockKey: first.blockKey }), + } + return [...listed, ...extra.slice(0, budget), summary] } From 954a88c8b06b5691755cd6fb544a68e39523e7e4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:51:07 -0800 Subject: [PATCH 073/104] fix(workspace-source): plan workflow folders and delete candidates without writing A workspace plan still allocated resource keys on three read paths: comparing four or more sent folders (readWorkflowSources), fingerprinting each --allow-delete candidate (a full readWorkflowSource that also recorded a source read and printed the source), and locating a renamed table column's line. The delete fingerprint, before the plan and again before the write, now comes from readDraftFingerprint, which prints nothing; the other two reads take plan: true, which binds no key and records no read. --- .../application/read-workflow-source.ts | 15 ++++- .../application/apply.integration.ts | 56 ++++++++++++++++++- .../application/kinds/table/renames.ts | 2 +- .../application/kinds/workflow/adapter.ts | 12 +++- 4 files changed, 78 insertions(+), 7 deletions(-) diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index ab821839f34..4c2fa7b670e 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -60,6 +60,11 @@ interface GetWorkflowSourceInput { assertedWorkspaceId?: string /** `files` (default): function code in `functions/*` files; `inline`: tagged templates. */ functionCode?: 'inline' | 'files' + /** + * A plan's read (never a route's): a resource with no key stays unkeyed instead of binding one, + * and no source read is recorded, so a plan writes nothing. + */ + plan?: boolean } /** A canonicalize or print finding, without source spans (the read path has no input text). */ @@ -294,13 +299,14 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ workflowId: context.workflowId, workspaceId: context.workspaceId, createdBy: resolvePrincipalSubjectUserId(principal) ?? null, + ...(input.plan ? { allocate: false } : {}), }), ]) const read = await printLoadedSource( { scope: context, stored, gate, sourceMeta, prefetched }, input.functionCode ?? 'files' ) - recordSourceRead(principal, context) + if (!input.plan) recordSourceRead(principal, context) return read }, }) @@ -323,6 +329,8 @@ interface ReadWorkflowSourcesInput { workspaceId: string /** Workflows of the workspace to read; one archived or in another workspace reads as missing. */ workflowIds: readonly string[] + /** A plan's read: a resource with no key stays unkeyed instead of binding one. */ + plan?: boolean } /** Workflows a batched read prints at once: each may wait on its own resolver queries. */ @@ -351,7 +359,10 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ loadWorkflowGraphs(workspaceId, input.workflowIds), resolveCatalogGate(principal, context, { customBlockInputs: true }), readWorkflowSourceMetas(db, input.workflowIds), - prefetchStoredResourcesFor({ workspaceId, createdBy }, input.workflowIds), + prefetchStoredResourcesFor( + { workspaceId, createdBy, ...(input.plan ? { allocate: false } : {}) }, + input.workflowIds + ), ]) const printed = await mapWithConcurrency( input.workflowIds, diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index a97ec64c0dc..4369d887730 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -14,7 +14,7 @@ import { createWorkspaceApiKeyPrincipal, } from '@sim/testing/factories/principal.factory' import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock' -import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock' +import { posthogServerMock, posthogServerMockFns } from '@sim/testing/mocks/posthog-server.mock' import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' import { generateId } from '@sim/utils/id' import { isRecordLike } from '@sim/utils/object' @@ -804,6 +804,60 @@ export default workflow('Notes', {}, () => { } ) + check( + 'a plan comparing many folders and fingerprinting delete candidates binds no key and records no read', + async () => { + const workspaceId = await newWorkspace() + const names = ['Ingest A', 'Ingest B', 'Ingest C', 'Ingest D', 'Doomed'] + const created = await apply(workspaceId, { + ...STARTER, + ...Object.fromEntries( + names.map((name) => [ + `workflows/${name.toLowerCase().replace(' ', '-')}/workflow.ts`, + INGEST.replace("workflow('Ingest'", `workflow('${name}'`), + ]) + ), + }) + expect(created.failed).toBeUndefined() + const read = await get(workspaceId) + const tableKeys = () => + db + .select({ key: workspaceResourceKey.key }) + .from(workspaceResourceKey) + .where( + and( + eq(workspaceResourceKey.workspaceId, workspaceId), + eq(workspaceResourceKey.kind, 'table') + ) + ) + expect(await tableKeys()).toEqual([{ key: 'leads' }]) + await db + .delete(workspaceResourceKey) + .where( + and( + eq(workspaceResourceKey.workspaceId, workspaceId), + eq(workspaceResourceKey.kind, 'table') + ) + ) + const files = Object.fromEntries( + Object.entries(read.files).filter(([path]) => !path.startsWith('workflows/doomed/')) + ) + posthogServerMockFns.mockCaptureServerEvent.mockClear() + + await apply(workspaceId, files, { + base: read.base, + kinds: ['workflow'], + allowDelete: true, + dryRun: true, + }).catch(() => undefined) + + expect(await tableKeys()).toEqual([]) + expect( + posthogServerMockFns.mockCaptureServerEvent.mock.calls.map(([, event]) => event) + ).not.toContain('workflow_source_read') + } + ) + check('deletes a workflow the directory no longer declares, with --allow-delete', async () => { const workspaceId = await newWorkspace() await apply(workspaceId, { 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 790ee72e3b9..5e814e546d7 100644 --- a/apps/sim/lib/workspace-source/application/kinds/table/renames.ts +++ b/apps/sim/lib/workspace-source/application/kinds/table/renames.ts @@ -133,7 +133,7 @@ export async function checkColumnRenamesInUse( ? ( await readWorkflowSource.execute({ principal: ctx.principal, - input: { workflowId: workflow.id }, + input: { workflowId: workflow.id, plan: true }, }) ).files[SOURCE_ENTRY_FILE] : undefined diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index 91d8b8e2aa6..1f6e25bb30e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -56,6 +56,7 @@ import { listWorkflows } from '@/lib/workflows/application/list-workflows' import { requireMutableWorkflow } from '@/lib/workflows/application/mutability' import { type ReadWorkflowSourceResult, + readDraftFingerprint, readWorkflowSource, readWorkflowSources, } from '@/lib/workflows/application/read-workflow-source' @@ -121,16 +122,20 @@ function workflowFingerprint(source: SourceBase): ResourceFingerprint { return fingerprintOf({ source: source.fingerprint }) } -/** The fingerprint of workflow `workflowId` as it is stored now. */ +/** + * The fingerprint of workflow `workflowId` as it is stored now: the `sf1:` fingerprint a read + * would report as `base.fingerprint`, computed without printing, so it writes nothing, records no + * read and holds for a workflow grown past the print limits. + */ async function readStoredFingerprint( ctx: SourceContext, workflowId: string ): Promise { - const source = await readWorkflowSource.execute({ + const fingerprint = await readDraftFingerprint.execute({ principal: ctx.principal, input: { workflowId }, }) - return workflowFingerprint(source.base) + return fingerprintOf({ source: fingerprint }) } /** Why `workflow` cannot be deleted for a lock (its own or its folder's), if so. */ @@ -569,6 +574,7 @@ async function foldersAsStored( input: { workspaceId: ctx.workspace.workspaceId, workflowIds: batch.map((step) => step.update.workflowId), + plan: true, }, }) } catch (error) { From 0a4f04a0038813297b239f107963973ccb679d4b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:55:19 -0800 Subject: [PATCH 074/104] fix(workflow-persistence): load graph rows in creation order The diff save updates rows in place, so with no ORDER BY the loaded block and edge order followed where Postgres left each updated tuple, and a condition with two incoming edges could change which one it read after an unrelated edit. The loader now orders each table by created_at, then id, which a diff save keeps for every row it rewrites. The condition handler also reads the incoming block that ran in this execution, falling back to the first edge only when none did. --- .../handlers/condition/handler.test.ts | 18 +++++++ .../executor/handlers/condition/handler.ts | 32 ++++++++---- .../normalized-save.integration.ts | 49 ++++++++++++++++++- .../workflow-persistence/src/load.test.ts | 2 + packages/workflow-persistence/src/load.ts | 22 +++++++-- 5 files changed, 106 insertions(+), 17 deletions(-) diff --git a/apps/sim/executor/handlers/condition/handler.test.ts b/apps/sim/executor/handlers/condition/handler.test.ts index 6a75c1ad97a..6535bb2ec7f 100644 --- a/apps/sim/executor/handlers/condition/handler.test.ts +++ b/apps/sim/executor/handlers/condition/handler.test.ts @@ -700,6 +700,24 @@ describe('ConditionBlockHandler', () => { }) }) + it('reads the incoming block that ran, not the first edge drawn into the condition', async () => { + mockExecuteTool.mockResolvedValueOnce(matchedAt(0)) + mockWorkflow.connections = [ + { source: 'skipped-branch', target: mockBlock.id }, + ...(mockWorkflow.connections ?? []), + ] + const conditions = [ + { id: 'cond1', title: 'if', value: 'context.value > 5' }, + { id: 'else1', title: 'else', value: '' }, + ] + + const result = await handler.execute(mockContext, mockBlock, { + conditions: JSON.stringify(conditions), + }) + + expect(result).toMatchObject({ value: 10, text: 'hello', selectedOption: 'cond1' }) + }) + describe('Source output filtering', () => { it('should not propagate error field from source block output', async () => { mockExecuteTool.mockResolvedValueOnce(matchedAt(0)) diff --git a/apps/sim/executor/handlers/condition/handler.ts b/apps/sim/executor/handlers/condition/handler.ts index bb198033611..eb9076af9f7 100644 --- a/apps/sim/executor/handlers/condition/handler.ts +++ b/apps/sim/executor/handlers/condition/handler.ts @@ -336,16 +336,7 @@ export class ConditionBlockHandler implements BlockHandler { const baseBlockId = extractBaseBlockId(block.id) const branchIndex = isBranchNodeId(block.id) ? extractBranchIndex(block.id) : null - const sourceConnection = ctx.workflow?.connections.find((conn) => conn.target === baseBlockId) - let sourceBlockId = sourceConnection?.source - - if (sourceBlockId && branchIndex !== null) { - const virtualSourceId = buildBranchNodeId(sourceBlockId, branchIndex) - if (ctx.blockStates.has(virtualSourceId)) { - sourceBlockId = virtualSourceId - } - } - + const sourceBlockId = this.resolveSourceBlockId(ctx, baseBlockId, branchIndex) const evalContext = this.buildEvaluationContext(ctx, sourceBlockId) const rawSourceOutput = sourceBlockId ? ctx.blockStates.get(sourceBlockId)?.output : null @@ -574,6 +565,27 @@ export class ConditionBlockHandler implements BlockHandler { return null } + /** + * The block whose output the condition evaluates against and passes on: of the blocks with an + * edge into it (each as its own branch's copy inside a parallel, when that copy ran), the first + * that ran in this execution, else the first. A condition joining an if/else so reads the + * branch that ran, whichever edge was drawn first. + */ + private resolveSourceBlockId( + ctx: ExecutionContext, + baseBlockId: string, + branchIndex: number | null + ): string | undefined { + const sources = (ctx.workflow?.connections ?? []) + .filter((conn) => conn.target === baseBlockId) + .map((conn) => { + if (branchIndex === null) return conn.source + const virtualSourceId = buildBranchNodeId(conn.source, branchIndex) + return ctx.blockStates.has(virtualSourceId) ? virtualSourceId : conn.source + }) + return sources.find((id) => ctx.blockStates.get(id)?.executed) ?? sources[0] + } + private findConnectionForCondition( connections: Array<{ source: string; target: string; sourceHandle?: string }>, conditionId: string diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts index 337692b89b8..9bb3927d9d2 100644 --- a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -8,9 +8,18 @@ * repeated in one state and an edge to a block the state does not hold. */ import { db } from '@sim/db' -import { user, workflow, workflowBlocks, workflowEdges, workflowSubflows } from '@sim/db/schema' +import { + user, + workflow, + workflowBlocks, + workflowEdges, + workflowSubflows, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { getPostgresErrorCode } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { loadWorkflowFromNormalizedTablesRaw } from '@sim/workflow-persistence/load' import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' import type { DbOrTx } from '@sim/workflow-persistence/types' import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' @@ -18,6 +27,7 @@ import { asc, eq } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it } from 'vitest' const ownerId = generateId() +const workspaceId = generateId() /** Deterministic PRNG (mulberry32) so a failing sequence replays from its seed. */ function seededRandom(seed: number): () => number { @@ -72,7 +82,8 @@ async function insertWorkflow(): Promise { await db.insert(workflow).values({ id, userId: ownerId, - name: 'Normalized save fixture', + workspaceId, + name: `Normalized save fixture ${id}`, lastSynced: now, createdAt: now, updatedAt: now, @@ -218,9 +229,16 @@ beforeAll(async () => { createdAt: now, updatedAt: now, }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Normalized save fixture', + ownerId, + billedAccountUserId: ownerId, + }) }) afterAll(async () => { + await deleteWorkspaceFixture(db, eq(workspace.ownerId, ownerId)) await db.delete(user).where(eq(user.id, ownerId)) }) @@ -284,6 +302,33 @@ describe('saveWorkflowToNormalizedTables', () => { expect(rewritten).toEqual([edited[7].id]) }) + it('loads blocks and edges in creation order, whatever rows a later save rewrote', async () => { + const workflowId = await insertWorkflow() + const blocks = ['b1', 'b2', 'b3'].map((id, index) => + functionBlock(`${workflowId}-${id}`, `Block ${index}`, index * 100) + ) + const [first, second, third] = blocks.map((block) => block.id) + const edges = [ + { id: `${workflowId}-e1`, source: first, target: third }, + { id: `${workflowId}-e2`, source: second, target: third }, + ] + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, edges))).toEqual({ + success: true, + }) + + const edited = structuredClone(blocks) + edited[0].name = 'Renamed' + const added = { id: `${workflowId}-e0`, source: first, target: second } + const editedEdges = [{ ...edges[0], sourceHandle: 'error' }, edges[1], added] + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(edited, editedEdges))).toEqual({ + success: true, + }) + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(Object.keys(loaded?.blocks ?? {})).toEqual([first, second, third]) + expect(loaded?.edges.map((edge) => edge.id)).toEqual([edges[0].id, edges[1].id, added.id]) + }) + it('refuses a block id another workflow owns and leaves the stored graph as it was', async () => { const owner = await insertWorkflow() const workflowId = await insertWorkflow() diff --git a/packages/workflow-persistence/src/load.test.ts b/packages/workflow-persistence/src/load.test.ts index 3b77f030a77..d0e7cf27058 100644 --- a/packages/workflow-persistence/src/load.test.ts +++ b/packages/workflow-persistence/src/load.test.ts @@ -27,6 +27,7 @@ vi.mock('@sim/logger', () => ({ vi.mock('drizzle-orm', () => ({ and: vi.fn(), + asc: vi.fn(), eq: vi.fn(), getTableColumns: vi.fn(() => ({})), inArray: vi.fn(), @@ -45,6 +46,7 @@ function createTx(rowsByTable: Record) { const resultFor = (rows: Row[]) => { const result = { where: () => result, + orderBy: () => result, limit: () => Promise.resolve(rows), then: (onFulfilled: (rows: Row[]) => unknown) => Promise.resolve(rows).then(onFulfilled), } diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 2a9720316d3..201fd167923 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -9,7 +9,7 @@ import { SUBFLOW_TYPES, } from '@sim/workflow-types/workflow' import type { Edge } from '@xyflow/react' -import { and, eq, getTableColumns, inArray, isNull, type SQLWrapper, sql } from 'drizzle-orm' +import { and, asc, eq, getTableColumns, inArray, isNull, type SQLWrapper, sql } from 'drizzle-orm' import { clampParallelBatchSize } from './subflow-helpers' import type { DbOrTx, NormalizedWorkflowData } from './types' @@ -181,7 +181,10 @@ export async function loadWorkflowsFromNormalizedTablesRaw( /** * The block, edge and subflow rows of `workflowIds`: a list, or a query of ids that each graph - * query embeds as a subquery. + * query embeds as a subquery. Each table's rows come in creation order, ties by id, so the + * assembled graph's block and edge order (which the executor reads, e.g. a router's or + * condition's first matching edge) is a fact of the stored rows, not of where an update left + * them in the heap. */ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWrapper)) { const ids = () => (typeof workflowIds === 'function' ? workflowIds() : workflowIds) @@ -192,9 +195,18 @@ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWra updatedAtText: sql`${workflowBlocks.updatedAt}::text`, }) .from(workflowBlocks) - .where(inArray(workflowBlocks.workflowId, ids())), - tx.select().from(workflowEdges).where(inArray(workflowEdges.workflowId, ids())), - tx.select().from(workflowSubflows).where(inArray(workflowSubflows.workflowId, ids())), + .where(inArray(workflowBlocks.workflowId, ids())) + .orderBy(asc(workflowBlocks.createdAt), asc(workflowBlocks.id)), + tx + .select() + .from(workflowEdges) + .where(inArray(workflowEdges.workflowId, ids())) + .orderBy(asc(workflowEdges.createdAt), asc(workflowEdges.id)), + tx + .select() + .from(workflowSubflows) + .where(inArray(workflowSubflows.workflowId, ids())) + .orderBy(asc(workflowSubflows.createdAt), asc(workflowSubflows.id)), ]) return { blocks, edges, subflows } } From c704e2ef4ae09507c44334533ce37dddd8ecb09e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:56:54 -0800 Subject: [PATCH 075/104] fix(workflows): take rename-settled finding codes whole from the recompile The filter kept a first-compile W_UNRESOLVED_REF only where the recompile reported one at the same position. The first compile withholds one finding per code, block and file, so when that one was settled by an inferred rename it dropped the key's only representative and a later unresolved reference in the same edited file was not refused as such. Those codes now come from the recompile, listed and withheld. --- .../apply-workflow-source.integration.ts | 31 +++++++++++++++++-- .../workflows/application/source-evaluate.ts | 13 ++++---- 2 files changed, 35 insertions(+), 9 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 dbe89bffa5a..1212e2364bf 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2248,7 +2248,10 @@ export default workflow('', {}, () => { describe('renames in source', () => { /** Start → Boom → Tally → Report, each a function; Report's code reads Boom and Tally by $ref. */ - async function seedChain(reportCode = 'return + ') { + async function seedChain( + reportCode = 'return + ', + tallyCode = 'return 2' + ) { const workflowId = generateId() const now = new Date() await db.insert(workflow).values({ @@ -2271,7 +2274,7 @@ describe('renames in source', () => { }) const start: BlockState = { ...fn('Start', ''), type: 'start_trigger', subBlocks: {} } const boom = fn('Boom', 'return 1') - const tally = fn('Tally', 'return 2') + const tally = fn('Tally', tallyCode) const report = fn('Report', reportCode) const chain = [start, boom, tally, report] const saved = await saveWorkflowToNormalizedTables(workflowId, { @@ -2772,6 +2775,30 @@ describe('renames in source', () => { } ) + check( + 'refuses a missing block an edited file reads after a reference an inferred rename settles', + async () => { + // The stored Tally already reads more missing blocks than a compile lists of that code, so + // each of Report's findings is left out of the listing. + const ghosts = Array.from({ length: 20 }, (_, i) => ``) + const seeded = await seedChain(undefined, `return [${ghosts.join(', ')}]`) + const source = await getSource(seeded.workflowId) + const files = { + ...edit(renameIdent(source.files, 'boom', 'bang'), "fn('Boom'", "fn('Bang'"), + 'functions/report.js': 'return $ref.boom.result + $ref.nosuchblock.result\n', + } + + const dryRun = await apply(source, files, { dryRun: true }) + + expect(codes(dryRun.diagnostics)).toContain('W_MAT_INFERRED_RENAME') + expect( + dryRun.diagnostics + .filter((d) => d.severity === 'error') + .map((d) => ({ code: d.code, file: d.file })) + ).toEqual([{ code: 'E_APPLY_UNRESOLVED_REF', file: 'functions/report.js' }]) + } + ) + check( 'a dangling reference the stored code already holds stays a warning, whatever else the apply changes', async () => { diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 70e3d2ea418..c5feefb2a7e 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -289,7 +289,9 @@ const RENAME_SETTLED_CODES: ReadonlySet = new Set([ * `diagnostics` without the {@link RENAME_SETTLED_CODES} findings a block rename settles. The * compile already knew the renames the lock names by ident; a rename materialize inferred (name * and const both changed) is known only now, so the source is compiled again with every rename and - * a finding stays only where that compile still reports it. + * its findings of those codes, listed and withheld, replace the first compile's. Taken whole, not + * matched by position: the first compile withholds one finding per code, block and file, so a + * settled one may stand for a later finding in that file that the rename leaves unresolved. */ function withoutRenameSettledFindings( compiled: Pick, @@ -300,14 +302,11 @@ function withoutRenameSettledFindings( if (renames.size === 0 || ![...compiled.diagnostics, ...compiled.withheld].some(settles)) { return compiled } - const at = (d: CompileResult['diagnostics'][number]) => - `${d.code}@${d.span.file}:${d.span.line}:${d.span.column}` const again = recompile() - const still = new Set([...again.diagnostics, ...again.withheld].filter(settles).map(at)) - const kept = (d: CompileResult['diagnostics'][number]) => !settles(d) || still.has(at(d)) + const unsettled = (d: CompileResult['diagnostics'][number]) => !settles(d) return { - diagnostics: compiled.diagnostics.filter(kept), - withheld: compiled.withheld.filter(kept), + diagnostics: [...compiled.diagnostics.filter(unsettled), ...again.diagnostics.filter(settles)], + withheld: [...compiled.withheld.filter(unsettled), ...again.withheld.filter(settles)], } } From 974bf64d0a71507df6964213d837eb001d5b5ae6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 01:58:10 -0800 Subject: [PATCH 076/104] fix(workspace-source): check hidden MCP headers against the server at the new URL too A declaration moved to a URL held by an unbound server was compared with that server's stored header values, but the hidden-header check covered only the bound server. A caller who cannot see those values got a replace plan for a right guess and E_NAME_TAKEN for a wrong one. Both rows the plan compares with are now checked first. --- .../application/kinds/mcp/adapter.ts | 11 +++-- .../application/mcp.integration.ts | 44 +++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts index 3df129e919e..435995f014e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/mcp/adapter.ts @@ -169,9 +169,14 @@ async function planServer( const adoptable = stored.unbound.find((record) => record.id === id) const target = bound ?? adoptable // A caller who cannot see a header's stored value may only keep it: comparing text they wrote - // with the hidden value would tell them whether they guessed it. - if (target && (await revealsHeaderValues(ctx)) !== true) { - for (const header of hiddenHeadersWritten(declared, target.state)) { + // with the hidden value would tell them whether they guessed it. The plan compares the + // declaration with the bound server and with the one at its URL, so both are checked. + const compared = [bound, adoptable].flatMap((record) => (record ? [record] : [])) + if (compared.length > 0 && (await revealsHeaderValues(ctx)) !== true) { + const hidden = new Set( + compared.flatMap((record) => hiddenHeadersWritten(declared, record.state)) + ) + for (const header of hidden) { finding( 'E_APPLY_FORBIDDEN', `Header "${header}" holds a value you cannot see, so it can only be kept as \`stored()\`.`, diff --git a/apps/sim/lib/workspace-source/application/mcp.integration.ts b/apps/sim/lib/workspace-source/application/mcp.integration.ts index e15d84a2019..99cb1585a43 100644 --- a/apps/sim/lib/workspace-source/application/mcp.integration.ts +++ b/apps/sim/lib/workspace-source/application/mcp.integration.ts @@ -819,6 +819,50 @@ describe('MCP servers as workspace source', () => { } ) + check( + 'never tells a read-only member whether a header they write to a new URL matches the server there', + async () => { + const workspaceId = await newWorkspace() + await createMcpServerUseCase.execute({ + principal: owner, + input: { workspaceId, name: 'Tenant', url, authType: 'headers' }, + }) + const read = await runner.get(workspaceId, reader) + const [path] = Object.keys(read.files) + // Created after the get, so no key binds it: the plan can only meet it at its URL. + await createMcpServerUseCase.execute({ + principal: owner, + input: { + workspaceId, + name: 'Tenant', + url: `${url}/v2`, + headers: { 'X-Tenant': 'acme' }, + authType: 'headers', + }, + }) + + const planWith = async (guess: string) => { + const moved = read.files[path].replace(url, `${url}/v2`) + const files = { + [path]: moved.replace( + /url: ('[^']*'),/, + `url: $1,\n headers: { 'X-Tenant': '${guess}' },` + ), + } + expect(files[path]).toContain(`'X-Tenant': '${guess}'`) + const plan = await planAs(reader, workspaceId, files, read.base) + return { plan: plan.plan, diagnostics: plan.diagnostics } + } + const right = await planWith('acme') + const wrong = await planWith('other') + + expect(right).toEqual(wrong) + expect(findings(right.diagnostics, 'error')).toEqual([ + `E_APPLY_FORBIDDEN mcp-server:${path.slice(4, -3)}`, + ]) + } + ) + check( 'refuses a replace that carries stored() header values to a new URL unless an admin applies it', async () => { From d01b35d18510ecb73c485910fccc307b115b97ca Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:00:49 -0800 Subject: [PATCH 077/104] fix(sim-cli): match the server's refusals for a repointed block and an inferred rename The server counts a block's code as edited when the block now runs another file whose text differs from what it ran; the CLI looked only at the file's own text, so pointing a bound block at an unedited file with a dangling $ref passed the check and failed the apply. The check now compares the same way. A $ref to a block the lock binds that the source no longer declares stays a warning, since the server may infer that rename and rewrite it, and the help says so, along with the cached-catalog condition on which a bound block counts as changed. --- .../protocol/workflow-source-check.test.ts | 88 +++++++++++++++++++ .../protocol/workflow-source-check.ts | 52 +++++++++-- .../workflow-code/src/diagnostics/refusals.ts | 6 +- 3 files changed, 140 insertions(+), 6 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 ecba07cac65..2da3618bd34 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 @@ -733,6 +733,94 @@ export default workflow('W', {}, () => { } }) + it('fails on a dangling $ref in an unedited file that a bound block now runs instead of its own', async () => { + cacheCatalog() + mkdirSync(join(dir, 'functions'), { recursive: true }) + writeFileSync( + join(dir, 'workflow.ts'), + `// @sim-sdk 1 +import { codeFile, fn, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', {}) + const total = fn('Total', { code: codeFile('./functions/sum.js') }) + const sum = fn('Sum', { code: codeFile('./functions/sum.js') }) + start.to(total) + total.to(sum) +}) +` + ) + const blocks = (codeFiles: Record) => + Object.fromEntries( + ['start', 'total', 'sum'].map((key, order) => [ + key, + { + id: `id-${key}`, + parent: null, + ident: key, + order, + ...(codeFiles[key] ? { codeFile: codeFiles[key] } : {}), + }, + ]) + ) + writeFileSync( + join(dir, '.sim/lock.json'), + JSON.stringify({ + version: 1, + blocks: blocks({ total: 'functions/total.js', sum: 'functions/sum.js' }), + variables: {}, + }) + ) + writeWritten({ + 'functions/total.js': 'return 1\n', + 'functions/sum.js': 'return $ref.ordertotals.sum\n', + }) + writeFileSync(join(dir, 'functions/sum.js'), 'return $ref.ordertotals.sum\n') + + await check() + + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ + code: 'E_APPLY_UNRESOLVED_REF', + severity: 'error', + file: 'functions/sum.js', + }) + ) + }) + + it('keeps a $ref to a block the source no longer declares a warning, as the server may infer its rename', async () => { + cacheCatalog() + mkdirSync(join(dir, 'functions'), { recursive: true }) + writeFileSync( + join(dir, 'workflow.ts'), + `// @sim-sdk 1 +import { codeFile, fn, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', {}) + const bang = fn('Bang', { code: 'return 1' }) + const report = fn('Report', { code: codeFile('./functions/report.js') }) + start.to(bang) + bang.to(report) +}) +` + ) + writeLock(['start', 'boom', 'report']) + writeWritten({ 'functions/report.js': 'return $ref.boom.result\n' }) + writeFileSync(join(dir, 'functions/report.js'), 'return $ref.boom.result + 1\n') + + await check() + + expect(result()).toMatchObject({ errors: 0 }) + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ + code: 'W_UNRESOLVED_REF', + severity: 'warning', + file: 'functions/report.js', + }) + ) + }) + describe('a reference to an output the block lacks', () => { /** Start → Call (an HTTP request) → Done, whose JSON body reads `call.`. */ const reads = (output: string) => 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 4f377d6a416..56442cfbbc1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -139,7 +139,11 @@ on none of them. In every mode, as the server refuses them: ${EDIT_REFUSALS.map( ({ warning, refusal, where }) => `${warning} is the error ${refusal} ${REFUSAL_WHERE[where]}` ).join('; ')}. 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). +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: the +server may infer that block was renamed and rewrite the reference, and refuses it otherwise. ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not bind, and with --strict on every block.` @@ -535,10 +539,48 @@ export async function checkWorkflowDir( const reported = (code: string, blockKey: string | undefined) => !SERVER_ONLY_CODES.has(code) && !(EDIT_SCOPED_CODES.has(code) && options.strict !== 'all' && bound(blockKey)) - const refused = refuseEditedFindings(compiled, { - changed, - codeEdited: (blockKey, file) => edited(file, blockKey), - }) + /** + * Whether the code `blockKey` runs from `file` changed, as the server compares it: the file's + * text, or a bound block now pointed at another file whose text differs from what it ran. + */ + const codeEdited = (blockKey: string, file: string) => { + if (edited(file, blockKey)) return true + const before = lock ? getOwn(lock.blocks, blockKey)?.codeFile : undefined + const text = files[file] + return ( + before !== undefined && + before !== file && + text !== undefined && + written.digests[before] !== digest(text) + ) + } + const removedKeys = new Set( + Object.keys(lock?.blocks ?? {}).filter( + (key) => !compiled.workflow || getOwn(compiled.workflow.blocks, key) === undefined + ) + ) + /** + * A refused `$ref` in a code file naming a block the lock binds that the source no longer + * declares: the server may infer that block's rename (name and const both changed) and then + * rewrite the reference, which only it can tell, so the check keeps the warning. + */ + const mayBeRenamed = (finding: (typeof compiled.diagnostics)[number]) => { + if (finding.code !== 'W_UNRESOLVED_REF' || finding.span.file === SOURCE_ENTRY_FILE) return false + const text = files[finding.span.file]?.slice(finding.span.start, finding.span.end) ?? '' + const head = /^(?:\$ref\.|<)([A-Za-z0-9_]+)/.exec(text)?.[1] + return head !== undefined && removedKeys.has(head) + } + const refusable = (finding: (typeof compiled.diagnostics)[number]) => !mayBeRenamed(finding) + const refused = [ + ...refuseEditedFindings( + { + diagnostics: compiled.diagnostics.filter(refusable), + withheld: compiled.withheld.filter(refusable), + }, + { changed, codeEdited } + ), + ...compiled.diagnostics.filter(mayBeRenamed), + ] const findings = [ ...refused.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)), ...declared, diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 814ceaaafa5..77e432faad9 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -19,7 +19,11 @@ export type EditRefusalCode = export interface EditedBlocks { /** Whether the edit added the block or changed it in any way, a move included. */ changed(blockKey: string): boolean - /** Whether the edit changed the text of the block's function code file `file`. */ + /** + * Whether the edit changed the function code the block runs from code file `file`: the file's + * text, or which file the block runs. A block runs one file, so a caller holding the block's + * code before and after may compare that alone. + */ codeEdited(blockKey: string, file: string): boolean } From 452aa4e13ee485d842f4c7fd60841cacfe51ba4f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:02:55 -0800 Subject: [PATCH 078/104] fix(workflow-code): tie no rename on 0, false or true, and hint at renames in a variable delete Two unrelated items both holding 0, false or true counted as one renamed item, so removing retries: 0 and adding offset: 0 skipped the delete refusal. Those values are no longer evidence. A variable delete refusal that removes one variable and adds one of the same type now says how to keep the id across a rename that also changes the value: apply the new key with the old value first, or pass --allow-delete. --- .../apply-workflow-source.integration.ts | 5 +- .../workflows/application/source-evaluate.ts | 48 +++++++++++++++---- .../src/materialize/index.test.ts | 20 ++++++++ .../workflow-code/src/materialize/rename.ts | 9 +++- 4 files changed, 70 insertions(+), 12 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 1212e2364bf..cf5f4c89756 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2964,7 +2964,10 @@ describe('workflow variables in source', () => { const source = await getSource(seeded.workflowId) const files = withVariables(source.files, "{ retries: { type: 'number', value: 5 } }") - await expectRejected(apply(source, files), 'E_APPLY_VARIABLE_DELETE') + const error = await expectRejected(apply(source, files), 'E_APPLY_VARIABLE_DELETE') + expect(error.diagnostics.find((d) => d.code === 'E_APPLY_VARIABLE_DELETE')?.hint).toMatch( + /If retries renames threshold, .* second apply, .* --allow-delete/ + ) const allowed = await apply(source, files, { allowDelete: true, dryRun: true }) expect(allowed.diff.variables).toMatchObject({ added: ['retries'], diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index c5feefb2a7e..494ea41f12d 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -321,13 +321,36 @@ function listNames(names: readonly string[]): string { return names.length > 10 ? `${shown}, and ${names.length - 10} more` : shown } -/** `E_APPLY_VARIABLE_DELETE` for the stored variables an apply removes, by name. */ -function variableDeleteRefusal(names: readonly string[], span: SourceSpan | undefined): Diagnostic { +/** A variable as a delete refusal names it. */ +interface NamedVariable { + name: string + type: string +} + +/** + * `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. + */ +function variableDeleteRefusal( + removed: readonly NamedVariable[], + added: readonly NamedVariable[], + span: SourceSpan | undefined +): Diagnostic { + const names = removed.map((variable) => variable.name) + const [former] = removed + const [next] = added + const rename = + removed.length === 1 && added.length === 1 && former.type === next.type + ? `If ${next.name} renames ${former.name}, apply the new key with the value ${former.name} holds first and change the value in a second apply, so the variable keeps its id; or pass --allow-delete (allowDelete=true) to replace it.` + : undefined return { code: 'E_APPLY_VARIABLE_DELETE', severity: 'error', message: `This apply deletes ${names.length} variable${names.length === 1 ? '' : 's'} the source no longer declares: ${listNames(names)}.`, - hint: 'Pass --allow-delete (allowDelete=true) to delete them, or declare them again in workflow(name, { variables }) to keep them.', + hint: + rename ?? + 'Pass --allow-delete (allowDelete=true) to delete them, or declare them again in workflow(name, { variables }) to keep them.', ...withSpan(span), } } @@ -838,15 +861,22 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise - keptVariableIds.has(id) - ? [] - : [getOwn(storedCanonical.workflow.variables, key)?.name ?? key] - ) + : Object.entries(storedCanonical.identity.variables).flatMap(([key, id]) => { + if (keptVariableIds.has(id)) return [] + const variable = getOwn(storedCanonical.workflow.variables, key) + return [{ name: variable?.name ?? key, type: variable?.type ?? '' }] + }) if (removedVariables.length > 0 && !input.allowDelete) { - sourceRefusals.push(variableDeleteRefusal(removedVariables, metaSpan())) + const addedVariables = Object.entries(materialized.identity.variables).flatMap(([key, id]) => { + const variable = getOwn(materialized.workflow.variables, key) + return storedVariableIds.has(id) || !variable + ? [] + : [{ name: variable.name, type: variable.type }] + }) + sourceRefusals.push(variableDeleteRefusal(removedVariables, addedVariables, metaSpan())) } const renameWarnings = input.allowDelete ? probableRenames(removedBlocks, addedBlocks).map( diff --git a/packages/workflow-code/src/materialize/index.test.ts b/packages/workflow-code/src/materialize/index.test.ts index 93129215d40..d8c5c43ed33 100644 --- a/packages/workflow-code/src/materialize/index.test.ts +++ b/packages/workflow-code/src/materialize/index.test.ts @@ -952,6 +952,26 @@ describe('materialize: identity', () => { ]) }) + it('ties no variable rename on a value as common as 0, false or true', () => { + for (const [type, value] of [ + ['number', 0], + ['boolean', false], + ['boolean', true], + ] as const) { + const pulled = { + ...base(), + variables: { 'var-1': { id: 'var-1', name: 'Retries', type, value } }, + } + const replaced = edit(canonical(pulled).workflow, (draft) => { + draft.variables = { offset: { key: 'offset', name: 'Offset', type, value } } + }) + + expect(Object.keys(run(replaced, null, { prev: pulled }).state.variables ?? {})).toEqual([ + 'new-1', + ]) + } + }) + it('leaves an inputFormat id two fields share out of the identity items', () => { const prev = workflowState([ blockState('start', 'start_trigger', 'Start', { diff --git a/packages/workflow-code/src/materialize/rename.ts b/packages/workflow-code/src/materialize/rename.ts index ca1b5dcfb1e..2c0382dd9d7 100644 --- a/packages/workflow-code/src/materialize/rename.ts +++ b/packages/workflow-code/src/materialize/rename.ts @@ -17,9 +17,14 @@ export function soleRename( return continues(item, formerKey) ? { item, id } : null } -/** Whether `value` says something about the item that holds it: not absent, empty or blank. */ +/** + * Whether `value` says something about the item that holds it: not absent, empty or blank, and + * not a value as common as `0`, `false` or `true`, which two unrelated items often both hold. + */ function isEvidence(value: unknown): boolean { - if (value === undefined || value === null) return false + if (value === undefined || value === null || typeof value === 'boolean' || value === 0) { + return false + } if (typeof value === 'string') return value.trim() !== '' if (Array.isArray(value)) return value.length > 0 if (typeof value === 'object') return Object.keys(value).length > 0 From 0c6d3d71d5b500618e5cc6244f19294807308037 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:04:28 -0800 Subject: [PATCH 079/104] fix(workflows): run the v2 workflow source get and apply in source slots The workflow source apply route (dry runs included) and its get ran with no per-process concurrency limit, while the plan and the workspace routes each hold a slot. They now run in the apply and read lanes and answer 429 with Retry-After when those are full. --- .../[workflowId]/source/route.test.ts | 37 +++++++++++++++++++ .../v2/workflows/[workflowId]/source/route.ts | 14 ++++--- apps/sim/lib/workflows/api/route-policies.ts | 12 +++++- 3 files changed, 56 insertions(+), 7 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 cc742967047..ea5f235926c 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 @@ -402,6 +402,43 @@ 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 () => { + const finish: Array<() => void> = [] + mocks.apply.mockImplementation( + () => new Promise((resolve) => finish.push(() => resolve({ ...applied, dryRun: true }))) + ) + const dryRun = () => POST(applyRequest(applyBody, '?dryRun=true'), context) + const running = Array.from({ length: 4 }, () => dryRun()) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + const refused = await dryRun() + expect(refused.status).toBe(429) + expect(refused.headers.get('Retry-After')).toBe('5') + + for (const done of finish) done() + expect((await Promise.all(running)).map((response) => response.status)).toEqual([ + 200, 200, 200, 200, + ]) + }) + + it('answers 429 with Retry-After to a get past the gets this server runs at once', async () => { + const finish: Array<() => void> = [] + mocks.read.mockImplementation( + () => new Promise((resolve) => finish.push(() => resolve(source))) + ) + const running = Array.from({ length: 4 }, () => GET(request(), context)) + await vi.waitFor(() => expect(finish).toHaveLength(4)) + + const refused = await GET(request(), context) + expect(refused.status).toBe(429) + expect(refused.headers.get('Retry-After')).toBe('5') + + for (const done of finish) done() + expect((await Promise.all(running)).map((response) => response.status)).toEqual([ + 200, 200, 200, 200, + ]) + }) + it('charges an apply and a create from source to one budget', async () => { await writesUntilLimited(() => POST(applyRequest(applyBody), context)) 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 14a45dafb6e..90e70a43e53 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/source/route.ts @@ -4,7 +4,7 @@ import { v2GetWorkflowSourceContract, } from '@/lib/api/contracts/v2/workflow-source' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { v2WorkflowErrorPolicies, withSourceSlot } from '@/lib/workflows/api' import { applyWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { workflowOperations } from '@/lib/workflows/application/operations' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' @@ -15,7 +15,8 @@ export const revalidate = 0 /** * GET /api/v2/workflows/[workflowId]/source — the draft as TypeScript source with its identity * lock and freshness fingerprint. Unaudited, like `GET .../state`, which it projects. Answers 403 - * while the `workflow-code` flag is off. + * while the `workflow-code` flag is off, and 429 with `Retry-After` while this server already + * runs as many source gets as it allows. * * `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. @@ -26,12 +27,12 @@ export const GET = defineV2JsonRoute({ headSafe: false, operation: workflowOperations.readSource, rateLimit: v2RateLimits.publicApi, - errorPolicy: v2WorkflowErrorPolicies.concealWorkflowAuthorization, + errorPolicy: v2WorkflowErrorPolicies.concealWorkflowSourceRead, mapInput: ({ params, query }) => ({ workflowId: params.workflowId, ...(query.functionCode ? { functionCode: query.functionCode } : {}), }), - useCase: readWorkflowSource, + useCase: withSourceSlot(readWorkflowSource, 'read'), present: (source) => ({ data: source }), }) @@ -41,7 +42,8 @@ export const GET = defineV2JsonRoute({ * 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`. + * 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`. */ export const POST = defineV2JsonRoute({ contract: v2ApplyWorkflowSourceContract, @@ -59,6 +61,6 @@ export const POST = defineV2JsonRoute({ ...(query.dryRun !== undefined ? { dryRun: query.dryRun } : {}), ...(query.allowDelete !== undefined ? { allowDelete: query.allowDelete } : {}), }), - useCase: applyWorkflowSource, + useCase: withSourceSlot(applyWorkflowSource, 'apply'), present: (result) => ({ data: result }), }) diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index 90f207b9237..b813b4b55b0 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -70,6 +70,16 @@ export const v2WorkflowErrorPolicies = { concealWorkflowAuthorization: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workflow not found', }), + /** + * A workflow's source read: concealed as {@link v2WorkflowErrorPolicies.concealWorkflowAuthorization} + * does, and refused for want of a slot with `429` and `Retry-After`. + */ + concealWorkflowSourceRead: createV2ResourceConcealmentPolicy({ + notFoundMessage: 'Workflow not found', + render(error) { + return renderSourceSlotBusy(error) ?? v2CaughtOrchestrationError(error) + }, + }), /** * Conceals cross-tenant reads exactly as * {@link v2WorkflowErrorPolicies.concealWorkflowAuthorization} does, and adds @@ -81,7 +91,7 @@ export const v2WorkflowErrorPolicies = { * source answers `409` with the current fingerprint, and a source rename onto * a name taken meanwhile answers `409` with `SOURCE_NAME_TAKEN`, so a pipeline * can act on each without a second request. A source plan refused for want of a - * slot answers `429` with `Retry-After`. + * slot answers `429` with `Retry-After`, as does a source apply or dry run. */ concealWorkflowGraphAuthorization: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workflow not found', From ad3c83baf9e86f1f2cb2ae9e5788ae60acd48354 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:05:40 -0800 Subject: [PATCH 080/104] fix(workflows): refuse a provenance repo with a fragment or a single-slash user carriesCredentials let https:/token@host through (a URL parser reads it as https://token@host) and never looked at a fragment, so either could reach the audit log. Both are refused now, and the CLI sends no remote the server would refuse rather than failing the apply on it. --- .../[workflowId]/source/route.test.ts | 4 ++++ .../lib/api/contracts/v2/workflow-source.ts | 20 +++++++++++++------ .../commands/protocol/git-provenance.test.ts | 14 +++++++++++++ .../src/commands/protocol/git-provenance.ts | 13 ++++++++++-- 4 files changed, 43 insertions(+), 8 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 ea5f235926c..997e14b4a71 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 @@ -266,6 +266,10 @@ describe('POST /api/v2/workflows/{workflowId}/source', () => { 'https://u:pa/ss@github.com/a/b.git', 'ssh://git:secret@github.com/a/b.git', 'user:secret@github.com:a/b.git', + 'https:/ghp_x@github.com/a/b.git', + 'https:ghp_x@github.com/a/b.git', + 'https://github.com/a/b.git#ghp_x', + 'git@github.com:a/b.git#ghp_x', ] for (const repo of credentialed) { const response = await POST( diff --git a/apps/sim/lib/api/contracts/v2/workflow-source.ts b/apps/sim/lib/api/contracts/v2/workflow-source.ts index 21ce8d8d635..6fdb06a3b03 100644 --- a/apps/sim/lib/api/contracts/v2/workflow-source.ts +++ b/apps/sim/lib/api/contracts/v2/workflow-source.ts @@ -68,21 +68,29 @@ const sourceFilesSchema = z /** * Whether a repository address carries credentials, judged by parsing it rather than matching - * one shape: a URL (`scheme://…`) that does not parse, holds a query, a password, or any user - * on an HTTP(S) transport (`git+https://token@…` included); or an scp-style address - * (`user@host:path`) whose user holds a password. Whitespace and control characters are refused - * outright, so no padding hides the address from the parser. + * one shape: a URL (`scheme://…`) that does not parse, holds a query, a fragment, a password, or + * any user on an HTTP(S) transport (`git+https://token@…` included); or any other address holding + * a query or fragment, a `scheme:` or `scheme:/` form with a user (`https:/token@host`, which a + * URL parser reads as `https://token@host`), or an scp-style address (`user@host:path`) whose + * user holds a password. Whitespace and control characters are refused outright, so no padding + * hides the address from the parser. */ function carriesCredentials(repo: string): boolean { if (/[\s\p{Cc}]/u.test(repo)) return true - if (!repo.includes('://')) return repo.includes('?') || /^[^@/]*:[^@/]*@/.test(repo) + if (!repo.includes('://')) { + return ( + /[?#]/.test(repo) || + /^[a-z][a-z0-9+.-]*:\/*[^/@]*@/i.test(repo) || + /^[^@/]*:[^@/]*@/.test(repo) + ) + } let url: URL try { url = new URL(repo) } catch { return true } - if (url.password !== '' || url.search !== '') return true + if (url.password !== '' || url.search !== '' || url.hash !== '') return true return url.username !== '' && /(^|\+)https?:$/i.test(url.protocol) } diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.test.ts b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts index aa030c88725..edbbb75564f 100644 --- a/packages/sim-cli/src/commands/protocol/git-provenance.test.ts +++ b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts @@ -50,6 +50,20 @@ describe('gitProvenance', () => { expect(await gitProvenance(root)).toEqual({ repo: 'git@github.com:acme/flows.git' }) }) + it('sends no remote the server would refuse as carrying credentials', async () => { + git('init', '-q') + git('remote', 'add', 'origin', 'git@github.com:acme/flows.git') + for (const remote of [ + 'https:/ghp_x@github.com/acme/flows.git', + 'deploy:secret@github.com:acme/flows.git', + 'git@github.com:acme/flows.git#ghp_x', + ]) { + git('remote', 'set-url', 'origin', remote) + + expect(await gitProvenance(root)).toEqual({}) + } + }) + it('sends nothing for a directory outside any repository', async () => { expect(await gitProvenance(root)).toEqual({}) }) diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.ts b/packages/sim-cli/src/commands/protocol/git-provenance.ts index 3f54b0af56b..f02c18a1e80 100644 --- a/packages/sim-cli/src/commands/protocol/git-provenance.ts +++ b/packages/sim-cli/src/commands/protocol/git-provenance.ts @@ -37,11 +37,20 @@ function git(dir: string, args: readonly string[]): Promise { /** * A remote URL with its credentials, query and fragment dropped (`https://token@host/x` → * `https://host/x`); an scp-style address (`git@host:org/repo.git`) carries none and is kept. - * `null` for one too long to record. + * `null` for one too long to record, or another address the server would refuse as carrying + * credentials: a query or fragment, a `scheme:/` form with a user, or a user with a password. */ function sanitizedRepoUrl(remote: string): string | null { let repo = remote - if (/^[a-z][a-z0-9+.-]*:\/\//i.test(remote)) { + if (!remote.includes('://')) { + if ( + /[?#\s]/.test(remote) || + /^[a-z][a-z0-9+.-]*:\/*[^/@]*@/i.test(remote) || + /^[^@/]*:[^@/]*@/.test(remote) + ) { + return null + } + } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(remote)) { try { const url = new URL(remote) url.username = '' From 19aea4d9413d61181b641aecaf9dd6ce9ef93524 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:06:06 -0800 Subject: [PATCH 081/104] docs(cli): regenerate the reference for the source check help --- apps/docs/content/docs/cli/reference.mdx | 4 ++-- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 8154355dadb..5efa2a22a54 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8641,7 +8641,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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: 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. ### sim workflows source status @@ -10019,7 +10019,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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: 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 8473f3cd48b..43d5047df31 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1445,7 +1445,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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: 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. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 98d9c078037..0aa5d685c6b 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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). W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +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_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_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: 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. From 419b73efbcc93520db5b4c0c6b55bed01a75332e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:07:43 -0800 Subject: [PATCH 082/104] fix(workflow-code): hint to inline a value const named like an SDK export A const holding a value whose name is also an SDK export (const table = 'users') got the add-it-to-the-import hint at each reference instead of the write-the-value-here one. --- packages/workflow-code/src/compile/checks.test.ts | 7 +++++++ packages/workflow-code/src/compile/context.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 33af4dea231..8f19bedaf05 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -785,6 +785,13 @@ describe('hints that name the fix', () => { ) }) + it('tells a reference to a non-block const named like an SDK export to inline its value', () => { + const result = run(["const table = 'users'", "const a = api('A', { url: table })"].join('\n')) + expect(findings(result, 'E_UNKNOWN_IDENTIFIER')[0]?.hint).toBe( + 'table is a const that holds a value, which a workflow file cannot name: write the value here.' + ) + }) + it.each([ ['an untagged template', "const a = api('A', { url: `https://${start.host}` })"], ['an unknown identifier', "const a = api('A', { url: process.env.API_URL })"], diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index f65afe14229..7399c46285e 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -311,7 +311,7 @@ export function reportUnresolvedIdentifier( ) return null } - if (isSdkImportable(ctx, identifier.name)) { + if (!ctx.valueConsts.has(identifier.name) && isSdkImportable(ctx, identifier.name)) { // A read of `agent` beside a block named agent1 is a typo of the handle more often than a // missing import: the did-you-mean leads, and the import is the second clause. const near = didYouMean(identifier.name, visibleNames(scope)) From c3dfc98b5abc22180675dc71fdde850fc3b4fde6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:08:13 -0800 Subject: [PATCH 083/104] fix(workflow-code): refuse a path no output has in an edited code file An edited function file reading $ref.block.missing compiled with W_UNKNOWN_OUTPUT_PATH, which the apply refused only in workflow.ts. The code-file rules now refuse it as E_APPLY_UNRESOLVED_REF too, on the server and in the CLI check. --- apps/docs/content/docs/cli/reference.mdx | 4 ++-- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../src/diagnostics/refusals.test.ts | 19 +++++++++++++++++++ .../workflow-code/src/diagnostics/refusals.ts | 4 +++- 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 5efa2a22a54..ba2c83230e8 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8641,7 +8641,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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: 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. +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_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: 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. ### sim workflows source status @@ -10019,7 +10019,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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: 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. +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_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: 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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 43d5047df31..571c17acea3 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1445,7 +1445,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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: 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. +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_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: 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. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 0aa5d685c6b..bd349a1758f 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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_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: 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. +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_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: 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. diff --git a/packages/workflow-code/src/diagnostics/refusals.test.ts b/packages/workflow-code/src/diagnostics/refusals.test.ts index c53fa5ea888..34562ddd5ee 100644 --- a/packages/workflow-code/src/diagnostics/refusals.test.ts +++ b/packages/workflow-code/src/diagnostics/refusals.test.ts @@ -83,6 +83,25 @@ describe('refuseEditedFindings', () => { expect(errors(refuseEditedFindings(compiled, edited('call')))).toEqual([]) }) + it('refuses a path no output has in an edited code file, and only there', () => { + const compiled = compile( + [ + START, + "const call = api('Call', { url: 'https://x' })", + "const next = fn('Next', { code: codeFile('./functions/next.js') })", + 'start.to(call)', + 'call.to(next)', + ], + { 'functions/next.js': 'return $ref.call.dat' } + ) + const changedOnly: EditedBlocks = { changed: (key) => key === 'next', codeEdited: () => false } + + expect(errors(refuseEditedFindings(compiled, edited('next')))).toEqual([ + 'E_APPLY_UNRESOLVED_REF next', + ]) + expect(errors(refuseEditedFindings(compiled, changedOnly))).toEqual([]) + }) + it('refuses an iteration field read outside its container in an unedited code file of a changed block', () => { const compiled = compile( [ diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 77e432faad9..5a7d59f85e7 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -42,10 +42,12 @@ const ENTRY_REFUSALS: ReadonlyMap = new Map([ /** * In a function code file whose text the edit changed: a `$ref` naming no block or variable, or a - * `$ref`/`$env` in a Python or shell file, which runs as text. + * path no output of its block has, or a `$ref`/`$env` in a Python or shell file, which runs as + * text. */ const CODE_FILE_REFUSALS: ReadonlyMap = new Map([ ['W_UNRESOLVED_REF', 'E_APPLY_UNRESOLVED_REF'], + ['W_UNKNOWN_OUTPUT_PATH', 'E_APPLY_UNRESOLVED_REF'], ['W_CODE_FILE_REF_SYNTAX', 'E_APPLY_CODE_FILE_REF_SYNTAX'], ]) From 89770d7b45f5244c5bb3f79482d19e97879b944e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:08:28 -0800 Subject: [PATCH 084/104] fix(sim-cli): send no git remote holding whitespace or a control character A local remote path with a space (/srv/shared repos/flows.git) went out unchanged as provenance.repo, which the server refuses, so the whole apply failed on an optional audit detail. --- .../sim-cli/src/commands/protocol/git-provenance.test.ts | 1 + packages/sim-cli/src/commands/protocol/git-provenance.ts | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.test.ts b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts index edbbb75564f..ba59d48115c 100644 --- a/packages/sim-cli/src/commands/protocol/git-provenance.test.ts +++ b/packages/sim-cli/src/commands/protocol/git-provenance.test.ts @@ -57,6 +57,7 @@ describe('gitProvenance', () => { 'https:/ghp_x@github.com/acme/flows.git', 'deploy:secret@github.com:acme/flows.git', 'git@github.com:acme/flows.git#ghp_x', + '/srv/shared repos/flows.git', ]) { git('remote', 'set-url', 'origin', remote) diff --git a/packages/sim-cli/src/commands/protocol/git-provenance.ts b/packages/sim-cli/src/commands/protocol/git-provenance.ts index f02c18a1e80..1839aaca2b8 100644 --- a/packages/sim-cli/src/commands/protocol/git-provenance.ts +++ b/packages/sim-cli/src/commands/protocol/git-provenance.ts @@ -38,13 +38,14 @@ function git(dir: string, args: readonly string[]): Promise { * A remote URL with its credentials, query and fragment dropped (`https://token@host/x` → * `https://host/x`); an scp-style address (`git@host:org/repo.git`) carries none and is kept. * `null` for one too long to record, or another address the server would refuse as carrying - * credentials: a query or fragment, a `scheme:/` form with a user, or a user with a password. + * credentials: whitespace or a control character (a local path with a space), a query or + * fragment, a `scheme:/` form with a user, or a user with a password. */ function sanitizedRepoUrl(remote: string): string | null { let repo = remote if (!remote.includes('://')) { if ( - /[?#\s]/.test(remote) || + /[?#\s\p{Cc}]/u.test(remote) || /^[a-z][a-z0-9+.-]*:\/*[^/@]*@/i.test(remote) || /^[^@/]*:[^@/]*@/.test(remote) ) { From 6b27abb1da29757dd2896044ca46543b2134d3cb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:09:01 -0800 Subject: [PATCH 085/104] fix(executor): keep the authorization error as the cause of a child read refusal --- apps/sim/executor/handlers/workflow/handler.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index c092ff0799f..ac17f6804e1 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -198,7 +198,8 @@ type WorkflowTraceSpan = TraceSpan & { function childReadError(error: unknown, workflowId: string): unknown { if (!(error instanceof DelegatedWorkspaceAuthorizationError)) return error return new Error( - `Child workflow ${workflowId} is not in this workspace, or this run may no longer read it: a workflow block runs only workflows of its own workspace.` + `Child workflow ${workflowId} is not in this workspace, or this run may no longer read it: a workflow block runs only workflows of its own workspace.`, + { cause: error } ) } From 4832ce0618743b43d943ab1954bc702e74fde356 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:10:20 -0800 Subject: [PATCH 086/104] fix(workflows): count renamed variables in the audit, analytics and plan display A rename-only apply recorded zero variable changes: the audit's variablesChanged, the analytics op count and the workspace plan's variables field summed added, removed and modified, never renamed. A renamed variable whose type or value also changed is now also listed under modified by its new key. --- .../apply-workflow-source.integration.ts | 2 ++ .../application/apply-workflow-source.ts | 6 +++++- .../workflows/application/source-analytics.ts | 1 + .../lib/workflows/application/source-diff.ts | 21 ++++++++++++------- .../application/kinds/workflow/adapter.ts | 5 ++++- 5 files changed, 26 insertions(+), 9 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 cf5f4c89756..9dc2c59a502 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -2955,6 +2955,8 @@ describe('workflow variables in source', () => { .from(workflow) .where(eq(workflow.id, seeded.workflowId)) expect(Object.keys(row.variables as Record)).toEqual([seeded.variableId]) + const [audit] = await settledAuditRows(seeded.workflowId, 1) + expect(audit?.metadata).toMatchObject({ variablesChanged: 1 }) }) check( diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.ts b/apps/sim/lib/workflows/application/apply-workflow-source.ts index 532c489df76..139b3bc146e 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.ts @@ -421,7 +421,11 @@ function sourceAuditMetadata( blocksModified: blocks.modified.length, edgesAdded: edges.added, edgesRemoved: edges.removed, - variablesChanged: variables.added.length + variables.removed.length + variables.modified.length, + variablesChanged: + variables.added.length + + variables.removed.length + + variables.renamed.length + + variables.modified.length, sdkMajor: result.sdkMajor, catalogHash: result.base.catalogHash, ...(input.provenance ? { client: input.provenance.client } : {}), diff --git a/apps/sim/lib/workflows/application/source-analytics.ts b/apps/sim/lib/workflows/application/source-analytics.ts index c7d5b5311cc..42f5de5bd60 100644 --- a/apps/sim/lib/workflows/application/source-analytics.ts +++ b/apps/sim/lib/workflows/application/source-analytics.ts @@ -53,6 +53,7 @@ function changeCount({ blocks, edges, variables }: SourceDiffSummary): number { edges.removed + variables.added.length + variables.removed.length + + variables.renamed.length + variables.modified.length ) } diff --git a/apps/sim/lib/workflows/application/source-diff.ts b/apps/sim/lib/workflows/application/source-diff.ts index bd9bdbcd926..2d97ce8c6c3 100644 --- a/apps/sim/lib/workflows/application/source-diff.ts +++ b/apps/sim/lib/workflows/application/source-diff.ts @@ -4,6 +4,7 @@ import { getOwn, type LockIdentity, } from '@sim/workflow-code' +import { isEqual } from 'es-toolkit' interface SourceBlockRef { id: string @@ -84,36 +85,42 @@ export function summarizeDiff( }), }, edges: { added: diff.edges.added.length, removed: diff.edges.removed.length }, - variables: variableChanges(diff, base.identity, target.identity), + variables: variableChanges(diff, base, target), } } /** * The variable changes, a removed key whose id an added key kept reported as a rename: the apply - * keeps that variable, so it is neither deleted nor needs `allowDelete`. + * keeps that variable, so it is neither deleted nor needs `allowDelete`. A renamed variable whose + * type or value also changed is listed under `modified` too, by its new key. */ function variableChanges( diff: CanonicalDiff, - base: LockIdentity, - target: LockIdentity + base: { workflow: CanonicalWorkflow; identity: LockIdentity }, + target: { workflow: CanonicalWorkflow; identity: LockIdentity } ): SourceDiffSummary['variables'] { const addedById = new Map( diff.variables.added.flatMap((key) => { - const id = getOwn(target.variables, key) + const id = getOwn(target.identity.variables, key) return id === undefined ? [] : [[id, key] as const] }) ) const renamed = diff.variables.removed.flatMap((from) => { - const id = getOwn(base.variables, from) + const id = getOwn(base.identity.variables, from) const to = id === undefined ? undefined : addedById.get(id) return to === undefined ? [] : [{ from, to }] }) const moved = new Set(renamed.flatMap(({ from, to }) => [from, to])) + const rewritten = renamed.flatMap(({ from, to }) => { + const before = getOwn(base.workflow.variables, from) + const after = getOwn(target.workflow.variables, to) + return before?.type === after?.type && isEqual(before?.value, after?.value) ? [] : [to] + }) return { added: diff.variables.added.filter((key) => !moved.has(key)), removed: diff.variables.removed.filter((key) => !moved.has(key)), renamed, - modified: diff.variables.modified, + modified: [...diff.variables.modified, ...rewritten], } } diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index 1f6e25bb30e..59984c8a16e 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -269,7 +269,10 @@ function diffFields(diff: SourceDiffSummary): string[] { for (const block of blocks.modified) fields.push(`${block.key}: ${block.fields.join(', ')}`) if (edges.added + edges.removed > 0) fields.push(`connections +${edges.added} -${edges.removed}`) const changedVariables = - variables.added.length + variables.removed.length + variables.modified.length + variables.added.length + + variables.removed.length + + variables.renamed.length + + variables.modified.length if (changedVariables > 0) fields.push(`variables ${changedVariables}`) return fields } From c0a44fdb1dee96afe321ffc2f6ebf46e397e95a6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:11:43 -0800 Subject: [PATCH 087/104] fix(workflows): count a pending resource id as held only in a field of its kind The foreign-id check skipped any id an enclosing apply creates or adopts, whatever field named it, so a knowledge base being adopted could pass as a table id. Pending ids are now matched by kind. --- .../workflows/application/source-evaluate.ts | 2 +- .../source-resource-scope.integration.ts | 28 +++++++++++++++---- .../application/source-resource-scope.ts | 25 ++++++++++++----- 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/apps/sim/lib/workflows/application/source-evaluate.ts b/apps/sim/lib/workflows/application/source-evaluate.ts index 494ea41f12d..da81eaca216 100644 --- a/apps/sim/lib/workflows/application/source-evaluate.ts +++ b/apps/sim/lib/workflows/application/source-evaluate.ts @@ -971,7 +971,7 @@ export async function evaluateSource(input: SourceEvaluationInput): Promise entry.id)), + pending: input.pendingResources ?? [], keyOf: keyOfId, }) const diagnostics = [ diff --git a/apps/sim/lib/workflows/application/source-resource-scope.integration.ts b/apps/sim/lib/workflows/application/source-resource-scope.integration.ts index ebd7f4c2e30..0f41d417dd4 100644 --- a/apps/sim/lib/workflows/application/source-resource-scope.integration.ts +++ b/apps/sim/lib/workflows/application/source-resource-scope.integration.ts @@ -9,6 +9,7 @@ import { db } from '@sim/db' import { knowledgeBase, user, userTableDefinitions, workflow, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { generateId } from '@sim/utils/id' +import type { ResourceKind } from '@sim/workflow-code' import type { BlockState } from '@sim/workflow-types/workflow' import { eq, inArray } from 'drizzle-orm' import { afterAll, beforeAll, describe, expect, it } from 'vitest' @@ -22,9 +23,13 @@ const otherWorkspace = generateId() /** The block type and the field id that names each kind by id. */ const KINDS = { - table: { blockType: 'table', selector: 'table-selector' }, - workflow: { blockType: 'workflow', selector: 'workflow-selector' }, - 'knowledge base': { blockType: 'knowledge', selector: 'knowledge-base-selector' }, + table: { blockType: 'table', selector: 'table-selector', kind: 'table' }, + workflow: { blockType: 'workflow', selector: 'workflow-selector', kind: 'workflow' }, + 'knowledge base': { + blockType: 'knowledge', + selector: 'knowledge-base-selector', + kind: 'knowledge-base', + }, } as const type Kind = keyof typeof KINDS @@ -89,13 +94,13 @@ function blockNaming(kind: Kind, value: string): BlockState { async function refusedIds( blocks: BlockState[], diff: Pick, - pendingIds: string[] = [] + pending: ReadonlyArray<{ kind: ResourceKind; id: string }> = [] ): Promise { const refusals = await foreignResourceRefusals({ blocks: Object.fromEntries(blocks.map((block) => [block.id, block])), diff: { removed: [], edgesAdded: [], edgesRemoved: [], ...diff }, workspaceId: ownWorkspace, - pendingIds: new Set(pendingIds), + pending, keyOf: () => undefined, }) expect(refusals.every((refusal) => refusal.code === 'E_MAT_UNKNOWN_RESOURCE')).toBe(true) @@ -140,13 +145,24 @@ describe('foreignResourceRefusals', () => { const refused = await refusedIds( blocks, { added: blocks.map((block) => block.id), modified: [] }, - [pending] + [{ kind: KINDS[kind].kind, id: pending }] ) expect(refused.sort()).toEqual([foreign, archived].sort()) } ) + it('counts a pending id as held only in a field of its own kind', async () => { + const adopted = await insertResource('knowledge base', ownWorkspace) + const block = blockNaming('table', adopted) + + expect( + await refusedIds([block], { added: [block.id], modified: [] }, [ + { kind: 'knowledge-base', id: adopted }, + ]) + ).toEqual([adopted]) + }) + it('checks every id of a comma-separated value', async () => { const own = await insertResource('table', ownWorkspace) const foreign = await insertResource('table', otherWorkspace) diff --git a/apps/sim/lib/workflows/application/source-resource-scope.ts b/apps/sim/lib/workflows/application/source-resource-scope.ts index 0b4841517a2..e7faebbb12f 100644 --- a/apps/sim/lib/workflows/application/source-resource-scope.ts +++ b/apps/sim/lib/workflows/application/source-resource-scope.ts @@ -7,7 +7,7 @@ */ import { db } from '@sim/db' import { knowledgeBase, userTableDefinitions, workflow } from '@sim/db/schema' -import type { Diagnostic } from '@sim/workflow-code' +import type { Diagnostic, ResourceKind } from '@sim/workflow-code' import type { BlockState } from '@sim/workflow-types/workflow' import { and, eq, inArray, isNull } from 'drizzle-orm' import type { GraphDiff } from '@/lib/workflows/code/apply/graph-diff' @@ -15,18 +15,25 @@ import { getBlock } from '@/blocks/registry' /** The workspace-owned resources a block names by id, by the picker type that names them. */ const SCOPED_SELECTORS = { - 'table-selector': { noun: 'table', plural: 'tables', example: "table('leads')" }, + 'table-selector': { + kind: 'table', + noun: 'table', + plural: 'tables', + example: "table('leads')", + }, 'workflow-selector': { + kind: 'workflow', noun: 'workflow', plural: 'workflows', example: "childWorkflow('report')", }, 'knowledge-base-selector': { + kind: 'knowledge-base', noun: 'knowledge base', plural: 'knowledge bases', example: "knowledgeBase('docs')", }, -} as const +} as const satisfies Record type ScopedSelector = keyof typeof SCOPED_SELECTORS @@ -127,16 +134,18 @@ async function heldIds( /** * `E_MAT_UNKNOWN_RESOURCE` for each table, workflow or knowledge base id a block this apply adds, * or a field it changes, writes verbatim that is not a live resource of `workspaceId`. An id an - * enclosing apply creates first (`pendingIds`) counts as held; a field the apply leaves alone is - * not checked, so a stored dangling id only refuses the edit that writes it. + * enclosing apply creates or adopts first (`pending`) counts as held in a field of its own kind + * only; a field the apply leaves alone is not checked, so a stored dangling id only refuses the + * edit that writes it. */ export async function foreignResourceRefusals(input: { blocks: Readonly> diff: GraphDiff workspaceId: string - pendingIds: ReadonlySet + pending: ReadonlyArray<{ kind: ResourceKind; id: string }> keyOf: (blockId: string) => string | undefined }): Promise { + const pending = new Set(input.pending.map(({ kind, id }) => `${kind}:${id}`)) const changedFields = new Map | 'all'>([ ...input.diff.added.map((id) => [id, 'all'] as const), ...input.diff.modified.map((change) => [change.id, new Set(change.subBlocks)] as const), @@ -148,7 +157,9 @@ export async function foreignResourceRefusals(input: { for (const [fieldId, field] of scopedFields(block.type)) { if (changed !== 'all' && !changed.has(fieldId)) continue for (const id of idsOf(block.subBlocks?.[fieldId]?.value)) { - if (!input.pendingIds.has(id)) named.push({ ...field, id, blockId }) + if (!pending.has(`${SCOPED_SELECTORS[field.selector].kind}:${id}`)) { + named.push({ ...field, id, blockId }) + } } } } From b0deb75a195d110edd9df183c05a7d1650a4af01 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:12:44 -0800 Subject: [PATCH 088/104] fix(workflow-code): keep the untyped-JSON warning on an undeclared start input W_JSON_REF_UNTYPED was suppressed wherever W_OUTPUT_PATH_UNDECLARED fired, which covers both x.error with no error edge (moot, nothing is read) and an input the start does not declare, which a caller may still pass as text that breaks the JSON. Only the x.error reads are suppressed now. --- .../workflow-code/src/compile/checks.test.ts | 26 +++++++++++++++++++ packages/workflow-code/src/compile/index.ts | 23 ++++++++-------- 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 8f19bedaf05..8529f4e3e72 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -584,6 +584,32 @@ describe('typed references in JSON fields', () => { expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) }) + it('still warns that an input the start does not declare is stored bare, as a caller may pass text', () => { + const result = run( + [ + "const start = trigger.start('Start', { inputFormat: { query: 'string' } })", + "const a = api('A', { url: 'https://x', body: { items: start.list } })", + 'start.to(a)', + ].join('\n') + ) + expect(findings(result, 'W_OUTPUT_PATH_UNDECLARED')).toHaveLength(1) + expect(findings(result, 'W_JSON_REF_UNTYPED')).toHaveLength(1) + }) + + it('reports x.error on a block with no error edge once, not also as untyped', () => { + const result = run( + [ + START, + "const a = api('A', { url: 'https://x' })", + "const b = api('B', { url: 'https://x', body: { failure: a.error } })", + 'start.to(a)', + 'a.to(b)', + ].join('\n') + ) + expect(findings(result, 'W_OUTPUT_PATH_UNDECLARED')).toHaveLength(1) + expect(findings(result, 'W_JSON_REF_UNTYPED')).toEqual([]) + }) + it('tells an untyped reference to stay bare unless it holds text', () => { const result = run( `${START}\nconst a = api('A', { url: 'https://x', body: { items: start.input.list } })` diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 17a3ea7c2c1..cc69dacb806 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -745,18 +745,17 @@ function compileEntry( if (edge.port.kind === 'error') erroring.add(edge.from) } checkErrorOutputRefs(ctx, erroring) - // A reference to an output that does not exist is that one finding: whether text there would - // break the JSON is moot until the path is fixed. - const unknownAt = new Set( - reporter.diagnostics - .filter( - (d) => - d.code === 'W_UNKNOWN_OUTPUT_PATH' || - d.code === 'W_OUTPUT_PATH_UNDECLARED' || - d.code === 'W_UNRESOLVED_REF' - ) - .map((d) => `${d.span.file}:${d.span.start}`) - ) + // A reference to an output that does not exist, or to `x.error` where nothing errors, is that + // one finding: whether text there would break the JSON is moot until the path is fixed. An input + // the start does not declare is not: a caller may still pass text there. + const unknownAt = new Set([ + ...reporter.diagnostics + .filter((d) => d.code === 'W_UNKNOWN_OUTPUT_PATH' || d.code === 'W_UNRESOLVED_REF') + .map((d) => `${d.span.file}:${d.span.start}`), + ...ctx.errorOutputRefs + .filter(({ target }) => !erroring.has(target.key)) + .map(({ at }) => `${at.file}:${at.start}`), + ]) for (const ref of untyped) { if (unknownAt.has(`${ref.range.file}:${ref.range.start}`)) continue reporter.report( From 6b64e6e2ea591ba5e8cb71d807b91a5882b77c1b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:13:45 -0800 Subject: [PATCH 089/104] fix(workflow-code): check a shared code file's iteration reads for every block that runs it A code file read by several blocks was parsed and checked once, for the first block, so a second block outside the loop could run return $ref.each.index without W_REF_OUT_OF_SCOPE, and a source apply (which turns the lint's scope walk off) saved it. Each later reader's iteration-field references are now checked for its own scope. --- packages/workflow-code/src/compile/blocks.ts | 6 +++- packages/workflow-code/src/compile/context.ts | 5 +++ packages/workflow-code/src/compile/index.ts | 2 +- packages/workflow-code/src/compile/values.ts | 32 +++++++++++++++++++ .../src/diagnostics/refusals.test.ts | 21 ++++++++++++ 5 files changed, 64 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 322f5bc4860..cca93f11280 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -387,7 +387,11 @@ function readCodeFile( return null } const cached = budget.reads.get(path) - if (cached !== undefined) return cached === null ? null : { code: cached, path } + if (cached !== undefined) { + if (cached === null) return null + budget.sharedReads.push({ path, blockKey: decl.key }) + return { code: cached, path } + } ctx.reporter.addFile(path, text) if (!checkStorableText(path, text, ctx.reporter, decl.key)) { budget.reads.set(path, null) diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 7399c46285e..fbd8f89b3df 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -126,6 +126,11 @@ interface CodeFileBudget { * once every block is known (`checkCodeFileRefs`). */ chains: Array<{ path: string; blockKey: BlockKey; refs: CodeFileRef[] }> + /** + * A file another block already read, by each later block that reads it too: its references are + * checked for that block's iteration scope only, as every other check depends on the file alone. + */ + sharedReads: Array<{ path: string; blockKey: BlockKey }> } /** The state one compile threads through every pass: inputs, the reporter and what it collected. */ diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index cc69dacb806..8744c7f4a17 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -549,7 +549,7 @@ function compileEntry( catalog: input.catalog, files: input.files, limits, - codeFiles: { reads: new Map(), refs: 0, bytes: utf8Bytes(text), chains: [] }, + codeFiles: { reads: new Map(), refs: 0, bytes: utf8Bytes(text), chains: [], sharedReads: [] }, comments: new CommentCollector(file, reporter), decls: [], declsByKey: new Map(), diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index ebaafb374a1..7ee3df45b0a 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -941,6 +941,7 @@ export function checkCodeFileRefs( ctx: CompileContext, renamed: ReadonlyMap ): void { + checkSharedCodeFileScopes(ctx, renamed) for (const { path, blockKey, refs } of ctx.codeFiles.chains) { for (const ref of refs) { const at: Range = { file: path, start: ref.start, end: ref.end } @@ -1008,6 +1009,37 @@ export function checkCodeFileRefs( } } +/** + * `W_REF_OUT_OF_SCOPE` for an iteration field a shared code file reads, for each block after the + * first that runs it (`sharedReads`): whether the read is in scope depends on where the block + * sits, which {@link checkCodeFileRefs} checked only for the first. + */ +function checkSharedCodeFileScopes( + ctx: CompileContext, + renamed: ReadonlyMap +): void { + const refsByPath = new Map(ctx.codeFiles.chains.map(({ path, refs }) => [path, refs])) + for (const { path, blockKey } of ctx.codeFiles.sharedReads) { + for (const ref of refsByPath.get(path) ?? []) { + if (ref.kind === 'env') continue + const at: Range = { file: path, start: ref.start, end: ref.end } + const [head, property] = ref.segments + if (head?.kind !== 'name' || property?.kind !== 'name') continue + if (isReservedWorkflowBlockName(head.name)) { + checkIterationTag(ctx, at, blockKey, ref.segments) + continue + } + const renamedTo = renamed.get(head.name) + const target = + ctx.declsByKey.get(head.name) ?? + (renamedTo === undefined ? undefined : ctx.declsByKey.get(renamedTo)) + if (target && containerKindOf(target)) { + checkIterationScope(ctx, at, blockKey, target, property.name) + } + } + } +} + /** * The hint for a code file reference whose head is the key of a block the workflow had (the lock * or the stored workflow binds it) and source no longer declares: most often a block renamed in diff --git a/packages/workflow-code/src/diagnostics/refusals.test.ts b/packages/workflow-code/src/diagnostics/refusals.test.ts index 34562ddd5ee..5e1dabd5007 100644 --- a/packages/workflow-code/src/diagnostics/refusals.test.ts +++ b/packages/workflow-code/src/diagnostics/refusals.test.ts @@ -83,6 +83,27 @@ describe('refuseEditedFindings', () => { expect(errors(refuseEditedFindings(compiled, edited('call')))).toEqual([]) }) + it('refuses an iteration field a shared code file reads for a block outside the loop', () => { + const compiled = compile( + [ + START, + "const lp = loop.forEach('Each', { collection: '[1]' }, (body) => {", + " const inner = fn('Inner', { code: codeFile('./functions/index.js') })", + ' body.to(inner)', + '})', + "const after = fn('After', { code: codeFile('./functions/index.js') })", + 'start.to(lp)', + 'lp.to(after)', + ], + { 'functions/index.js': 'return $ref.each.index' } + ) + + expect(errors(refuseEditedFindings(compiled, edited('after')))).toEqual([ + 'E_APPLY_REF_OUT_OF_SCOPE after', + ]) + expect(errors(refuseEditedFindings(compiled, edited('inner')))).toEqual([]) + }) + it('refuses a path no output has in an edited code file, and only there', () => { const compiled = compile( [ From 5a2cb237e8e26c0d5f39a7fed9be833953af6349 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:14:56 -0800 Subject: [PATCH 090/104] fix(workflow-code): check {{NAME}} env tokens in code files A Python or shell file (or a JavaScript string) writes an env variable as {{NAME}}, which the run substitutes, but the code-file scan kept only tags, so a misspelled name compiled without W_ENV_UNKNOWN. Tokens holding an env-variable name are now checked like $env.NAME. --- packages/workflow-code/src/compile/blocks.ts | 10 +++++++++ .../workflow-code/src/compile/grammar.test.ts | 21 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index cca93f11280..1d43d1f8a17 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -511,6 +511,9 @@ function reportScriptRefSyntax( } } +/** The name inside a `{{NAME}}` env token a run substitutes; other `{{…}}` text is left alone. */ +const ENV_TOKEN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ + /** * The `` references a code file writes as text, found by the runtime's own scanner (a * JavaScript string, a Python or shell line): the run resolves each one, so compile checks them as @@ -519,6 +522,13 @@ function reportScriptRefSyntax( function referenceTags(text: string): CodeFileRef[] { const tags: CodeFileRef[] = [] for (const token of findWorkflowReferenceTokens(text)) { + if (token.kind === 'environment') { + const name = token.value.slice(2, -2).trim() + if (ENV_TOKEN_NAME.test(name)) { + tags.push({ kind: 'env', name, start: token.start, end: token.end }) + } + continue + } if (token.kind !== 'workflow') continue const segments = parseStoredPath(token.value.slice(1, -1)) if (!segments || segments.length < 2) continue diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index d2e433b3e94..19c4408587d 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1515,6 +1515,27 @@ describe('env names the workspace does not hold', () => { }), ]) }) + it('warns on a {{NAME}} env token in a Python code file at the file location', () => { + const result = compileWorkflow({ + entry: { + path: ENTRY, + text: source( + "const f = fn('F', { language: 'python', code: codeFile('./functions/f.py') })" + ), + }, + files: new Map([['workflows/functions/f.py', 'url = "{{API_URL}}" + "{{MISSING_KEY}}"']]), + catalog: TEST_CATALOG, + sdkMajor: 1, + envNames: new Set(['API_URL']), + }) + const unknown = result.diagnostics.filter((d) => d.code === 'W_ENV_UNKNOWN') + expect(unknown).toEqual([ + expect.objectContaining({ + message: expect.stringContaining('MISSING_KEY'), + span: expect.objectContaining({ file: 'workflows/functions/f.py', line: 1, column: 24 }), + }), + ]) + }) }) describe('numbers JSON cannot carry as written', () => { From 622a930f1a9cc4965bb2d5f3a06db86390f9c3f5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:15:26 -0800 Subject: [PATCH 091/104] docs(rules): name the source operations and isWorkflowCodeEnabled in the flag section --- .claude/rules/sim-workflow-code.md | 11 +++++++---- .cursor/rules/sim-workflow-code.mdc | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index 91aeb6975ad..d513811c96a 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -73,10 +73,13 @@ and "The catalog". One global flag, `workflow-code` (`lib/core/config/feature-flags.ts`, env fallback `WORKFLOW_CODE`), gates workflow source, workspace source, the source catalog and resources, and -the Code tab. Every operation declares `feature: WORKFLOW_CODE_FEATURE` -(`lib/workflows/application/operations.ts`), which the shared use-case wrapper checks after -authorization (`FEATURE_NOT_ENABLED`); the UI reads it from the workspace layout's flags. A new -operation declares the same feature, never its own check. +the Code tab. Every source operation (the workflow source ones in +`lib/workflows/application/operations.ts` and the workspace source ones in +`lib/workspace-source/application/operations.ts`) declares `feature: WORKFLOW_CODE_FEATURE`, which +the shared use-case wrapper checks after authorization (`FEATURE_NOT_ENABLED`); a new source +operation declares the same feature, never its own check. A surface outside an operation (the Code +tab, Copilot entitlements) calls `isWorkflowCodeEnabled()` (`lib/workflows/code/feature-flag.ts`); +the UI reads it from the workspace layout's flags. ## Adding things diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index fdd56c3e701..02c9437d166 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -63,10 +63,13 @@ and "The catalog". One global flag, `workflow-code` (`lib/core/config/feature-flags.ts`, env fallback `WORKFLOW_CODE`), gates workflow source, workspace source, the source catalog and resources, and -the Code tab. Every operation declares `feature: WORKFLOW_CODE_FEATURE` -(`lib/workflows/application/operations.ts`), which the shared use-case wrapper checks after -authorization (`FEATURE_NOT_ENABLED`); the UI reads it from the workspace layout's flags. A new -operation declares the same feature, never its own check. +the Code tab. Every source operation (the workflow source ones in +`lib/workflows/application/operations.ts` and the workspace source ones in +`lib/workspace-source/application/operations.ts`) declares `feature: WORKFLOW_CODE_FEATURE`, which +the shared use-case wrapper checks after authorization (`FEATURE_NOT_ENABLED`); a new source +operation declares the same feature, never its own check. A surface outside an operation (the Code +tab, Copilot entitlements) calls `isWorkflowCodeEnabled()` (`lib/workflows/code/feature-flag.ts`); +the UI reads it from the workspace layout's flags. ## Adding things From 784e6b450c1648ccc8bfeb4921ef3e64ca768d5f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:15:56 -0800 Subject: [PATCH 092/104] fix(workflow-code): give the credential create hint the flags the command requires --- packages/workflow-code/src/materialize/index.test.ts | 3 +++ packages/workflow-code/src/materialize/values.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/materialize/index.test.ts b/packages/workflow-code/src/materialize/index.test.ts index d8c5c43ed33..7828aa36e89 100644 --- a/packages/workflow-code/src/materialize/index.test.ts +++ b/packages/workflow-code/src/materialize/index.test.ts @@ -263,6 +263,9 @@ describe('materialize: params keep prev bytes unless they changed', () => { resources: { ...RESOURCES, keysOf }, }).diagnostics.filter((d) => d.code === 'E_MAT_UNKNOWN_RESOURCE') expect(finding?.hint).toContain('sim credentials connect --name ""') + expect(finding?.hint).toContain( + 'sim credentials create --name "" --credentials @' + ) }) it('recomputes stored outputs when an edit changes what they derive from', () => { diff --git a/packages/workflow-code/src/materialize/values.ts b/packages/workflow-code/src/materialize/values.ts index 6376ef50e7a..26f840f7833 100644 --- a/packages/workflow-code/src/materialize/values.ts +++ b/packages/workflow-code/src/materialize/values.ts @@ -55,7 +55,7 @@ const LISTED_KEYS = 20 */ const CREATE_COMMANDS: Partial> = { credential: - '`sim credentials connect --name ""` (OAuth; hand the link to the person who owns the account) or `sim credentials create `', + '`sim credentials connect --name ""` (OAuth; hand the link to the person who owns the account) or `sim credentials create --name "" --credentials @` (a service account)', table: '`sim tables create`', 'knowledge-base': '`sim knowledge create`', skill: '`sim skills create`', From f11dfd2021ae9673d0f2483b79dd8bf84e76e009 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:16:44 -0800 Subject: [PATCH 093/104] fix(workflow-code): compute a withheld warning's hint only when it is read withhold() built each refusable warning past the cap with its hint resolved, so the lazy did-you-mean ran for every withheld warning although few are ever listed. The hint is now a getter computed on first read, and the refusal raises only the withheld findings it lists, so it reads at most the error budget's worth. --- .../workflow-code/src/compile/hostile.test.ts | 24 +++++++++++++++++++ packages/workflow-code/src/compile/report.ts | 21 ++++++++++++++-- .../workflow-code/src/diagnostics/refusals.ts | 9 +++---- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 6a761e4f8e4..12ba5f9ab6d 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -256,6 +256,30 @@ describe('hostile sources produce diagnostics only', () => { expect(reporter.diagnostics[0]?.hint).toBe('Did you mean y?') }) + it('never computes the did-you-mean of a refusable warning it withholds until it is read', () => { + const reporter = new Reporter() + reporter.addFile('w.ts', 'x') + let computed = 0 + for (let i = 0; i < 1_000; i++) { + reporter.report( + 'W_UNRESOLVED_REF', + `x${i}`, + { file: 'w.ts', start: 0, end: 1 }, + { + blockKey: `b${i}`, + hint: () => { + computed++ + return 'Did you mean y?' + }, + } + ) + } + expect(reporter.withheld).toHaveLength(1_000 - MAX_WARNINGS_PER_CODE) + expect(computed).toBe(MAX_WARNINGS_PER_CODE) + expect({ ...reporter.withheld[0] }.hint).toBe('Did you mean y?') + expect(computed).toBe(MAX_WARNINGS_PER_CODE + 1) + }) + it('keeps infos from crowding out a warning', () => { const reporter = new Reporter() reporter.addFile('w.ts', 'x') diff --git a/packages/workflow-code/src/compile/report.ts b/packages/workflow-code/src/compile/report.ts index 2c588ec96df..ea645adf345 100644 --- a/packages/workflow-code/src/compile/report.ts +++ b/packages/workflow-code/src/compile/report.ts @@ -54,7 +54,8 @@ export interface Range { interface ReportExtras { /** * A function is called only when the diagnostic is recorded, so a costly did-you-mean is never - * computed for a warning past {@link MAX_WARNINGS}. + * computed for a warning past {@link MAX_WARNINGS}; a withheld warning computes it when its + * `hint` is first read. */ hint?: string | (() => string | undefined) blockKey?: BlockKey @@ -219,7 +220,23 @@ export class Reporter { const held = refusableKey(code, at, extras) if (held === undefined || this.refusableHeld.has(held)) return this.refusableHeld.add(held) - this.withheld.push(this.build(code, message, at, extras, framesSource(code))) + const { hint, ...listed } = extras + const diagnostic = this.build(code, message, at, listed, framesSource(code)) + if (hint !== undefined) { + let resolved: { hint: string | undefined } | undefined + Object.defineProperty(diagnostic, 'hint', { + enumerable: true, + configurable: true, + get: () => { + if (!resolved) { + const text = typeof hint === 'function' ? hint() : hint + resolved = { hint: text === undefined ? undefined : capLength(text) } + } + return resolved.hint + }, + }) + } + this.withheld.push(diagnostic) } /** Records one diagnostic; `framed` is false when the finding at `at` is about a literal secret. */ diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 5a7d59f85e7..45de916b849 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -136,22 +136,23 @@ export function refuseEditedFindings( const listed: Array = compiled.diagnostics.map( (finding) => refused(finding) ?? finding ) - const extra = compiled.withheld.flatMap((finding) => refused(finding) ?? []) + const extra = compiled.withheld.filter((finding) => refusalOf(finding, edit) !== undefined) const budget = Math.max( 0, MAX_ERRORS - listed.filter((finding) => finding.severity === 'error').length ) - if (extra.length <= budget) return [...listed, ...extra] + const raised = extra.slice(0, budget).flatMap((finding) => refused(finding) ?? []) + if (extra.length <= budget) return [...listed, ...raised] const [first] = extra.slice(budget) const omitted = extra.length - budget const summary: LocatedDiagnostic<'E_TOO_MANY_ERRORS'> = { code: 'E_TOO_MANY_ERRORS', severity: 'error', - message: `${omitted} more edited ${omitted === 1 ? 'finding is' : 'findings are'} refused, as the ones listed are. The next: ${first.message}`, + message: `${omitted} more edited ${omitted === 1 ? 'finding is' : 'findings are'} refused, as the ones listed are. The next: ${raisedMessage(first.message)}`, hint: 'Fix the errors listed and check again to see the rest.', span: first.span, ...(first.frame === undefined ? {} : { frame: first.frame }), ...(first.blockKey === undefined ? {} : { blockKey: first.blockKey }), } - return [...listed, ...extra.slice(0, budget), summary] + return [...listed, ...raised, summary] } From 1fdacb8dc563586378a9f041c94f7ba6ac9aed88 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:17:24 -0800 Subject: [PATCH 094/104] fix(sim-cli): clear the paging progress line before a 429 retry notice on a terminal --- packages/sim-cli/src/http/client.test.ts | 25 ++++++++++++++++++++++++ packages/sim-cli/src/http/client.ts | 3 ++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/sim-cli/src/http/client.test.ts b/packages/sim-cli/src/http/client.test.ts index ee04ffdb25c..8d563a9d067 100644 --- a/packages/sim-cli/src/http/client.test.ts +++ b/packages/sim-cli/src/http/client.test.ts @@ -495,6 +495,31 @@ describe('rate limiting', () => { expect(written.join('')).toMatch(/Rate limited \(HTTP 429\); retrying in 7s \(retry 1 of 6\)/) }) + it('clears a terminal progress line before saying it waits on a 429', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const written: string[] = [] + const tty = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY') + Object.defineProperty(process.stderr, 'isTTY', { value: true, configurable: true }) + const write = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + written.push(String(chunk)) + return true + }) + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValueOnce(limited('7')) + .mockResolvedValueOnce(Response.json({ data: {} })) + ) + + await settle(client().request('/api/v2/tables/tbl_1')) + write.mockRestore() + if (tty) Object.defineProperty(process.stderr, 'isTTY', tty) + else Reflect.deleteProperty(process.stderr, 'isTTY') + + expect(written.join('')).toMatch(/^\r\u001b\[K.*Rate limited \(HTTP 429\)/) + }) + it('resends a GET answered 429 even when that response body is lost', async () => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) const lostBody = new Response( diff --git a/packages/sim-cli/src/http/client.ts b/packages/sim-cli/src/http/client.ts index 1e50672c1c2..6b0a597bc1e 100644 --- a/packages/sim-cli/src/http/client.ts +++ b/packages/sim-cli/src/http/client.ts @@ -797,8 +797,9 @@ export class SimClient { ) const backoffMs = backoffWithJitter(rateLimitResends + 1, null, RATE_LIMIT_BACKOFF) const waitMs = Math.max(retryAfterMs ?? 0, backoffMs) + // On a terminal, clear a `fetched N…` paging line first, so the notice starts its own line. writeStderr( - `${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` + `${hasProgressTerminal() ? '\r\u001b[K' : ''}${styles().dim(`Rate limited (HTTP 429); retrying in ${Math.ceil(waitMs / 1000)}s (retry ${rateLimitResends + 1} of ${RATE_LIMIT_RETRIES}).`)}\n` ) await interruptibleSleep(waitMs, caller) if (caller?.aborted) throw new SimApiError('Request cancelled.', 0, REQUEST_CANCELLED) From 86f32e62034f9eb3180c21d2b84192a41b7f10be Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:18:15 -0800 Subject: [PATCH 095/104] fix(sim-cli): refuse a workspace directory by its kind before an apply reads a lock A workflow apply in a workspace source directory failed on the missing .sim/lock.json and told the user to run a get, which would replace the workspace base, instead of the directory-kind refusal that names the workspace commands. --- .../protocol/workflow-source-apply.test.ts | 14 ++++++++++++++ .../src/commands/protocol/workflow-source-apply.ts | 1 + 2 files changed, 15 insertions(+) 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 a9a2aa94613..2a287718dce 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 @@ -288,6 +288,20 @@ describe('sim workflows source apply', () => { expect(request).not.toHaveBeenCalled() }) + it('refuses a workspace source directory by its kind before reading a lock', async () => { + setTerminal(false) + rmSync(join(dir, '.sim/lock.json')) + writeFileSync( + join(dir, '.sim/base.json'), + JSON.stringify({ version: 1, workspaceId: WORKSPACE_ID, resources: {} }) + ) + + await expect(apply('--dir', dir, '--yes')).rejects.toMatchObject({ + code: 'SOURCE_DIR_KIND_MISMATCH', + }) + expect(request).not.toHaveBeenCalled() + }) + it('points tsconfig.json at a block the applied source added, from the cached catalog', async () => { setTerminal(false) vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) 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 d50d78befbc..2e68fbf376e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -496,6 +496,7 @@ export function attachWorkflowSourceApply(source: Command): void { .action(async (named: string | undefined, options: SourceWriteOptions) => withWorkspaceFolderLock(options.dir, async () => { assertDeployable(options) + await assertSourceDirKind(options.dir, 'workflow') const { client, profile } = connectApply() const lock = await readLock(options.dir) const base = await readBase(options.dir, named) From 54fcfc0536c3cf1d5f03806f66f68cf8ce752ef2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:18:50 -0800 Subject: [PATCH 096/104] fix(workflow-code): write a well-formed placeholder in the renamed-block tag hint For a tag in a code file the fallback hint read <>, a tag users might copy. It now writes (or $ref.newkey) and says what newkey is. --- .../workflow-code/src/compile/grammar.test.ts | 31 +++++++++++++++++++ packages/workflow-code/src/compile/values.ts | 3 +- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/grammar.test.ts b/packages/workflow-code/src/compile/grammar.test.ts index 19c4408587d..fcc21519559 100644 --- a/packages/workflow-code/src/compile/grammar.test.ts +++ b/packages/workflow-code/src/compile/grammar.test.ts @@ -1163,6 +1163,37 @@ describe('errors, each with its code, location and hint', () => { ) }) + it('writes the placeholder of a renamed block once in a tag, for a tag the file writes', () => { + const text = source( + [ + START, + "const a = api('Fetch Page', { url: 'x' })", + "const b = api('Load Page', { url: 'x' })", + "const f = fn('F', { code: codeFile('./functions/f.js') })", + ].join('\n') + ) + const storedUnread = { + version: 1 as const, + blocks: { + start: { id: 'b-start', parent: null, ident: 'start', order: 0 }, + lookup: { id: 'b-lookup', parent: null, ident: 'lookup', order: 1 }, + f: { id: 'b-f', parent: null, ident: 'f', order: 2 }, + }, + variables: {}, + } + const result = compileWorkflow({ + entry: { path: ENTRY, text }, + files: new Map([['workflows/functions/f.js', "return ''"]]), + catalog: TEST_CATALOG, + sdkMajor: 1, + knownKeys: new Set(Object.keys(storedUnread.blocks)), + storedUnread, + }) + + const finding = result.diagnostics.find((d) => d.code === 'W_UNRESOLVED_REF') + expect(finding?.hint).toContain('if you renamed it, write , where newkey is') + }) + it('reports a syntax error inside a code file at its own location', () => { const result = run(source("const f = fn('F', { code: codeFile('./functions/bad.js') })"), { 'workflows/functions/bad.js': 'return (', diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 7ee3df45b0a..bda93e592c5 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -1061,10 +1061,9 @@ function formerBlockHint( ) const lead = `${spell([{ kind: 'name', name: formerKey }])} is a block this workflow had that ${SOURCE_ENTRY_FILE} no longer declares under that key` const [only] = unbound - const placeholder = spell([{ kind: 'name', name: 'NEWKEY' }]).replace('NEWKEY', '') return unbound.length === 1 && only ? `${lead}: if ${only.name} is it renamed, write ${rewritten(only.key)}.` - : `${lead}: if you renamed it, write ${placeholder}, the display name lowercased with whitespace and dots removed.` + : `${lead}: if you renamed it, write ${spell([{ kind: 'name', name: 'newkey' }])}, where newkey is its display name lowercased with whitespace and dots removed.` } function subflowScopeRef( From 8113283b8632bebc62a5da9870377cf76fd8cc87 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:19:57 -0800 Subject: [PATCH 097/104] fix(sim-cli): name only the deletes a part-way promotion wrote as target-only deletes A promotion that stopped part-way warned of every planned delete of a resource only the target holds, including the ones it never reached, so the result claimed deletes that did not happen. Once an apply has failed, only the deletes it wrote are named. --- .../protocol/workspace-source-apply.test.ts | 42 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 15 ++++--- 2 files changed, 52 insertions(+), 5 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 b5bd4fa7fb0..cd685259b45 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 @@ -553,6 +553,48 @@ describe('workspaces source apply', () => { expect(stderr).not.toContain('resource(s) that only workspace ws_prod holds') }) + it('names only the target-only deletes a promotion that stopped part-way wrote', async () => { + const target = { + version: 1, + workspaceId: 'ws_prod', + resources: { 'table:one': { id: 'tbl_one' }, 'table:two': { id: 'tbl_two' } }, + } + request.mockImplementation(async (path: string, options: { body?: unknown }) => { + if (path === '/api/v2/workspaces/ws_prod/source' && options.body === undefined) { + return { + data: { + workspaceId: 'ws_prod', + kinds: ['table'], + files: { 'tables/one.ts': LEADS, 'tables/two.ts': LEADS }, + blobs: [], + base: target, + skipped: [], + diagnostics: [], + }, + } + } + return answer({ + workspaceId: 'ws_prod', + base: target, + plan: [ + { kind: 'table', key: 'one', action: 'delete' }, + { kind: 'table', key: 'two', action: 'delete' }, + ], + applied: [{ kind: 'table', key: 'one', action: 'delete' }], + failed: { kind: 'table', key: 'two', code: 'E_APPLY_FAILED', message: 'failed' }, + }) + }) + + await apply('--to', 'ws_prod', '--only', 'tables', '--allow-delete', '--yes') + + const summary = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0])) + expect( + summary.diagnostics + .filter((finding: { code: string }) => finding.code === 'W_PROMOTE_DELETES_TARGET_ONLY') + .map((finding: { key: string }) => finding.key) + ).toEqual(['one']) + }) + it('refuses --to naming the workspace the directory was read from', async () => { await expect(apply('--to', 'ws_local', '--yes')).rejects.toThrow(/apply it without --to/) expect(request).not.toHaveBeenCalled() 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 a259d59429d..20aa7b7e2de 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -564,9 +564,12 @@ function promotionDiagnostics(diagnostics: readonly Finding[], promotion: Promot /** * The warnings only a promotion knows to give: each declared resource the target deleted since the * last promotion (kept deleted), and each resource only the target holds that `--allow-delete` - * deletes there. + * deletes there (of an apply that stopped part-way, each it deleted). */ -function promotionWarnings(promotion: Promotion, plan: readonly Change[]): Finding[] { +function promotionWarnings( + promotion: Promotion, + outcome: Pick +): Finding[] { const { target } = promotion const deleted = promotion.deletedInTarget.flatMap((address): Finding[] => { const parsed = parseResourceAddress(address) @@ -582,8 +585,10 @@ function promotionWarnings(promotion: Promotion, plan: readonly Change[]): Findi }, ] }) - const targetOnly = plan - .filter((change) => change.action === 'delete') + const targetOnly = outcome.plan + .filter( + (change) => change.action === 'delete' && (!outcome.failed || wasWritten(change, outcome)) + ) .map( (change): Finding => ({ code: 'W_PROMOTE_DELETES_TARGET_ONLY', @@ -760,7 +765,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ? { ...data, diagnostics: [ - ...promotionWarnings(promotion, data.plan), + ...promotionWarnings(promotion, data), ...promotionDiagnostics(data.diagnostics, promotion), ], } From 3107738b1f3b0260550767c42460435ca16d61bb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:21:11 -0800 Subject: [PATCH 098/104] fix(workflows): type the scoped selector table with every field it holds --- apps/sim/lib/workflows/application/source-resource-scope.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/application/source-resource-scope.ts b/apps/sim/lib/workflows/application/source-resource-scope.ts index e7faebbb12f..1ecaa8a6889 100644 --- a/apps/sim/lib/workflows/application/source-resource-scope.ts +++ b/apps/sim/lib/workflows/application/source-resource-scope.ts @@ -33,7 +33,10 @@ const SCOPED_SELECTORS = { plural: 'knowledge bases', example: "knowledgeBase('docs')", }, -} as const satisfies Record +} as const satisfies Record< + string, + { kind: ResourceKind; noun: string; plural: string; example: string } +> type ScopedSelector = keyof typeof SCOPED_SELECTORS From 31a17e7946ba6b542fcb1313306fc6367c41fcac Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:30:02 -0800 Subject: [PATCH 099/104] fix(workflow-code): list a diff's removed blocks by key diffCanonical listed removed blocks in the base's block order, which is the order the stored rows load in, so the delete refusal and the diff summary named them in an order that said nothing and changed with the rows' ids. They are now sorted by key. --- packages/workflow-code/src/diff/index.test.ts | 11 +++++++++++ packages/workflow-code/src/diff/index.ts | 6 +++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/diff/index.test.ts b/packages/workflow-code/src/diff/index.test.ts index 838e1c6e5b4..8d96c6362dd 100644 --- a/packages/workflow-code/src/diff/index.test.ts +++ b/packages/workflow-code/src/diff/index.test.ts @@ -92,6 +92,17 @@ describe('diffCanonical', () => { ]) }) + it('lists removed blocks by key, whatever order the stored blocks loaded in', () => { + const reordered = draftOf(base.workflow) + reordered.blocks = Object.fromEntries(Object.entries(reordered.blocks).reverse()) + const target = edit((draft) => { + draft.blocks = omit(draft.blocks, ['fetch', 'report']) + draft.edges = [] + }) + + expect(diffCanonical(reordered, target).blocks.removed).toEqual(['fetch', 'report']) + }) + it('reports added and removed blocks, edges and variables', () => { const target = edit((draft) => { draft.blocks = omit(draft.blocks, ['report']) diff --git a/packages/workflow-code/src/diff/index.ts b/packages/workflow-code/src/diff/index.ts index 4e968fd2edf..49d31d818a5 100644 --- a/packages/workflow-code/src/diff/index.ts +++ b/packages/workflow-code/src/diff/index.ts @@ -3,6 +3,7 @@ * Like every CWM comparison it ignores `annotations`, key order and edge order. */ +import { compareStrings } from '@sim/utils/string' import { edgeTupleKey, portKey } from '../anchors' import type { LockIdentity } from '../lock' import type { @@ -150,7 +151,10 @@ export function diffCanonical( const baseKeyOf = (targetKey: BlockKey) => pairs.get(targetKey) ?? `${UNPAIRED}${targetKey}` const added = Object.keys(target.blocks).filter((key) => !pairs.has(key)) - const removed = Object.keys(base.blocks).filter((key) => !claimedBase.has(key)) + // By key: the base's block order is the order its rows loaded in, which says nothing. + const removed = Object.keys(base.blocks) + .filter((key) => !claimedBase.has(key)) + .sort(compareStrings) const renamed: CanonicalDiff['blocks']['renamed'] = [] const modified: CanonicalBlockDiff[] = [] for (const [targetKey, baseKey] of pairs) { From fa3269f46fac5c9461d989b41fb80f4e20d2b3b2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 02:38:29 -0800 Subject: [PATCH 100/104] test(workflows): expect a delete refusal to name removed blocks by key --- .../workflows/application/apply-workflow-source.integration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9dc2c59a502..e9106767534 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -1797,7 +1797,7 @@ export default workflow('', {}, () => { const error = await expectRejected(apply(source, emptied), 'E_APPLY_BLOCK_DELETE') expect(error.diagnostics.find((d) => d.code === 'E_APPLY_BLOCK_DELETE')).toMatchObject({ - message: 'This apply deletes 2 blocks the source no longer declares: Start, Score.', + message: 'This apply deletes 2 blocks the source no longer declares: Score, Start.', file: 'workflow.ts', ...positionOf(emptied['workflow.ts'], "'Source apply edge"), }) From 0cbcab361c6720d8aa2bdd60231b0e69b36fd78a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 03:26:21 -0800 Subject: [PATCH 101/104] fix(workflow-persistence): keep edges in the order the state lists them Ordering edges by created_at then id put edges saved together (one timestamp) in id order, and the executor assigns a handle-less condition or router edge its branch by position, so a reload could switch branches. A save now rewrites a workflow's edges whole, in the state's order and a microsecond apart, whenever any edge or their order changes, and the loader orders edges by created_at then ctid, so rows an older save wrote with one timestamp keep their insertion order. --- .../normalized-save.integration.ts | 39 +++++++++++++++ packages/workflow-persistence/src/load.ts | 17 +++++-- packages/workflow-persistence/src/save.ts | 48 +++++++++++++------ 3 files changed, 85 insertions(+), 19 deletions(-) diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts index 9bb3927d9d2..367c8d2ecea 100644 --- a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -329,6 +329,45 @@ describe('saveWorkflowToNormalizedTables', () => { expect(loaded?.edges.map((edge) => edge.id)).toEqual([edges[0].id, edges[1].id, added.id]) }) + it('loads edges saved together in the order the state listed them, not by id', async () => { + const workflowId = await insertWorkflow() + const blocks = ['b1', 'b2', 'b3'].map((id, index) => + functionBlock(`${workflowId}-${id}`, `Block ${index}`, index * 100) + ) + const [first, second, third] = blocks.map((block) => block.id) + const edges = [ + { id: `${workflowId}-z`, source: first, target: second }, + { id: `${workflowId}-a`, source: first, target: third }, + ] + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, edges))).toEqual({ + success: true, + }) + + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(loaded?.edges.map((edge) => edge.id)).toEqual(edges.map((edge) => edge.id)) + }) + + it('loads edges an older save wrote with one timestamp in the order they were inserted', async () => { + const workflowId = await insertWorkflow() + const blocks = ['b1', 'b2', 'b3'].map((id, index) => + functionBlock(`${workflowId}-${id}`, `Block ${index}`, index * 100) + ) + const [first, second, third] = blocks.map((block) => block.id) + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, []))).toEqual({ + success: true, + }) + const createdAt = new Date() + await db.insert(workflowEdges).values([ + { id: `${workflowId}-z`, workflowId, sourceBlockId: first, targetBlockId: second, createdAt }, + { id: `${workflowId}-a`, workflowId, sourceBlockId: first, targetBlockId: third, createdAt }, + ]) + + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(loaded?.edges.map((edge) => edge.id)).toEqual([`${workflowId}-z`, `${workflowId}-a`]) + }) + it('refuses a block id another workflow owns and leaves the stored graph as it was', async () => { const owner = await insertWorkflow() const workflowId = await insertWorkflow() diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 201fd167923..4e1b76c56cb 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -179,12 +179,19 @@ export async function loadWorkflowsFromNormalizedTablesRaw( return loaded } +/** + * 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. + */ +export const EDGE_LOAD_ORDER = [asc(workflowEdges.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. Each table's rows come in creation order, ties by id, so the - * assembled graph's block and edge order (which the executor reads, e.g. a router's or - * condition's first matching edge) is a fact of the stored rows, not of where an update left - * them in the heap. + * query embeds as a subquery. Blocks and subflows come in creation order, ties by id, and edges + * in {@link EDGE_LOAD_ORDER}, so the assembled graph's order is a fact of the stored rows, not of + * where an update left them in the heap. */ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWrapper)) { const ids = () => (typeof workflowIds === 'function' ? workflowIds() : workflowIds) @@ -201,7 +208,7 @@ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWra .select() .from(workflowEdges) .where(inArray(workflowEdges.workflowId, ids())) - .orderBy(asc(workflowEdges.createdAt), asc(workflowEdges.id)), + .orderBy(...EDGE_LOAD_ORDER), tx .select() .from(workflowSubflows) diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index ffcdad3faa6..307e3eec67a 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -10,6 +10,7 @@ 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 { EDGE_LOAD_ORDER } from './load' import { pruneWorkflowSourceMeta } from './source-meta' import { generateLoopBlocks, generateParallelBlocks } from './subflow-helpers' import type { DbOrTx } from './types' @@ -148,13 +149,6 @@ const BLOCK_UPDATE_SET = { updatedAt: sql`now()`, } as const -const EDGE_UPDATE_SET = { - sourceBlockId: sql`excluded.source_block_id`, - targetBlockId: sql`excluded.target_block_id`, - sourceHandle: sql`excluded.source_handle`, - targetHandle: sql`excluded.target_handle`, -} as const - const SUBFLOW_UPDATE_SET = { type: sql`excluded.type`, config: sql`excluded.config`, @@ -196,9 +190,12 @@ async function deleteRows( /** * 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 - * refused before anything is written, as that re-insert's foreign keys refused it. Only the difference is written: 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. + * refused before anything is written, as that re-insert's foreign keys refused it. Only the + * 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 (see `EDGE_LOAD_ORDER`). * * 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 @@ -240,7 +237,12 @@ export async function saveWorkflowToNormalizedTables( .from(workflowBlocks) .where(eq(workflowBlocks.workflowId, workflowId)) .for('update'), - tx.select().from(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)).for('update'), + tx + .select() + .from(workflowEdges) + .where(eq(workflowEdges.workflowId, workflowId)) + .orderBy(...EDGE_LOAD_ORDER) + .for('update'), tx .select() .from(workflowSubflows) @@ -250,15 +252,33 @@ export async function saveWorkflowToNormalizedTables( const blocks = planRows(storedBlocks, desiredBlocks) const edges = planRows(storedEdges, desiredEdges) const subflows = planRows(storedSubflows, desiredSubflows) + // Edges are rewritten whole, in the state's order, whenever any of them or their order + // changes: the executor reads a handle-less condition or router edge by its position. + const rewriteEdges = + edges.inserts.length + edges.updates.length + edges.deleteIds.length > 0 || + storedEdges.some((edge, index) => edge.id !== desiredEdges[index]?.id) - await deleteRows(tx, workflowEdges, workflowId, edges.deleteIds) + if (rewriteEdges) { + await deleteRows( + tx, + workflowEdges, + workflowId, + storedEdges.map((edge) => edge.id) + ) + } await deleteRows(tx, workflowSubflows, workflowId, subflows.deleteIds) if (blocks.inserts.length > 0) await tx.insert(workflowBlocks).values(blocks.inserts) await updateRows(tx, workflowBlocks, workflowId, blocks.updates, BLOCK_UPDATE_SET) - if (edges.inserts.length > 0) await tx.insert(workflowEdges).values(edges.inserts) - await updateRows(tx, workflowEdges, workflowId, edges.updates, EDGE_UPDATE_SET) + if (rewriteEdges && desiredEdges.length > 0) { + await tx.insert(workflowEdges).values( + desiredEdges.map((edge, index) => ({ + ...edge, + createdAt: sql`now() + ${index} * interval '1 microsecond'`, + })) + ) + } await deleteRows(tx, workflowBlocks, workflowId, blocks.deleteIds) From 6875c4807afd3738d620d2225d5d82250d23e743 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 03:26:57 -0800 Subject: [PATCH 102/104] fix(sim-cli): exempt no possible-rename reference once a warning cap left findings out Past the cap the compile keeps one W_UNRESOLVED_REF per code, block and file, so the listed references to a removed block could stand for a genuinely missing one after them, and exempting them let the check pass what the server refuses. --- apps/docs/content/docs/cli/reference.mdx | 4 +-- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../protocol/workflow-source-check.test.ts | 32 +++++++++++++++++++ .../protocol/workflow-source-check.ts | 11 +++++-- 5 files changed, 44 insertions(+), 7 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index ba2c83230e8..e1c915767fa 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8641,7 +8641,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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: 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. +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_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. ### sim workflows source status @@ -10019,7 +10019,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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: 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. +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_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. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 571c17acea3..382c4395d7d 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1445,7 +1445,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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: 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. +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_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. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index bd349a1758f..083554ef028 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -788,7 +788,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_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_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: 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. +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_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. 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 2da3618bd34..0c4adca3dbc 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 @@ -821,6 +821,38 @@ export default workflow('W', {}, () => { ) }) + it('still fails on a missing block past the warning cap when the listed ones may be renames', async () => { + cacheCatalog() + mkdirSync(join(dir, 'functions'), { recursive: true }) + writeFileSync( + join(dir, 'workflow.ts'), + `// @sim-sdk 1 +import { codeFile, fn, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('W', {}, () => { + const start = trigger.start('Start', {}) + const bang = fn('Bang', { code: 'return 1' }) + const report = fn('Report', { code: codeFile('./functions/report.js') }) + start.to(bang) + bang.to(report) +}) +` + ) + writeLock(['start', 'boom', 'report']) + writeWritten({ 'functions/report.js': 'return 1\n' }) + const renamed = Array.from({ length: 20 }, (_, i) => `$ref.boom.r${i}`) + writeFileSync( + join(dir, 'functions/report.js'), + `return [${[...renamed, '$ref.nosuchblock.value'].join(', ')}]\n` + ) + + await check() + + expect(result().diagnostics).toContainEqual( + expect.objectContaining({ code: 'E_APPLY_UNRESOLVED_REF', file: 'functions/report.js' }) + ) + }) + describe('a reference to an output the block lacks', () => { /** Start → Call (an HTTP request) → Done, whose JSON body reads `call.`. */ const reads = (output: string) => 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 56442cfbbc1..6b8b24da9e7 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -142,8 +142,9 @@ into another container, or when it compiles differently than in the source the l 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: the -server may infer that block was renamed and rewrite the reference, and refuses it otherwise. +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. ${[...EDIT_SCOPED_CODES].join(', ')} is reported only on blocks the lock does not bind, and with --strict on every block.` @@ -564,8 +565,12 @@ export async function checkWorkflowDir( * declares: the server may infer that block's rename (name and const both changed) and then * rewrite the reference, which only it can tell, so the check keeps the warning. */ + // Past a warning cap the compile keeps one finding per code, block and file, which could stand + // for a reference no rename settles, so then nothing is exempt. + const listedEvery = !compiled.diagnostics.some((d) => d.code === 'W_TOO_MANY_WARNINGS') const mayBeRenamed = (finding: (typeof compiled.diagnostics)[number]) => { - if (finding.code !== 'W_UNRESOLVED_REF' || finding.span.file === SOURCE_ENTRY_FILE) return false + if (!listedEvery || finding.code !== 'W_UNRESOLVED_REF') return false + if (finding.span.file === SOURCE_ENTRY_FILE) return false const text = files[finding.span.file]?.slice(finding.span.start, finding.span.end) ?? '' const head = /^(?:\$ref\.|<)([A-Za-z0-9_]+)/.exec(text)?.[1] return head !== undefined && removedKeys.has(head) From fa7711c0bff6e6be6395503a9fb2feeaf5cc9d9c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 03:45:58 -0800 Subject: [PATCH 103/104] fix(workflow-persistence): build the edge load order lazily A module-level order read workflowEdges at import, which broke every test that mocks @sim/db without it and imports the loader. --- packages/workflow-persistence/src/load.ts | 8 +++++--- packages/workflow-persistence/src/save.ts | 6 +++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/workflow-persistence/src/load.ts b/packages/workflow-persistence/src/load.ts index 4e1b76c56cb..31bfb779193 100644 --- a/packages/workflow-persistence/src/load.ts +++ b/packages/workflow-persistence/src/load.ts @@ -185,12 +185,14 @@ export async function loadWorkflowsFromNormalizedTablesRaw( * 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. */ -export const EDGE_LOAD_ORDER = [asc(workflowEdges.createdAt), sql`ctid`] as const +export function edgeLoadOrder() { + return [asc(workflowEdges.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 EDGE_LOAD_ORDER}, so the assembled graph's order is a fact of the stored rows, not of + * 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. */ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWrapper)) { @@ -208,7 +210,7 @@ async function selectGraphRows(tx: DbOrTx, workflowIds: string[] | (() => SQLWra .select() .from(workflowEdges) .where(inArray(workflowEdges.workflowId, ids())) - .orderBy(...EDGE_LOAD_ORDER), + .orderBy(...edgeLoadOrder()), tx .select() .from(workflowSubflows) diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index 307e3eec67a..ec33767ae03 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -10,7 +10,7 @@ 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 { EDGE_LOAD_ORDER } from './load' +import { edgeLoadOrder } from './load' import { pruneWorkflowSourceMeta } from './source-meta' import { generateLoopBlocks, generateParallelBlocks } from './subflow-helpers' import type { DbOrTx } from './types' @@ -195,7 +195,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 `EDGE_LOAD_ORDER`). + * state's order (see `edgeLoadOrder`). * * 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 @@ -241,7 +241,7 @@ export async function saveWorkflowToNormalizedTables( .select() .from(workflowEdges) .where(eq(workflowEdges.workflowId, workflowId)) - .orderBy(...EDGE_LOAD_ORDER) + .orderBy(...edgeLoadOrder()) .for('update'), tx .select() From a2b132dd38a4f40c3b704e3cd335e66d4013b18d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 20 Nov 2026 04:32:14 -0800 Subject: [PATCH 104/104] fix(workflow-persistence): insert rewritten edges in bounded batches Each rewritten edge binds seven parameters with its timestamp offset, so a workflow at the 10,000-edge source limit sent 70,000 in one insert, past Postgres's 65,535, and the save rolled back. Edges now go in batches of 5,000, keeping their offsets, and the old ones are deleted by workflow rather than by a list of ids. --- .../normalized-save.integration.ts | 20 +++++++++++++ packages/workflow-persistence/src/save.ts | 29 ++++++++++--------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts index 367c8d2ecea..10f31572999 100644 --- a/apps/sim/lib/workflows/persistence/normalized-save.integration.ts +++ b/apps/sim/lib/workflows/persistence/normalized-save.integration.ts @@ -368,6 +368,26 @@ describe('saveWorkflowToNormalizedTables', () => { expect(loaded?.edges.map((edge) => edge.id)).toEqual([`${workflowId}-z`, `${workflowId}-a`]) }) + 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) => + functionBlock(`${workflowId}-${id}`, `Block ${index}`, index * 100) + ) + const [first, second] = blocks.map((block) => block.id) + const edges = Array.from({ length: 10_000 }, (_, index) => ({ + id: `${workflowId}-e${String(9_999 - index).padStart(5, '0')}`, + source: first, + target: second, + })) + + expect(await saveWorkflowToNormalizedTables(workflowId, stateOf(blocks, edges))).toEqual({ + success: true, + }) + const loaded = await loadWorkflowFromNormalizedTablesRaw(workflowId) + + expect(loaded?.edges.map((edge) => edge.id)).toEqual(edges.map((edge) => edge.id)) + }) + it('refuses a block id another workflow owns and leaves the stored graph as it was', async () => { const owner = await insertWorkflow() const workflowId = await insertWorkflow() diff --git a/packages/workflow-persistence/src/save.ts b/packages/workflow-persistence/src/save.ts index ec33767ae03..b10a9959685 100644 --- a/packages/workflow-persistence/src/save.ts +++ b/packages/workflow-persistence/src/save.ts @@ -1,6 +1,7 @@ import { db, workflowBlocks, workflowEdges, workflowSubflows } from '@sim/db' import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { chunkArray } from '@sim/utils/helpers' import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' import { normalizeWorkflowEdgeSourceHandle, @@ -22,6 +23,12 @@ type BlockRow = InferInsertModel type EdgeRow = InferInsertModel type SubflowRow = InferInsertModel +/** + * Edges one insert writes: each binds seven parameters, so a workflow's edges at the source limit + * stay under Postgres's 65,535 per statement. + */ +const EDGE_INSERT_BATCH = 5_000 + /** Columns the database stamps; the save never compares them. */ const UNCOMPARED_COLUMNS = new Set(['createdAt', 'updatedAt']) @@ -259,25 +266,21 @@ export async function saveWorkflowToNormalizedTables( storedEdges.some((edge, index) => edge.id !== desiredEdges[index]?.id) if (rewriteEdges) { - await deleteRows( - tx, - workflowEdges, - workflowId, - storedEdges.map((edge) => edge.id) - ) + await tx.delete(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)) } await deleteRows(tx, workflowSubflows, workflowId, subflows.deleteIds) if (blocks.inserts.length > 0) await tx.insert(workflowBlocks).values(blocks.inserts) await updateRows(tx, workflowBlocks, workflowId, blocks.updates, BLOCK_UPDATE_SET) - if (rewriteEdges && desiredEdges.length > 0) { - await tx.insert(workflowEdges).values( - desiredEdges.map((edge, index) => ({ - ...edge, - createdAt: sql`now() + ${index} * interval '1 microsecond'`, - })) - ) + 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)) { + await tx.insert(workflowEdges).values(batch) + } } await deleteRows(tx, workflowBlocks, workflowId, blocks.deleteIds)