diff --git a/doc/DATABASE.md b/doc/DATABASE.md index f79643718f1..8d8c6a81db2 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -751,4 +751,6 @@ Migration [0333_pretty_infant_terrible.sql](../packages/db/src/migrations/0333_p `execution_workspace_repositories` is company-scoped inventory beneath an execution workspace. It records repository identity, contained relative path, requested ref, pinned commit, preparation state and idempotency receipts. Credentials are resolved at use and are never stored in this inventory. Connection/destination `execution_defaults` JSON contains optional typed project/workspace choices, never arbitrary host paths or commands. +Migration [0334_stiff_ted_forrester.sql](../packages/db/src/migrations/0334_stiff_ted_forrester.sql) adds internal `execution_workspace_repository_roots` records. A company and hash of its canonical physical path uniquely identify a sticky `anonymous_only` or `managed` acquisition reservation. Short transactions serialize reservations with repository requests and credential promotion, preventing private publication after low-trust admission checks. Records have no workspace foreign key: mutable workspace metadata, relocation, archival or deletion cannot release a physical folder still accessible to an admitted run. There is no automatic mode change or reservation deletion. + No migration scans or copies existing agent home directories. Keep admitted native descriptors and recovery references until compatible controllers finish their persistence obligations. See [the architecture rollout contract](plans/2026-10-09-task-workspaces.md). diff --git a/doc/plans/2026-10-09-task-workspaces.md b/doc/plans/2026-10-09-task-workspaces.md index cb0be24c749..79fb22465cf 100644 --- a/doc/plans/2026-10-09-task-workspaces.md +++ b/doc/plans/2026-10-09-task-workspaces.md @@ -39,6 +39,10 @@ Source inspection and isolated copies require source-project read access. Writab Independent repository acquisition does not inherit private-repository authority from a chat endpoint's sponsor. Effective low-trust tasks may submit anonymous repository URLs only; catalog selection, managed credentials and reuse of managed repository receipts remain forbidden. Resolve current agent, task, organizational project and workspace-source policies together with the retained run policy at request and admission. Existing configured-source authorization remains the path for private sources. A trust change must fail before cloning or reusing existing private bytes. +Admission with no repository requests remains heartbeat-owned and requires no additional repository-mutation permission. Low-trust admission still rejects managed acquisition bytes in the same physical folder. Immutable recovery uses its admitted folder and skips new repository acquisition even if the task's current binding has changed. A reservation-only recovery hook fences legacy admitted roots before provider reattachment; remote recovery obtains the host path from its verified immutable sync descriptor. + +Independent acquisition reserves a company-scoped canonical physical root as either `anonymous_only` or `managed` in an internal durable record. A short database fence serializes these reservations with repository requests and credential promotion. Low-trust use rejects every managed intent, including a clone still in staging, and reserves anonymous use before capture. Future managed requests cannot publish into that reserved root. The reservation survives controller restart, workspace aliases, metadata replacement, relocation and archival; changing the acquisition mode requires a separate physical root. No database lock remains held through cloning, input capture or provider execution. Arbitrary external file writers remain subject to the existing shared-folder constraints. + Channel defaults use optional properties (inherit), explicit null (clear), concrete value (override). Resource override beats endpoint. Defaults are captured once at task creation and reauthorized on use. Changing/deleting/revoking configuration cannot relocate existing tasks. Project choice and workspace choice are independent; choosing a source does not silently assign organizational project. Endpoints without configuration work normally. The organizational task project retains task identity, environment, and secret scope regardless of the filesystem source. Both task-project and source-project policies constrain run trust; source policy controls workspace realization. Channel task creation separately checks assignment authority for the effective organizational project and actual assignee against locked endpoint values inside its transaction. Saving defaults does not grant future senders that authority. diff --git a/packages/db/src/migrations/0334_stiff_ted_forrester.sql b/packages/db/src/migrations/0334_stiff_ted_forrester.sql new file mode 100644 index 00000000000..a9f0cc8b53c --- /dev/null +++ b/packages/db/src/migrations/0334_stiff_ted_forrester.sql @@ -0,0 +1,12 @@ +CREATE TABLE "execution_workspace_repository_roots" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "canonical_cwd" text NOT NULL, + "root_key" text NOT NULL, + "mode" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "execution_workspace_repository_roots" ADD CONSTRAINT "execution_workspace_repository_roots_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "execution_workspace_repository_roots_company_root_idx" ON "execution_workspace_repository_roots" USING btree ("company_id","root_key"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0323_snapshot.json b/packages/db/src/migrations/meta/0334_snapshot.json similarity index 96% rename from packages/db/src/migrations/meta/0323_snapshot.json rename to packages/db/src/migrations/meta/0334_snapshot.json index 6486606667b..4abbb1c61a5 100644 --- a/packages/db/src/migrations/meta/0323_snapshot.json +++ b/packages/db/src/migrations/meta/0334_snapshot.json @@ -1,6 +1,6 @@ { - "id": "76861d12-d9a9-4f5f-bcbc-0fb06c0addbc", - "prevId": "677c8c43-8767-4e2b-9cc4-35a76061e6df", + "id": "77110fc0-2a50-45eb-913d-e507ba74439a", + "prevId": "64c77972-2c34-4fb7-ba72-f48dadcf794d", "version": "7", "dialect": "postgresql", "tables": { @@ -416,6 +416,12 @@ "primaryKey": false, "notNull": false }, + "fast_response_request_id": { + "name": "fast_response_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "agent_id": { "name": "agent_id", "type": "uuid", @@ -462,6 +468,27 @@ } }, "indexes": { + "budget_reservations_fast_response_idx": { + "name": "budget_reservations_fast_response_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "fast_response_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, "budget_reservations_decision_idx": { "name": "budget_reservations_decision_idx", "columns": [ @@ -580,7 +607,7 @@ "checkConstraints": { "budget_reservations_source_check": { "name": "budget_reservations_source_check", - "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int = 1" + "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int = 1" }, "budget_reservations_state_check": { "name": "budget_reservations_state_check", @@ -3737,6 +3764,28 @@ "method": "btree", "with": {} }, + "agent_wakeup_requests_question_response_history_idx": { + "name": "agent_wakeup_requests_question_response_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'question-response:%'", + "concurrently": true, + "method": "btree", + "with": {} + }, "agent_wakeup_requests_connection_intent_delivery_idempotency_uq": { "name": "agent_wakeup_requests_connection_intent_delivery_idempotency_uq", "columns": [ @@ -9809,6 +9858,12 @@ "notNull": true, "default": false }, + "execution_defaults": { + "name": "execution_defaults", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "metadata": { "name": "metadata", "type": "jsonb", @@ -10049,6 +10104,12 @@ "notNull": true, "default": "''" }, + "execution_defaults": { + "name": "execution_defaults", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "allow_direct_messages": { "name": "allow_direct_messages", "type": "boolean", @@ -10455,7 +10516,7 @@ }, "chat_endpoints_provider_check": { "name": "chat_endpoints_provider_check", - "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')" + "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')" }, "chat_endpoints_status_check": { "name": "chat_endpoints_status_check", @@ -10640,7 +10701,7 @@ "checkConstraints": { "chat_external_principals_provider_check": { "name": "chat_external_principals_provider_check", - "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')" + "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')" }, "chat_external_principals_kind_check": { "name": "chat_external_principals_kind_check", @@ -12931,6 +12992,1267 @@ }, "isRLSEnabled": false }, + "public.chat_voice_callbacks": { + "name": "chat_voice_callbacks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_number": { + "name": "phone_number", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chat_voice_callbacks_owner_uq": { + "name": "chat_voice_callbacks_owner_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "endpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_callbacks_endpoint_fk": { + "name": "chat_voice_callbacks_endpoint_fk", + "tableFrom": "chat_voice_callbacks", + "tableTo": "chat_endpoints", + "columnsFrom": [ + "company_id", + "endpoint_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chat_voice_callbacks_phone_check": { + "name": "chat_voice_callbacks_phone_check", + "value": "\"chat_voice_callbacks\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_inbound_calls": { + "name": "chat_voice_inbound_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider_session_id": { + "name": "provider_session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'awaiting_approval'" + }, + "approval_code": { + "name": "approval_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "credential_fingerprint": { + "name": "credential_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool_token_hash": { + "name": "tool_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_fingerprint": { + "name": "request_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved_by_user_id": { + "name": "approved_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "caller_authority": { + "name": "caller_authority", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "intake_issue_id": { + "name": "intake_issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "requested_issue_id": { + "name": "requested_issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "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": { + "chat_voice_inbound_expiry_idx": { + "name": "chat_voice_inbound_expiry_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_inbound_endpoint_fk": { + "name": "chat_voice_inbound_endpoint_fk", + "tableFrom": "chat_voice_inbound_calls", + "tableTo": "chat_endpoints", + "columnsFrom": [ + "company_id", + "endpoint_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_voice_inbound_session_fk": { + "name": "chat_voice_inbound_session_fk", + "tableFrom": "chat_voice_inbound_calls", + "tableTo": "chat_voice_sessions", + "columnsFrom": [ + "company_id", + "session_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_inbound_intake_fk": { + "name": "chat_voice_inbound_intake_fk", + "tableFrom": "chat_voice_inbound_calls", + "tableTo": "issues", + "columnsFrom": [ + "company_id", + "intake_issue_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_inbound_requested_issue_fk": { + "name": "chat_voice_inbound_requested_issue_fk", + "tableFrom": "chat_voice_inbound_calls", + "tableTo": "issues", + "columnsFrom": [ + "company_id", + "requested_issue_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "chat_voice_inbound_provider_uq": { + "name": "chat_voice_inbound_provider_uq", + "nullsNotDistinct": false, + "columns": [ + "provider_session_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "chat_voice_inbound_state_check": { + "name": "chat_voice_inbound_state_check", + "value": "\"chat_voice_inbound_calls\".\"state\" in ('guest_intake', 'awaiting_approval', 'approving', 'approved', 'denied', 'expired', 'ended')" + }, + "chat_voice_inbound_token_check": { + "name": "chat_voice_inbound_token_check", + "value": "\"chat_voice_inbound_calls\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'" + }, + "chat_voice_inbound_code_check": { + "name": "chat_voice_inbound_code_check", + "value": "\"chat_voice_inbound_calls\".\"approval_code\" ~ '^[0-9]{6}$'" + }, + "chat_voice_inbound_generation_check": { + "name": "chat_voice_inbound_generation_check", + "value": "\"chat_voice_inbound_calls\".\"generation\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_phone_lines": { + "name": "chat_voice_phone_lines", + "schema": "", + "columns": { + "endpoint_id": { + "name": "endpoint_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider_number_id": { + "name": "provider_number_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_number": { + "name": "phone_number", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "guest_intake": { + "name": "guest_intake", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "low_trust_environment_id": { + "name": "low_trust_environment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk": { + "name": "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk", + "tableFrom": "chat_voice_phone_lines", + "tableTo": "environments", + "columnsFrom": [ + "low_trust_environment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_phone_lines_endpoint_fk": { + "name": "chat_voice_phone_lines_endpoint_fk", + "tableFrom": "chat_voice_phone_lines", + "tableTo": "chat_endpoints", + "columnsFrom": [ + "company_id", + "endpoint_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "chat_voice_phone_lines_number_uq": { + "name": "chat_voice_phone_lines_number_uq", + "nullsNotDistinct": false, + "columns": [ + "provider_number_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "chat_voice_phone_lines_number_check": { + "name": "chat_voice_phone_lines_number_check", + "value": "\"chat_voice_phone_lines\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_reports": { + "name": "chat_voice_reports", + "schema": "", + "columns": { + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "transcript": { + "name": "transcript", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cost_micro_usd": { + "name": "cost_micro_usd", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "provider_updated_at": { + "name": "provider_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chat_voice_reports_pending_idx": { + "name": "chat_voice_reports_pending_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_check_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_reports_session_fk": { + "name": "chat_voice_reports_session_fk", + "tableFrom": "chat_voice_reports", + "tableTo": "chat_voice_sessions", + "columnsFrom": [ + "company_id", + "session_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chat_voice_reports_status_check": { + "name": "chat_voice_reports_status_check", + "value": "\"chat_voice_reports\".\"status\" in ('pending', 'available', 'unavailable')" + }, + "chat_voice_reports_cost_check": { + "name": "chat_voice_reports_cost_check", + "value": "\"chat_voice_reports\".\"cost_micro_usd\" is null or \"chat_voice_reports\".\"cost_micro_usd\" ~ '^[0-9]{1,30}$'" + }, + "chat_voice_reports_duration_check": { + "name": "chat_voice_reports_duration_check", + "value": "\"chat_voice_reports\".\"duration_seconds\" is null or \"chat_voice_reports\".\"duration_seconds\" >= 0" + }, + "chat_voice_reports_attempts_check": { + "name": "chat_voice_reports_attempts_check", + "value": "\"chat_voice_reports\".\"attempts\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_replies": { + "name": "chat_voice_replies", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "publication_id": { + "name": "publication_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "cursor": { + "name": "cursor", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "spoken_at": { + "name": "spoken_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()" + } + }, + "indexes": { + "chat_voice_replies_publication_uq": { + "name": "chat_voice_replies_publication_uq", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "publication_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_voice_replies_cursor_uq": { + "name": "chat_voice_replies_cursor_uq", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cursor", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_replies_company_id_companies_id_fk": { + "name": "chat_voice_replies_company_id_companies_id_fk", + "tableFrom": "chat_voice_replies", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_voice_replies_session_fk": { + "name": "chat_voice_replies_session_fk", + "tableFrom": "chat_voice_replies", + "tableTo": "chat_voice_sessions", + "columnsFrom": [ + "company_id", + "session_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_replies_publication_fk": { + "name": "chat_voice_replies_publication_fk", + "tableFrom": "chat_voice_replies", + "tableTo": "chat_publications", + "columnsFrom": [ + "company_id", + "publication_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chat_voice_replies_cursor_check": { + "name": "chat_voice_replies_cursor_check", + "value": "\"chat_voice_replies\".\"cursor\" > 0" + }, + "chat_voice_replies_spoken_check": { + "name": "chat_voice_replies_spoken_check", + "value": "\"chat_voice_replies\".\"spoken_at\" is null or \"chat_voice_replies\".\"delivered_at\" is not null" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_sessions": { + "name": "chat_voice_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "conversation_id": { + "name": "conversation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "assigned_agent_id": { + "name": "assigned_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "caller_id": { + "name": "caller_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "caller_authority": { + "name": "caller_authority", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "approved_by_user_id": { + "name": "approved_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'reserved'" + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "credential_fingerprint": { + "name": "credential_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_session_id": { + "name": "provider_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_token_hash": { + "name": "tool_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_fingerprint": { + "name": "request_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reply_cursor": { + "name": "reply_cursor", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ended_at": { + "name": "ended_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": { + "chat_voice_sessions_provider_uq": { + "name": "chat_voice_sessions_provider_uq", + "columns": [ + { + "expression": "provider_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_voice_sessions_request_uq": { + "name": "chat_voice_sessions_request_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "caller_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_voice_sessions_live_caller_task_uq": { + "name": "chat_voice_sessions_live_caller_task_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "caller_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"chat_voice_sessions\".\"state\" not in ('ended', 'failed', 'expired')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_voice_sessions_expiry_idx": { + "name": "chat_voice_sessions_expiry_idx", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_sessions_company_id_companies_id_fk": { + "name": "chat_voice_sessions_company_id_companies_id_fk", + "tableFrom": "chat_voice_sessions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_voice_sessions_endpoint_fk": { + "name": "chat_voice_sessions_endpoint_fk", + "tableFrom": "chat_voice_sessions", + "tableTo": "chat_endpoints", + "columnsFrom": [ + "company_id", + "endpoint_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_sessions_conversation_fk": { + "name": "chat_voice_sessions_conversation_fk", + "tableFrom": "chat_voice_sessions", + "tableTo": "chat_conversations", + "columnsFrom": [ + "company_id", + "conversation_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_sessions_issue_fk": { + "name": "chat_voice_sessions_issue_fk", + "tableFrom": "chat_voice_sessions", + "tableTo": "issues", + "columnsFrom": [ + "company_id", + "issue_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_sessions_agent_fk": { + "name": "chat_voice_sessions_agent_fk", + "tableFrom": "chat_voice_sessions", + "tableTo": "agents", + "columnsFrom": [ + "company_id", + "assigned_agent_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "chat_voice_sessions_company_id_uq": { + "name": "chat_voice_sessions_company_id_uq", + "nullsNotDistinct": false, + "columns": [ + "company_id", + "id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "chat_voice_sessions_state_check": { + "name": "chat_voice_sessions_state_check", + "value": "\"chat_voice_sessions\".\"state\" in ('reserved', 'creating', 'creation_unknown', 'connecting', 'active', 'awaiting_approval', 'ending', 'ended', 'failed', 'expired')" + }, + "chat_voice_sessions_mode_check": { + "name": "chat_voice_sessions_mode_check", + "value": "\"chat_voice_sessions\".\"mode\" in ('browser', 'inbound_phone', 'outbound_phone')" + }, + "chat_voice_sessions_authority_check": { + "name": "chat_voice_sessions_authority_check", + "value": "\"chat_voice_sessions\".\"caller_authority\" in ('member', 'instance_admin', 'local_board', 'guest_intake', 'pending_approval')" + }, + "chat_voice_sessions_counters_check": { + "name": "chat_voice_sessions_counters_check", + "value": "\"chat_voice_sessions\".\"generation\" >= 1 and \"chat_voice_sessions\".\"reply_cursor\" >= 0" + }, + "chat_voice_sessions_token_check": { + "name": "chat_voice_sessions_token_check", + "value": "\"chat_voice_sessions\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'" + }, + "chat_voice_sessions_expiry_check": { + "name": "chat_voice_sessions_expiry_check", + "value": "\"chat_voice_sessions\".\"expires_at\" > \"chat_voice_sessions\".\"created_at\"" + } + }, + "isRLSEnabled": false + }, + "public.chat_voice_tool_calls": { + "name": "chat_voice_tool_calls", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider_tool_call_id": { + "name": "provider_tool_call_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "fingerprint": { + "name": "fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tool": { + "name": "tool", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "delivery_id": { + "name": "delivery_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "response": { + "name": "response", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "chat_voice_tool_calls_tool_uq": { + "name": "chat_voice_tool_calls_tool_uq", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_tool_call_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chat_voice_tool_calls_webhook_uq": { + "name": "chat_voice_tool_calls_webhook_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "webhook_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chat_voice_tool_calls_company_id_companies_id_fk": { + "name": "chat_voice_tool_calls_company_id_companies_id_fk", + "tableFrom": "chat_voice_tool_calls", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "chat_voice_tool_calls_session_fk": { + "name": "chat_voice_tool_calls_session_fk", + "tableFrom": "chat_voice_tool_calls", + "tableTo": "chat_voice_sessions", + "columnsFrom": [ + "company_id", + "session_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chat_voice_tool_calls_delivery_fk": { + "name": "chat_voice_tool_calls_delivery_fk", + "tableFrom": "chat_voice_tool_calls", + "tableTo": "chat_deliveries", + "columnsFrom": [ + "company_id", + "delivery_id" + ], + "columnsTo": [ + "company_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chat_voice_tool_calls_tool_check": { + "name": "chat_voice_tool_calls_tool_check", + "value": "\"chat_voice_tool_calls\".\"tool\" in ('submit_request', 'get_updates', 'answer_question')" + } + }, + "isRLSEnabled": false + }, "public.cli_auth_challenges": { "name": "cli_auth_challenges", "schema": "", @@ -18565,7 +19887,7 @@ "checkConstraints": { "cost_events_usage_kind_check": { "name": "cost_events_usage_kind_check", - "value": "\"cost_events\".\"usage_kind\" = 'decision' or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" + "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" }, "cost_events_nonnegative_amounts": { "name": "cost_events_nonnegative_amounts", @@ -24920,6 +26242,346 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.execution_workspace_repositories": { + "name": "execution_workspace_repositories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "execution_workspace_id": { + "name": "execution_workspace_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "requested_by_issue_id": { + "name": "requested_by_issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "repository_identity": { + "name": "repository_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "catalog_repository_id": { + "name": "catalog_repository_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repo_url": { + "name": "repo_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "relative_path": { + "name": "relative_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_ref": { + "name": "requested_ref", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'HEAD'" + }, + "pinned_commit": { + "name": "pinned_commit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "branch_name": { + "name": "branch_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_key": { + "name": "request_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_keys": { + "name": "request_keys", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "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": { + "execution_workspace_repositories_identity_idx": { + "name": "execution_workspace_repositories_identity_idx", + "columns": [ + { + "expression": "execution_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repository_identity", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_workspace_repositories_path_idx": { + "name": "execution_workspace_repositories_path_idx", + "columns": [ + { + "expression": "execution_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "relative_path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_workspace_repositories_request_idx": { + "name": "execution_workspace_repositories_request_idx", + "columns": [ + { + "expression": "execution_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "execution_workspace_repositories_company_workspace_idx": { + "name": "execution_workspace_repositories_company_workspace_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "execution_workspace_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_workspace_repositories_company_id_companies_id_fk": { + "name": "execution_workspace_repositories_company_id_companies_id_fk", + "tableFrom": "execution_workspace_repositories", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk": { + "name": "execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk", + "tableFrom": "execution_workspace_repositories", + "tableTo": "execution_workspaces", + "columnsFrom": [ + "execution_workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "execution_workspace_repositories_requested_by_issue_id_issues_id_fk": { + "name": "execution_workspace_repositories_requested_by_issue_id_issues_id_fk", + "tableFrom": "execution_workspace_repositories", + "tableTo": "issues", + "columnsFrom": [ + "requested_by_issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.execution_workspace_repository_roots": { + "name": "execution_workspace_repository_roots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "canonical_cwd": { + "name": "canonical_cwd", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "root_key": { + "name": "root_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "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": { + "execution_workspace_repository_roots_company_root_idx": { + "name": "execution_workspace_repository_roots_company_root_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "root_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "execution_workspace_repository_roots_company_id_companies_id_fk": { + "name": "execution_workspace_repository_roots_company_id_companies_id_fk", + "tableFrom": "execution_workspace_repository_roots", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.execution_workspace_runtime_leases": { "name": "execution_workspace_runtime_leases", "schema": "", @@ -25175,7 +26837,7 @@ "name": "project_id", "type": "uuid", "primaryKey": false, - "notNull": true + "notNull": false }, "project_workspace_id": { "name": "project_workspace_id", @@ -25453,7 +27115,7 @@ "columnsTo": [ "id" ], - "onDelete": "cascade", + "onDelete": "restrict", "onUpdate": "no action" }, "execution_workspaces_project_workspace_id_project_workspaces_id_fk": { @@ -26230,6 +27892,378 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_fast_responses": { + "name": "company_fast_responses", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "allow_sponsored": { + "name": "allow_sponsored", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "company_fast_responses_company_id_companies_id_fk": { + "name": "company_fast_responses_company_id_companies_id_fk", + "tableFrom": "company_fast_responses", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_fast_responses_configured": { + "name": "company_fast_responses_configured", + "value": "(\"company_fast_responses\".\"connection_id\" is null) = (\"company_fast_responses\".\"grant_id\" is null) and (not \"company_fast_responses\".\"enabled\" or (\"company_fast_responses\".\"connection_id\" is not null and \"company_fast_responses\".\"model\" is not null))" + } + }, + "isRLSEnabled": false + }, + "public.fast_response_requests": { + "name": "fast_response_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_key": { + "name": "source_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_comment_id": { + "name": "source_comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sponsored": { + "name": "sponsored", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "delivery_id": { + "name": "delivery_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "session_generation": { + "name": "session_generation", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "publication_status": { + "name": "publication_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_request_id": { + "name": "provider_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cost_event_id": { + "name": "cost_event_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "comment_id": { + "name": "comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "input_tokens": { + "name": "input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "output_tokens": { + "name": "output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "fast_response_requests_source_idx": { + "name": "fast_response_requests_source_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "fast_response_requests_history_idx": { + "name": "fast_response_requests_history_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "accepted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "fast_response_requests_work_idx": { + "name": "fast_response_requests_work_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"fast_response_requests\".\"status\" in ('pending', 'running')", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "fast_response_requests_company_id_companies_id_fk": { + "name": "fast_response_requests_company_id_companies_id_fk", + "tableFrom": "fast_response_requests", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "fast_response_requests_cost_event_id_cost_events_id_fk": { + "name": "fast_response_requests_cost_event_id_cost_events_id_fk", + "tableFrom": "fast_response_requests", + "tableTo": "cost_events", + "columnsFrom": [ + "cost_event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "fast_response_requests_status_check": { + "name": "fast_response_requests_status_check", + "value": "\"fast_response_requests\".\"status\" in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped')" + } + }, + "isRLSEnabled": false + }, "public.feedback_exports": { "name": "feedback_exports", "schema": "", @@ -31131,6 +33165,19 @@ "primaryKey": false, "notNull": false }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'comment'" + }, + "fast_response_request_id": { + "name": "fast_response_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "body": { "name": "body", "type": "text", @@ -35828,6 +37875,25 @@ "primaryKey": false, "notNull": false }, + "workspace_binding_revision": { + "name": "workspace_binding_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "workspace_selection": { + "name": "workspace_selection", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "workspace_pending_selection": { + "name": "workspace_pending_selection", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "execution_workspace_preference": { "name": "execution_workspace_preference", "type": "text", @@ -49952,7 +52018,7 @@ }, "tool_connections_transport_check": { "name": "tool_connections_transport_check", - "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'runtime_auth')" + "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth')" }, "tool_connections_purpose_check": { "name": "tool_connections_purpose_check", @@ -49960,7 +52026,7 @@ }, "tool_connections_channel_transport_check": { "name": "tool_connections_channel_transport_check", - "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" = 'chat_sdk' or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )" + "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'voice', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" in ('chat_sdk', 'voice') or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )" }, "tool_connections_auth_kind_check": { "name": "tool_connections_auth_kind_check", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 8b39941d07e..7f57225b13c 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2325,6 +2325,13 @@ "when": 1791717218544, "tag": "0333_pretty_infant_terrible", "breakpoints": true + }, + { + "idx": 334, + "version": "7", + "when": 1791719734041, + "tag": "0334_stiff_ted_forrester", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/execution_workspace_repository_roots.ts b/packages/db/src/schema/execution_workspace_repository_roots.ts new file mode 100644 index 00000000000..59abd8e7a82 --- /dev/null +++ b/packages/db/src/schema/execution_workspace_repository_roots.ts @@ -0,0 +1,15 @@ +import { pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; + +/** Sticky root ownership survives workspace moves, archival, and metadata changes. */ +export const executionWorkspaceRepositoryRoots = pgTable("execution_workspace_repository_roots", { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + canonicalCwd: text("canonical_cwd").notNull(), + rootKey: text("root_key").notNull(), + mode: text("mode").$type<"anonymous_only" | "managed">().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), +}, (table) => ({ + rootIdx: uniqueIndex("execution_workspace_repository_roots_company_root_idx").on(table.companyId, table.rootKey), +})); diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 6ae0c54aa8e..6b93239d984 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -246,4 +246,5 @@ export { userCompanyPreferences } from "./user_company_preferences.js"; export { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections } from "./ai_subscriptions.js"; export { executionWorkspaceRepositories } from "./execution_workspace_repositories.js"; +export { executionWorkspaceRepositoryRoots } from "./execution_workspace_repository_roots.js"; export * from "./fast_responses.js"; diff --git a/server/src/__tests__/native-workspace-sync.test.ts b/server/src/__tests__/native-workspace-sync.test.ts index 072e8fdcedd..f690abcd5be 100644 --- a/server/src/__tests__/native-workspace-sync.test.ts +++ b/server/src/__tests__/native-workspace-sync.test.ts @@ -13,6 +13,7 @@ import { classifyNativeWorkspaceInbound, nativeWorkspaceSyncInternals, readNativeWorkspaceSyncReference, + readNativeWorkspaceSyncLocalCwd, resumeNativeWorkspaceSync, prepareNativeWorkspaceSync, cleanupNativeWorkspaceSync, @@ -185,6 +186,9 @@ describe("native workspace sync durable metadata", () => { const recovered = await nativeWorkspaceSyncInternals.readDescriptor({ runId, reference }); expect(recovered.baseline.entries.get("private-filename-雪")).toMatchObject({ kind: "file" }); await disposeDirectorySnapshot(recovered.baseline); + await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "company", workspaceId: "workspace", reference })).resolves.toBe(workspace); + await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "other-company", workspaceId: "workspace", reference })).rejects.toThrow(/binding_mismatch/); + await expect(readNativeWorkspaceSyncLocalCwd({ runId, companyId: "company", workspaceId: "other-workspace", reference })).rejects.toThrow(/binding_mismatch/); if (tamper === "corrupt") { await appendFile(serialized.entries.filePath, "corrupt"); } else if (tamper === "symlink") { diff --git a/server/src/__tests__/task-workspace-repositories-trust.test.ts b/server/src/__tests__/task-workspace-repositories-trust.test.ts index 0e9ec6968b0..7e3c884d3ea 100644 --- a/server/src/__tests__/task-workspace-repositories-trust.test.ts +++ b/server/src/__tests__/task-workspace-repositories-trust.test.ts @@ -1,12 +1,12 @@ import { execFile as execFileCallback } from "node:child_process"; import { promisify } from "node:util"; import { randomUUID } from "node:crypto"; -import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, readFile, realpath, rm, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; -import { agents, authUsers, companies, companyMemberships, createDb, executionWorkspaceRepositories, executionWorkspaces, +import { agents, authUsers, companies, companyMemberships, createDb, executionWorkspaceRepositoryRoots, executionWorkspaceRepositories, executionWorkspaces, heartbeatRuns, issues, projects, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; import { executionWorkspaceRepositoryService } from "../services/execution-workspace-repositories.js"; import { buildGitAuthInvocation } from "../services/git-credentials.js"; @@ -68,6 +68,19 @@ const support = await getEmbeddedPostgresTestSupport(); return { companyId, agentId, issueId, runId, userId, workspace, policy, service, actor, request, admission }; } + async function lowTrustPeer(f: Awaited>, cwd = f.admission.cwd) { + const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, name: "Low-trust alias", + cwd, mode: "isolated_workspace", strategyType: "task_directory" }).returning(); + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Low-trust peer", + assigneeAgentId: f.agentId, executionWorkspaceId: workspace.id }); + const policy = { ...f.policy, authorizationPolicy: { ...f.policy.authorizationPolicy, + trustBoundary: { ...f.policy.authorizationPolicy.trustBoundary, rootIssueId: issueId } } }; + await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", + responsibleUserId: f.userId, contextSnapshot: { issueId, executionPolicy: policy } }); + return { workspace, admission: { ...f.admission, cwd, issueId, runId, workspaceId: workspace.id }, actor: { ...f.actor, runId } }; + } + it.each(["agent", "issue", "project", "workspace_source_project", "run"] as const)( "rejects catalog acquisition from raw %s low-trust policy", async source => { const f = await fixture(); @@ -148,14 +161,19 @@ const support = await getEmbeddedPostgresTestSupport(); expect(acquisition.managedAuth).not.toHaveBeenCalled(); }); - it.each(["same_repository", "different_repository", "empty_inventory", "unpinned_publication"] as const)( + it.each(["same_repository", "different_repository", "empty_inventory", "unpinned_publication", "pending_intent"] as const)( "rejects managed peer bytes in the same physical root with %s", async scenario => { const f = await fixture(); const managed = await f.request({ kind: "catalog", id: "private-repo" }); const checkout = path.join(f.admission.cwd, managed.repository.relativePath); - await mkdir(path.join(checkout, ".git"), { recursive: true }); - await writeFile(path.join(checkout, "private.txt"), "Private peer bytes"); - if (scenario !== "unpinned_publication") await db.update(executionWorkspaceRepositories) + if (scenario !== "pending_intent") { + await mkdir(path.join(checkout, ".git"), { recursive: true }); + await writeFile(path.join(checkout, "private.txt"), "Private peer bytes"); + } else { + // A legacy pending intent has neither a root-policy row nor published bytes. + await db.delete(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId)); + } + if (scenario !== "unpinned_publication" && scenario !== "pending_intent") await db.update(executionWorkspaceRepositories) .set({ state: "ready", pinnedCommit: "b".repeat(40) }).where(eq(executionWorkspaceRepositories.id, managed.operationId)); const [peer] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, name: "Same physical folder", cwd: f.admission.cwd, mode: "isolated_workspace", strategyType: "task_directory" }).returning(); @@ -167,15 +185,123 @@ const support = await getEmbeddedPostgresTestSupport(); await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", responsibleUserId: f.userId, contextSnapshot: { issueId, executionPolicy: policy } }); await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); - if (scenario !== "empty_inventory") await f.service.request({ companyId: f.companyId, issueId, actor: { ...f.actor, runId }, - request: { requestKey: randomUUID(), repository: { kind: "url", url: scenario === "same_repository" ? managed.repository.repoUrl : "https://github.com/public/other" } } }); + if (scenario !== "empty_inventory") await expect(f.service.request({ companyId: f.companyId, issueId, actor: { ...f.actor, runId }, + request: { requestKey: randomUUID(), repository: { kind: "url", url: scenario === "same_repository" ? managed.repository.repoUrl : "https://github.com/public/other" } } })) + .rejects.toThrow(/anonymous public URLs only/); await expect(f.service.prepareForAdmission({ ...f.admission, issueId, runId, workspaceId: peer.id })).rejects.toThrow(/anonymous public URLs only/); expect(acquisition.materialize).not.toHaveBeenCalled(); expect(acquisition.managedAuth).not.toHaveBeenCalled(); - expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("Private peer bytes"); + if (scenario !== "pending_intent") expect(await readFile(path.join(checkout, "private.txt"), "utf8")).toBe("Private peer bytes"); }, ); + it("reserves a legacy low-trust recovery folder after its task binding moves", async () => { + const f = await fixture(); + const peer = await lowTrustPeer(f); + await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, peer.admission.issueId)); + await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-recovery"), metadata: {}, status: "archived" }) + .where(eq(executionWorkspaces.id, peer.workspace.id)); + await f.service.reserveForRecovery(peer.admission); + await expect(executionWorkspaceRepositoryService(db).request({ companyId: f.companyId, issueId: f.issueId, actor: f.actor, + request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })) + .rejects.toThrow(/anonymous public URLs only/); + const [reservation] = await db.select().from(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId)); + expect(reservation).toMatchObject({ canonicalCwd: await realpath(f.admission.cwd), mode: "anonymous_only" }); + expect(acquisition.materialize).not.toHaveBeenCalled(); + expect(acquisition.managedAuth).not.toHaveBeenCalled(); + }); + + it("reserves a legacy managed recovery folder before a low-trust peer resumes", async () => { + const f = await fixture(); + await f.request({ kind: "catalog", id: "private-repo" }); + await db.delete(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId)); + const peer = await lowTrustPeer(f); + await f.service.reserveForRecovery(f.admission); + await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-managed-recovery") }).where(eq(executionWorkspaces.id, f.workspace.id)); + await expect(executionWorkspaceRepositoryService(db).reserveForRecovery(peer.admission)).rejects.toThrow(/anonymous public URLs only/); + expect(acquisition.materialize).not.toHaveBeenCalled(); + }); + + it("serializes a managed request against anonymous admission through physical aliases", async () => { + const f = await fixture(); + const alias = path.join(root, `${f.issueId}-alias`); + await symlink(f.admission.cwd, alias); + const peer = await lowTrustPeer(f, alias); + const outcomes = await Promise.allSettled([ + f.service.prepareForAdmission(peer.admission), + f.request({ kind: "catalog", id: "private-repo" }), + ]); + expect(outcomes.filter(result => result.status === "fulfilled")).toHaveLength(1); + expect(outcomes.filter(result => result.status === "rejected")).toHaveLength(1); + const [reservation] = await db.select().from(executionWorkspaceRepositoryRoots).where(eq(executionWorkspaceRepositoryRoots.companyId, f.companyId)); + expect(reservation.mode).toBe(outcomes[0].status === "fulfilled" ? "anonymous_only" : "managed"); + const restarted = executionWorkspaceRepositoryService(db); + if (reservation.mode === "anonymous_only") { + await expect(f.request({ kind: "catalog", id: "private-repo" })).rejects.toThrow(/anonymous public URLs only/); + await expect(restarted.prepareForAdmission(peer.admission)).resolves.toEqual([]); + } else await expect(restarted.prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/); + expect(acquisition.materialize).not.toHaveBeenCalled(); + }); + + it("keeps anonymous root ownership across workspace moves and blocks future catalog promotion", async () => { + const f = await fixture(); + // A standard task's initially anonymous intent may later appear in its catalog. + const pending = await f.request({ kind: "url", url: "https://github.com/public/later-catalog" }); + const peer = await lowTrustPeer(f); + await f.service.prepareForAdmission(peer.admission); + await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-anonymous-workspace"), metadata: {}, status: "archived" }) + .where(eq(executionWorkspaces.id, peer.workspace.id)); + const restarted = executionWorkspaceRepositoryService(db); + await expect(restarted.request({ companyId: f.companyId, issueId: f.issueId, actor: f.actor, + request: { repository: { kind: "catalog", id: "private-repo" }, requestKey: randomUUID() } })).rejects.toThrow(/anonymous public URLs only/); + acquisition.catalog.mockResolvedValue({ repositories: [{ id: "later", fullName: "public/later-catalog", private: true, + url: pending.repository.repoUrl, connections: ["sponsor-github"] }] }); + await expect(restarted.prepareForAdmission(f.admission)).rejects.toThrow(/anonymous public URLs only/); + expect(acquisition.managedAuth).not.toHaveBeenCalled(); + expect(acquisition.materialize).not.toHaveBeenCalled(); + expect((await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, pending.operationId)))[0].catalogRepositoryId).toBeNull(); + }); + + it("rejects anonymous admission while a managed clone is waiting to publish", async () => { + const f = await fixture(); + const receipt = await f.request({ kind: "catalog", id: "private-repo" }); + const peer = await lowTrustPeer(f); + const source = path.join(root, `${f.issueId}-private-source`); + await mkdir(source); + const exec = promisify(execFileCallback); + await exec("git", ["init", "--initial-branch=main", source]); + await writeFile(path.join(source, "private.txt"), "Private fixture bytes\n"); + await exec("git", ["-C", source, "add", "."]); + await exec("git", ["-C", source, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "private source"]); + let release!: () => void, started!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const staged = new Promise(resolve => { started = resolve; }); + const actual = await vi.importActual("../services/managed-repository-checkout.js"); + acquisition.materialize.mockImplementationOnce(async (cwd, input) => { + const result = await actual.materializeManagedProjectWorkspace(cwd, { ...input, localSource: source, + beforePublish: async cloneCwd => { + await input.beforePublish(cloneCwd); + started(); + await gate; + } }); + await exec("git", ["-C", cwd, "remote", "set-url", "origin", input.repoUrl]); + return result; + }); + const preparation = f.service.prepareForAdmission(f.admission); + try { + await Promise.race([staged, preparation.then(() => { throw new Error("Managed preparation finished before publication barrier"); })]); + const [pending] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, receipt.operationId)); + expect(pending).toMatchObject({ state: "preparing", pinnedCommit: null }); + // The reservation remains anchored to the physical root even if ordinary + // metadata/placement maintenance changes the originating workspace row. + await db.update(executionWorkspaces).set({ cwd: path.join(root, "moved-managed-workspace"), metadata: {} }).where(eq(executionWorkspaces.id, f.workspace.id)); + await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/); + } finally { release(); } + const [prepared] = await preparation; + expect(await readFile(path.join(prepared.cwd, "private.txt"), "utf8")).toBe("Private fixture bytes\n"); + await expect(executionWorkspaceRepositoryService(db).prepareForAdmission(peer.admission)).rejects.toThrow(/anonymous public URLs only/); + }); + it("retains previous run trust without confusing a board request's reassigned agent", async () => { const f = await fixture(); const [replacement] = await db.insert(agents).values({ companyId: f.companyId, name: "Replacement", adapterType: "process" }).returning(); @@ -189,6 +315,29 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(request()).rejects.toThrow(/anonymous public URLs only/); }); + it("preserves standard empty-inventory admission without repository mutation authority", async () => { + const f = await fixture(); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, f.companyId)); + await expect(f.service.prepareForAdmission(f.admission)).resolves.toEqual([]); + expect(acquisition.catalog).not.toHaveBeenCalled(); + expect(acquisition.materialize).not.toHaveBeenCalled(); + // Adding an acquisition still requires the full authorization intersection. + await db.insert(executionWorkspaceRepositories).values({ companyId: f.companyId, executionWorkspaceId: f.workspace.id, + requestedByIssueId: f.issueId, repositoryIdentity: "https://github.com/public/example", repoUrl: "https://github.com/public/example", + relativePath: ".paperclip-repositories/unused", requestedRef: "HEAD", requestKey: "requires-authority", requestKeys: ["requires-authority"] }); + await expect(f.service.prepareForAdmission(f.admission)).rejects.toThrow(); + expect(acquisition.materialize).not.toHaveBeenCalled(); + }); + + it("keeps low-trust empty-inventory admission free of acquisition-only filesystem and membership requirements", async () => { + const f = await fixture(); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, executionPolicy: f.policy } }).where(eq(heartbeatRuns.id, f.runId)); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, f.companyId)); + await expect(f.service.prepareForAdmission({ ...f.admission, cwd: path.join(root, "not-materialized") })).resolves.toEqual([]); + expect(acquisition.catalog).not.toHaveBeenCalled(); + expect(acquisition.materialize).not.toHaveBeenCalled(); + }); + it("rejects admission without the persisted task run before materialization", async () => { const f = await fixture(); await f.request({ kind: "catalog", id: "private-repo" }); diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts index 6bb0714865e..e561b4075bc 100644 --- a/server/src/services/execution-workspace-repositories.ts +++ b/server/src/services/execution-workspace-repositories.ts @@ -5,7 +5,7 @@ import fs from "node:fs/promises"; import { constants as fsConstants } from "node:fs"; import path from "node:path"; import { and, eq, isNotNull, or, sql } from "drizzle-orm"; -import { activityLog, agents, heartbeatRuns, projects, executionWorkspaceRepositories, executionWorkspaces, issues, type Db } from "@paperclipai/db"; +import { activityLog, agents, heartbeatRuns, projects, executionWorkspaceRepositoryRoots, executionWorkspaceRepositories, executionWorkspaces, issues, type Db } from "@paperclipai/db"; import { prepareWorkspaceRepositorySchema, type PrepareWorkspaceRepository, type ProjectRepository } from "@paperclipai/shared"; import { withDirectoryPublicationLock } from "@paperclipai/adapter-utils/workspace-restore-merge"; import { conflict, forbidden, notFound } from "../errors.js"; @@ -22,6 +22,18 @@ const execFile = promisify(execFileCallback); type RepositoryRow = typeof executionWorkspaceRepositories.$inferSelect; type DbTransaction = Parameters[0]>[0]; +/** Match physical aliases, including task directories not materialized yet. */ +async function canonicalRepositoryRoot(cwd: string): Promise { + const absolute = path.resolve(cwd); + try { return await fs.realpath(absolute); } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + const parent = path.dirname(absolute); + if (parent === absolute) throw error; + return path.join(await canonicalRepositoryRoot(parent), path.basename(absolute)); + } +} + const lowTrustRepositoryMessage = "Low-trust tasks may prepare anonymous public URLs only. Use an authorized configured source for private repositories."; function resolveAcquisitionSource(request: PrepareWorkspaceRepository["repository"], available: ProjectRepository[], anonymousOnly: boolean) { @@ -78,6 +90,37 @@ export function executionWorkspaceRepositoryService(db: Db) { if (trust.kind === "denied") throw forbidden(trust.detail); return trust.kind === "low_trust_review"; } + async function lockRootPolicies(tx: DbTransaction, companyId: string) { + // Acquire before task/workspace row locks. Hold only for policy and receipt + // transactions, never Git, provider execution, or snapshot capture. + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`task-repository-roots:${companyId}`}, 0))`); + } + async function reserveRootPolicy(tx: DbTransaction, companyId: string, cwd: string, mode: "anonymous_only" | "managed") { + const canonicalCwd = await canonicalRepositoryRoot(cwd); + const rootKey = createHash("sha256").update(canonicalCwd).digest("hex"); + const [existing] = await tx.select().from(executionWorkspaceRepositoryRoots).where(and( + eq(executionWorkspaceRepositoryRoots.companyId, companyId), eq(executionWorkspaceRepositoryRoots.rootKey, rootKey))); + if (existing && (existing.canonicalCwd !== canonicalCwd || existing.mode !== mode)) throw forbidden(lowTrustRepositoryMessage); + if (mode === "anonymous_only") { + // Legacy receipts predate root reservations. Even pending/staging work + // can publish after admission, so no managed intent in this root is safe. + const managed = await tx.select({ cwd: executionWorkspaces.cwd }).from(executionWorkspaceRepositories) + .innerJoin(executionWorkspaces, eq(executionWorkspaces.id, executionWorkspaceRepositories.executionWorkspaceId)) + .where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaces.companyId, companyId), + isNotNull(executionWorkspaceRepositories.catalogRepositoryId))); + for (const peer of managed) { + if (peer.cwd && await canonicalRepositoryRoot(peer.cwd) === canonicalCwd) throw forbidden(lowTrustRepositoryMessage); + } + } + if (!existing) await tx.insert(executionWorkspaceRepositoryRoots).values({ companyId, canonicalCwd, rootKey, mode }); + return canonicalCwd; + } + async function reserveAdmissionRoot(companyId: string, cwd: string, mode: "anonymous_only" | "managed") { + return db.transaction(async tx => { + await lockRootPolicies(tx, companyId); + return reserveRootPolicy(tx, companyId, cwd, mode); + }); + } async function request(input: { companyId: string; issueId: string; actor: AuthorizationActor; request: PrepareWorkspaceRepository }) { const parsed = prepareWorkspaceRepositorySchema.parse(input.request); const [requestedIssue] = await db.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), await issueReadSqlCondition(db, input.actor))); @@ -100,6 +143,7 @@ export function executionWorkspaceRepositoryService(db: Db) { const available = await catalog(input.companyId, userId, localTrusted); const requestedRef = parsed.ref ?? "HEAD"; const receipt = await db.transaction(async tx => { + await lockRootPolicies(tx, input.companyId); const [issue] = await tx.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), await issueReadSqlCondition(tx, input.actor))).for("no key update"); if (!issue) throw notFound("Task not found"); const currentDecision = await authorizationService(tx).decide({ actor: input.actor, action: "issue:mutate", resource: issueResource(issue) }); @@ -114,6 +158,10 @@ export function executionWorkspaceRepositoryService(db: Db) { const anonymousOnly = await requiresAnonymousAcquisition(tx, { issue, workspace, agentId: input.actor.agentId, runId: input.actor.runId }); const source = resolveAcquisitionSource(parsed.repository, available, anonymousOnly); + if (anonymousOnly || source.catalogRepositoryId) { + if (!workspace.cwd) throw conflict("The task workspace has no directory for repository preparation"); + await reserveRootPolicy(tx, input.companyId, workspace.cwd, anonymousOnly ? "anonymous_only" : "managed"); + } const existing = await tx.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.executionWorkspaceId, workspace.id), or(eq(executionWorkspaceRepositories.repositoryIdentity, source.repositoryIdentity), sql`${executionWorkspaceRepositories.requestKeys} ? ${parsed.requestKey}`))); for (const row of existing) { assertAcquisitionReceipt(row, anonymousOnly); @@ -137,6 +185,17 @@ export function executionWorkspaceRepositoryService(db: Db) { async function list(companyId: string, workspaceId: string) { return db.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId))); } + /** Recovery keeps its admitted identity and folder; only fence future publication. */ + async function reserveForRecovery(input: { companyId: string; issueId: string; workspaceId: string; cwd: string; agentId: string; runId: string }) { + const [issue] = await db.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))); + const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, input.companyId))); + if (!issue || !workspace) throw forbidden("Task repository recovery identity is unavailable"); + const anonymousOnly = await requiresAnonymousAcquisition(db, { issue, workspace, agentId: input.agentId, runId: input.runId }); + if (anonymousOnly) await reserveAdmissionRoot(input.companyId, input.cwd, "anonymous_only"); + else if ((await list(input.companyId, input.workspaceId)).some(row => row.catalogRepositoryId)) { + await reserveAdmissionRoot(input.companyId, input.cwd, "managed"); + } + } /** Logical rows may deliberately name one physical folder. Reuse bytes only * after validating every published owner's retained privacy and source intent. */ async function sharedPublicationPin(input: { issueId: string; row: RepositoryRow; root: string; actor: AuthorizationActor; anonymousOnly: boolean; ownership: { repositoryId?: string; pinnedCommit?: string } | null }) { @@ -160,21 +219,6 @@ export function executionWorkspaceRepositoryService(db: Db) { } return pin; } - async function assertAnonymousPhysicalRoot(companyId: string, root: string) { - const publications = await db.select({ repository: executionWorkspaceRepositories, cwd: executionWorkspaces.cwd }) - .from(executionWorkspaceRepositories).innerJoin(executionWorkspaces, eq(executionWorkspaces.id, executionWorkspaceRepositories.executionWorkspaceId)) - .where(and(eq(executionWorkspaceRepositories.companyId, companyId), eq(executionWorkspaces.companyId, companyId), - isNotNull(executionWorkspaceRepositories.catalogRepositoryId))); - for (const { repository, cwd } of publications) { - if (!cwd || await fs.realpath(cwd).catch(() => null) !== root) continue; - if (repository.relativePath !== taskRepositoryRelativePath(repository.repositoryIdentity)) throw conflict("Repository preparation receipt does not match its source"); - // Include an interrupted publication whose database pin was not saved yet. - // Even another repository's files would be included in the root snapshot. - if (repository.pinnedCommit || await fs.lstat(path.join(root, repository.relativePath)).catch(() => null)) { - throw forbidden(lowTrustRepositoryMessage); - } - } - } async function prepareForAdmission(input: { companyId: string; issueId: string; workspaceId: string; cwd: string; agentId: string; runId: string; responsibleUserId: string | null }) { const rows = await list(input.companyId, input.workspaceId); const actor: AuthorizationActor = { type: "agent", source: "agent_jwt", companyId: input.companyId, @@ -182,14 +226,17 @@ export function executionWorkspaceRepositoryService(db: Db) { // local-board is a server identity, not a membership record. Preserve the // agent's own authority rather than promoting it to a board actor. onBehalfOfUserId: input.responsibleUserId === "local-board" ? null : input.responsibleUserId }; - await assertTaskWorkspaceAccess(db, actor, input.companyId, input.workspaceId, { write: true, issueId: input.issueId }); const [issue] = await db.select().from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))); const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, input.companyId))); if (!issue || !workspace || issue.executionWorkspaceId !== workspace.id) throw forbidden("Task repository workspace binding is unavailable"); const anonymousOnly = await requiresAnonymousAcquisition(db, { issue, workspace, agentId: input.agentId, runId: input.runId }); + // Ordinary admission without acquisitions is owned by heartbeat, not this mutation service. + if (!rows.length) { + if (anonymousOnly) await reserveAdmissionRoot(input.companyId, input.cwd, "anonymous_only"); + return []; + } + await assertTaskWorkspaceAccess(db, actor, input.companyId, input.workspaceId, { write: true, issueId: input.issueId }); const root = await fs.realpath(input.cwd); - if (anonymousOnly) await assertAnonymousPhysicalRoot(input.companyId, root); - if (!rows.length) return []; const available = anonymousOnly ? [] : await catalog(input.companyId, input.responsibleUserId, input.responsibleUserId === "local-board"); const resolveAuth = createGitRemoteAuthProvider(db, input.companyId, { issueId: input.issueId, heartbeatRunId: input.runId, agentId: input.agentId, responsibleUserId: input.responsibleUserId }); // Validate every receipt before reading or transferring any prepared bytes. @@ -197,6 +244,10 @@ export function executionWorkspaceRepositoryService(db: Db) { assertAcquisitionReceipt(row, anonymousOnly); return resolveAcquisitionSource(row.catalogRepositoryId ? { kind: "catalog", id: row.catalogRepositoryId } : { kind: "url", url: row.repoUrl }, available, anonymousOnly); }); + if (anonymousOnly || sources.some(source => source.catalogRepositoryId)) { + const reservedRoot = await reserveAdmissionRoot(input.companyId, root, anonymousOnly ? "anonymous_only" : "managed"); + if (reservedRoot !== root) throw conflict("Repository workspace root changed during admission"); + } const repositoryRoot = path.join(root, ".paperclip-repositories"); await fs.mkdir(repositoryRoot, { recursive: true }); if ((await fs.lstat(repositoryRoot)).isSymbolicLink() || await fs.realpath(repositoryRoot) !== repositoryRoot) throw conflict("Repository directory escapes the task workspace"); @@ -293,5 +344,5 @@ export function executionWorkspaceRepositoryService(db: Db) { } return prepared; } - return { request, list, prepareForAdmission }; + return { request, list, prepareForAdmission, reserveForRecovery }; } diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 1e27ed25b64..507cc01b375 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -2153,6 +2153,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic requestTaskRepository: executionWorkspaceRepositoryService(db).request, listTaskRepositories: executionWorkspaceRepositoryService(db).list, prepareTaskRepositoriesForAdmission: executionWorkspaceRepositoryService(db).prepareForAdmission, + reserveTaskRepositoryRootForRecovery: executionWorkspaceRepositoryService(db).reserveForRecovery, resolveSourceWorkspaceStrategy, validateSelection, inspectTaskWorkspace, selectTaskWorkspace, applyPendingTaskWorkspaceSelection, bindTaskWorkspace, prepareTaskWorkspaceUpdate, assertTaskWorkspaceUpdateAccess, listOverview: async ( companyId: string, diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts index df8db77dc52..abb5afa2511 100644 --- a/server/src/services/heartbeat/workspace-preparation.test.ts +++ b/server/src/services/heartbeat/workspace-preparation.test.ts @@ -3,6 +3,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile, access } from "node:fs/promise import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; +import { captureDirectorySnapshot, directorySnapshotSha256, serializeDirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge"; import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, heartbeatRuns, issues, projects, projectWorkspaces, type Db } from "@paperclipai/db"; import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; @@ -12,6 +13,7 @@ import { environmentService } from "../environments.js"; import { executionWorkspaceService } from "../execution-workspaces.js"; import { instanceSettingsService } from "../instance-settings.js"; import { workspaceOperationService } from "../workspace-operations.js"; +import { nativeWorkspaceSyncInternals } from "../native-runtime/native-workspace-sync.js"; import { createHeartbeatWorkspaceResolver, resolveExecutionWorkspaceReuseRequestForIssue } from "./workspaces.js"; import { prepareHeartbeatWorkspace, type HeartbeatWorkspacePreparationInput } from "./workspace-preparation.js"; @@ -156,12 +158,60 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary", input.task.issueRef = { ...input.task.issueRef!, executionWorkspaceId: null, projectWorkspaceId: null }; input.reuse.nativeRecoveryExecutionWorkspaceId = first.persistedExecutionWorkspace!.id; const anchor = vi.spyOn(input.services, "resolveReusedGitWorkspaceAnchor"); + const prepareRepositories = vi.spyOn(input.services.executionWorkspacesSvc, "prepareTaskRepositoriesForAdmission"); + const reserveRoot = vi.spyOn(input.services.executionWorkspacesSvc, "reserveTaskRepositoryRootForRecovery"); + const acquire = input.services.envOrchestrator.acquireForRun; + vi.spyOn(input.services.envOrchestrator, "acquireForRun").mockImplementation(async args => { + expect(reserveRoot).toHaveBeenCalledWith({ companyId: issue.companyId, issueId: issue.id, + workspaceId: first.persistedExecutionWorkspace!.id, cwd: first.executionWorkspace.cwd, + agentId: input.agent.id, runId: input.run.id }); + return acquire(args); + }); const next = await prepareHeartbeatWorkspace(db, input); + expect(prepareRepositories).not.toHaveBeenCalled(); expect(next.persistedExecutionWorkspace!.id).toBe(first.persistedExecutionWorkspace!.id); expect(anchor).toHaveBeenCalledWith(expect.objectContaining({ immutableNativeBinding: true, explicitProjectWorkspaceId: first.persistedExecutionWorkspace!.projectWorkspaceId })); expect(await readIssue(issue.id)).toMatchObject({ executionWorkspaceId: null, projectWorkspaceId: null }); }); + it.each([false, true])("requires the immutable host descriptor for remote recovery (present=%s)", async present => { + const { input, issue } = await fixture(true); + const first = await prepareHeartbeatWorkspace(db, input); + await reuse(input, first.persistedExecutionWorkspace!); + await db.update(issues).set({ executionWorkspaceId: null, projectWorkspaceId: null }).where(eq(issues.id, issue.id)); + input.task.issueRef = { ...input.task.issueRef!, executionWorkspaceId: null, projectWorkspaceId: null }; + input.reuse.nativeRecoveryExecutionWorkspaceId = first.persistedExecutionWorkspace!.id; + input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "ssh" }; + const admittedRoot = join(home, `admitted-${input.run.id}`); + await mkdir(admittedRoot); + if (present) { + const baseline = await captureDirectorySnapshot(admittedRoot); + const reference = await nativeWorkspaceSyncInternals.writeDescriptor({ + schema: "paperclip.native-workspace-sync/v1", state: "prepared", + binding: { companyId: issue.companyId, runId: input.run.id, workspaceId: first.persistedExecutionWorkspace!.id, + leaseId: "admitted-lease", providerLeaseId: "admitted-provider", localCwd: admittedRoot, remoteCwd: "/workspace" }, + baseline: serializeDirectorySnapshot(baseline), baselineSha256: directorySnapshotSha256(baseline), + gitSnapshot: null, seed: null, createdAt: new Date().toISOString(), finalizedAt: null, finalHostSha256: null, resourceDisposition: null, + }); + input.run.runnerProfileJson = { nativeWorkspaceSync: reference }; + } + const reserve = vi.spyOn(input.services.executionWorkspacesSvc, "reserveTaskRepositoryRootForRecovery"); + const prepare = vi.spyOn(input.services.executionWorkspacesSvc, "prepareTaskRepositoriesForAdmission"); + const acquire = vi.spyOn(input.services.envOrchestrator, "acquireForRun"); + if (present) { + await prepareHeartbeatWorkspace(db, input); + expect(reserve).toHaveBeenCalledWith({ companyId: issue.companyId, issueId: issue.id, + workspaceId: first.persistedExecutionWorkspace!.id, cwd: admittedRoot, agentId: input.agent.id, runId: input.run.id }); + expect(admittedRoot).not.toBe(first.executionWorkspace.cwd); + } else { + await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow("native_workspace_sync_descriptor_binding_missing"); + expect(reserve).not.toHaveBeenCalled(); + expect(acquire).not.toHaveBeenCalled(); + } + expect(prepare).not.toHaveBeenCalled(); + expect((await readIssue(issue.id)).executionWorkspaceId).toBeNull(); + }); + it("removes a newly created worktree when persistence fails and preserves the original error", async () => { const { input, source } = await fixture(true); const error = new Error("workspace persistence unavailable"); diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts index fc5c1b59585..7dc493cccf1 100644 --- a/server/src/services/heartbeat/workspace-preparation.ts +++ b/server/src/services/heartbeat/workspace-preparation.ts @@ -24,7 +24,7 @@ import { createHostDuplexObservabilityRecorder } from "../duplex-observability-r import { incrementToolRuntimeMetricCounter } from "../tool-runtime-metrics.js"; import { logger } from "../../middleware/logger.js"; import { createGitRemoteAuthProvider } from "../git-credentials.js"; -import { readNativeWorkspaceSyncReference } from "../native-runtime/index.js"; +import { readNativeWorkspaceSyncReference, readNativeWorkspaceSyncLocalCwd } from "../native-runtime/index.js"; import { parseObject } from "../../adapters/utils.js"; import { materializeNativeChatTaskRoot } from "../native-runtime/native-chat-workspace.js"; import { materializeIsolatedTaskDirectory } from "../isolated-task-directory.js"; @@ -126,7 +126,7 @@ export interface HeartbeatWorkspacePreparationInput { }; services: { envOrchestrator: Pick, "resolveEnvironment" | "acquireForRun" | "realizeForRun">; - executionWorkspacesSvc: Pick, "create" | "update" | "bindTaskWorkspace" | "prepareTaskRepositoriesForAdmission">; + executionWorkspacesSvc: Pick, "create" | "update" | "bindTaskWorkspace" | "prepareTaskRepositoriesForAdmission" | "reserveTaskRepositoryRootForRecovery">; workspaceOperationsSvc: Pick, "createRecorder">; resolveWorkspaceForRun: WorkspaceResolver["resolveWorkspaceForRun"]; resolveReusedGitWorkspaceAnchor: WorkspaceResolver["resolveReusedGitWorkspaceAnchor"]; @@ -885,12 +885,29 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspac repoRef: readNonEmptyString(source.repoRef), })); } - if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput) { + if (persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) { const taskRepositories = await executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId, issueId, workspaceId: persistedExecutionWorkspace.id, cwd: executionWorkspace.cwd, agentId: agent.id, runId: run.id, responsibleUserId }); projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath)); } + if (!isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)) { + const workspaceId = persistedNativeExecutionInput?.binding.executionWorkspaceId ?? nativeRecoveryExecutionWorkspaceId!; + const reference = readNativeWorkspaceSyncReference(parseObject(run.runnerProfileJson).nativeWorkspaceSync); + if (!reference && selectedEnvironmentForConfig?.driver !== "local") { + throw new Error("native_workspace_sync_descriptor_binding_missing"); + } + // Recovery keeps admitted files and trust even when the task now selects + // another workspace. Reserve only; never acquire newly requested repositories. + const cwd = reference + ? await readNativeWorkspaceSyncLocalCwd({ companyId: agent.companyId, runId: run.id, workspaceId, reference }) + : persistedNativeExecutionInput && persistedNativeExecutionInput.schema !== "paperclip.native-execution-input.v6" + && selectedEnvironmentForConfig?.driver === "local" + ? persistedNativeExecutionInput.workspace.cwd + : executionWorkspace.cwd; + await executionWorkspacesSvc.reserveTaskRepositoryRootForRecovery({ companyId: agent.companyId, + issueId, workspaceId, cwd, agentId: agent.id, runId: run.id }); + } if (persistedExecutionWorkspace) { context.executionWorkspaceId = persistedExecutionWorkspace.id; await db diff --git a/server/src/services/native-runtime/native-workspace-sync.ts b/server/src/services/native-runtime/native-workspace-sync.ts index f935ce0e35d..acad5392af6 100644 --- a/server/src/services/native-runtime/native-workspace-sync.ts +++ b/server/src/services/native-runtime/native-workspace-sync.ts @@ -1091,6 +1091,29 @@ export async function prepareNativeWorkspaceSync(input: { } } +/** Read the admitted host root without reacquiring or transferring workspace files. */ +export async function readNativeWorkspaceSyncLocalCwd(input: { + companyId: string; + runId: string; + workspaceId: string; + reference: NativeWorkspaceSyncReference; +}): Promise { + const existing = await readDescriptor(input); + try { + if (existing.descriptor.binding.companyId !== input.companyId || + existing.descriptor.binding.workspaceId !== input.workspaceId) { + throw new Error("native_workspace_sync_descriptor_binding_mismatch"); + } + return existing.descriptor.binding.localCwd; + } finally { + await disposeDirectorySnapshot(existing.baseline); + await disposeGitWorkspaceSnapshot(existing.descriptor.gitSnapshot); + for (const repository of existing.descriptor.repositories ?? []) { + await disposeGitWorkspaceSnapshot(repository.snapshot); + } + } +} + export async function resumeNativeWorkspaceSync(input: { db: Db; runId: string;