diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index 8305fafe8eb..e601ab361cd 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -1569,7 +1569,13 @@ sizes and hashes stay. A step that cannot confirm its deletion fails, and the request stays pending and retries; it completes only when every step succeeded. A `tool_connection_content_deletions` row is the durable request; the `tool-connection-content-deletion` delivery queue resumes it after a restart. -Runs that are still working are skipped and counted. The user-facing help is +Runs that are still working are skipped and counted. Deleting a task queues an +`issue_connection_content_deletions` row that runs the same steps for the +task's runs and waits, for up to a day, for runs and approvals still open. Deleting a company queues its run +logs and files in `stored_object_deletions`, which outlives the company. A new +store that keeps connection content must be covered by all three paths; +`tool-connection-content-deletion-canary.test.ts` scans every text column and +every storage copy after each one. The user-facing help is `docs/guides/board-operator/deleting-connection-data.md`. Responses may contain secret IDs, version selectors, header names, prefixes, diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index a2766023916..4cb85ab50d0 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -133,7 +133,8 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). 4. Switch services to REST one at a time, each after its live test. 5. Revoke at Google when the last connection is removed. 6. Security scans. -7. Run the same data cleanup when a task or a company is deleted. +7. Request revocation at Google when a company with Google connections is + deleted. ## Environments @@ -284,21 +285,36 @@ From #22010's store inventory. The earlier audit understated it: it missed the second audit table, approval cards, results passed to later runs, app views, nested run answers and migrated log originals. -| Place | What is kept | Removed by "Delete data" | -| --- | --- | --- | -| Tool-call records (`tool_invocations`, `tool_call_events`) | About 4,000 characters of each request and result | Yes. Size and fingerprint kept. | -| Connection audit history (`tool_access_audit_events`) | Argument preview | Yes. Decision, IDs, size and fingerprint kept. | -| Approval requests and their approval cards in the task | Preview, arguments and the executed result | Yes, for settled requests. | -| Results passed to a later run (run context and wake payload) | Approved action results | Yes, for settled runs and wakes. | -| App views | Tool input, result and shared context | Yes, rows deleted. | -| Run transcripts: the run log in every copy (object journal, archive, original local file and its S3 mirror), run events, output excerpts and answer text at any depth of the run result | Full content | Yes, the whole transcript of every settled run that called the connection or received an approved result. | -| Comments, documents, files and chat messages agents wrote into tasks | Whatever the agent copied | No, by design. The user edits or deletes them, or the task. | -| Transcripts of later runs that read an app view's shared context | Shared context | No. Nothing records which runs read it. | -| Questions a provider asked a person; provider tool and skill definitions | Not tool results | No. | -| Raw provider traces | Full traffic | No. Admin opt-in, encrypted, expire within 24 hours. | -| Feedback exports already sent | Run logs the user chose to share | No. Already outside Paperclip. | -| Optional model check for injection screening | If a company turns it on, the full tool result is sent to an OpenRouter model | Not stored by Paperclip. | -| Connection removal | Deletes tokens locally | Asks Paperclip Cloud to revoke at Google; it does so only when no other connection could share the grant. Customer-owned clients stay local. | +| Place | What is kept | Removed by "Delete data" | Task deleted | Company deleted | +| --- | --- | --- | --- | --- | +| Tool-call records (`tool_invocations`, `tool_call_events`) | About 4,000 characters of each request and result | Yes. Size and fingerprint kept. | Yes, cleared like "Delete data" | Yes, rows deleted | +| Connection audit history (`tool_access_audit_events`) | Argument preview | Yes. Decision, IDs, size and fingerprint kept. | Yes, for the task's runs | Yes, rows deleted | +| Approval requests and their approval cards in the task | Preview, arguments and the executed result | Yes, for settled requests. | Yes. Cards are deleted with the task; requests are cleared. | Yes, rows deleted | +| Results passed to a later run (run context and wake payload) | Approved action results | Yes, for settled runs and wakes. | Yes | Yes, rows deleted | +| App views | Tool input, result and shared context | Yes, rows deleted. | Yes, rows deleted | Yes, rows deleted | +| Run transcripts: the run log in every copy (object journal, archive, original local file and its S3 mirror), run events, output excerpts and answer text at any depth of the run result | Full content | Yes, the whole transcript of every settled run that called the connection or received an approved result. | Yes, for each of the task's runs that called a connection or received an approved result. The runs themselves stay. | Yes. Rows deleted, then every run log is removed from storage in the background. | +| Saved tool results over 500,000 bytes (`runner-api` files and their asset rows) | Full result | Yes, for the runs whose transcript is deleted. Files attached to a task stay. | Yes, for those runs | Yes, file and row | +| Comments, documents and attached files agents wrote into tasks | Whatever the agent copied | No, by design. The user edits or deletes them, or the task. | Yes. Attached files are also removed from storage, and retried until it succeeds. | Yes. Every company file is removed from storage in the background. | +| Transcripts of later runs that read an app view's shared context | Shared context | No. Nothing records which runs read it. | Only when the run belongs to the deleted task | Yes | +| Questions a provider asked a person; provider tool and skill definitions | Not tool results | No. | Not changed | Yes, rows deleted | +| Raw provider traces | Full traffic | No. Admin opt-in, encrypted, expire within 24 hours. | No | No, they expire | +| Feedback exports already sent | Run logs the user chose to share | No. Already outside Paperclip. | No | No | +| Optional model check for injection screening | If a company turns it on, the full tool result is sent to an OpenRouter model | Not stored by Paperclip. | Not stored | Not stored | +| Connection removal | Deletes tokens locally | Asks Paperclip Cloud to revoke at Google; it does so only when no other connection could share the grant. Customer-owned clients stay local. | Not changed | Connections are deleted locally; revocation at Google is not requested | + +Task and company deletion are hard deletes. A task deletion queues an +`issue_connection_content_deletions` job that records the task's runs +(including runs still working), calls and call events, including calls made +without a run, before the task row goes, and runs the same steps as "Delete data". It +waits for runs and approvals that are still open, rechecking every one to +five minutes for up to a day, and then finishes on its own. It writes +`issue.connection_content_deleted` only when it deleted something, and +`issue.connection_content_deletion_incomplete` when it stopped waiting with +items still open. The ledger lives in `stored-object-deletion.ts` and the task +request in `issue-content-deletion.ts`. A company +deletion records every run log and file in `stored_object_deletions`, which has +no foreign key to the company, so the background removal outlives the company. +Both are covered by `tool-connection-content-deletion-canary.test.ts`. What "Delete data" keeps: the record that each call happened (time, tool, agent, outcome, size, fingerprint), and activity entries with counts only. @@ -307,7 +323,6 @@ Limits: - Runs still in progress are skipped and counted; delete again after they finish. -- Deleting a task or a company does not yet run the same cleanup. - A local log file on another server's disk stays until that server is replaced; its S3 mirror is deleted. - On versioned buckets, earlier object versions stay until the bucket's diff --git a/doc/plans/2026-11-17-google-workspace-code-fixes.md b/doc/plans/2026-11-17-google-workspace-code-fixes.md index 12e81e5cf3e..3c1a1dc698b 100644 --- a/doc/plans/2026-11-17-google-workspace-code-fixes.md +++ b/doc/plans/2026-11-17-google-workspace-code-fixes.md @@ -165,9 +165,10 @@ reasoning mostly goes away, and reviewers expect disconnect to end access. Any connection's page has "Delete data", and removing a connection offers the same. It clears previews, approval cards, results passed to later runs, app views and the whole transcript of each settled run that used the connection. -It keeps call records without content. Limits: content agents wrote into -tasks stays; deleting a task or a company does not yet run the same cleanup; -runs in progress are skipped. The help page is +It keeps call records without content. Deleting a task or a company runs +the same cleanup, including run logs and saved files in storage. Limits: +content agents wrote into tasks stays until the task is deleted; "Delete data" +skips runs in progress. The help page is `docs/guides/board-operator/deleting-connection-data.md`. The inventory is in the working memory under "Where Google content is kept". Revoking at Google is fix 5. The plan below is kept for reference. diff --git a/doc/plans/2026-11-17-google-workspace-production-checklist.md b/doc/plans/2026-11-17-google-workspace-production-checklist.md index d3959172fec..a6c7bd8c35e 100644 --- a/doc/plans/2026-11-17-google-workspace-production-checklist.md +++ b/doc/plans/2026-11-17-google-workspace-production-checklist.md @@ -77,8 +77,8 @@ Decisions and the details behind them are kept in the (Nov 17, [#22010](https://github.com/paperclipai/paperclip/pull/22010) store inventory; summary in the working memory's "Where Google content is kept"). Users can now delete it per connection. Content agents wrote - into tasks stays, and task or company deletion does not yet run the same - cleanup. + into tasks stays until the task is deleted. Task and company deletion + run the same cleanup, including run logs and saved files in storage. - [x] REST-backed tool set for all 36 actions exists but is not switched on (Nov 17): Gmail 9 ([#22000](https://github.com/paperclipai/paperclip/pull/22000), diff --git a/docs/guides/board-operator/deleting-connection-data.md b/docs/guides/board-operator/deleting-connection-data.md index 5c431ce9e9a..87696b62a5f 100644 --- a/docs/guides/board-operator/deleting-connection-data.md +++ b/docs/guides/board-operator/deleting-connection-data.md @@ -42,6 +42,7 @@ Deletion starts right away and continues in the background. It finishes even if - Approval previews, arguments and results for those calls, on the approval card and in what was passed back to the agent - Interactive app views from those calls - The whole transcript of every run that called the connection or received an approved action's result, including that run's other steps and its final summary +- Tool results too large to pass to the agent directly, which Paperclip saved as files for those runs ## What is kept @@ -51,6 +52,12 @@ Deletion starts right away and continues in the background. It finishes even if - Transcripts of later runs that only read the context an interactive app view shared. Paperclip does not record which runs read it. Delete those tasks if you need that text gone. - Raw provider traces. An administrator must turn them on, and they expire on their own within 24 hours. +## Deleting a task or a company + +Deleting a task also deletes this data for the task's runs, from every connected app. Comments, documents and files in the task are deleted with it, including the files in storage. If a run of the task is still working, or an approval for it is still open, Paperclip waits for up to a day and then deletes the data on its own. After a day, it stops waiting and leaves what is still open. + +Deleting a company deletes all of its data, including run transcripts and files in storage. Storage clean-up continues in the background after the company is gone, and Paperclip retries it until it succeeds. + ## Runs that are still working Paperclip does not change a run while it is still working. The confirmation tells you how many runs are skipped for this reason. Select **Delete data** again after they finish. diff --git a/packages/db/src/migrations/0501_charming_living_lightning.sql b/packages/db/src/migrations/0501_charming_living_lightning.sql new file mode 100644 index 00000000000..315b86170cb --- /dev/null +++ b/packages/db/src/migrations/0501_charming_living_lightning.sql @@ -0,0 +1,35 @@ +CREATE TABLE "issue_connection_content_deletions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "issue_id" uuid NOT NULL, + "scope" jsonb NOT NULL, + "status" text DEFAULT 'pending' NOT NULL, + "requested_by_actor_type" text NOT NULL, + "requested_by_actor_id" text, + "requested_at" timestamp with time zone DEFAULT now() NOT NULL, + "progress" jsonb DEFAULT '{}'::jsonb NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "last_error" text, + "not_before" timestamp with time zone DEFAULT now() NOT NULL, + "completed_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "stored_object_deletions" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL, + "kind" text NOT NULL, + "log_store" text, + "object_key" text NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "last_error" text, + "not_before" timestamp with time zone DEFAULT now() NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "issue_connection_content_deletions" ADD CONSTRAINT "issue_connection_content_deletions_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "issue_connection_content_deletions_issue_idx" ON "issue_connection_content_deletions" USING btree ("company_id","issue_id");--> statement-breakpoint +CREATE INDEX "issue_connection_content_deletions_pending_idx" ON "issue_connection_content_deletions" USING btree ("not_before") WHERE "issue_connection_content_deletions"."status" = 'pending';--> statement-breakpoint +CREATE INDEX "stored_object_deletions_due_idx" ON "stored_object_deletions" USING btree ("not_before","id");--> statement-breakpoint +CREATE INDEX "stored_object_deletions_company_idx" ON "stored_object_deletions" USING btree ("company_id"); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0491_snapshot.json b/packages/db/src/migrations/meta/0501_snapshot.json similarity index 96% rename from packages/db/src/migrations/meta/0491_snapshot.json rename to packages/db/src/migrations/meta/0501_snapshot.json index d5540a0635a..21bf4afaa90 100644 --- a/packages/db/src/migrations/meta/0491_snapshot.json +++ b/packages/db/src/migrations/meta/0501_snapshot.json @@ -1,6 +1,6 @@ { - "id": "82234354-6a19-4132-ae58-f545f798bbb7", - "prevId": "a8bc890a-cc97-4b54-b426-5687b134a8b0", + "id": "62fdf61f-883c-4e82-a4ab-4311ff6d39e5", + "prevId": "51525362-c4bc-44be-b4a7-95cb4aae7748", "version": "7", "dialect": "postgresql", "tables": { @@ -428,6 +428,12 @@ "primaryKey": false, "notNull": false }, + "responsibility_summary_invocation_id": { + "name": "responsibility_summary_invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "agent_id": { "name": "agent_id", "type": "uuid", @@ -537,6 +543,27 @@ "method": "btree", "with": {} }, + "budget_reservations_responsibility_summary_idx": { + "name": "budget_reservations_responsibility_summary_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "responsibility_summary_invocation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, "budget_reservations_run_idx": { "name": "budget_reservations_run_idx", "columns": [ @@ -634,7 +661,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 + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int + (\"budget_reservations\".\"prompt_injection_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 + (\"budget_reservations\".\"prompt_injection_invocation_id\" is not null)::int + (\"budget_reservations\".\"responsibility_summary_invocation_id\" is not null)::int = 1" }, "budget_reservations_state_check": { "name": "budget_reservations_state_check", @@ -21928,6 +21955,153 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_workload_identity_keys": { + "name": "company_workload_identity_keys", + "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 + }, + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "algorithm": { + "name": "algorithm", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_jwk": { + "name": "public_jwk", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "private_key_material": { + "name": "private_key_material", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status_changed_at": { + "name": "status_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_workload_identity_keys_company_key_uq": { + "name": "company_workload_identity_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "key_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_active_uq": { + "name": "company_workload_identity_keys_one_active_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'active'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "company_workload_identity_keys_one_next_uq": { + "name": "company_workload_identity_keys_one_next_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"company_workload_identity_keys\".\"status\" = 'next'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_workload_identity_keys_company_id_companies_id_fk": { + "name": "company_workload_identity_keys_company_id_companies_id_fk", + "tableFrom": "company_workload_identity_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_workload_identity_keys_algorithm_check": { + "name": "company_workload_identity_keys_algorithm_check", + "value": "\"company_workload_identity_keys\".\"algorithm\" = 'ES256'" + }, + "company_workload_identity_keys_status_check": { + "name": "company_workload_identity_keys_status_check", + "value": "\"company_workload_identity_keys\".\"status\" in ('next', 'active', 'retiring', 'retired')" + } + }, + "isRLSEnabled": false + }, "public.completion_contracts": { "name": "completion_contracts", "schema": "", @@ -23092,7 +23266,7 @@ "checkConstraints": { "cost_events_usage_kind_check": { "name": "cost_events_usage_kind_check", - "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response', 'prompt_injection') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" + "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response', 'prompt_injection', 'responsibility_summary') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)" }, "cost_events_nonnegative_amounts": { "name": "cost_events_nonnegative_amounts", @@ -38896,6 +39070,169 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_connection_content_deletions": { + "name": "issue_connection_content_deletions", + "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 + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "requested_by_actor_type": { + "name": "requested_by_actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_by_actor_id": { + "name": "requested_by_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_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": { + "issue_connection_content_deletions_issue_idx": { + "name": "issue_connection_content_deletions_issue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issue_connection_content_deletions_pending_idx": { + "name": "issue_connection_content_deletions_pending_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issue_connection_content_deletions\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_connection_content_deletions_company_id_companies_id_fk": { + "name": "issue_connection_content_deletions_company_id_companies_id_fk", + "tableFrom": "issue_connection_content_deletions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_create_idempotency_keys": { "name": "issue_create_idempotency_keys", "schema": "", @@ -52317,6 +52654,1492 @@ }, "isRLSEnabled": false }, + "public.responsibilities": { + "name": "responsibilities", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "area_id": { + "name": "area_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "standard": { + "name": "standard", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_kind": { + "name": "metric_kind", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_name": { + "name": "metric_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_unit": { + "name": "metric_unit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metric_target": { + "name": "metric_target", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_low": { + "name": "metric_low", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_high": { + "name": "metric_high", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_current": { + "name": "metric_current", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "metric_direction": { + "name": "metric_direction", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'at_least'" + }, + "metric_updated_at": { + "name": "metric_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "run_by_agent_id": { + "name": "run_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "evidence": { + "name": "evidence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "health_override": { + "name": "health_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "health_note": { + "name": "health_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "proposed_by_agent_id": { + "name": "proposed_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "confirmed_at": { + "name": "confirmed_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": { + "responsibilities_company_owner_status_idx": { + "name": "responsibilities_company_owner_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibilities_area_idx": { + "name": "responsibilities_area_idx", + "columns": [ + { + "expression": "area_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibilities_company_id_companies_id_fk": { + "name": "responsibilities_company_id_companies_id_fk", + "tableFrom": "responsibilities", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibilities_area_id_responsibility_areas_id_fk": { + "name": "responsibilities_area_id_responsibility_areas_id_fk", + "tableFrom": "responsibilities", + "tableTo": "responsibility_areas", + "columnsFrom": [ + "area_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_run_by_agent_id_agents_id_fk": { + "name": "responsibilities_run_by_agent_id_agents_id_fk", + "tableFrom": "responsibilities", + "tableTo": "agents", + "columnsFrom": [ + "run_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_proposed_by_agent_id_agents_id_fk": { + "name": "responsibilities_proposed_by_agent_id_agents_id_fk", + "tableFrom": "responsibilities", + "tableTo": "agents", + "columnsFrom": [ + "proposed_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibilities_owned_area_fk": { + "name": "responsibilities_owned_area_fk", + "tableFrom": "responsibilities", + "tableTo": "responsibility_areas", + "columnsFrom": [ + "company_id", + "owner_user_id", + "area_id" + ], + "columnsTo": [ + "company_id", + "owner_user_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibilities_status_check": { + "name": "responsibilities_status_check", + "value": "\"responsibilities\".\"status\" in ('proposed', 'active', 'let_go', 'dismissed')" + }, + "responsibilities_source_check": { + "name": "responsibilities_source_check", + "value": "\"responsibilities\".\"source\" in ('manual', 'onboarding')" + }, + "responsibilities_health_override_check": { + "name": "responsibilities_health_override_check", + "value": "\"responsibilities\".\"health_override\" is null or \"responsibilities\".\"health_override\" in ('behind', 'at_risk', 'on_track')" + }, + "responsibilities_metric_direction_check": { + "name": "responsibilities_metric_direction_check", + "value": "\"responsibilities\".\"metric_direction\" is null or \"responsibilities\".\"metric_direction\" in ('at_least', 'at_most')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_areas": { + "name": "responsibility_areas", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "proposed_by_agent_id": { + "name": "proposed_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "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": { + "responsibility_areas_company_status_idx": { + "name": "responsibility_areas_company_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_areas_identity_uq": { + "name": "responsibility_areas_identity_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_areas_owner_title_uq": { + "name": "responsibility_areas_owner_title_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"title\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_areas\".\"status\" <> 'archived'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_areas_company_id_companies_id_fk": { + "name": "responsibility_areas_company_id_companies_id_fk", + "tableFrom": "responsibility_areas", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_areas_proposed_by_agent_id_agents_id_fk": { + "name": "responsibility_areas_proposed_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_areas", + "tableTo": "agents", + "columnsFrom": [ + "proposed_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_areas_status_check": { + "name": "responsibility_areas_status_check", + "value": "\"responsibility_areas\".\"status\" in ('proposed', 'active', 'archived')" + }, + "responsibility_areas_source_check": { + "name": "responsibility_areas_source_check", + "value": "\"responsibility_areas\".\"source\" in ('manual', 'onboarding')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_dashboard_versions": { + "name": "responsibility_dashboard_versions", + "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 + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cause": { + "name": "cause", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "snapshot_hash": { + "name": "snapshot_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_agent_id": { + "name": "actor_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "interaction_id": { + "name": "interaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "previous_version_id": { + "name": "previous_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "restored_from_version_id": { + "name": "restored_from_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_dashboard_versions_owner_created_idx": { + "name": "responsibility_dashboard_versions_owner_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_dashboard_versions_company_id_companies_id_fk": { + "name": "responsibility_dashboard_versions_company_id_companies_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_actor_agent_id_agents_id_fk": { + "name": "responsibility_dashboard_versions_actor_agent_id_agents_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "agents", + "columnsFrom": [ + "actor_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_issue_id_issues_id_fk": { + "name": "responsibility_dashboard_versions_issue_id_issues_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_previous_version_id_responsibility_dashboard_versions_id_fk": { + "name": "responsibility_dashboard_versions_previous_version_id_responsibility_dashboard_versions_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "responsibility_dashboard_versions", + "columnsFrom": [ + "previous_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "responsibility_dashboard_versions_restored_from_version_id_responsibility_dashboard_versions_id_fk": { + "name": "responsibility_dashboard_versions_restored_from_version_id_responsibility_dashboard_versions_id_fk", + "tableFrom": "responsibility_dashboard_versions", + "tableTo": "responsibility_dashboard_versions", + "columnsFrom": [ + "restored_from_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_dashboard_versions_cause_check": { + "name": "responsibility_dashboard_versions_cause_check", + "value": "\"responsibility_dashboard_versions\".\"cause\" in ('change_set', 'person', 'restore')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_links": { + "name": "responsibility_links", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "routine_id": { + "name": "routine_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "skill_id": { + "name": "skill_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_links_responsibility_idx": { + "name": "responsibility_links_responsibility_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_project_uq": { + "name": "responsibility_links_responsibility_project_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"project_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_issue_uq": { + "name": "responsibility_links_responsibility_issue_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"issue_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_routine_uq": { + "name": "responsibility_links_responsibility_routine_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "routine_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"routine_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_responsibility_skill_uq": { + "name": "responsibility_links_responsibility_skill_uq", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"responsibility_links\".\"skill_id\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_project_idx": { + "name": "responsibility_links_project_idx", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_issue_idx": { + "name": "responsibility_links_issue_idx", + "columns": [ + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_routine_idx": { + "name": "responsibility_links_routine_idx", + "columns": [ + { + "expression": "routine_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_links_skill_idx": { + "name": "responsibility_links_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_links_company_id_companies_id_fk": { + "name": "responsibility_links_company_id_companies_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_links_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_project_id_projects_id_fk": { + "name": "responsibility_links_project_id_projects_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_issue_id_issues_id_fk": { + "name": "responsibility_links_issue_id_issues_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_routine_id_routines_id_fk": { + "name": "responsibility_links_routine_id_routines_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "routines", + "columnsFrom": [ + "routine_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_links_skill_id_company_skills_id_fk": { + "name": "responsibility_links_skill_id_company_skills_id_fk", + "tableFrom": "responsibility_links", + "tableTo": "company_skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_links_single_target_check": { + "name": "responsibility_links_single_target_check", + "value": "(\"responsibility_links\".\"project_id\" is not null)::int + (\"responsibility_links\".\"issue_id\" is not null)::int + (\"responsibility_links\".\"routine_id\" is not null)::int + (\"responsibility_links\".\"skill_id\" is not null)::int = 1" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_metric_readings": { + "name": "responsibility_metric_readings", + "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 + }, + "metric_id": { + "name": "metric_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "recorded_by_agent_id": { + "name": "recorded_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "recorded_by_user_id": { + "name": "recorded_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_metric_readings_metric_recorded_idx": { + "name": "responsibility_metric_readings_metric_recorded_idx", + "columns": [ + { + "expression": "metric_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recorded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_metric_readings_company_id_companies_id_fk": { + "name": "responsibility_metric_readings_company_id_companies_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metric_readings_metric_id_responsibility_metrics_id_fk": { + "name": "responsibility_metric_readings_metric_id_responsibility_metrics_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "responsibility_metrics", + "columnsFrom": [ + "metric_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metric_readings_recorded_by_agent_id_agents_id_fk": { + "name": "responsibility_metric_readings_recorded_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_metric_readings", + "tableTo": "agents", + "columnsFrom": [ + "recorded_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.responsibility_metrics": { + "name": "responsibility_metrics", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display": { + "name": "display", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target": { + "name": "target", + "type": "numeric", + "primaryKey": false, + "notNull": false + }, + "direction": { + "name": "direction", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "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": { + "responsibility_metrics_responsibility_status_position_idx": { + "name": "responsibility_metrics_responsibility_status_position_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_metrics_company_id_companies_id_fk": { + "name": "responsibility_metrics_company_id_companies_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metrics_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_metrics_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_metrics_created_by_agent_id_agents_id_fk": { + "name": "responsibility_metrics_created_by_agent_id_agents_id_fk", + "tableFrom": "responsibility_metrics", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_metrics_display_check": { + "name": "responsibility_metrics_display_check", + "value": "\"responsibility_metrics\".\"display\" in ('number', 'percent', 'line', 'bar')" + }, + "responsibility_metrics_direction_check": { + "name": "responsibility_metrics_direction_check", + "value": "\"responsibility_metrics\".\"direction\" is null or \"responsibility_metrics\".\"direction\" in ('at_least', 'at_most')" + }, + "responsibility_metrics_status_check": { + "name": "responsibility_metrics_status_check", + "value": "\"responsibility_metrics\".\"status\" in ('active', 'archived')" + } + }, + "isRLSEnabled": false + }, + "public.responsibility_status_reports": { + "name": "responsibility_status_reports", + "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 + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "responsibility_status_reports_responsibility_created_idx": { + "name": "responsibility_status_reports_responsibility_created_idx", + "columns": [ + { + "expression": "responsibility_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_status_reports_company_id_companies_id_fk": { + "name": "responsibility_status_reports_company_id_companies_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_status_reports_responsibility_id_responsibilities_id_fk": { + "name": "responsibility_status_reports_responsibility_id_responsibilities_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "responsibilities", + "columnsFrom": [ + "responsibility_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_status_reports_agent_id_agents_id_fk": { + "name": "responsibility_status_reports_agent_id_agents_id_fk", + "tableFrom": "responsibility_status_reports", + "tableTo": "agents", + "columnsFrom": [ + "agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_status_reports_status_check": { + "name": "responsibility_status_reports_status_check", + "value": "\"responsibility_status_reports\".\"status\" in ('behind', 'at_risk', 'on_track', 'unknown')" + }, + "responsibility_status_reports_author_check": { + "name": "responsibility_status_reports_author_check", + "value": "not (\"responsibility_status_reports\".\"agent_id\" is not null and \"responsibility_status_reports\".\"user_id\" is not null)" + } + }, + "isRLSEnabled": false + }, "public.routine_documents": { "name": "routine_documents", "schema": "", @@ -56128,6 +57951,114 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.stored_object_deletions": { + "name": "stored_object_deletions", + "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 + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "log_store": { + "name": "log_store", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "not_before": { + "name": "not_before", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "stored_object_deletions_due_idx": { + "name": "stored_object_deletions_due_idx", + "columns": [ + { + "expression": "not_before", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "stored_object_deletions_company_idx": { + "name": "stored_object_deletions_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.summary_slots": { "name": "summary_slots", "schema": "", @@ -70109,6 +72040,249 @@ }, "isRLSEnabled": false }, + "public.responsibility_summary_invocations": { + "name": "responsibility_summary_invocations", + "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 + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "responsibility_id": { + "name": "responsibility_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owner_user_id": { + "name": "owner_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prompt_version": { + "name": "prompt_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "error_code": { + "name": "error_code", + "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 + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "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": { + "responsibility_summary_invocations_company_started_idx": { + "name": "responsibility_summary_invocations_company_started_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_summary_invocations_pending_idx": { + "name": "responsibility_summary_invocations_pending_idx", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"responsibility_summary_invocations\".\"status\" = 'running'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "responsibility_summary_invocations_cost_idx": { + "name": "responsibility_summary_invocations_cost_idx", + "columns": [ + { + "expression": "cost_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "responsibility_summary_invocations_company_id_companies_id_fk": { + "name": "responsibility_summary_invocations_company_id_companies_id_fk", + "tableFrom": "responsibility_summary_invocations", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "responsibility_summary_invocations_cost_event_id_cost_events_id_fk": { + "name": "responsibility_summary_invocations_cost_event_id_cost_events_id_fk", + "tableFrom": "responsibility_summary_invocations", + "tableTo": "cost_events", + "columnsFrom": [ + "cost_event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "responsibility_summary_invocations_feature_check": { + "name": "responsibility_summary_invocations_feature_check", + "value": "\"responsibility_summary_invocations\".\"feature\" in ('where_things_stand', 'what_is_affecting_the_number')" + }, + "responsibility_summary_invocations_status_check": { + "name": "responsibility_summary_invocations_status_check", + "value": "\"responsibility_summary_invocations\".\"status\" in ('running', 'succeeded', 'failed', 'unknown')" + } + }, + "isRLSEnabled": false + }, "public.plugin_connector_legacy_access": { "name": "plugin_connector_legacy_access", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index dac3100b055..2e48d538cf6 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3494,6 +3494,13 @@ "when": 1795206084746, "tag": "0500_funny_malcolm_colcord", "breakpoints": true + }, + { + "idx": 501, + "version": "7", + "when": 1795444424088, + "tag": "0501_charming_living_lightning", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index c09b5f48721..0f66eba2418 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -301,4 +301,6 @@ export { tailscaleConnections } from "./tailscale_connections.js"; export { nativeProviderArtifacts, nativeProviderArtifactReferences } from "./native_provider_artifacts.js"; export { linkPreviews } from "./link_previews.js"; export { toolConnectionContentDeletions } from "./tool_connection_content_deletions.js"; +export { issueConnectionContentDeletions } from "./issue_connection_content_deletions.js"; +export { storedObjectDeletions } from "./stored_object_deletions.js"; export * from "./plugin_connector_legacy_access.js"; diff --git a/packages/db/src/schema/issue_connection_content_deletions.ts b/packages/db/src/schema/issue_connection_content_deletions.ts new file mode 100644 index 00000000000..2586628dfe0 --- /dev/null +++ b/packages/db/src/schema/issue_connection_content_deletions.ts @@ -0,0 +1,30 @@ +import { sql } from "drizzle-orm"; +import { index, integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; + +export const issueConnectionContentDeletions = pgTable( + "issue_connection_content_deletions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + issueId: uuid("issue_id").notNull(), + scope: jsonb("scope").$type<{ runIds: string[]; invocationIds: string[]; eventIds?: string[] }>().notNull(), + status: text("status").$type<"pending" | "completed">().notNull().default("pending"), + requestedByActorType: text("requested_by_actor_type").notNull(), + requestedByActorId: text("requested_by_actor_id"), + requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(), + progress: jsonb("progress").$type>().notNull().default({}), + attempts: integer("attempts").notNull().default(0), + lastError: text("last_error"), + notBefore: timestamp("not_before", { withTimezone: true }).notNull().defaultNow(), + completedAt: timestamp("completed_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + index("issue_connection_content_deletions_issue_idx").on(table.companyId, table.issueId), + index("issue_connection_content_deletions_pending_idx") + .on(table.notBefore) + .where(sql`${table.status} = 'pending'`), + ], +); diff --git a/packages/db/src/schema/stored_object_deletions.ts b/packages/db/src/schema/stored_object_deletions.ts new file mode 100644 index 00000000000..0cb952d391a --- /dev/null +++ b/packages/db/src/schema/stored_object_deletions.ts @@ -0,0 +1,20 @@ +import { index, integer, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; + +export const storedObjectDeletions = pgTable( + "stored_object_deletions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull(), + kind: text("kind").$type<"run_log" | "asset">().notNull(), + logStore: text("log_store"), + objectKey: text("object_key").notNull(), + attempts: integer("attempts").notNull().default(0), + lastError: text("last_error"), + notBefore: timestamp("not_before", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => [ + index("stored_object_deletions_due_idx").on(table.notBefore, table.id), + index("stored_object_deletions_company_idx").on(table.companyId), + ], +); diff --git a/server/src/__tests__/tool-connection-content-deletion-canary.test.ts b/server/src/__tests__/tool-connection-content-deletion-canary.test.ts index 7aea9491925..c36607ce4be 100644 --- a/server/src/__tests__/tool-connection-content-deletion-canary.test.ts +++ b/server/src/__tests__/tool-connection-content-deletion-canary.test.ts @@ -4,15 +4,18 @@ import os from "node:os"; import path from "node:path"; import { Readable } from "node:stream"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { sql } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { agentWakeupRequests, agents, + assets, companies, createDb, heartbeatRunEvents, heartbeatRuns, + issueAttachments, issueComments, + issueConnectionContentDeletions, issues, issueThreadInteractions, toolAccessAuditEvents, @@ -22,6 +25,7 @@ import { toolConnections, toolInvocations, toolMcpAppViews, + runnerApiResponseReservations, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { createConnectionContentDeletion } from "../services/tool-access/connections/content-deletion.js"; @@ -29,6 +33,10 @@ import { composeRunLogStore, createDurableRunLogStore, type RunLogHandle, type R import { createObjectRunLogStore } from "../services/object-run-log-store.js"; import { summarizeToolValue } from "../services/tool-content-guards.js"; import type { StorageProvider } from "../storage/types.js"; +import { createStorageService } from "../storage/service.js"; +import { issueService } from "../services/issues.js"; +import { deleteCompany } from "../services/company-deletion.js"; +import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -36,6 +44,7 @@ const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : const OUT_OF_SCOPE_COLUMNS = new Map([ ["issue_comments.body", "Comments an agent wrote into the task. The user removes them by editing or deleting the comment or the task."], ]); +const TASK_FILE_NAMESPACE = "/issues/"; function memoryProvider() { const objects = new Map(); @@ -105,7 +114,8 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy const objects = memoryProvider(); const local = createDurableRunLogStore({ basePath: dir, s3: { provider: mirror.provider } }); const external = createObjectRunLogStore({ provider: objects.provider, keyPrefix: "run-logs", assertWriterAuthority: async () => undefined }); - return { dir, mirror, objects, local, external, store: composeRunLogStore(local, external) }; + const files = memoryProvider(); + return { dir, mirror, objects, files, storage: createStorageService(files.provider), local, external, store: composeRunLogStore(local, external) }; } async function writeLog(store: RunLogStore, ids: { companyId: string; agentId: string; runId: string }, text: string) { @@ -195,6 +205,15 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy await db.insert(issueComments).values({ companyId, issueId: base.issue.id, authorAgentId: base.agent.id, body: `Agent note: ${marker}` }); + const saved = await logs.storage.putFile({ companyId, namespace: "runner-api", originalFilename: "response.json", contentType: "application/json", + body: Buffer.from(JSON.stringify({ text: `Oversized result ${marker}` })) }); + const [savedAsset] = await db.insert(assets).values({ companyId, ...saved, createdByAgentId: base.agent.id }).returning(); + await db.insert(runnerApiResponseReservations).values({ companyId, runId: callingRunId, assetId: savedAsset!.id, reservedBytes: saved.byteSize }); + const attached = await logs.storage.putFile({ companyId, namespace: "issues", originalFilename: "notes.txt", contentType: "text/plain", + body: Buffer.from(`Attached copy of ${marker}`) }); + const [attachedAsset] = await db.insert(assets).values({ companyId, ...attached, createdByAgentId: base.agent.id }).returning(); + await db.insert(issueAttachments).values({ companyId, issueId: base.issue.id, assetId: attachedAsset!.id }); + return { connection: connection!, actionRequest: actionRequest!, result, callingRunId }; } @@ -225,13 +244,13 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy return runId; } - async function scan(markers: string[], logs: ReturnType) { + async function scan(markers: string[], logs: ReturnType, options: { taskOwnedCopies?: boolean } = {}) { const columns = await db.execute(sql`select table_name, column_name from information_schema.columns where table_schema = 'public' and data_type in ('text', 'character varying', 'jsonb', 'json')`); const hits: string[] = []; for (const row of columns as unknown as Array<{ table_name: string; column_name: string }>) { const name = `${row.table_name}.${row.column_name}`; - if (OUT_OF_SCOPE_COLUMNS.has(name)) continue; + if (!options.taskOwnedCopies && OUT_OF_SCOPE_COLUMNS.has(name)) continue; for (const marker of markers) { const found = await db.execute(sql`select 1 from ${sql.identifier(row.table_name)} where ${sql.identifier(row.column_name)}::text like ${`%${marker}%`} limit 1`); @@ -239,17 +258,28 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy } } for (const marker of markers) { - for (const [label, objects] of [["object store", logs.objects.objects], ["legacy mirror", logs.mirror.objects]] as const) { - for (const [key, bytes] of objects) if (bytes.includes(marker)) hits.push(`${label} ${key} contains ${marker}`); + for (const [label, objects] of [["object store", logs.objects.objects], ["legacy mirror", logs.mirror.objects], ["file storage", logs.files.objects]] as const) { + for (const [key, bytes] of objects) { + if (!options.taskOwnedCopies && key.includes(TASK_FILE_NAMESPACE)) continue; + if (bytes.includes(marker)) hits.push(`${label} ${key} contains ${marker}`); + } } for (const file of await filesContaining(logs.dir, marker)) hits.push(`file ${file} contains ${marker}`); } return hits; } - async function outOfScopeStillHolds(marker: string) { + async function outOfScopeStillHolds(marker: string, logs: ReturnType) { const rows = await db.execute(sql`select 1 from issue_comments where body like ${`%${marker}%`}`); - return (rows as unknown as unknown[]).length > 0; + return (rows as unknown as unknown[]).length > 0 + && [...logs.files.objects].some(([key, bytes]) => key.includes(TASK_FILE_NAMESPACE) && bytes.includes(marker)); + } + + async function drainPending(service: ReturnType) { + for (let i = 0; i < 200 && await service.nextDeadline() !== null; i++) { + await service.processPending(new AbortController().signal); + } + expect(await service.nextDeadline()).toBeNull(); } async function drain(service: ReturnType, deletionIds: string[]) { @@ -276,17 +306,241 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]); await seenBefore([marker], logs); - const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store }); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); const before = await service.storedContent(flow.connection); expect(before.stored).toMatchObject({ toolCalls: 2, approvals: 1, appViews: 1, runs: 2, runsInProgress: 0 }); const { deletion } = await service.request(flow.connection, { actorType: "user", actorId: "board-user" }); await drain(service, [deletion.id]); expect(await scan([marker], logs)).toEqual([]); - expect(await outOfScopeStillHolds(marker)).toBe(true); + expect(await outOfScopeStillHolds(marker, logs)).toBe(true); expect((await service.storedContent(flow.connection)).stored).toEqual({ toolCalls: 0, approvals: 0, appViews: 0, runs: 0, runsInProgress: 0 }); }); + it("leaves the marker nowhere after the task is deleted, and keeps another task's content", async () => { + const logs = stores(path.join(baseDir, "task")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const kept = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]); + const [otherIssue] = await db.insert(issues).values({ companyId: base.company.id, title: "Another task" }).returning(); + const otherBase = { ...base, issue: otherIssue! }; + const otherFlow = await seedConnectionFlow(otherBase, logs, kept); + await seedDeliveryRun(otherBase, logs, [{ actionRequestId: otherFlow.actionRequest.id, marker: kept }]); + await seenBefore([marker, kept], logs); + expect((await scan([marker], logs, { taskOwnedCopies: true })).filter((hit) => hit.startsWith("file storage"))).toHaveLength(2); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + const remaining = await scan([kept], logs, { taskOwnedCopies: true }); + expect(remaining.some((hit) => hit.startsWith("tool_invocations."))).toBe(true); + expect(remaining.some((hit) => hit.startsWith("object store"))).toBe(true); + expect(remaining.some((hit) => hit.startsWith("file storage"))).toBe(true); + const [activity] = await db.execute(sql`select entity_type, entity_id, details from activity_log + where company_id = ${base.company.id} and action = 'issue.connection_content_deleted'`) as unknown as Array<{ entity_type: string; entity_id: string; details: Record }>; + expect(activity).toMatchObject({ entity_type: "issue", entity_id: base.issue.id }); + expect(activity!.details).toMatchObject({ toolCalls: 2, runs: 2 }); + }); + + it("leaves the marker nowhere after deleting a task whose connection call had no run", async () => { + const logs = stores(path.join(baseDir, "task-runless")); + const base = await seedCompany(); + const companyId = base.company.id; + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const [connection] = await db.insert(toolConnections).values({ + companyId, applicationId: base.application.id, name: "Docs runless", uid: randomUUID(), transport: "mcp_remote", status: "active", + }).returning(); + const args = summarizeToolValue({ query: marker }); + const result = summarizeToolValue({ text: `Result ${marker}` }); + const [call] = await db.insert(toolInvocations).values({ + companyId, connectionId: connection!.id, runId: null, issueId: base.issue.id, toolName: "read_doc", status: "succeeded", + argumentsSummary: args, resultSummary: result, createdAt: new Date(Date.now() - 30_000), + }).returning(); + await db.insert(toolCallEvents).values([ + { companyId, connectionId: connection!.id, issueId: base.issue.id, eventType: "policy_decision", argumentsSummary: args }, + { companyId, connectionId: connection!.id, issueId: base.issue.id, invocationId: call!.id, eventType: "call_completed", resultSummary: result }, + ]); + await db.insert(toolAccessAuditEvents).values({ + companyId, connectionId: connection!.id, action: "tool_access.policy_decision", outcome: "success", + details: { decision: "allow", issueId: base.issue.id, runId: null, toolName: "read_doc", argumentsSummary: args }, + }); + expect((await scan([marker], logs)).length).toBeGreaterThan(0); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("removes content a run of the task writes after the task is deleted", async () => { + const logs = stores(path.join(baseDir, "task-late")); + const base = await seedCompany(); + const companyId = base.company.id; + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const [connection] = await db.insert(toolConnections).values({ + companyId, applicationId: base.application.id, name: "Docs late", uid: randomUUID(), transport: "mcp_remote", status: "active", + }).returning(); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: base.agent.id, issueId: base.issue.id, status: "running" }); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + + const summary = summarizeToolValue({ text: `Late ${marker}` }); + await db.insert(toolInvocations).values({ + companyId, connectionId: connection!.id, runId, agentId: base.agent.id, toolName: "read_doc", status: "succeeded", + argumentsSummary: summary, resultSummary: summary, + }); + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId: base.agent.id, seq: 1, eventType: "tool.execution.completed", message: marker, payload: { output: marker } }); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(), stdoutExcerpt: `read_doc -> ${marker}` }).where(eq(heartbeatRuns.id, runId)); + expect((await scan([marker], logs)).length).toBeGreaterThan(0); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("waits for a run that is still going when the task is deleted, then removes its content", async () => { + const logs = stores(path.join(baseDir, "task-live")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, flow.callingRunId)); + + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [waiting] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(waiting).toMatchObject({ status: "pending", lastError: null }); + expect(waiting!.notBefore.getTime()).toBeGreaterThan(Date.now()); + expect((await scan([marker], logs)).some((hit) => hit.startsWith("object store"))).toBe(true); + + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, flow.callingRunId)); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, waiting!.id)); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("stops waiting a day after the task was deleted and records what was still in progress", async () => { + const logs = stores(path.join(baseDir, "task-stuck")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, flow.callingRunId)); + await issueService(db).remove(base.issue.id); + const old = new Date(Date.now() - 25 * 60 * 60_000); + await db.update(issueConnectionContentDeletions).set({ requestedAt: old }).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + const [job] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(job!.status).toBe("completed"); + const [activity] = await db.execute(sql`select details from activity_log + where company_id = ${base.company.id} and action = 'issue.connection_content_deletion_incomplete'`) as unknown as Array<{ details: Record }>; + expect(activity!.details.runsInProgress + activity!.details.itemsInProgress).toBeGreaterThan(0); + }); + + it("finishes without an activity entry when the deleted task's open run never calls a connection", async () => { + const logs = stores(path.join(baseDir, "task-open-quiet")); + const base = await seedCompany(); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: base.company.id, agentId: base.agent.id, issueId: base.issue.id, status: "running" }); + await issueService(db).remove(base.issue.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await service.processPending(new AbortController().signal); + const [waiting] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id)); + expect(waiting!.status).toBe("pending"); + + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId)); + await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, waiting!.id)); + await drainPending(service); + const [finished] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, waiting!.id)); + expect(finished!.status).toBe("completed"); + expect(await db.execute(sql`select 1 from activity_log where company_id = ${base.company.id} + and action like 'issue.connection_content_%'`)).toHaveLength(0); + }); + + it("queues nothing when the deleted task never used a connection", async () => { + const base = await seedCompany(); + await issueService(db).remove(base.issue.id); + expect(await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id))).toEqual([]); + }); + + it("wakes the cleanup worker when the deleted task has files but never used a connection", async () => { + const logs = stores(path.join(baseDir, "task-files")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const attached = await logs.storage.putFile({ companyId: base.company.id, namespace: "issues", originalFilename: "notes.txt", contentType: "text/plain", + body: Buffer.from(`Attached copy of ${marker}`) }); + const [asset] = await db.insert(assets).values({ companyId: base.company.id, ...attached }).returning(); + await db.insert(issueAttachments).values({ companyId: base.company.id, issueId: base.issue.id, assetId: asset!.id }); + let woken = 0; + const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.toolConnectionContentDeletion, () => { woken += 1; }); + try { + await issueService(db).remove(base.issue.id); + } finally { + unsubscribe(); + } + expect(woken).toBeGreaterThan(0); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + + it("leaves the marker nowhere after the company is deleted, and keeps another company's content", async () => { + const logs = stores(path.join(baseDir, "company")); + const base = await seedCompany(); + const otherBase = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + const kept = `CANARY${randomUUID().replace(/-/g, "")}`; + const flow = await seedConnectionFlow(base, logs, marker); + await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]); + const otherFlow = await seedConnectionFlow(otherBase, logs, kept); + await seedDeliveryRun(otherBase, logs, [{ actionRequestId: otherFlow.actionRequest.id, marker: kept }]); + await seenBefore([marker, kept], logs); + + await db.update(agents).set({ lifecycleState: "terminated" }).where(eq(agents.companyId, base.company.id)); + await deleteCompany(db, base.company.id); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); + await drainPending(service); + + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + const remaining = await scan([kept], logs, { taskOwnedCopies: true }); + expect(remaining.some((hit) => hit.startsWith("object store"))).toBe(true); + expect(remaining.some((hit) => hit.startsWith("file storage"))).toBe(true); + expect(remaining.some((hit) => hit.startsWith("file "))).toBe(true); + }); + + it("finishes removing a deleted company's files after storage fails once", async () => { + const logs = stores(path.join(baseDir, "company-retry")); + const base = await seedCompany(); + const marker = `CANARY${randomUUID().replace(/-/g, "")}`; + await seedConnectionFlow(base, logs, marker); + await db.update(agents).set({ lifecycleState: "terminated" }).where(eq(agents.companyId, base.company.id)); + await deleteCompany(db, base.company.id); + + let failures = 1; + const flaky = { + ...logs.storage, + deleteObject: async (...args: Parameters) => { + if (failures > 0) { + failures -= 1; + throw new Error("object storage unavailable"); + } + return logs.storage.deleteObject(...args); + }, + }; + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => flaky, objectRetryMs: 0 }); + await expect(service.processPending(new AbortController().signal)).rejects.toThrow("object storage unavailable"); + expect(await service.nextDeadline()).not.toBeNull(); + await drainPending(service); + expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]); + }); + it("leaves the marker nowhere after an interrupted deletion resumes", async () => { const logs = stores(path.join(baseDir, "interrupted")); const base = await seedCompany(); @@ -306,7 +560,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy return logs.store.remove!(handle, signal); }, }; - const service = createConnectionContentDeletion(db, { runLogStore: () => flaky }); + const service = createConnectionContentDeletion(db, { runLogStore: () => flaky, storage: () => logs.storage }); const { deletion } = await service.request(flow.connection, { actorType: "user", actorId: "board-user" }); let interrupted = 0; for (let i = 0; i < 200; i++) { @@ -318,7 +572,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy } expect(interrupted).toBe(2); expect(await scan([marker], logs)).toEqual([]); - expect(await outOfScopeStillHolds(marker)).toBe(true); + expect(await outOfScopeStillHolds(marker, logs)).toBe(true); }); it("leaves no marker after two deletions for different connections run at the same time on one task", async () => { @@ -334,13 +588,13 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy ]); await seenBefore([first, second], logs); - const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store }); + const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage }); const one = await service.request(flowOne.connection, { actorType: "user", actorId: "board-user" }); const two = await service.request(flowTwo.connection, { actorType: "user", actorId: "board-user" }); await drain(service, [one.deletion.id, two.deletion.id]); expect(await scan([first, second], logs)).toEqual([]); - expect(await outOfScopeStillHolds(first)).toBe(true); - expect(await outOfScopeStillHolds(second)).toBe(true); + expect(await outOfScopeStillHolds(first, logs)).toBe(true); + expect(await outOfScopeStillHolds(second, logs)).toBe(true); }); }); diff --git a/server/src/services/company-deletion.ts b/server/src/services/company-deletion.ts index 48cc4a776ca..0ce2dfbf414 100644 --- a/server/src/services/company-deletion.ts +++ b/server/src/services/company-deletion.ts @@ -21,6 +21,7 @@ import type { Db } from "@paperclipai/db"; import { eq, inArray } from "drizzle-orm"; import { createAgentLifecycle, processAgentLifecycle } from "./agent-lifecycle.js"; import { requestRestorePointDeletion } from "./git-restore-point-ledger.js"; +import { requestCompanyStoredObjectDeletion } from "./tool-access/connections/stored-object-deletion.js"; import { agentLifecycleCompanyDeletion } from "../modules/agent-lifecycle/company-deletion.js"; import { executionAdmissionCompanyDeletion } from "../modules/execution-admission/company-deletion.js"; import { @@ -78,6 +79,7 @@ export async function deleteCompany(db: Db, id: string) { const [existing] = await tx.select({ id: companies.id }).from(companies) .where(eq(companies.id, id)).for("no key update"); if (!existing) return null; + await requestCompanyStoredObjectDeletion(tx as unknown as Db, id); await mcpCompanyDeletion.deleteCompanyData(tx, id); await notifyExternalObjectRefresh(tx, id); await notifyIssueRecovery(tx, { companyId: id }); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 7b28f59f68a..265607ea5a9 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -45,6 +45,7 @@ import { executionWorkspaceService } from "./execution-workspaces.js"; import { notifyChatPublicationWork } from "./chat-work-notifications.js"; import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js"; import { requestRestorePointDeletion } from "./git-restore-point-ledger.js"; +import { requestIssueConnectionContentDeletion } from "./tool-access/connections/issue-content-deletion.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { recordChatHandoff, recordAcceptedChatHandoff, lockAcceptedChatHandoffSource, recordChatCompletion, existingChatCompletionReply, acknowledgeChatCompletionReply } from "./chat-completion-delivery.js"; import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js"; @@ -12793,6 +12794,9 @@ export function issueService(db: Db) { } await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); await notifyRoutineExecutionStatus(tx, id); + if (owner) { + await requestIssueConnectionContentDeletion(tx as unknown as Db, { companyId: owner.companyId, issueId: id, actorAgentId }); + } removedIssue = await tx .delete(issues) .where(eq(issues.id, id)) diff --git a/server/src/services/tool-access/connections/content-deletion.ts b/server/src/services/tool-access/connections/content-deletion.ts index 063d2dbd0de..6a9226ba223 100644 --- a/server/src/services/tool-access/connections/content-deletion.ts +++ b/server/src/services/tool-access/connections/content-deletion.ts @@ -1,9 +1,12 @@ import { and, asc, desc, eq, gt, inArray, lte, sql, type SQL } from "drizzle-orm"; import { agentWakeupRequests, + assets, heartbeatRunEvents, heartbeatRuns, + issueConnectionContentDeletions, issueThreadInteractions, + runnerApiResponseReservations, toolAccessAuditEvents, toolActionRequests, toolCallEvents, @@ -19,7 +22,10 @@ import type { } from "@paperclipai/shared"; import { isRunLogStoreType, type RunLogHandle, type RunLogStore } from "../../run-log-store.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js"; -import { logActivity } from "../../activity-log.js"; +import { logActivity, type LogActivityInput } from "../../activity-log.js"; +import { getStorageService } from "../../../storage/index.js"; +import type { StorageService } from "../../../storage/types.js"; +import { createStoredObjectDeletion } from "./stored-object-deletion.js"; const BATCH_SIZE = 200; const EVENT_BATCH_SIZE = 1000; @@ -48,6 +54,9 @@ type Phase = "invocations" | "events" | "auditEvents" | "appViews" | "deliveredR const PHASES: Phase[] = ["invocations", "events", "auditEvents", "appViews", "deliveredResults", "runs", "done"]; const RUN_BATCH_SIZE = 50; const DELIVERY_BATCH_SIZE = 50; +const ISSUE_WAIT_MS = 60_000; +const ISSUE_WAIT_MAX_MS = 5 * 60_000; +const ISSUE_WAIT_LIMIT_MS = 24 * 60 * 60_000; type RunInProgress = { id: string; eventAfterId: number; changed: boolean; stage?: "events" | "log" }; @@ -61,6 +70,62 @@ type Progress = { }; type DeletionRow = typeof toolConnectionContentDeletions.$inferSelect; +type IssueDeletionRow = typeof issueConnectionContentDeletions.$inferSelect; +type JobRow = Pick; +type JobActivity = Pick; + +type JobStore = { + load(id: string): Promise; + scope(row: Row): Scope; + waitMs(row: Row, progress: Progress): number | null; + save(tx: Db, row: Row, progress: Progress, waitMs: number | null): Promise; + finish(tx: Db, row: Row, now: Date): Promise; + activity(row: Row, counts: ToolConnectionContentDeletionCounts): JobActivity | null; + fail(row: Row, message: string): Promise; +}; + +type Scope = { + companyId: string; + cutoff: Date | null; + connectionId: string | null; + issueId: string | null; + runIds: string[]; + invocationIds: string[]; + eventIds: string[]; +}; + +function connectionScope(connection: { id: string; companyId: string }, cutoff: Date): Scope { + return { companyId: connection.companyId, cutoff, connectionId: connection.id, issueId: null, runIds: [], invocationIds: [], eventIds: [] }; +} + +export function uuidList(values: string[]): SQL { + return values.length > 0 ? sql`array[${sql.join(values.map((value) => sql`${value}::uuid`), sql`, `)}]` : sql`array[]::uuid[]`; +} + +function textList(values: string[]): SQL { + return values.length > 0 ? sql`array[${listSql(values)}]::text[]` : sql`array[]::text[]`; +} + +function cutoffSql(column: SQL | typeof toolInvocations.createdAt, scope: Scope) { + return scope.cutoff ? sql`${column} <= ${scope.cutoff.toISOString()}::timestamptz` : undefined; +} + +function callsInScopeSql(scope: Scope, columns: { connectionId: SQL; runId: SQL; invocationId: SQL }): SQL { + if (scope.connectionId) return sql`${columns.connectionId} = ${scope.connectionId}`; + return sql`(${columns.runId} = any(${uuidList(scope.runIds)}) or ${columns.invocationId} = any(${uuidList(scope.invocationIds)}))`; +} + +function invocationsInScopeSql(scope: Scope) { + return callsInScopeSql(scope, { connectionId: sql`${toolInvocations.connectionId}`, runId: sql`${toolInvocations.runId}`, invocationId: sql`${toolInvocations.id}` }); +} + +function savedResultSql(runId: SQL): SQL { + return sql`exists (select 1 from ${runnerApiResponseReservations} capture + where capture.run_id = ${runId} and capture.asset_id is not null + and not exists (select 1 from issue_attachments link where link.asset_id = capture.asset_id) + and not exists (select 1 from case_attachments link where link.asset_id = capture.asset_id) + and not exists (select 1 from company_logos link where link.asset_id = capture.asset_id))`; +} export type ContentDeletionActor = { actorType: "user" | "agent" | "system"; actorId: string | null }; @@ -70,7 +135,7 @@ export function emptyContentDeletionCounts(): ToolConnectionContentDeletionCount return { toolCalls: 0, approvals: 0, auditEvents: 0, appViews: 0, runs: 0, runsInProgress: 0, itemsInProgress: 0 }; } -function readProgress(row: DeletionRow): Progress { +function readProgress(row: { progress: unknown }): Progress { const raw = row.progress as Partial; const counts = { ...emptyContentDeletionCounts(), ...(raw.counts ?? {}) }; const phase = PHASES.includes(raw.phase as Phase) ? raw.phase as Phase : "invocations"; @@ -94,21 +159,34 @@ export function settledRunSql(runId: SQL | typeof toolInvocations.runId): SQL { and f.phase not in ('committed', 'terminal_failure', 'applied')))`; } -export function runsWithStoredContentSql(scope: { companyId: string; connectionId: string; cutoff: Date }): SQL { +function runsCallingConnectionSql(scope: Scope & { connectionId: string; cutoff: Date }): SQL { const calls = sql`${toolInvocations.companyId} = ${scope.companyId} and ${toolInvocations.connectionId} = ${scope.connectionId} and ${toolInvocations.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz`; - const resultText = sql.join(RESULT_TEXT_KEYS.map((key) => - sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `); - return sql`${heartbeatRuns.companyId} = ${scope.companyId} - and (${heartbeatRuns.id} in (select ${toolInvocations.runId} from ${toolInvocations} where ${calls} and ${toolInvocations.runId} is not null) + return sql`(${heartbeatRuns.id} in (select ${toolInvocations.runId} from ${toolInvocations} where ${calls} and ${toolInvocations.runId} is not null) or ${heartbeatRuns.id} in (select ${toolCallEvents.runId} from ${toolCallEvents} where ${toolCallEvents.companyId} = ${scope.companyId} and ${toolCallEvents.connectionId} = ${scope.connectionId} and ${toolCallEvents.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz and ${toolCallEvents.runId} is not null) or (${heartbeatRuns.issueId} in (select ${toolActionRequests.issueId} from ${toolActionRequests} join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls}) and ${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| array(select ${toolActionRequests.id}::text from ${toolActionRequests} - join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls}))) - and (${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null + join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})))`; +} + +export function runUsedToolsSql(companyId: string): SQL { + return sql`(exists (select 1 from ${toolInvocations} where ${toolInvocations.companyId} = ${companyId} and ${toolInvocations.runId} = ${heartbeatRuns.id}) + or exists (select 1 from ${toolCallEvents} where ${toolCallEvents.companyId} = ${companyId} and ${toolCallEvents.runId} = ${heartbeatRuns.id}) + or coalesce(${heartbeatRuns.contextSnapshot} ? 'toolActionRequestIds', false))`; +} + +export function runsWithStoredContentSql(scope: Scope): SQL { + const resultText = sql.join(RESULT_TEXT_KEYS.map((key) => + sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `); + const inScope = scope.connectionId && scope.cutoff + ? runsCallingConnectionSql({ ...scope, connectionId: scope.connectionId, cutoff: scope.cutoff }) + : sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)}) and ${runUsedToolsSql(scope.companyId)}`; + return sql`${heartbeatRuns.companyId} = ${scope.companyId} + and ${inScope} + and (${savedResultSql(sql`${heartbeatRuns.id}`)} or ${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null or ${heartbeatRuns.stdoutExcerpt} is not null or ${heartbeatRuns.stderrExcerpt} is not null or ${resultText} or exists (select 1 from ${heartbeatRunEvents} where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId} @@ -179,7 +257,18 @@ function toDeletion(row: DeletionRow): ToolConnectionContentDeletion { }; } -export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () => RunLogStore }) { +export function initialContentDeletionProgress(): Progress { + return { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() }; +} + +export function createConnectionContentDeletion(db: Db, deps: { + runLogStore: () => RunLogStore; + storage?: () => StorageService; + objectRetryMs?: number; +}) { + const storage = deps.storage ?? (() => getStorageService()); + const storedObjects = createStoredObjectDeletion(db, { runLogStore: deps.runLogStore, storage, retryMs: deps.objectRetryMs }); + async function latestDeletion(connection: { id: string; companyId: string }) { const [latest] = await db .select() @@ -222,7 +311,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () runsInProgress: sql`count(*) filter (where not ${settledRunSql(sql`${heartbeatRuns.id}`)})::int`, }) .from(heartbeatRuns) - .where(runsWithStoredContentSql({ companyId: connection.companyId, connectionId: connection.id, cutoff: new Date() })); + .where(runsWithStoredContentSql(connectionScope(connection, new Date()))); return { stored: { toolCalls: calls?.toolCalls ?? 0, @@ -260,7 +349,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () connectionId: connection.id, requestedByActorType: actor.actorType, requestedByActorId: actor.actorId, - progress: { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() }, + progress: initialContentDeletionProgress() as unknown as Record, }) .onConflictDoNothing() .returning(); @@ -279,8 +368,8 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () return new Set(rows.map((row) => row.id)); } - async function clearDeliveredResults(tx: Db, job: DeletionRow, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) { - const issueIds = [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))]; + async function clearDeliveredResults(tx: Db, scope: Scope, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) { + const issueIds = scope.issueId ? [scope.issueId] : [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))]; if (issueIds.length === 0) return []; const ids = new Set(requests.map((row) => row.id)); const idList = sql`array[${listSql([...ids])}]::text[]`; @@ -288,8 +377,8 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () .select({ id: heartbeatRuns.id, contextSnapshot: heartbeatRuns.contextSnapshot }) .from(heartbeatRuns) .where(and( - eq(heartbeatRuns.companyId, job.companyId), - inArray(heartbeatRuns.issueId, issueIds), + eq(heartbeatRuns.companyId, scope.companyId), + scope.issueId ? sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)})` : inArray(heartbeatRuns.issueId, issueIds), sql`${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| ${idList}`, )) .for("update"); @@ -308,7 +397,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () .select({ id: agentWakeupRequests.id, status: agentWakeupRequests.status, payload: agentWakeupRequests.payload }) .from(agentWakeupRequests) .where(and( - eq(agentWakeupRequests.companyId, job.companyId), + eq(agentWakeupRequests.companyId, scope.companyId), inArray(sql`${agentWakeupRequests.payload}->>'issueId'`, issueIds), sql`(${agentWakeupRequests.payload}->'toolActionRequestIds' ?| ${idList} or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'toolActionRequestIds' ?| ${idList})`, @@ -326,16 +415,16 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () return runs.filter((row) => settled.has(row.id)).map((row) => row.id); } - async function invocationsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) { + async function invocationsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) { const cursor = progress.cursor; const page = await tx .select({ id: toolInvocations.id, createdAt: toolInvocations.createdAt, runId: toolInvocations.runId, status: toolInvocations.status }) .from(toolInvocations) .where(and( - eq(toolInvocations.companyId, job.companyId), - lte(toolInvocations.createdAt, job.requestedAt), + eq(toolInvocations.companyId, scope.companyId), + cutoffSql(sql`${toolInvocations.createdAt}`, scope), cursor ? sql`(${toolInvocations.createdAt}, ${toolInvocations.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined, - eq(toolInvocations.connectionId, job.connectionId), + invocationsInScopeSql(scope), )) .orderBy(asc(toolInvocations.createdAt), asc(toolInvocations.id)) .limit(BATCH_SIZE); @@ -353,7 +442,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () progress: null, }) .where(and( - eq(toolInvocations.companyId, job.companyId), + eq(toolInvocations.companyId, scope.companyId), inArray(toolInvocations.id, ids), sql`coalesce(${toolInvocations.resultSummary}->>'contentDeletedAt', ${toolInvocations.argumentsSummary}->>'contentDeletedAt') is null`, sql`(${toolInvocations.resultSummary} is not null or ${toolInvocations.argumentsSummary} is not null or ${toolInvocations.progress} is not null)`, @@ -363,7 +452,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () const requests = await tx .select({ id: toolActionRequests.id, interactionId: toolActionRequests.interactionId, issueId: toolActionRequests.issueId, status: toolActionRequests.status }) .from(toolActionRequests) - .where(and(eq(toolActionRequests.companyId, job.companyId), inArray(toolActionRequests.invocationId, ids))); + .where(and(eq(toolActionRequests.companyId, scope.companyId), inArray(toolActionRequests.invocationId, ids))); const settledRequests = requests.filter((row) => !UNSETTLED_ACTION_REQUEST_STATUSES.includes(row.status)); progress.counts.itemsInProgress += requests.length - settledRequests.length; if (settledRequests.length > 0) { @@ -376,7 +465,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () signedArguments: null, }) .where(and( - eq(toolActionRequests.companyId, job.companyId), + eq(toolActionRequests.companyId, scope.companyId), inArray(toolActionRequests.id, requestIds), sql`(${toolActionRequests.canonicalArgumentsSummary}->>'contentDeletedAt' is null or ${toolActionRequests.previewMarkdown} is not null or ${toolActionRequests.signedArguments} is not null)`, )) @@ -395,7 +484,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () else ${issueThreadInteractions.result} end` as never, }) .where(and( - eq(issueThreadInteractions.companyId, job.companyId), + eq(issueThreadInteractions.companyId, scope.companyId), inArray(issueThreadInteractions.id, interactionIds), sql`(${issueThreadInteractions.payload} ? 'detailsMarkdown' or ${issueThreadInteractions.payload}->'toolAction'->>'previewMarkdown' is not null @@ -410,16 +499,19 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () return page.length < BATCH_SIZE; } - async function eventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) { + async function eventsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) { const cursor = progress.cursor; const page = await tx .select({ id: toolCallEvents.id, createdAt: toolCallEvents.createdAt, runId: toolCallEvents.runId }) .from(toolCallEvents) .where(and( - eq(toolCallEvents.companyId, job.companyId), - lte(toolCallEvents.createdAt, job.requestedAt), + eq(toolCallEvents.companyId, scope.companyId), + cutoffSql(sql`${toolCallEvents.createdAt}`, scope), cursor ? sql`(${toolCallEvents.createdAt}, ${toolCallEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined, - eq(toolCallEvents.connectionId, job.connectionId), + scope.connectionId + ? callsInScopeSql(scope, { connectionId: sql`${toolCallEvents.connectionId}`, runId: sql`${toolCallEvents.runId}`, invocationId: sql`${toolCallEvents.invocationId}` }) + : sql`(${callsInScopeSql(scope, { connectionId: sql`${toolCallEvents.connectionId}`, runId: sql`${toolCallEvents.runId}`, invocationId: sql`${toolCallEvents.invocationId}` })} + or ${toolCallEvents.id} = any(${uuidList(scope.eventIds)}))`, )) .orderBy(asc(toolCallEvents.createdAt), asc(toolCallEvents.id)) .limit(BATCH_SIZE); @@ -436,7 +528,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () resultSummary: clearedSummary(sql`${toolCallEvents.resultSummary}`, deletedAt) as never, }) .where(and( - eq(toolCallEvents.companyId, job.companyId), + eq(toolCallEvents.companyId, scope.companyId), inArray(toolCallEvents.id, ids), sql`coalesce(${toolCallEvents.resultSummary}->>'contentDeletedAt', ${toolCallEvents.requestSummary}->>'contentDeletedAt', ${toolCallEvents.argumentsSummary}->>'contentDeletedAt') is null`, sql`(${toolCallEvents.resultSummary} is not null or ${toolCallEvents.requestSummary} is not null or ${toolCallEvents.argumentsSummary} is not null)`, @@ -449,16 +541,20 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () return page.length < BATCH_SIZE; } - async function auditEventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) { + async function auditEventsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) { const cursor = progress.cursor; const page = await tx .select({ id: toolAccessAuditEvents.id, createdAt: toolAccessAuditEvents.createdAt, runId: sql`${toolAccessAuditEvents.details}->>'runId'` }) .from(toolAccessAuditEvents) .where(and( - eq(toolAccessAuditEvents.companyId, job.companyId), - lte(toolAccessAuditEvents.createdAt, job.requestedAt), + eq(toolAccessAuditEvents.companyId, scope.companyId), + cutoffSql(sql`${toolAccessAuditEvents.createdAt}`, scope), cursor ? sql`(${toolAccessAuditEvents.createdAt}, ${toolAccessAuditEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined, - eq(toolAccessAuditEvents.connectionId, job.connectionId), + scope.connectionId + ? eq(toolAccessAuditEvents.connectionId, scope.connectionId) + : sql`(${toolAccessAuditEvents.details}->>'runId' = any(${textList(scope.runIds)}) + or ${toolAccessAuditEvents.details}->>'invocationId' = any(${textList(scope.invocationIds)}) + or ${toolAccessAuditEvents.details}->>'issueId' = ${scope.issueId})`, )) .orderBy(asc(toolAccessAuditEvents.createdAt), asc(toolAccessAuditEvents.id)) .limit(BATCH_SIZE); @@ -476,7 +572,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () ${toolAccessAuditEvents.details}->'argumentsSummary' || jsonb_build_object('summary', '', 'contentDeletedAt', ${deletedAt}::text))` as never, }) .where(and( - eq(toolAccessAuditEvents.companyId, job.companyId), + eq(toolAccessAuditEvents.companyId, scope.companyId), inArray(toolAccessAuditEvents.id, ids), sql`jsonb_typeof(${toolAccessAuditEvents.details}->'argumentsSummary') = 'object'`, sql`${toolAccessAuditEvents.details}->'argumentsSummary'->>'contentDeletedAt' is null`, @@ -489,14 +585,14 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () return page.length < BATCH_SIZE; } - async function appViewsStep(tx: Db, job: DeletionRow, progress: Progress) { + async function appViewsStep(tx: Db, scope: Scope, progress: Progress) { const page = await tx .select({ id: toolMcpAppViews.id, runId: toolMcpAppViews.runId }) .from(toolMcpAppViews) .where(and( - eq(toolMcpAppViews.connectionId, job.connectionId), - eq(toolMcpAppViews.companyId, job.companyId), - lte(toolMcpAppViews.createdAt, job.requestedAt), + callsInScopeSql(scope, { connectionId: sql`${toolMcpAppViews.connectionId}`, runId: sql`${toolMcpAppViews.runId}`, invocationId: sql`${toolMcpAppViews.invocationId}` }), + eq(toolMcpAppViews.companyId, scope.companyId), + cutoffSql(sql`${toolMcpAppViews.createdAt}`, scope), progress.runCursor ? gt(toolMcpAppViews.id, progress.runCursor) : undefined, )) .orderBy(asc(toolMcpAppViews.id)) @@ -508,7 +604,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () if (ids.length > 0) { const removed = await tx .delete(toolMcpAppViews) - .where(and(eq(toolMcpAppViews.companyId, job.companyId), inArray(toolMcpAppViews.id, ids))) + .where(and(eq(toolMcpAppViews.companyId, scope.companyId), inArray(toolMcpAppViews.id, ids))) .returning({ id: toolMcpAppViews.id }); progress.counts.appViews += removed.length; } @@ -566,6 +662,25 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () throw new Error("run_log_reference_changed"); } + async function removeSavedResults(companyId: string, runId: string, signal: AbortSignal) { + const saved = await db + .select({ id: assets.id, objectKey: assets.objectKey }) + .from(assets) + .where(and( + eq(assets.companyId, companyId), + sql`${assets.id} in (select capture.asset_id from ${runnerApiResponseReservations} capture + where capture.company_id = ${companyId} and capture.run_id = ${runId} and capture.asset_id is not null)`, + sql`not exists (select 1 from issue_attachments link where link.asset_id = ${assets.id})`, + sql`not exists (select 1 from case_attachments link where link.asset_id = ${assets.id})`, + sql`not exists (select 1 from company_logos link where link.asset_id = ${assets.id})`, + )); + for (const asset of saved) { + await storage().deleteObject(companyId, asset.objectKey, { signal, allVersions: true }); + await db.delete(assets).where(and(eq(assets.id, asset.id), eq(assets.companyId, companyId))); + } + return saved.length > 0; + } + async function finishRun(tx: Db, companyId: string, run: RunInProgress) { const [row] = await tx .select({ stdoutExcerpt: heartbeatRuns.stdoutExcerpt, stderrExcerpt: heartbeatRuns.stderrExcerpt, resultJson: heartbeatRuns.resultJson }) @@ -582,27 +697,27 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () run.changed = true; } - async function deliveredResultsStep(tx: Db, job: DeletionRow, progress: Progress) { + async function deliveredResultsStep(tx: Db, scope: Scope, progress: Progress) { const requests = await tx .select({ id: toolActionRequests.id, issueId: toolActionRequests.issueId }) .from(toolActionRequests) .innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) .where(and( - eq(toolActionRequests.companyId, job.companyId), - eq(toolInvocations.companyId, job.companyId), - eq(toolInvocations.connectionId, job.connectionId), - lte(toolInvocations.createdAt, job.requestedAt), + eq(toolActionRequests.companyId, scope.companyId), + eq(toolInvocations.companyId, scope.companyId), + invocationsInScopeSql(scope), + cutoffSql(sql`${toolInvocations.createdAt}`, scope), progress.runCursor ? gt(toolActionRequests.id, progress.runCursor) : undefined, )) .orderBy(asc(toolActionRequests.id)) .limit(DELIVERY_BATCH_SIZE); if (requests.length === 0) return true; progress.runCursor = requests[requests.length - 1]!.id; - await clearDeliveredResults(tx, job, progress, requests); + await clearDeliveredResults(tx, scope, progress, requests); return requests.length < DELIVERY_BATCH_SIZE; } - async function runsStep(tx: Db, job: DeletionRow, progress: Progress) { + async function runsStep(tx: Db, scope: Scope, progress: Progress) { if (!progress.currentRun) { let runId = progress.pendingRuns.shift() ?? null; if (!runId) { @@ -611,7 +726,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () .from(heartbeatRuns) .where(and( progress.runCursor ? gt(heartbeatRuns.id, progress.runCursor) : undefined, - runsWithStoredContentSql({ companyId: job.companyId, connectionId: job.connectionId, cutoff: job.requestedAt }), + runsWithStoredContentSql(scope), )) .orderBy(asc(heartbeatRuns.id)) .limit(RUN_BATCH_SIZE); @@ -633,129 +748,229 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () progress.currentRun = null; return false; } - if (!(await runEventPage(tx, job.companyId, run))) return false; - await finishRun(tx, job.companyId, run); + if (!(await runEventPage(tx, scope.companyId, run))) return false; + await finishRun(tx, scope.companyId, run); run.stage = "log"; return false; } - async function step(job: DeletionRow, signal: AbortSignal) { + const connectionJobs: JobStore = { + load: async (id) => (await db.select().from(toolConnectionContentDeletions).where(eq(toolConnectionContentDeletions.id, id)))[0], + scope: (row) => connectionScope({ id: row.connectionId, companyId: row.companyId }, row.requestedAt), + waitMs: () => null, + save: async (tx, row, progress) => (await tx + .update(toolConnectionContentDeletions) + .set({ progress: progress as unknown as Record, updatedAt: new Date() }) + .where(and( + eq(toolConnectionContentDeletions.id, row.id), + eq(toolConnectionContentDeletions.status, "pending"), + eq(toolConnectionContentDeletions.updatedAt, row.updatedAt), + )) + .returning())[0], + finish: async (tx, row, now) => (await tx + .update(toolConnectionContentDeletions) + .set({ status: "completed", completedAt: now, updatedAt: now, lastError: null }) + .where(and( + eq(toolConnectionContentDeletions.id, row.id), + eq(toolConnectionContentDeletions.status, "pending"), + eq(toolConnectionContentDeletions.updatedAt, row.updatedAt), + sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`, + )) + .returning())[0], + activity: (row, counts) => ({ action: "tool_connection.content_deleted", entityType: "tool_connection", entityId: row.connectionId, details: { ...counts } }), + fail: async (row, message) => { + await db + .update(toolConnectionContentDeletions) + .set({ attempts: sql`${toolConnectionContentDeletions.attempts} + 1`, lastError: message, updatedAt: new Date() }) + .where(and(eq(toolConnectionContentDeletions.id, row.id), eq(toolConnectionContentDeletions.status, "pending"))); + }, + }; + + const issueJobs: JobStore = { + load: async (id) => (await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, id)))[0], + scope: (row) => ({ companyId: row.companyId, cutoff: null, connectionId: null, issueId: row.issueId, + runIds: row.scope.runIds ?? [], invocationIds: row.scope.invocationIds ?? [], eventIds: row.scope.eventIds ?? [] }), + waitMs: (row, progress) => { + const waitedMs = Date.now() - row.requestedAt.getTime(); + if (waitedMs >= ISSUE_WAIT_LIMIT_MS || progress.counts.itemsInProgress + progress.counts.runsInProgress === 0) return null; + return Math.min(Math.max(ISSUE_WAIT_MS, waitedMs / 10), ISSUE_WAIT_MAX_MS); + }, + save: async (tx, row, progress, waitMs) => (await tx + .update(issueConnectionContentDeletions) + .set({ + progress: progress as unknown as Record, + updatedAt: new Date(), + ...(waitMs === null ? {} : { notBefore: new Date(Date.now() + waitMs) }), + }) + .where(and( + eq(issueConnectionContentDeletions.id, row.id), + eq(issueConnectionContentDeletions.status, "pending"), + eq(issueConnectionContentDeletions.updatedAt, row.updatedAt), + )) + .returning())[0], + finish: async (tx, row, now) => (await tx + .update(issueConnectionContentDeletions) + .set({ status: "completed", completedAt: now, updatedAt: now, lastError: null }) + .where(and( + eq(issueConnectionContentDeletions.id, row.id), + eq(issueConnectionContentDeletions.status, "pending"), + eq(issueConnectionContentDeletions.updatedAt, row.updatedAt), + sql`${issueConnectionContentDeletions.progress}->>'phase' = 'done'`, + )) + .returning())[0], + activity: (row, counts) => { + const deleted = counts.toolCalls + counts.approvals + counts.auditEvents + counts.appViews + counts.runs; + const open = counts.itemsInProgress + counts.runsInProgress; + if (deleted === 0 && open === 0) return null; + return { action: open > 0 ? "issue.connection_content_deletion_incomplete" : "issue.connection_content_deleted", + entityType: "issue", entityId: row.issueId, details: { ...counts } }; + }, + fail: async (row, message) => { + await db + .update(issueConnectionContentDeletions) + .set({ attempts: sql`${issueConnectionContentDeletions.attempts} + 1`, lastError: message, updatedAt: new Date() }) + .where(and(eq(issueConnectionContentDeletions.id, row.id), eq(issueConnectionContentDeletions.status, "pending"))); + }, + }; + + async function countOpenRunsWithoutTools(tx: Db, scope: Scope) { + if (scope.runIds.length === 0) return 0; + const [open] = await tx + .select({ count: sql`count(*)::int` }) + .from(heartbeatRuns) + .where(and( + eq(heartbeatRuns.companyId, scope.companyId), + sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)})`, + sql`not ${runUsedToolsSql(scope.companyId)}`, + sql`not ${settledRunSql(sql`${heartbeatRuns.id}`)}`, + )); + return open?.count ?? 0; + } + + async function step(store: JobStore, job: Row, signal: AbortSignal) { + const scope = store.scope(job); const progress = readProgress(job); const deletedAt = job.requestedAt.toISOString(); - if (progress.currentRun?.stage === "log" && await removeRunLog(job.companyId, progress.currentRun.id, signal)) { - progress.currentRun.changed = true; + if (progress.currentRun?.stage === "log") { + const removedLog = await removeRunLog(scope.companyId, progress.currentRun.id, signal); + const removedResults = await removeSavedResults(scope.companyId, progress.currentRun.id, signal); + if (removedLog || removedResults) progress.currentRun.changed = true; } return db.transaction(async (rawTx) => { const tx = rawTx as unknown as Db; - const done = progress.phase === "invocations" ? await invocationsStep(tx, job, progress, deletedAt) - : progress.phase === "events" ? await eventsStep(tx, job, progress, deletedAt) - : progress.phase === "auditEvents" ? await auditEventsStep(tx, job, progress, deletedAt) - : progress.phase === "appViews" ? await appViewsStep(tx, job, progress) - : progress.phase === "deliveredResults" ? await deliveredResultsStep(tx, job, progress) - : await runsStep(tx, job, progress); + const done = progress.phase === "invocations" ? await invocationsStep(tx, scope, progress, deletedAt) + : progress.phase === "events" ? await eventsStep(tx, scope, progress, deletedAt) + : progress.phase === "auditEvents" ? await auditEventsStep(tx, scope, progress, deletedAt) + : progress.phase === "appViews" ? await appViewsStep(tx, scope, progress) + : progress.phase === "deliveredResults" ? await deliveredResultsStep(tx, scope, progress) + : await runsStep(tx, scope, progress); if (done) { progress.phase = nextPhase(progress.phase); progress.cursor = null; progress.runCursor = null; progress.currentRun = null; progress.pendingRuns = []; + if (progress.phase === "done" && scope.issueId) progress.counts.runsInProgress += await countOpenRunsWithoutTools(tx, scope); } - const [saved] = await tx - .update(toolConnectionContentDeletions) - .set({ progress: progress as unknown as Record, updatedAt: new Date() }) - .where(and( - eq(toolConnectionContentDeletions.id, job.id), - eq(toolConnectionContentDeletions.status, "pending"), - eq(toolConnectionContentDeletions.updatedAt, job.updatedAt), - )) - .returning(); + const waitMs = progress.phase === "done" ? store.waitMs(job, progress) : null; + if (waitMs !== null) { + Object.assign(progress, { ...initialContentDeletionProgress(), counts: { ...progress.counts, itemsInProgress: 0, runsInProgress: 0 } }); + } + const saved = await store.save(tx, job, progress, waitMs); if (!saved) throw new ProgressConflict(); - return saved; + return { row: saved, waiting: waitMs !== null }; }); } - async function complete(job: DeletionRow) { - const progress = readProgress(job); - const now = new Date(); - return db.transaction(async (tx) => { - const [done] = await tx - .update(toolConnectionContentDeletions) - .set({ status: "completed", completedAt: now, updatedAt: now, lastError: null }) - .where(and( - eq(toolConnectionContentDeletions.id, job.id), - eq(toolConnectionContentDeletions.status, "pending"), - eq(toolConnectionContentDeletions.updatedAt, job.updatedAt), - sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`, - )) - .returning(); + async function complete(store: JobStore, job: Row) { + const counts = readProgress(job).counts; + return db.transaction(async (rawTx) => { + const tx = rawTx as unknown as Db; + const done = await store.finish(tx, job, new Date()); if (!done) return null; - await logActivity(tx as unknown as Db, { - companyId: job.companyId, - actorType: job.requestedByActorType === "agent" ? "agent" : job.requestedByActorType === "user" ? "user" : "system", - actorId: job.requestedByActorId ?? "tool-connection-content-deletion", - action: "tool_connection.content_deleted", - entityType: "tool_connection", - entityId: job.connectionId, - details: { ...progress.counts }, - }); + const activity = store.activity(job, counts); + if (activity) { + await logActivity(tx, { + companyId: job.companyId, + actorType: job.requestedByActorType === "agent" ? "agent" : job.requestedByActorType === "user" ? "user" : "system", + actorId: job.requestedByActorId ?? "tool-connection-content-deletion", + ...activity, + }); + } return done; }); } - async function process(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) { + async function runJob(store: JobStore, jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) { const startedAt = Date.now(); - let [job] = await db.select().from(toolConnectionContentDeletions).where(eq(toolConnectionContentDeletions.id, jobId)); - if (!job || job.status !== "pending") return job ?? null; + const loaded = await store.load(jobId); + if (!loaded || loaded.status !== "pending") return loaded ?? null; + let job: Row = loaded; try { while (!signal.aborted) { - if (readProgress(job).phase === "done") return await complete(job); - job = await step(job, signal); - if (Date.now() - startedAt >= budgetMs) return job; + if (readProgress(job).phase === "done") return await complete(store, job); + const next: { row: Row; waiting: boolean } = await step(store, job, signal); + job = next.row; + if (next.waiting || Date.now() - startedAt >= budgetMs) return job; } return job; } catch (error) { if (error instanceof ProgressConflict) return null; - await db - .update(toolConnectionContentDeletions) - .set({ - attempts: sql`${toolConnectionContentDeletions.attempts} + 1`, - lastError: error instanceof Error ? error.message.slice(0, 500) : "content deletion failed", - updatedAt: new Date(), - }) - .where(and(eq(toolConnectionContentDeletions.id, job.id), eq(toolConnectionContentDeletions.status, "pending"))); + await store.fail(job, error instanceof Error ? error.message.slice(0, 500) : "content deletion failed"); throw error; } } + async function process(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) { + return runJob(connectionJobs, jobId, signal, budgetMs); + } + + async function processIssueDeletion(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) { + return runJob(issueJobs, jobId, signal, budgetMs); + } + async function processPending(signal: AbortSignal) { - const rows = await db + let failure: unknown = null; + const connectionPending = await db .select({ id: toolConnectionContentDeletions.id }) .from(toolConnectionContentDeletions) .where(eq(toolConnectionContentDeletions.status, "pending")) .orderBy(asc(toolConnectionContentDeletions.updatedAt)) .limit(10); - let failure: unknown = null; - for (const { id } of rows) { + for (const { id } of connectionPending) { if (signal.aborted) break; - try { - await process(id, signal); - } catch (error) { - failure ??= error; - } + await process(id, signal).catch((error: unknown) => { failure ??= error; }); } + const issuePending = await db + .select({ id: issueConnectionContentDeletions.id }) + .from(issueConnectionContentDeletions) + .where(and(eq(issueConnectionContentDeletions.status, "pending"), lte(issueConnectionContentDeletions.notBefore, new Date()))) + .orderBy(asc(issueConnectionContentDeletions.notBefore)) + .limit(10); + for (const { id } of issuePending) { + if (signal.aborted) break; + await processIssueDeletion(id, signal).catch((error: unknown) => { failure ??= error; }); + } + if (!signal.aborted) await storedObjects.drain(signal).catch((error: unknown) => { failure ??= error; }); if (failure) throw failure; } async function nextDeadline() { - const [row] = await db + const [connectionJob] = await db .select({ id: toolConnectionContentDeletions.id }) .from(toolConnectionContentDeletions) .where(eq(toolConnectionContentDeletions.status, "pending")) .limit(1); - return row ? Date.now() : null; + if (connectionJob) return Date.now(); + const [issueJob] = await db + .select({ at: sql`min(${issueConnectionContentDeletions.notBefore})`.mapWith(issueConnectionContentDeletions.notBefore) }) + .from(issueConnectionContentDeletions) + .where(eq(issueConnectionContentDeletions.status, "pending")); + const due = [issueJob?.at?.getTime() ?? null, await storedObjects.nextDeadline()].flatMap((at) => at === null ? [] : [at]); + return due.length > 0 ? Math.max(Date.now(), Math.min(...due)) : null; } - return { storedContent, latestDeletion, request, process, processPending, nextDeadline }; + return { storedContent, latestDeletion, request, process, processIssueDeletion, processPending, nextDeadline }; } export type ConnectionContentDeletionService = ReturnType; diff --git a/server/src/services/tool-access/connections/issue-content-deletion.ts b/server/src/services/tool-access/connections/issue-content-deletion.ts new file mode 100644 index 00000000000..15595954b9b --- /dev/null +++ b/server/src/services/tool-access/connections/issue-content-deletion.ts @@ -0,0 +1,57 @@ +import { and, eq, sql } from "drizzle-orm"; +import { heartbeatRuns, issueConnectionContentDeletions, toolCallEvents, toolInvocations, type Db } from "@paperclipai/db"; +import { initialContentDeletionProgress, runUsedToolsSql, settledRunSql, uuidList } from "./content-deletion.js"; +import { requestIssueAttachmentObjectDeletion } from "./stored-object-deletion.js"; + +export async function requestIssueConnectionContentDeletion( + tx: Db, + input: { companyId: string; issueId: string; actorAgentId?: string | null }, +) { + await requestIssueAttachmentObjectDeletion(tx, input); + const runs = await tx + .select({ id: heartbeatRuns.id }) + .from(heartbeatRuns) + .where(and( + eq(heartbeatRuns.companyId, input.companyId), + sql`(${heartbeatRuns.issueId} = ${input.issueId} or ${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}::text)`, + sql`(${runUsedToolsSql(input.companyId)} or not ${settledRunSql(sql`${heartbeatRuns.id}`)})`, + )); + const runIds = runs.map((row) => row.id); + const calls = await tx + .select({ id: toolInvocations.id }) + .from(toolInvocations) + .where(and( + eq(toolInvocations.companyId, input.companyId), + eq(toolInvocations.issueId, input.issueId), + sql`(${toolInvocations.runId} is null or not (${toolInvocations.runId} = any(${uuidList(runIds)})))`, + )); + const invocationIds = calls.map((row) => row.id); + const events = await tx + .select({ id: toolCallEvents.id }) + .from(toolCallEvents) + .where(and( + eq(toolCallEvents.companyId, input.companyId), + eq(toolCallEvents.issueId, input.issueId), + sql`(${toolCallEvents.runId} is null or not (${toolCallEvents.runId} = any(${uuidList(runIds)})))`, + sql`(${toolCallEvents.invocationId} is null or not (${toolCallEvents.invocationId} = any(${uuidList(invocationIds)})))`, + )); + const eventIds = events.map((row) => row.id); + if (runIds.length === 0 && invocationIds.length === 0 && eventIds.length === 0) return null; + const now = new Date(); + const [created] = await tx + .insert(issueConnectionContentDeletions) + .values({ + requestedAt: now, + notBefore: now, + createdAt: now, + updatedAt: now, + companyId: input.companyId, + issueId: input.issueId, + scope: { runIds, invocationIds, eventIds }, + requestedByActorType: input.actorAgentId ? "agent" : "system", + requestedByActorId: input.actorAgentId ?? null, + progress: initialContentDeletionProgress() as unknown as Record, + }) + .returning({ id: issueConnectionContentDeletions.id }); + return created!.id; +} diff --git a/server/src/services/tool-access/connections/stored-object-deletion.ts b/server/src/services/tool-access/connections/stored-object-deletion.ts new file mode 100644 index 00000000000..b22e1f6f1aa --- /dev/null +++ b/server/src/services/tool-access/connections/stored-object-deletion.ts @@ -0,0 +1,80 @@ +import { asc, eq, lte, sql } from "drizzle-orm"; +import { assets, heartbeatRuns, runnerApiResponseReservations, storedObjectDeletions, type Db } from "@paperclipai/db"; +import { isRunLogStoreType, type RunLogStore } from "../../run-log-store.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js"; +import type { StorageService } from "../../../storage/types.js"; + +const OBJECT_BATCH_SIZE = 50; +const OBJECT_RETRY_MS = 30_000; + +export async function requestIssueAttachmentObjectDeletion(tx: Db, input: { companyId: string; issueId: string }) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolConnectionContentDeletion); + await tx.execute(sql`insert into ${storedObjectDeletions} (company_id, kind, object_key) + select asset.company_id, 'asset', asset.object_key from ${assets} asset + join issue_attachments link on link.asset_id = asset.id + where link.company_id = ${input.companyId} and link.issue_id = ${input.issueId} and asset.company_id = ${input.companyId}`); +} + +export async function requestCompanyStoredObjectDeletion(tx: Db, companyId: string) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolConnectionContentDeletion); + await tx.execute(sql`insert into ${storedObjectDeletions} (company_id, kind, log_store, object_key) + select company_id, 'run_log', log_store, log_ref from ${heartbeatRuns} + where company_id = ${companyId} and log_ref is not null and log_store is not null + union all + select company_id, 'asset', null, object_key from ${assets} where company_id = ${companyId} + union all + select company_id, 'asset', null, pending_delete_object_key from ${runnerApiResponseReservations} + where company_id = ${companyId} and pending_delete_object_key is not null`); +} + +export function createStoredObjectDeletion(db: Db, deps: { + runLogStore: () => RunLogStore; + storage: () => StorageService; + retryMs?: number; +}) { + const retryMs = deps.retryMs ?? OBJECT_RETRY_MS; + + async function drain(signal: AbortSignal) { + const rows = await db + .select() + .from(storedObjectDeletions) + .where(lte(storedObjectDeletions.notBefore, new Date())) + .orderBy(asc(storedObjectDeletions.notBefore), asc(storedObjectDeletions.id)) + .limit(OBJECT_BATCH_SIZE); + let failure: unknown = null; + for (const row of rows) { + if (signal.aborted) break; + try { + if (row.kind === "run_log") { + if (!isRunLogStoreType(row.logStore)) throw new Error("run_log_store_unrecognised"); + const store = deps.runLogStore(); + if (!store.remove) throw new Error("run_log_removal_unavailable"); + await store.remove({ store: row.logStore, logRef: row.objectKey }, signal); + } else { + await deps.storage().deleteObject(row.companyId, row.objectKey, { signal, allVersions: true }); + } + await db.delete(storedObjectDeletions).where(eq(storedObjectDeletions.id, row.id)); + } catch (error) { + failure ??= error; + await db + .update(storedObjectDeletions) + .set({ + attempts: sql`${storedObjectDeletions.attempts} + 1`, + lastError: error instanceof Error ? error.message.slice(0, 500) : "object deletion failed", + notBefore: new Date(Date.now() + retryMs * 2 ** Math.min(row.attempts, 6)), + }) + .where(eq(storedObjectDeletions.id, row.id)); + } + } + if (failure) throw failure; + } + + async function nextDeadline() { + const [row] = await db + .select({ at: sql`min(${storedObjectDeletions.notBefore})`.mapWith(storedObjectDeletions.notBefore) }) + .from(storedObjectDeletions); + return row?.at ? row.at.getTime() : null; + } + + return { drain, nextDeadline }; +}