The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix: recover saved work and provide reliable task Retry (#16965)
Dottad33b40a5c361
diff --git a/doc/task-recovery.md b/doc/task-recovery.mdnew file mode 100644index 0000000000..bc59048df5--- /dev/null+++ b/doc/task-recovery.md@@ -0,0 +1,128 @@+# Automatic task recovery++Infrastructure recovery belongs to the system. A task shows one working state,+one scheduled retry, or an ordinary **Retry** action. Approval, credentials,+assignment, budget and deliberate pause remain separate user decisions.++## Admission and execution++`POST /api/issues/:id/retry` accepts `{ idempotencyKey, observedRunId }`.+It requires authenticated board task-mutation authority. It records an+`agent_wakeup_requests` receipt before physical work. Company/key uniqueness+covers completed and failed receipts as well as pending ones. Concurrent clicks+attach to accepted work. A new deliberate click after exhaustion can create a+new generation; a repeated HTTP request cannot.++The existing exact-run retry endpoint retains its source-bound contract.+Connected conversations use their existing inbound authorization owner. A board+Retry changes the workspace strategy, not the external principal, source batch,+conversation access or publication authority.++Agent Chat additionally requires the current conversation owner and enabled+Agent Chat. Admission and dispatch both recheck these conditions under the+issue lock. An unadmitted receipt from a former owner cannot own the current+owner's Retry.++The normal dispatch queue rechecks task eligibility and claims saved input.+An accepted native result goes back to its existing finalizer. Recovery does+not create a second agent to reproduce that result.++## Files, ownership and effects++The source recovery action holds a validated `systemRecovery` record. Its+revision and generation fence late bookkeeping writes. Physical exports still+use the existing workspace ownership lock and controller stop receipts.++Execution containment and file preservation are independent facts:++- Another agent needs authoritative containment of the old executor.+- Copyback needs a quiescent writer and a verified destination.+- A fresh attempt uses a new execution workspace and the separate+ `isolated-workspace-attempts` namespace. It does not modify the original+ directory or satisfy that source's preservation/cleanup obligation.++Fresh attempts currently require Core-managed storage. Plugin-owned storage+does not yet support importing these preserved snapshots. Preparation stops+before calling that provider or acquiring an environment. It retains the+original workspace rather than reopening it as a fresh attempt.++Valid native baselines use the existing merge. A bound historical source+without a merge baseline is exported to configured storage as an immutable,+verified snapshot. Upload operations have stable identities and manifests.+Recovered snapshots attach separately with provenance; they never become an+invented baseline for overwriting newer files.++Known publication receipts and exact API mutation receipts carry forward.+Uncertain API mutations and upstream tool mutations remain fenced across run+replacement. Reads and independent work remain available. Generic upstream+tools have no universal result-query protocol, so their unknown mutations+require authoritative reconciliation rather than a new call key. Existing+GitHub publication reconciliation stays with its dedicated receipt owner.++## Retry policy and historical adoption++Maintenance allows an initial attempt and five retries at 30, 60, 120, 240 and+480 seconds with persisted ±20% jitter. Scheduling stops 30 minutes after the+first failure. A longer provider cooldown takes precedence. Restarts, phase+changes and rescans do not replenish the budget. Existing stricter execution+retry limits remain separate.++The maintenance sweep classifies at most 50 historical records per tick.+Indexed source queries and durable policy markers prevent repeat adoption.+It includes retained leases, legacy runs without native descriptors, exhausted+actions and resolved actions that still owe preservation. Historical failure+evidence remains intact.++Saved authorized follow-ups may continue through normal dispatch. A task with+no waiting request requires Retry before another agent turn. Completed,+cancelled, deliberately paused and superseded tasks do not reopen merely+because old files need maintenance.++`historicalRecoveryCounts` reports classification, preservation, input delivery,+waiting-for-Retry and unresolved-source counts for protected diagnostics.+Adoption alone is not proof that files were recovered.++## Local diagnostics and presentation++Recovery and its durable failure evidence stay inside the stack. Exhausted+attempts remain on the system-owned source recovery record with their failure+code, evidence fingerprint and retry budget. The existing local server log+records preservation failures. Recovery does not add a Cloud incident endpoint,+notification worker or outbound reporting channel.++The task interruption projection drives thread, composer and list status.+Thinking is optimistic presentation, not a fake run or provider-start record.+Unknown admission reconciles the same request key. Backoff and real user gates+replace Thinking when work is not active. Saved input is editable; Steer and+Interrupt require a live target. Technical diagnostics remain inspectable.++## Qualification++Run the focused PostgreSQL/filesystem suites from `server/`:++```sh+../node_modules/.bin/vitest run --config vitest.config.ts \+ src/services/system-recovery-state.test.ts \+ src/services/task-retry.test.ts \+ src/services/workspace-recovery.test.ts \+ src/services/explicit-native-continuation.test.ts \+ src/services/heartbeat/workspace-preparation.test.ts \+ src/services/native-runtime/native-chat-workspace.test.ts+```++`server/scripts/workspace-recovery-provider.test.mjs` is an opt-in controlled+Daytona probe. It requires `PAPERCLIP_RECOVERY_LIVE=1`, `DAYTONA_API_KEY`,+`PAPERCLIP_DAYTONA_SDK_PATH` and an immutable `PAPERCLIP_RECOVERY_IMAGE`.+It interrupts export,+joins the first controller, starts a second controller and verifies files,+preservation receipts, agent-start count and external-operation count before+cleanup. It does not claim an abrupt controller kill or a live LLM/GitHub test.++The local browser fixture uses the actual API, PostgreSQL and native runner+with a deterministic model process. Verify immediate Thinking with delayed+HTTP, one successor, the independent directory, unchanged source files, a+useful result and stable completion after reload.++Neither this probe nor a green build proves hosted recovery. Hosted acceptance+requires the actual served revision, the original saved input, readable+preserved files, and confirmation that completed publications were not repeated.diff --git a/maps/agent-access-map/recovery.md b/maps/agent-access-map/recovery.mdindex 8824b6a345..2b37935279 100644--- a/maps/agent-access-map/recovery.md+++ b/maps/agent-access-map/recovery.md@@ -64,6 +64,18 @@ Gaps: Component host test doesn't prove actual filesystem/provider repair.Capability ID: `recovery/bounded-continuation`.+Ordinary task Retry uses `POST /api/issues/{id}/retry`. This is authenticated+board task-mutation authority, not agent retry authority. The only request+fields are a UUID idempotency key and observed source run (or null). It accepts+no paths, stop attestations or client-selected strategy. The source-scoped+exact-run and maintenance APIs retain their existing contracts. Connected-chat+Retry reuses chat admission and its external identity. See the+[durable contract](../../doc/task-recovery.md). Agent Chat also requires its+current conversation owner and feature enablement at admission and locked+dispatch; generic board mutation permission does not replace chat ownership.+Local PostgreSQL and assembled+browser qualification do not establish hosted agent access or recovery.+Review: `operation-reviewed`.Supported restoration and automatic attempts retain source/owner/attempt authority.diff --git a/maps/feature-map/recovery.md b/maps/feature-map/recovery.mdindex dbb7ea7c62..8f9f00902b 100644--- a/maps/feature-map/recovery.md+++ b/maps/feature-map/recovery.md@@ -21,12 +21,13 @@ Agent access: [companion](../agent-access-map/recovery.md).conversation context and bounded attempts, without blindly replaying tools.- `source-action`: `recovery/source-action` — source-scoped recovery actions remain attached to the task;independent repair work may have its own issue and return owner.-- `exhaustion`: `recovery/exhaustion` — exhausted or overdue recovery exposes the current gate and- permitted operator action; it does not claim an automatic path is still live.+- `exhaustion`: `recovery/exhaustion` — an exhausted infrastructure attempt offers ordinary Retry.+ Internal repair stays system-owned; genuine user decisions retain their+ specific action.- `workspace`: `recovery/workspace` — workspace divergence/export failures show the applicable repair,reconcile, or isolated reissue action with evidence and authority checks.Retained-file recovery runs in the harness with observed task progress and a- Retry recovery action only after transient failures. It preserves newer files,+ ordinary Retry action after exhaustion or during backoff. It preserves newer files,keeps uncertain sources held, and delivers saved human input through ordinaryadmission. The task does not expose infrastructure-certification forms or aworkspace link when the destination is disabled. Local PostgreSQL and real@@ -44,15 +45,13 @@ Agent access: [companion](../agent-access-map/recovery.md).### `source-task`Open the affected task from Tasks, Inbox/Blocked, search, or a direct task link.-Inspect the recovery notice/card in its history, expand details if needed, and-use the currently offered action. Follow any linked repair task and return owner.+Observe one working, backoff, failed or waiting-for-user state. Use Retry after+an infrastructure failure. No process or file certification is required.-An authorized board user can expand Recovery details on a stopped-run notice to-read the decision that still blocks replay, including a settled recovery record.-The notice matches the current action and run; it does not show another run's-historical decision or authorize a retry. Source-reviewed behavior; the-[notice regressions](../../ui/src/components/ExecutionBlockerNotice.test.tsx)-cover empty active recovery, a mismatched source, and failed history reads.+Thinking appears immediately after Retry, before the request completes.+Technical source/run details remain in deliberate diagnostics. The+[task recovery contract](../../doc/task-recovery.md) describes receipt identity,+fresh workspaces, bounded retries, historical adoption and service incidents.### `run-detail`@@ -64,9 +63,9 @@ stopped-run recovery checks.### `operator-retry`-On an exhausted disposition or workspace recovery card, inspect the current-reason and use the permitted retry/repair/reconcile action. Some repairs require-confirmation; unavailable actions must explain the gate or remain absent.+Use the task's Retry action. It can create an isolated attempt after old execution+is contained even when old-file preservation remains unresolved. Approval,+credentials, budget and deliberate pause use their existing specific controls.### `post-stop-message`@@ -210,10 +209,9 @@ confirmation. [Workspace export](../../ui/src/components/WorkspaceExportRecoverycovers quiet restoration, legacy/operator assistance and resolved states.For a retained legacy or native file hold, open the source task after its recovery-action has resolved but its files still need recovery. The task shows a compact-operator-attention notice with inspection and collapsed diagnostics, without a-file-certification form. A source-bound live recovery uses the ordinary working-state; a missed or exhausted retry and an unknown action outcome remain visible.+action has resolved but its files still need recovery. The shared task projection+shows actual working/backoff state or ordinary Retry. It does not show a separate+infrastructure attention card. Unknown external outcomes remain fenced internally.An authorized board operator can use the resolution API to record verified filesand a backup link without changing task status or starting another run. Theserver independently validates the original stopped-execution receipt. Agentdiff --git a/packages/adapter-utils/src/sandbox-managed-runtime.ts b/packages/adapter-utils/src/sandbox-managed-runtime.tsindex abbb34aca4..0997fb87fb 100644--- a/packages/adapter-utils/src/sandbox-managed-runtime.ts+++ b/packages/adapter-utils/src/sandbox-managed-runtime.ts@@ -916,7 +916,7 @@ async function* walkDirectory(root: string, relative = "", childrenFirst = false}}-async function confineFullWorkspaceExport(root: string): Promise<void> {+async function confineFullWorkspaceExport(root: string, rejectExternalSymlinks = false): Promise<void> {const unsafe = () => Object.assign(new Error("Unsafe workspace export directory"), { code: "WORKSPACE_RESTORE_UNSAFE_ARCHIVE" });if (!(await fs.lstat(root)).isDirectory()) throw unsafe();const canonicalRoot = await fs.realpath(root);@@ -930,14 +930,61 @@ async function confineFullWorkspaceExport(root: string): Promise<void> {const target = await fs.readlink(entryPath);const resolved = path.resolve(directory, target);if (path.isAbsolute(target) || (resolved !== canonicalRoot && !resolved.startsWith(`${canonicalRoot}${path.sep}`))) {+ if (rejectExternalSymlinks) throw unsafe();await fs.unlink(entryPath);}+ if (rejectExternalSymlinks) {+ const canonicalTarget = await fs.realpath(entryPath).catch(() => { throw unsafe(); });+ if (canonicalTarget !== canonicalRoot && !canonicalTarget.startsWith(`${canonicalRoot}${path.sep}`)) throw unsafe();+ }} else if (!stats.isFile()) throw unsafe();}};await walk(canonicalRoot);}+/** Export into a caller-owned empty staging directory, without a merge baseline+ * or any writes to the original host workspace. The normal transfer client owns+ * archive validation; snapshots additionally reject links that cannot be kept. */+export async function exportSandboxWorkspaceSnapshot(input: {+ client: SandboxManagedRuntimeClient;+ remoteDir: string;+ stagingDir: string;+ operationId: string;+}): Promise<void> {+ await fs.mkdir(input.stagingDir, { recursive: true });+ if ((await fs.readdir(input.stagingDir)).length) throw new Error("Workspace snapshot destination is not empty");+ const operations: SandboxSyncOperation[] = [{+ operationId: input.operationId,+ files: [{ sourcePath: input.remoteDir, targetPath: input.stagingDir, kind: "directory", exclude: [".paperclip-runtime"] }],+ }];+ assertSyncOperationsConfined(operations, { sourceRoots: [input.remoteDir], targetRoots: [input.stagingDir] });+ if (!input.client.syncOut) throw Object.assign(new Error("Validated workspace export is unavailable for this provider"),+ { code: "WORKSPACE_SNAPSHOT_EXPORT_UNSUPPORTED" });+ await input.client.syncOut(operations);+ await confineFullWorkspaceExport(input.stagingDir, true);+}++/** Only host-created snapshot archives qualify: the expected digest comes from+ * a verified preservation receipt, never an agent or upload request. */+export async function restoreVerifiedSnapshotArchive(input: {+ archivePath: string; localDir: string; sha256: string; byteSize: number;+}): Promise<void> {+ const hash = createHash("sha256");+ let size = 0;+ for await (const bytes of createReadStream(input.archivePath)) {+ size += bytes.length;+ if (size > input.byteSize) throw new Error("Workspace snapshot size changed");+ hash.update(bytes);+ }+ if (size !== input.byteSize || hash.digest("hex") !== input.sha256)+ throw new Error("Workspace snapshot digest changed");+ await fs.mkdir(input.localDir, { recursive: true });+ if ((await fs.readdir(input.localDir)).length) throw new Error("Workspace snapshot destination is not empty");+ await extractTarballToDirectory(input);+ await confineFullWorkspaceExport(input.localDir, true);+}+async function copyWorkspaceEntry(sourceRoot: string, targetRoot: string, relative: string): Promise<void> {const sourcePath = path.join(sourceRoot, relative);const targetPath = path.join(targetRoot, relative);diff --git a/packages/db/src/client.ts b/packages/db/src/client.tsindex 5efa60e511..2673eae108 100644--- a/packages/db/src/client.ts+++ b/packages/db/src/client.ts@@ -474,6 +474,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set(["0314_private_task_draft_assets.sql","0332_little_night_nurse.sql","0345_luxuriant_carmella_unuscione.sql",+ "0369_late_logan.sql",]);async function applyPendingMigrationsManually(diff --git a/packages/db/src/migrations/0369_late_logan.sql b/packages/db/src/migrations/0369_late_logan.sqlnew file mode 100644index 0000000000..2f34bf493d--- /dev/null+++ b/packages/db/src/migrations/0369_late_logan.sql@@ -0,0 +1,13 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "agent_wakeup_requests_task_retry_idempotency_uq" ON "agent_wakeup_requests" USING btree ("company_id","idempotency_key") WHERE "agent_wakeup_requests"."idempotency_key" LIKE 'task-retry:%';--> statement-breakpoint+CREATE INDEX CONCURRENTLY IF NOT EXISTS "environment_leases_retained_recovery_adoption_idx" ON "environment_leases" USING btree ("heartbeat_run_id") WHERE "environment_leases"."lease_policy" = 'retain_on_failure'+ and "environment_leases"."heartbeat_run_id" is not null+ and not (coalesce("environment_leases"."metadata", '{}'::jsonb) ? 'systemRecoveryAdoption');--> statement-breakpoint+CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_retained_recovery_adoption_idx" ON "heartbeat_runs" USING btree ("id") WHERE "heartbeat_runs"."result_json"->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ and not (coalesce("heartbeat_runs"."result_json", '{}'::jsonb) ? 'systemRecoveryAdoption')+ and "heartbeat_runs"."status" in ('failed', 'interrupted', 'timed_out', 'cancelled', 'succeeded');--> statement-breakpoint+CREATE INDEX CONCURRENTLY IF NOT EXISTS "issue_recovery_actions_source_run_idx" ON "issue_recovery_actions" USING btree ("company_id","source_issue_id",("evidence"->>'runId'));--> statement-breakpoint+CREATE INDEX CONCURRENTLY IF NOT EXISTS "issue_recovery_actions_system_recovery_due_idx" ON "issue_recovery_actions" USING btree (("evidence"#>'{systemRecovery,nextAttemptAt}'),"id") WHERE "issue_recovery_actions"."evidence" ? 'systemRecovery';--> statement-breakpoint+CREATE INDEX CONCURRENTLY IF NOT EXISTS "issue_recovery_actions_system_recovery_adoption_idx" ON "issue_recovery_actions" USING btree ("id") WHERE not ("issue_recovery_actions"."evidence" ? 'systemRecovery') and (+ "issue_recovery_actions"."evidence"->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ or "issue_recovery_actions"."cause" in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted')+ );diff --git a/packages/db/src/migrations/meta/0364_snapshot.json b/packages/db/src/migrations/meta/0369_snapshot.jsonsimilarity index 93%rename from packages/db/src/migrations/meta/0364_snapshot.jsonrename to packages/db/src/migrations/meta/0369_snapshot.jsonindex 0b2afe2572..5759c0dc99 100644--- a/packages/db/src/migrations/meta/0364_snapshot.json+++ b/packages/db/src/migrations/meta/0369_snapshot.json@@ -1,6 +1,6 @@{- "id": "f31e8e2c-93a9-4dd5-8e85-08fe53d76afc",- "prevId": "3f3c40f1-0a9c-4f45-b194-c5af168277a3",+ "id": "9fa514b5-5cd1-4350-9b77-f60924655298",+ "prevId": "a9c12cbc-ed4b-4e5d-9d33-36f9a7fb746c","version": "7","dialect": "postgresql","tables": {@@ -64,37 +64,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"accounting_runtime_baselines_agent_id_agents_id_fk": {"name": "accounting_runtime_baselines_agent_id_agents_id_fk","tableFrom": "accounting_runtime_baselines",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"accounting_runtime_baselines_company_id_companies_id_fk": {"name": "accounting_runtime_baselines_company_id_companies_id_fk","tableFrom": "accounting_runtime_baselines",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -200,9 +200,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"billing_invoice_lines_company_idx": {"name": "billing_invoice_lines_company_idx",@@ -221,50 +221,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"billing_invoice_lines_company_id_companies_id_fk": {"name": "billing_invoice_lines_company_id_companies_id_fk","tableFrom": "billing_invoice_lines",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"billing_invoice_lines_invoice_id_billing_invoices_id_fk": {"name": "billing_invoice_lines_invoice_id_billing_invoices_id_fk","tableFrom": "billing_invoice_lines",+ "tableTo": "billing_invoices","columnsFrom": ["invoice_id"],- "tableTo": "billing_invoices","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"billing_invoice_lines_cost_event_id_cost_events_id_fk": {"name": "billing_invoice_lines_cost_event_id_cost_events_id_fk","tableFrom": "billing_invoice_lines",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -361,24 +361,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"billing_invoices_company_id_companies_id_fk": {"name": "billing_invoices_company_id_companies_id_fk","tableFrom": "billing_invoices",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -491,9 +491,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_reservations_prompt_injection_idx": {"name": "budget_reservations_prompt_injection_idx",@@ -512,9 +512,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_reservations_decision_idx": {"name": "budget_reservations_decision_idx",@@ -533,9 +533,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_reservations_run_idx": {"name": "budget_reservations_run_idx",@@ -554,9 +554,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_reservations_active_idx": {"name": "budget_reservations_active_idx",@@ -581,51 +581,51 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"budget_reservations\".\"state\" = 'held'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"budget_reservations_company_id_companies_id_fk": {"name": "budget_reservations_company_id_companies_id_fk","tableFrom": "budget_reservations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"budget_reservations_run_id_heartbeat_runs_id_fk": {"name": "budget_reservations_run_id_heartbeat_runs_id_fk","tableFrom": "budget_reservations",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"budget_reservations_agent_id_agents_id_fk": {"name": "budget_reservations_agent_id_agents_id_fk","tableFrom": "budget_reservations",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -758,9 +758,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_adjustments_event_idx": {"name": "cost_adjustments_event_idx",@@ -785,9 +785,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_adjustments_invoice_line_idx": {"name": "cost_adjustments_invoice_line_idx",@@ -806,50 +806,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"cost_adjustments_company_id_companies_id_fk": {"name": "cost_adjustments_company_id_companies_id_fk","tableFrom": "cost_adjustments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"cost_adjustments_cost_event_id_cost_events_id_fk": {"name": "cost_adjustments_cost_event_id_cost_events_id_fk","tableFrom": "cost_adjustments",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"cost_adjustments_invoice_line_id_billing_invoice_lines_id_fk": {"name": "cost_adjustments_invoice_line_id_billing_invoice_lines_id_fk","tableFrom": "cost_adjustments",+ "tableTo": "billing_invoice_lines","columnsFrom": ["invoice_line_id"],- "tableTo": "billing_invoice_lines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -961,24 +961,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"provider_billing_snapshots_company_id_companies_id_fk": {"name": "provider_billing_snapshots_company_id_companies_id_fk","tableFrom": "provider_billing_snapshots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -1088,9 +1088,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"run_usage_receipts_run_latest_idx": {"name": "run_usage_receipts_run_latest_idx",@@ -1115,37 +1115,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"run_usage_receipts_company_id_companies_id_fk": {"name": "run_usage_receipts_company_id_companies_id_fk","tableFrom": "run_usage_receipts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"run_usage_receipts_run_id_heartbeat_runs_id_fk": {"name": "run_usage_receipts_run_id_heartbeat_runs_id_fk","tableFrom": "run_usage_receipts",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -1257,9 +1257,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"activity_log_company_agent_created_idx": {"name": "activity_log_company_agent_created_idx",@@ -1284,9 +1284,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"activity_log_company_responsible_user_created_idx": {"name": "activity_log_company_responsible_user_created_idx",@@ -1311,9 +1311,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"activity_log_run_id_idx": {"name": "activity_log_run_id_idx",@@ -1326,9 +1326,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"activity_log_entity_type_id_idx": {"name": "activity_log_entity_type_id_idx",@@ -1347,50 +1347,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"activity_log_company_id_companies_id_fk": {"name": "activity_log_company_id_companies_id_fk","tableFrom": "activity_log",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"activity_log_agent_id_agents_id_fk": {"name": "activity_log_agent_id_agents_id_fk","tableFrom": "activity_log",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"activity_log_run_id_heartbeat_runs_id_fk": {"name": "activity_log_run_id_heartbeat_runs_id_fk","tableFrom": "activity_log",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -1546,9 +1546,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"adapter_auth_sessions_company_owner_adapter_active_uq": {"name": "adapter_auth_sessions_company_owner_adapter_active_uq",@@ -1573,10 +1573,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"adapter_auth_sessions\".\"status\" IN ('starting', 'waiting_for_user', 'promoting', 'awaiting_code', 'submitting')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"adapter_auth_sessions_public_session_id_uq": {"name": "adapter_auth_sessions_public_session_id_uq",@@ -1589,9 +1589,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"adapter_auth_sessions_environment_idx": {"name": "adapter_auth_sessions_environment_idx",@@ -1604,9 +1604,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"adapter_auth_sessions_expires_idx": {"name": "adapter_auth_sessions_expires_idx",@@ -1619,9 +1619,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"adapter_auth_sessions_provider_lease_idx": {"name": "adapter_auth_sessions_provider_lease_idx",@@ -1634,37 +1634,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"adapter_auth_sessions_company_id_companies_id_fk": {"name": "adapter_auth_sessions_company_id_companies_id_fk","tableFrom": "adapter_auth_sessions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"adapter_auth_sessions_environment_id_environments_id_fk": {"name": "adapter_auth_sessions_environment_id_environments_id_fk","tableFrom": "adapter_auth_sessions",+ "tableTo": "environments","columnsFrom": ["environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -1752,9 +1752,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_api_keys_company_agent_idx": {"name": "agent_api_keys_company_agent_idx",@@ -1773,37 +1773,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_api_keys_agent_id_agents_id_fk": {"name": "agent_api_keys_agent_id_agents_id_fk","tableFrom": "agent_api_keys",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_api_keys_company_id_companies_id_fk": {"name": "agent_api_keys_company_id_companies_id_fk","tableFrom": "agent_api_keys",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -1903,9 +1903,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_commentary_company_kind_created_idx": {"name": "agent_commentary_company_kind_created_idx",@@ -1930,63 +1930,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_commentary_company_id_companies_id_fk": {"name": "agent_commentary_company_id_companies_id_fk","tableFrom": "agent_commentary",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_commentary_agent_id_agents_id_fk": {"name": "agent_commentary_agent_id_agents_id_fk","tableFrom": "agent_commentary",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_commentary_run_id_heartbeat_runs_id_fk": {"name": "agent_commentary_run_id_heartbeat_runs_id_fk","tableFrom": "agent_commentary",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_commentary_issue_id_issues_id_fk": {"name": "agent_commentary_issue_id_issues_id_fk","tableFrom": "agent_commentary",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -2099,9 +2099,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_config_revisions_agent_created_idx": {"name": "agent_config_revisions_agent_created_idx",@@ -2120,50 +2120,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_config_revisions_company_id_companies_id_fk": {"name": "agent_config_revisions_company_id_companies_id_fk","tableFrom": "agent_config_revisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_config_revisions_agent_id_agents_id_fk": {"name": "agent_config_revisions_agent_id_agents_id_fk","tableFrom": "agent_config_revisions",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_config_revisions_created_by_agent_id_agents_id_fk": {"name": "agent_config_revisions_created_by_agent_id_agents_id_fk","tableFrom": "agent_config_revisions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -2225,17 +2225,17 @@"agent_identity_keys_owner_fk": {"name": "agent_identity_keys_owner_fk","tableFrom": "agent_identity_keys",+ "tableTo": "agents","columnsFrom": ["company_id","agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -2290,33 +2290,33 @@"agent_instruction_heads_company_id_agent_id_entry_file_revision_id_agent_instruction_revisions_company_id_agent_id_entry_file_id_fk": {"name": "agent_instruction_heads_company_id_agent_id_entry_file_revision_id_agent_instruction_revisions_company_id_agent_id_entry_file_id_fk","tableFrom": "agent_instruction_heads",+ "tableTo": "agent_instruction_revisions","columnsFrom": ["company_id","agent_id","entry_file","revision_id"],- "tableTo": "agent_instruction_revisions","columnsTo": ["company_id","agent_id","entry_file","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"agent_instruction_heads_identity_uq": {"name": "agent_instruction_heads_identity_uq",+ "nullsNotDistinct": false,"columns": ["company_id","agent_id","entry_file"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -2462,39 +2462,39 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_instruction_revisions_company_id_agent_id_agents_company_id_id_fk": {"name": "agent_instruction_revisions_company_id_agent_id_agents_company_id_id_fk","tableFrom": "agent_instruction_revisions",+ "tableTo": "agents","columnsFrom": ["company_id","agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"agent_instruction_revisions_identity_uq": {"name": "agent_instruction_revisions_identity_uq",+ "nullsNotDistinct": false,"columns": ["company_id","agent_id","entry_file","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -2654,9 +2654,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_instruction_copies_agent_idx": {"name": "agent_instruction_copies_agent_idx",@@ -2681,39 +2681,39 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_instruction_working_copies_run_id_heartbeat_runs_id_fk": {"name": "agent_instruction_working_copies_run_id_heartbeat_runs_id_fk","tableFrom": "agent_instruction_working_copies",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_instruction_working_copies_company_id_agent_id_agents_company_id_id_fk": {"name": "agent_instruction_working_copies_company_id_agent_id_agents_company_id_id_fk","tableFrom": "agent_instruction_working_copies",+ "tableTo": "agents","columnsFrom": ["company_id","agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -2797,9 +2797,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_memberships_company_user_starred_idx": {"name": "agent_memberships_company_user_starred_idx",@@ -2824,9 +2824,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_memberships_agent_idx": {"name": "agent_memberships_agent_idx",@@ -2839,9 +2839,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_memberships_company_user_agent_uq": {"name": "agent_memberships_company_user_agent_uq",@@ -2866,37 +2866,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_memberships_company_id_companies_id_fk": {"name": "agent_memberships_company_id_companies_id_fk","tableFrom": "agent_memberships",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"agent_memberships_agent_id_agents_id_fk": {"name": "agent_memberships_agent_id_agents_id_fk","tableFrom": "agent_memberships",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -3019,9 +3019,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_runtime_state_company_updated_idx": {"name": "agent_runtime_state_company_updated_idx",@@ -3040,37 +3040,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_runtime_state_agent_id_agents_id_fk": {"name": "agent_runtime_state_agent_id_agents_id_fk","tableFrom": "agent_runtime_state",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_runtime_state_company_id_companies_id_fk": {"name": "agent_runtime_state_company_id_companies_id_fk","tableFrom": "agent_runtime_state",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -3184,9 +3184,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_session_goal_actions_company_status_created_idx": {"name": "agent_session_goal_actions_company_status_created_idx",@@ -3211,9 +3211,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_session_goal_actions_session_created_idx": {"name": "agent_session_goal_actions_session_created_idx",@@ -3232,37 +3232,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_session_goal_actions_company_id_companies_id_fk": {"name": "agent_session_goal_actions_company_id_companies_id_fk","tableFrom": "agent_session_goal_actions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_session_goal_actions_session_id_agent_task_sessions_id_fk": {"name": "agent_session_goal_actions_session_id_agent_task_sessions_id_fk","tableFrom": "agent_session_goal_actions",+ "tableTo": "agent_task_sessions","columnsFrom": ["session_id"],- "tableTo": "agent_task_sessions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -3424,9 +3424,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_task_sessions_company_agent_updated_idx": {"name": "agent_task_sessions_company_agent_updated_idx",@@ -3451,9 +3451,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_task_sessions_company_task_updated_idx": {"name": "agent_task_sessions_company_task_updated_idx",@@ -3478,50 +3478,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_task_sessions_company_id_companies_id_fk": {"name": "agent_task_sessions_company_id_companies_id_fk","tableFrom": "agent_task_sessions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_task_sessions_agent_id_agents_id_fk": {"name": "agent_task_sessions_agent_id_agents_id_fk","tableFrom": "agent_task_sessions",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_task_sessions_last_run_id_heartbeat_runs_id_fk": {"name": "agent_task_sessions_last_run_id_heartbeat_runs_id_fk","tableFrom": "agent_task_sessions",+ "tableTo": "heartbeat_runs","columnsFrom": ["last_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -3656,6 +3656,28 @@}},"indexes": {+ "agent_wakeup_requests_task_retry_idempotency_uq": {+ "name": "agent_wakeup_requests_task_retry_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'task-retry:%'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"agent_wakeup_requests_company_agent_status_idx": {"name": "agent_wakeup_requests_company_agent_status_idx","columns": [@@ -3679,9 +3701,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_wakeup_requests_company_requested_idx": {"name": "agent_wakeup_requests_company_requested_idx",@@ -3700,9 +3722,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_wakeup_requests_agent_requested_idx": {"name": "agent_wakeup_requests_agent_requested_idx",@@ -3721,9 +3743,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agent_wakeup_requests_review_path_recovery_idempotency_uq": {"name": "agent_wakeup_requests_review_path_recovery_idempotency_uq",@@ -3742,10 +3764,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'issue_review_path_lost:%' AND \"agent_wakeup_requests\".\"status\" <> 'skipped'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_disposition_repair_idempotency_uq": {"name": "agent_wakeup_requests_disposition_repair_idempotency_uq",@@ -3764,10 +3786,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'issue_disposition_repair:%' AND \"agent_wakeup_requests\".\"status\" <> 'skipped'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_question_response_delivery_idempotency_uq": {"name": "agent_wakeup_requests_question_response_delivery_idempotency_uq",@@ -3786,10 +3808,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "(\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'question-response:%' OR \"agent_wakeup_requests\".\"idempotency_key\" LIKE 'interaction:%') AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_question_response_history_idx": {"name": "agent_wakeup_requests_question_response_history_idx",@@ -3808,10 +3830,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'question-response:%'",- "concurrently": true+ "concurrently": true,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_connection_intent_delivery_idempotency_uq": {"name": "agent_wakeup_requests_connection_intent_delivery_idempotency_uq",@@ -3830,10 +3852,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'connection-intent:%' AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_tool_action_delivery_uq": {"name": "agent_wakeup_requests_tool_action_delivery_uq",@@ -3852,10 +3874,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'tool-action-response:%' AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_chat_completion_uq": {"name": "agent_wakeup_requests_chat_completion_uq",@@ -3874,10 +3896,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'chat-completion:%'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"agent_wakeup_requests_company_payload_issue_idx": {"name": "agent_wakeup_requests_company_payload_issue_idx",@@ -3890,43 +3912,43 @@},{"expression": "(\"payload\" ->> 'issueId')",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agent_wakeup_requests_company_id_companies_id_fk": {"name": "agent_wakeup_requests_company_id_companies_id_fk","tableFrom": "agent_wakeup_requests",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agent_wakeup_requests_agent_id_agents_id_fk": {"name": "agent_wakeup_requests_agent_id_agents_id_fk","tableFrom": "agent_wakeup_requests",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -4170,9 +4192,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agents_company_status_idx": {"name": "agents_company_status_idx",@@ -4191,9 +4213,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agents_company_reports_to_idx": {"name": "agents_company_reports_to_idx",@@ -4212,9 +4234,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"agents_company_default_environment_idx": {"name": "agents_company_default_environment_idx",@@ -4233,61 +4255,61 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"agents_company_id_companies_id_fk": {"name": "agents_company_id_companies_id_fk","tableFrom": "agents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agents_reports_to_agents_id_fk": {"name": "agents_reports_to_agents_id_fk","tableFrom": "agents",+ "tableTo": "agents","columnsFrom": ["reports_to"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"agents_default_environment_id_environments_id_fk": {"name": "agents_default_environment_id_environments_id_fk","tableFrom": "agents",+ "tableTo": "environments","columnsFrom": ["default_environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"agents_company_id_uq": {"name": "agents_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -4373,39 +4395,39 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_connection_defaults_company_id_companies_id_fk": {"name": "ai_connection_defaults_company_id_companies_id_fk","tableFrom": "ai_connection_defaults",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_defaults_company_grant_fk": {"name": "ai_connection_defaults_company_grant_fk","tableFrom": "ai_connection_defaults",+ "tableTo": "connection_grants","columnsFrom": ["company_id","grant_id"],- "tableTo": "connection_grants","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -4478,54 +4500,54 @@"ai_connection_pools_id_tool_connections_id_fk": {"name": "ai_connection_pools_id_tool_connections_id_fk","tableFrom": "ai_connection_pools",+ "tableTo": "tool_connections","columnsFrom": ["id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_pools_company_id_companies_id_fk": {"name": "ai_connection_pools_company_id_companies_id_fk","tableFrom": "ai_connection_pools",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_pools_company_connection_fk": {"name": "ai_connection_pools_company_connection_fk","tableFrom": "ai_connection_pools",+ "tableTo": "tool_connections","columnsFrom": ["company_id","id"],- "tableTo": "tool_connections","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"ai_connection_pools_company_id_uq": {"name": "ai_connection_pools_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -4567,43 +4589,43 @@"ai_connection_router_cursors_pool_id_ai_connection_pools_id_fk": {"name": "ai_connection_router_cursors_pool_id_ai_connection_pools_id_fk","tableFrom": "ai_connection_router_cursors",+ "tableTo": "ai_connection_pools","columnsFrom": ["pool_id"],- "tableTo": "ai_connection_pools","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_router_cursors_company_id_companies_id_fk": {"name": "ai_connection_router_cursors_company_id_companies_id_fk","tableFrom": "ai_connection_router_cursors",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_router_cursors_company_pool_fk": {"name": "ai_connection_router_cursors_company_pool_fk","tableFrom": "ai_connection_router_cursors",+ "tableTo": "ai_connection_pools","columnsFrom": ["company_id","pool_id"],- "tableTo": "ai_connection_pools","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -4697,80 +4719,80 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_connection_task_pins_company_id_companies_id_fk": {"name": "ai_connection_task_pins_company_id_companies_id_fk","tableFrom": "ai_connection_task_pins",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_task_pins_pool_id_ai_connection_pools_id_fk": {"name": "ai_connection_task_pins_pool_id_ai_connection_pools_id_fk","tableFrom": "ai_connection_task_pins",+ "tableTo": "ai_connection_pools","columnsFrom": ["pool_id"],- "tableTo": "ai_connection_pools","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_task_pins_agent_id_agents_id_fk": {"name": "ai_connection_task_pins_agent_id_agents_id_fk","tableFrom": "ai_connection_task_pins",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_task_pins_company_pool_fk": {"name": "ai_connection_task_pins_company_pool_fk","tableFrom": "ai_connection_task_pins",+ "tableTo": "ai_connection_pools","columnsFrom": ["company_id","pool_id"],- "tableTo": "ai_connection_pools","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_connection_task_pins_company_agent_fk": {"name": "ai_connection_task_pins_company_agent_fk","tableFrom": "ai_connection_task_pins",+ "tableTo": "agents","columnsFrom": ["company_id","agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -4846,39 +4868,39 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_provider_defaults_company_id_companies_id_fk": {"name": "ai_provider_defaults_company_id_companies_id_fk","tableFrom": "ai_provider_defaults",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_provider_defaults_company_grant_fk": {"name": "ai_provider_defaults_company_grant_fk","tableFrom": "ai_provider_defaults",+ "tableTo": "connection_grants","columnsFrom": ["company_id","grant_id"],- "tableTo": "connection_grants","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -4952,9 +4974,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"ai_subscription_connections_credential_idx": {"name": "ai_subscription_connections_credential_idx",@@ -4973,9 +4995,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"ai_subscription_connections_account_idx": {"name": "ai_subscription_connections_account_idx",@@ -4994,63 +5016,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_subscription_connections_company_id_companies_id_fk": {"name": "ai_subscription_connections_company_id_companies_id_fk","tableFrom": "ai_subscription_connections",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_subscription_connections_connection_id_tool_connections_id_fk": {"name": "ai_subscription_connections_connection_id_tool_connections_id_fk","tableFrom": "ai_subscription_connections",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_subscription_connections_grant_id_connection_grants_id_fk": {"name": "ai_subscription_connections_grant_id_connection_grants_id_fk","tableFrom": "ai_subscription_connections",+ "tableTo": "connection_grants","columnsFrom": ["grant_id"],- "tableTo": "connection_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_subscription_connections_subscription_id_ai_subscriptions_id_fk": {"name": "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk","tableFrom": "ai_subscription_connections",+ "tableTo": "ai_subscriptions","columnsFrom": ["subscription_id"],- "tableTo": "ai_subscriptions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -5159,9 +5181,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"ai_subscription_prices_company_idx": {"name": "ai_subscription_prices_company_idx",@@ -5174,37 +5196,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_subscription_prices_company_id_companies_id_fk": {"name": "ai_subscription_prices_company_id_companies_id_fk","tableFrom": "ai_subscription_prices",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_subscription_prices_subscription_id_ai_subscriptions_id_fk": {"name": "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk","tableFrom": "ai_subscription_prices",+ "tableTo": "ai_subscriptions","columnsFrom": ["subscription_id"],- "tableTo": "ai_subscriptions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -5343,9 +5365,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"ai_subscriptions_company_idx": {"name": "ai_subscriptions_company_idx",@@ -5358,37 +5380,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"ai_subscriptions_company_id_companies_id_fk": {"name": "ai_subscriptions_company_id_companies_id_fk","tableFrom": "ai_subscriptions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"ai_subscriptions_merged_into_id_ai_subscriptions_id_fk": {"name": "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk","tableFrom": "ai_subscriptions",+ "tableTo": "ai_subscriptions","columnsFrom": ["merged_into_id"],- "tableTo": "ai_subscriptions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -5529,9 +5551,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"approval_comments_approval_idx": {"name": "approval_comments_approval_idx",@@ -5544,9 +5566,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"approval_comments_approval_created_idx": {"name": "approval_comments_approval_created_idx",@@ -5565,50 +5587,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"approval_comments_company_id_companies_id_fk": {"name": "approval_comments_company_id_companies_id_fk","tableFrom": "approval_comments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"approval_comments_approval_id_approvals_id_fk": {"name": "approval_comments_approval_id_approvals_id_fk","tableFrom": "approval_comments",+ "tableTo": "approvals","columnsFrom": ["approval_id"],- "tableTo": "approvals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"approval_comments_author_agent_id_agents_id_fk": {"name": "approval_comments_author_agent_id_agents_id_fk","tableFrom": "approval_comments",+ "tableTo": "agents","columnsFrom": ["author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -5722,37 +5744,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"approvals_company_id_companies_id_fk": {"name": "approvals_company_id_companies_id_fk","tableFrom": "approvals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"approvals_requested_by_agent_id_agents_id_fk": {"name": "approvals_requested_by_agent_id_agents_id_fk","tableFrom": "approvals",+ "tableTo": "agents","columnsFrom": ["requested_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -5859,9 +5881,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"assets_company_provider_idx": {"name": "assets_company_provider_idx",@@ -5880,9 +5902,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"assets_company_object_key_uq": {"name": "assets_company_object_key_uq",@@ -5901,37 +5923,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"assets_company_id_companies_id_fk": {"name": "assets_company_id_companies_id_fk","tableFrom": "assets",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"assets_created_by_agent_id_agents_id_fk": {"name": "assets_created_by_agent_id_agents_id_fk","tableFrom": "assets",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6047,24 +6069,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"account_user_id_user_id_fk": {"name": "account_user_id_user_id_fk","tableFrom": "account",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6131,15 +6153,15 @@"session_user_id_user_id_fk": {"name": "session_user_id_user_id_fk","tableFrom": "session",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6320,9 +6342,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"board_api_keys_user_idx": {"name": "board_api_keys_user_idx",@@ -6335,24 +6357,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"board_api_keys_user_id_user_id_fk": {"name": "board_api_keys_user_id_user_id_fk","tableFrom": "board_api_keys",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6423,9 +6445,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"browser_use_browsers_session_idx": {"name": "browser_use_browsers_session_idx",@@ -6438,37 +6460,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"browser_use_browsers_company_id_companies_id_fk": {"name": "browser_use_browsers_company_id_companies_id_fk","tableFrom": "browser_use_browsers",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_browsers_session_id_browser_use_sessions_id_fk": {"name": "browser_use_browsers_session_id_browser_use_sessions_id_fk","tableFrom": "browser_use_browsers",+ "tableTo": "browser_use_sessions","columnsFrom": ["session_id"],- "tableTo": "browser_use_sessions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6590,9 +6612,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"browser_use_runs_provider_uq": {"name": "browser_use_runs_provider_uq",@@ -6605,9 +6627,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"browser_use_runs_session_idx": {"name": "browser_use_runs_session_idx",@@ -6620,50 +6642,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"browser_use_runs_company_id_companies_id_fk": {"name": "browser_use_runs_company_id_companies_id_fk","tableFrom": "browser_use_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_runs_session_id_browser_use_sessions_id_fk": {"name": "browser_use_runs_session_id_browser_use_sessions_id_fk","tableFrom": "browser_use_runs",+ "tableTo": "browser_use_sessions","columnsFrom": ["session_id"],- "tableTo": "browser_use_sessions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_runs_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "browser_use_runs_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "browser_use_runs",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6796,9 +6818,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"browser_use_sessions_provider_uq": {"name": "browser_use_sessions_provider_uq",@@ -6811,76 +6833,76 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"browser_use_sessions_company_id_companies_id_fk": {"name": "browser_use_sessions_company_id_companies_id_fk","tableFrom": "browser_use_sessions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_sessions_issue_id_issues_id_fk": {"name": "browser_use_sessions_issue_id_issues_id_fk","tableFrom": "browser_use_sessions",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_sessions_agent_id_agents_id_fk": {"name": "browser_use_sessions_agent_id_agents_id_fk","tableFrom": "browser_use_sessions",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_sessions_connection_id_tool_connections_id_fk": {"name": "browser_use_sessions_connection_id_tool_connections_id_fk","tableFrom": "browser_use_sessions",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_sessions_grant_id_connection_grants_id_fk": {"name": "browser_use_sessions_grant_id_connection_grants_id_fk","tableFrom": "browser_use_sessions",+ "tableTo": "connection_grants","columnsFrom": ["grant_id"],- "tableTo": "connection_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -6924,28 +6946,28 @@"browser_use_settings_grant_id_connection_grants_id_fk": {"name": "browser_use_settings_grant_id_connection_grants_id_fk","tableFrom": "browser_use_settings",+ "tableTo": "connection_grants","columnsFrom": ["grant_id"],- "tableTo": "connection_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"browser_use_settings_company_id_companies_id_fk": {"name": "browser_use_settings_company_id_companies_id_fk","tableFrom": "browser_use_settings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7083,9 +7105,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_incidents_company_scope_idx": {"name": "budget_incidents_company_scope_idx",@@ -7116,9 +7138,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_incidents_policy_window_threshold_idx": {"name": "budget_incidents_policy_window_threshold_idx",@@ -7143,51 +7165,51 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"budget_incidents\".\"status\" = 'open'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"budget_incidents_company_id_companies_id_fk": {"name": "budget_incidents_company_id_companies_id_fk","tableFrom": "budget_incidents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"budget_incidents_policy_id_budget_policies_id_fk": {"name": "budget_incidents_policy_id_budget_policies_id_fk","tableFrom": "budget_incidents",+ "tableTo": "budget_policies","columnsFrom": ["policy_id"],- "tableTo": "budget_policies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"budget_incidents_approval_id_approvals_id_fk": {"name": "budget_incidents_approval_id_approvals_id_fk","tableFrom": "budget_incidents",+ "tableTo": "approvals","columnsFrom": ["approval_id"],- "tableTo": "approvals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7358,9 +7380,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_policies_company_window_idx": {"name": "budget_policies_company_window_idx",@@ -7385,9 +7407,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"budget_policies_company_scope_metric_unique_idx": {"name": "budget_policies_company_scope_metric_unique_idx",@@ -7424,24 +7446,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"budget_policies_company_id_companies_id_fk": {"name": "budget_policies_company_id_companies_id_fk","tableFrom": "budget_policies",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7542,9 +7564,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"built_in_managed_resources_resource_idx": {"name": "built_in_managed_resources_resource_idx",@@ -7563,9 +7585,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"built_in_managed_resources_company_bundle_resource_uq": {"name": "built_in_managed_resources_company_bundle_resource_uq",@@ -7596,24 +7618,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"built_in_managed_resources_company_id_companies_id_fk": {"name": "built_in_managed_resources_company_id_companies_id_fk","tableFrom": "built_in_managed_resources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7689,9 +7711,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_access_sources_company_case_idx": {"name": "case_access_sources_company_case_idx",@@ -7710,37 +7732,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_access_sources_company_id_companies_id_fk": {"name": "case_access_sources_company_id_companies_id_fk","tableFrom": "case_access_sources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_access_sources_case_id_cases_id_fk": {"name": "case_access_sources_case_id_cases_id_fk","tableFrom": "case_access_sources",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7816,9 +7838,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_attachments_asset_uq": {"name": "case_attachments_asset_uq",@@ -7831,50 +7853,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_attachments_company_id_companies_id_fk": {"name": "case_attachments_company_id_companies_id_fk","tableFrom": "case_attachments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_attachments_case_id_cases_id_fk": {"name": "case_attachments_case_id_cases_id_fk","tableFrom": "case_attachments",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_attachments_asset_id_assets_id_fk": {"name": "case_attachments_asset_id_assets_id_fk","tableFrom": "case_attachments",+ "tableTo": "assets","columnsFrom": ["asset_id"],- "tableTo": "assets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -7957,9 +7979,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_documents_document_uq": {"name": "case_documents_document_uq",@@ -7972,9 +7994,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_documents_company_case_updated_idx": {"name": "case_documents_company_case_updated_idx",@@ -7999,50 +8021,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_documents_company_id_companies_id_fk": {"name": "case_documents_company_id_companies_id_fk","tableFrom": "case_documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_documents_case_id_cases_id_fk": {"name": "case_documents_case_id_cases_id_fk","tableFrom": "case_documents",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_documents_document_id_documents_id_fk": {"name": "case_documents_document_id_documents_id_fk","tableFrom": "case_documents",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -8144,9 +8166,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_events_company_case_idx": {"name": "case_events_company_case_idx",@@ -8165,50 +8187,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_events_company_id_companies_id_fk": {"name": "case_events_company_id_companies_id_fk","tableFrom": "case_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_events_case_id_cases_id_fk": {"name": "case_events_case_id_cases_id_fk","tableFrom": "case_events",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_events_actor_agent_id_agents_id_fk": {"name": "case_events_actor_agent_id_agents_id_fk","tableFrom": "case_events",+ "tableTo": "agents","columnsFrom": ["actor_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -8459,9 +8481,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_handoffs_actor_idempotency_uq": {"name": "case_handoffs_actor_idempotency_uq",@@ -8492,9 +8514,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_handoffs_pending_case_uq": {"name": "case_handoffs_pending_case_uq",@@ -8507,10 +8529,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"case_handoffs\".\"state\" in ('awaiting_release', 'pending_dispatch', 'awaiting_completion')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"case_handoffs_pending_issue_uq": {"name": "case_handoffs_pending_issue_uq",@@ -8523,10 +8545,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"case_handoffs\".\"state\" in ('awaiting_release', 'pending_dispatch', 'awaiting_completion')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"case_handoffs_pending_attempt_idx": {"name": "case_handoffs_pending_attempt_idx",@@ -8539,10 +8561,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"case_handoffs\".\"state\" in ('awaiting_release', 'pending_dispatch')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"case_handoffs_case_created_idx": {"name": "case_handoffs_case_created_idx",@@ -8561,9 +8583,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_handoffs_source_run_idx": {"name": "case_handoffs_source_run_idx",@@ -8582,10 +8604,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"case_handoffs\".\"source_run_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"case_handoffs_wakeup_request_uq": {"name": "case_handoffs_wakeup_request_uq",@@ -8598,76 +8620,76 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_handoffs_company_id_companies_id_fk": {"name": "case_handoffs_company_id_companies_id_fk","tableFrom": "case_handoffs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_handoffs_case_id_cases_id_fk": {"name": "case_handoffs_case_id_cases_id_fk","tableFrom": "case_handoffs",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_handoffs_issue_id_issues_id_fk": {"name": "case_handoffs_issue_id_issues_id_fk","tableFrom": "case_handoffs",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"case_handoffs_from_agent_id_agents_id_fk": {"name": "case_handoffs_from_agent_id_agents_id_fk","tableFrom": "case_handoffs",+ "tableTo": "agents","columnsFrom": ["from_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"case_handoffs_to_agent_id_agents_id_fk": {"name": "case_handoffs_to_agent_id_agents_id_fk","tableFrom": "case_handoffs",+ "tableTo": "agents","columnsFrom": ["to_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -8767,9 +8789,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_issue_links_company_case_idx": {"name": "case_issue_links_company_case_idx",@@ -8788,9 +8810,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_issue_links_issue_idx": {"name": "case_issue_links_issue_idx",@@ -8803,50 +8825,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_issue_links_company_id_companies_id_fk": {"name": "case_issue_links_company_id_companies_id_fk","tableFrom": "case_issue_links",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_issue_links_case_id_cases_id_fk": {"name": "case_issue_links_case_id_cases_id_fk","tableFrom": "case_issue_links",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_issue_links_issue_id_issues_id_fk": {"name": "case_issue_links_issue_id_issues_id_fk","tableFrom": "case_issue_links",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -8922,9 +8944,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_labels_company_case_idx": {"name": "case_labels_company_case_idx",@@ -8943,9 +8965,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"case_labels_label_idx": {"name": "case_labels_label_idx",@@ -8958,50 +8980,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"case_labels_company_id_companies_id_fk": {"name": "case_labels_company_id_companies_id_fk","tableFrom": "case_labels",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_labels_case_id_cases_id_fk": {"name": "case_labels_case_id_cases_id_fk","tableFrom": "case_labels",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"case_labels_label_id_labels_id_fk": {"name": "case_labels_label_id_labels_id_fk","tableFrom": "case_labels",+ "tableTo": "labels","columnsFrom": ["label_id"],- "tableTo": "labels","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -9159,9 +9181,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_identifier_uq": {"name": "cases_identifier_uq",@@ -9174,9 +9196,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_work_issue_uq": {"name": "cases_work_issue_uq",@@ -9189,10 +9211,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"cases\".\"work_issue_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"cases_company_type_key_uq": {"name": "cases_company_type_key_uq",@@ -9217,9 +9239,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_company_status_idx": {"name": "cases_company_status_idx",@@ -9238,9 +9260,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_company_type_idx": {"name": "cases_company_type_idx",@@ -9259,9 +9281,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_company_project_idx": {"name": "cases_company_project_idx",@@ -9280,9 +9302,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_parent_idx": {"name": "cases_parent_idx",@@ -9295,9 +9317,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cases_title_search_idx": {"name": "cases_title_search_idx",@@ -9311,9 +9333,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"cases_identifier_search_idx": {"name": "cases_identifier_search_idx",@@ -9327,9 +9349,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"cases_summary_search_idx": {"name": "cases_summary_search_idx",@@ -9343,76 +9365,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}}},"foreignKeys": {"cases_company_id_companies_id_fk": {"name": "cases_company_id_companies_id_fk","tableFrom": "cases",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"cases_project_id_projects_id_fk": {"name": "cases_project_id_projects_id_fk","tableFrom": "cases",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"cases_work_issue_id_issues_id_fk": {"name": "cases_work_issue_id_issues_id_fk","tableFrom": "cases",+ "tableTo": "issues","columnsFrom": ["work_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"cases_parent_case_id_cases_id_fk": {"name": "cases_parent_case_id_cases_id_fk","tableFrom": "cases",+ "tableTo": "cases","columnsFrom": ["parent_case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"cases_created_by_agent_id_agents_id_fk": {"name": "cases_created_by_agent_id_agents_id_fk","tableFrom": "cases",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -9532,97 +9554,97 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_actions_company_id_companies_id_fk": {"name": "chat_actions_company_id_companies_id_fk","tableFrom": "chat_actions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_actions_delivery_id_chat_deliveries_id_fk": {"name": "chat_actions_delivery_id_chat_deliveries_id_fk","tableFrom": "chat_actions",+ "tableTo": "chat_deliveries","columnsFrom": ["delivery_id"],- "tableTo": "chat_deliveries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_actions_company_delivery_fk": {"name": "chat_actions_company_delivery_fk","tableFrom": "chat_actions",+ "tableTo": "chat_deliveries","columnsFrom": ["company_id","delivery_id"],- "tableTo": "chat_deliveries","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_actions_company_conversation_fk": {"name": "chat_actions_company_conversation_fk","tableFrom": "chat_actions",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_actions_company_principal_fk": {"name": "chat_actions_company_principal_fk","tableFrom": "chat_actions",+ "tableTo": "chat_external_principals","columnsFrom": ["company_id","principal_id"],- "tableTo": "chat_external_principals","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_actions_company_endpoint_fk": {"name": "chat_actions_company_endpoint_fk","tableFrom": "chat_actions",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -9720,54 +9742,54 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_agent_routes_company_id_companies_id_fk": {"name": "chat_agent_routes_company_id_companies_id_fk","tableFrom": "chat_agent_routes",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_agent_routes_company_source_fk": {"name": "chat_agent_routes_company_source_fk","tableFrom": "chat_agent_routes",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","source_endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_agent_routes_company_destination_fk": {"name": "chat_agent_routes_company_destination_fk","tableFrom": "chat_agent_routes",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","destination_endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -9907,9 +9929,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_conversations_thread_uq": {"name": "chat_conversations_thread_uq",@@ -9940,106 +9962,106 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_conversations_company_id_companies_id_fk": {"name": "chat_conversations_company_id_companies_id_fk","tableFrom": "chat_conversations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_conversations_resource_id_chat_endpoint_resources_id_fk": {"name": "chat_conversations_resource_id_chat_endpoint_resources_id_fk","tableFrom": "chat_conversations",+ "tableTo": "chat_endpoint_resources","columnsFrom": ["resource_id"],- "tableTo": "chat_endpoint_resources","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_conversations_issue_id_issues_id_fk": {"name": "chat_conversations_issue_id_issues_id_fk","tableFrom": "chat_conversations",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"chat_conversations_company_issue_fk": {"name": "chat_conversations_company_issue_fk","tableFrom": "chat_conversations",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_conversations_company_endpoint_fk": {"name": "chat_conversations_company_endpoint_fk","tableFrom": "chat_conversations",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_conversations_company_resource_fk": {"name": "chat_conversations_company_resource_fk","tableFrom": "chat_conversations",+ "tableTo": "chat_endpoint_resources","columnsFrom": ["company_id","resource_id"],- "tableTo": "chat_endpoint_resources","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_conversations_company_id_uq": {"name": "chat_conversations_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -10182,9 +10204,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_deliveries_event_uq": {"name": "chat_deliveries_event_uq",@@ -10203,9 +10225,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_deliveries_dedupe_uq": {"name": "chat_deliveries_dedupe_uq",@@ -10224,106 +10246,106 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_deliveries_company_id_companies_id_fk": {"name": "chat_deliveries_company_id_companies_id_fk","tableFrom": "chat_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_deliveries_conversation_id_chat_conversations_id_fk": {"name": "chat_deliveries_conversation_id_chat_conversations_id_fk","tableFrom": "chat_deliveries",+ "tableTo": "chat_conversations","columnsFrom": ["conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_deliveries_principal_id_chat_external_principals_id_fk": {"name": "chat_deliveries_principal_id_chat_external_principals_id_fk","tableFrom": "chat_deliveries",+ "tableTo": "chat_external_principals","columnsFrom": ["principal_id"],- "tableTo": "chat_external_principals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_deliveries_company_endpoint_fk": {"name": "chat_deliveries_company_endpoint_fk","tableFrom": "chat_deliveries",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_deliveries_company_conversation_fk": {"name": "chat_deliveries_company_conversation_fk","tableFrom": "chat_deliveries",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_deliveries_company_principal_fk": {"name": "chat_deliveries_company_principal_fk","tableFrom": "chat_deliveries",+ "tableTo": "chat_external_principals","columnsFrom": ["company_id","principal_id"],- "tableTo": "chat_external_principals","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_deliveries_company_id_uq": {"name": "chat_deliveries_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -10409,9 +10431,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoint_leases_expiry_idx": {"name": "chat_endpoint_leases_expiry_idx",@@ -10424,39 +10446,39 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_endpoint_leases_company_id_companies_id_fk": {"name": "chat_endpoint_leases_company_id_companies_id_fk","tableFrom": "chat_endpoint_leases",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_endpoint_leases_company_endpoint_fk": {"name": "chat_endpoint_leases_company_endpoint_fk","tableFrom": "chat_endpoint_leases",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -10584,9 +10606,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoint_resources_external_uq": {"name": "chat_endpoint_resources_external_uq",@@ -10611,50 +10633,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_endpoint_resources_company_id_companies_id_fk": {"name": "chat_endpoint_resources_company_id_companies_id_fk","tableFrom": "chat_endpoint_resources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_endpoint_resources_company_endpoint_fk": {"name": "chat_endpoint_resources_company_endpoint_fk","tableFrom": "chat_endpoint_resources",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_endpoint_resources_company_id_uq": {"name": "chat_endpoint_resources_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -10902,9 +10924,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoints_agent_idx": {"name": "chat_endpoints_agent_idx",@@ -10923,9 +10945,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoints_status_idx": {"name": "chat_endpoints_status_idx",@@ -10944,9 +10966,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoints_public_id_uq": {"name": "chat_endpoints_public_id_uq",@@ -10959,9 +10981,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoints_agentmail_inbox_uq": {"name": "chat_endpoints_agentmail_inbox_uq",@@ -10974,10 +10996,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"provider\" = 'agentmail' and \"chat_endpoints\".\"status\" != 'archived' and \"chat_endpoints\".\"bot_external_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_endpoints_connection_uq": {"name": "chat_endpoints_connection_uq",@@ -10990,9 +11012,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_endpoints_live_bot_external_uq": {"name": "chat_endpoints_live_bot_external_uq",@@ -11017,10 +11039,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"status\" in ('verifying', 'active', 'paused', 'attention')\n and \"chat_endpoints\".\"provider_account_id\" is not null\n and \"chat_endpoints\".\"bot_external_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_endpoints_photon_number_uq": {"name": "chat_endpoints_photon_number_uq",@@ -11033,10 +11055,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"provider\" = 'imessage-photon' and \"chat_endpoints\".\"status\" <> 'archived' and \"chat_endpoints\".\"bot_external_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_endpoints_live_discord_bot_external_uq": {"name": "chat_endpoints_live_discord_bot_external_uq",@@ -11055,10 +11077,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"provider\" = 'discord'\n and \"chat_endpoints\".\"status\" in ('verifying', 'active', 'paused', 'attention')\n and \"chat_endpoints\".\"bot_external_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_endpoints_live_global_app_bot_external_uq": {"name": "chat_endpoints_live_global_app_bot_external_uq",@@ -11077,10 +11099,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"provider\" in ('github', 'microsoft-teams')\n and \"chat_endpoints\".\"status\" in ('verifying', 'active', 'paused', 'attention')\n and \"chat_endpoints\".\"bot_external_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_endpoints_live_bot_username_uq": {"name": "chat_endpoints_live_bot_username_uq",@@ -11105,79 +11127,79 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_endpoints\".\"status\" in ('verifying', 'active', 'paused', 'attention')\n and \"chat_endpoints\".\"provider_account_id\" is not null\n and \"chat_endpoints\".\"bot_username\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"chat_endpoints_company_id_companies_id_fk": {"name": "chat_endpoints_company_id_companies_id_fk","tableFrom": "chat_endpoints",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_endpoints_assigned_agent_id_agents_id_fk": {"name": "chat_endpoints_assigned_agent_id_agents_id_fk","tableFrom": "chat_endpoints",+ "tableTo": "agents","columnsFrom": ["assigned_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"chat_endpoints_company_agent_fk": {"name": "chat_endpoints_company_agent_fk","tableFrom": "chat_endpoints",+ "tableTo": "agents","columnsFrom": ["company_id","assigned_agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_endpoints_company_connection_fk": {"name": "chat_endpoints_company_connection_fk","tableFrom": "chat_endpoints",+ "tableTo": "tool_connections","columnsFrom": ["company_id","connection_id"],- "tableTo": "tool_connections","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_endpoints_company_id_uq": {"name": "chat_endpoints_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -11313,9 +11335,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_external_principals_external_uq": {"name": "chat_external_principals_external_uq",@@ -11346,35 +11368,35 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_external_principals_company_id_companies_id_fk": {"name": "chat_external_principals_company_id_companies_id_fk","tableFrom": "chat_external_principals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_external_principals_company_id_uq": {"name": "chat_external_principals_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -11489,9 +11511,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_identity_links_endpoint_principal_uq": {"name": "chat_identity_links_endpoint_principal_uq",@@ -11510,54 +11532,54 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_identity_links_company_id_companies_id_fk": {"name": "chat_identity_links_company_id_companies_id_fk","tableFrom": "chat_identity_links",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_identity_links_company_endpoint_fk": {"name": "chat_identity_links_company_endpoint_fk","tableFrom": "chat_identity_links",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_identity_links_company_principal_fk": {"name": "chat_identity_links_company_principal_fk","tableFrom": "chat_identity_links",+ "tableTo": "chat_external_principals","columnsFrom": ["company_id","principal_id"],- "tableTo": "chat_external_principals","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -11662,138 +11684,138 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_message_links_company_id_companies_id_fk": {"name": "chat_message_links_company_id_companies_id_fk","tableFrom": "chat_message_links",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_message_links_delivery_id_chat_deliveries_id_fk": {"name": "chat_message_links_delivery_id_chat_deliveries_id_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_deliveries","columnsFrom": ["delivery_id"],- "tableTo": "chat_deliveries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_message_links_publication_id_chat_publications_id_fk": {"name": "chat_message_links_publication_id_chat_publications_id_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_publications","columnsFrom": ["publication_id"],- "tableTo": "chat_publications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_message_links_comment_id_issue_comments_id_fk": {"name": "chat_message_links_comment_id_issue_comments_id_fk","tableFrom": "chat_message_links",+ "tableTo": "issue_comments","columnsFrom": ["comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_message_links_company_endpoint_fk": {"name": "chat_message_links_company_endpoint_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_message_links_company_delivery_fk": {"name": "chat_message_links_company_delivery_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_deliveries","columnsFrom": ["company_id","delivery_id"],- "tableTo": "chat_deliveries","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_message_links_company_publication_fk": {"name": "chat_message_links_company_publication_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_publications","columnsFrom": ["company_id","publication_id"],- "tableTo": "chat_publications","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_message_links_company_comment_fk": {"name": "chat_message_links_company_comment_fk","tableFrom": "chat_message_links",+ "tableTo": "issue_comments","columnsFrom": ["company_id","comment_id"],- "tableTo": "issue_comments","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_message_links_company_conversation_fk": {"name": "chat_message_links_company_conversation_fk","tableFrom": "chat_message_links",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -11937,9 +11959,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_publications_work_idx": {"name": "chat_publications_work_idx",@@ -11958,9 +11980,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_publications_idempotency_uq": {"name": "chat_publications_idempotency_uq",@@ -11979,110 +12001,110 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_publications_company_id_companies_id_fk": {"name": "chat_publications_company_id_companies_id_fk","tableFrom": "chat_publications",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_publications_issue_id_issues_id_fk": {"name": "chat_publications_issue_id_issues_id_fk","tableFrom": "chat_publications",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"chat_publications_comment_id_issue_comments_id_fk": {"name": "chat_publications_comment_id_issue_comments_id_fk","tableFrom": "chat_publications",+ "tableTo": "issue_comments","columnsFrom": ["comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_publications_company_issue_fk": {"name": "chat_publications_company_issue_fk","tableFrom": "chat_publications",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_publications_company_comment_fk": {"name": "chat_publications_company_comment_fk","tableFrom": "chat_publications",+ "tableTo": "issue_comments","columnsFrom": ["company_id","comment_id"],- "tableTo": "issue_comments","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_publications_company_endpoint_fk": {"name": "chat_publications_company_endpoint_fk","tableFrom": "chat_publications",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_publications_company_conversation_fk": {"name": "chat_publications_company_conversation_fk","tableFrom": "chat_publications",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12177,9 +12199,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_sdk_state_expiry_idx": {"name": "chat_sdk_state_expiry_idx",@@ -12192,39 +12214,39 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_sdk_state_company_id_companies_id_fk": {"name": "chat_sdk_state_company_id_companies_id_fk","tableFrom": "chat_sdk_state",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_sdk_state_company_endpoint_fk": {"name": "chat_sdk_state_company_endpoint_fk","tableFrom": "chat_sdk_state",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12327,9 +12349,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_completion_deliveries_pending_idx": {"name": "chat_completion_deliveries_pending_idx",@@ -12348,63 +12370,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_completion_deliveries_company_id_companies_id_fk": {"name": "chat_completion_deliveries_company_id_companies_id_fk","tableFrom": "chat_completion_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_completion_deliveries_task_id_chat_task_handoffs_task_id_fk": {"name": "chat_completion_deliveries_task_id_chat_task_handoffs_task_id_fk","tableFrom": "chat_completion_deliveries",+ "tableTo": "chat_task_handoffs","columnsFrom": ["task_id"],- "tableTo": "chat_task_handoffs","columnsTo": ["task_id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_completion_deliveries_target_run_id_heartbeat_runs_id_fk": {"name": "chat_completion_deliveries_target_run_id_heartbeat_runs_id_fk","tableFrom": "chat_completion_deliveries",+ "tableTo": "heartbeat_runs","columnsFrom": ["target_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_completion_deliveries_response_comment_id_issue_comments_id_fk": {"name": "chat_completion_deliveries_response_comment_id_issue_comments_id_fk","tableFrom": "chat_completion_deliveries",+ "tableTo": "issue_comments","columnsFrom": ["response_comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12473,63 +12495,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_task_handoffs_task_id_issues_id_fk": {"name": "chat_task_handoffs_task_id_issues_id_fk","tableFrom": "chat_task_handoffs",+ "tableTo": "issues","columnsFrom": ["task_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_task_handoffs_company_id_companies_id_fk": {"name": "chat_task_handoffs_company_id_companies_id_fk","tableFrom": "chat_task_handoffs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_task_handoffs_conversation_id_issues_id_fk": {"name": "chat_task_handoffs_conversation_id_issues_id_fk","tableFrom": "chat_task_handoffs",+ "tableTo": "issues","columnsFrom": ["conversation_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_task_handoffs_agent_id_agents_id_fk": {"name": "chat_task_handoffs_agent_id_agents_id_fk","tableFrom": "chat_task_handoffs",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12642,17 +12664,17 @@"chat_github_configurations_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "chat_github_configurations_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "chat_github_configurations",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12771,9 +12793,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_github_registration_endpoint_idx": {"name": "chat_github_registration_endpoint_idx",@@ -12792,26 +12814,26 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_github_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "chat_github_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "chat_github_registrations",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -12991,9 +13013,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_github_reviews_pull_idx": {"name": "chat_github_reviews_pull_idx",@@ -13024,9 +13046,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_github_reviews_task_idx": {"name": "chat_github_reviews_task_idx",@@ -13051,65 +13073,65 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_github_reviews_run_id_heartbeat_runs_id_fk": {"name": "chat_github_reviews_run_id_heartbeat_runs_id_fk","tableFrom": "chat_github_reviews",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"chat_github_reviews_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "chat_github_reviews_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "chat_github_reviews",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_github_reviews_company_id_issue_id_issues_company_id_id_fk": {"name": "chat_github_reviews_company_id_issue_id_issues_company_id_id_fk","tableFrom": "chat_github_reviews",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_github_reviews_company_id_uq": {"name": "chat_github_reviews_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -13244,9 +13266,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_slack_manager_grants_owner_idx": {"name": "chat_slack_manager_grants_owner_idx",@@ -13277,24 +13299,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_slack_manager_grants_company_id_companies_id_fk": {"name": "chat_slack_manager_grants_company_id_companies_id_fk","tableFrom": "chat_slack_manager_grants",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -13423,32 +13445,32 @@"chat_slack_registrations_company_id_manager_grant_id_chat_slack_manager_grants_company_id_id_fk": {"name": "chat_slack_registrations_company_id_manager_grant_id_chat_slack_manager_grants_company_id_id_fk","tableFrom": "chat_slack_registrations",+ "tableTo": "chat_slack_manager_grants","columnsFrom": ["company_id","manager_grant_id"],- "tableTo": "chat_slack_manager_grants","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_slack_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "chat_slack_registrations_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "chat_slack_registrations",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -13712,9 +13734,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_teams_file_transfers_token_uq": {"name": "chat_teams_file_transfers_token_uq",@@ -13733,9 +13755,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_teams_file_transfers_work_idx": {"name": "chat_teams_file_transfers_work_idx",@@ -13760,97 +13782,97 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_teams_file_transfers_company_id_companies_id_fk": {"name": "chat_teams_file_transfers_company_id_companies_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_teams_file_transfers_issue_id_issues_id_fk": {"name": "chat_teams_file_transfers_issue_id_issues_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk": {"name": "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_publications","columnsFrom": ["company_id","publication_id"],- "tableTo": "chat_publications","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk": {"name": "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk": {"name": "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk","tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_external_principals","columnsFrom": ["company_id","principal_id"],- "tableTo": "chat_external_principals","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -13950,26 +13972,26 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_callbacks_endpoint_fk": {"name": "chat_voice_callbacks_endpoint_fk","tableFrom": "chat_voice_callbacks",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -14118,81 +14140,81 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_inbound_endpoint_fk": {"name": "chat_voice_inbound_endpoint_fk","tableFrom": "chat_voice_inbound_calls",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_voice_inbound_session_fk": {"name": "chat_voice_inbound_session_fk","tableFrom": "chat_voice_inbound_calls",+ "tableTo": "chat_voice_sessions","columnsFrom": ["company_id","session_id"],- "tableTo": "chat_voice_sessions","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_inbound_intake_fk": {"name": "chat_voice_inbound_intake_fk","tableFrom": "chat_voice_inbound_calls",+ "tableTo": "issues","columnsFrom": ["company_id","intake_issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_inbound_requested_issue_fk": {"name": "chat_voice_inbound_requested_issue_fk","tableFrom": "chat_voice_inbound_calls",+ "tableTo": "issues","columnsFrom": ["company_id","requested_issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_voice_inbound_provider_uq": {"name": "chat_voice_inbound_provider_uq",+ "nullsNotDistinct": false,"columns": ["provider_session_id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -14277,40 +14299,40 @@"chat_voice_phone_lines_low_trust_environment_id_environments_id_fk": {"name": "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk","tableFrom": "chat_voice_phone_lines",+ "tableTo": "environments","columnsFrom": ["low_trust_environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_phone_lines_endpoint_fk": {"name": "chat_voice_phone_lines_endpoint_fk","tableFrom": "chat_voice_phone_lines",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_voice_phone_lines_number_uq": {"name": "chat_voice_phone_lines_number_uq",+ "nullsNotDistinct": false,"columns": ["provider_number_id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -14410,26 +14432,26 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_reports_session_fk": {"name": "chat_voice_reports_session_fk","tableFrom": "chat_voice_reports",+ "tableTo": "chat_voice_sessions","columnsFrom": ["company_id","session_id"],- "tableTo": "chat_voice_sessions","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -14528,9 +14550,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_voice_replies_cursor_uq": {"name": "chat_voice_replies_cursor_uq",@@ -14549,54 +14571,54 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_replies_company_id_companies_id_fk": {"name": "chat_voice_replies_company_id_companies_id_fk","tableFrom": "chat_voice_replies",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_voice_replies_session_fk": {"name": "chat_voice_replies_session_fk","tableFrom": "chat_voice_replies",+ "tableTo": "chat_voice_sessions","columnsFrom": ["company_id","session_id"],- "tableTo": "chat_voice_sessions","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_replies_publication_fk": {"name": "chat_voice_replies_publication_fk","tableFrom": "chat_voice_replies",+ "tableTo": "chat_publications","columnsFrom": ["company_id","publication_id"],- "tableTo": "chat_publications","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -14774,9 +14796,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_voice_sessions_request_uq": {"name": "chat_voice_sessions_request_uq",@@ -14801,9 +14823,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_voice_sessions_live_caller_task_uq": {"name": "chat_voice_sessions_live_caller_task_uq",@@ -14828,10 +14850,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"chat_voice_sessions\".\"state\" not in ('ended', 'failed', 'expired')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"chat_voice_sessions_expiry_idx": {"name": "chat_voice_sessions_expiry_idx",@@ -14850,95 +14872,95 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_sessions_company_id_companies_id_fk": {"name": "chat_voice_sessions_company_id_companies_id_fk","tableFrom": "chat_voice_sessions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_voice_sessions_endpoint_fk": {"name": "chat_voice_sessions_endpoint_fk","tableFrom": "chat_voice_sessions",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_sessions_conversation_fk": {"name": "chat_voice_sessions_conversation_fk","tableFrom": "chat_voice_sessions",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_sessions_issue_fk": {"name": "chat_voice_sessions_issue_fk","tableFrom": "chat_voice_sessions",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_sessions_agent_fk": {"name": "chat_voice_sessions_agent_fk","tableFrom": "chat_voice_sessions",+ "tableTo": "agents","columnsFrom": ["company_id","assigned_agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"chat_voice_sessions_company_id_uq": {"name": "chat_voice_sessions_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -15055,9 +15077,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"chat_voice_tool_calls_webhook_uq": {"name": "chat_voice_tool_calls_webhook_uq",@@ -15076,54 +15098,54 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"chat_voice_tool_calls_company_id_companies_id_fk": {"name": "chat_voice_tool_calls_company_id_companies_id_fk","tableFrom": "chat_voice_tool_calls",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"chat_voice_tool_calls_session_fk": {"name": "chat_voice_tool_calls_session_fk","tableFrom": "chat_voice_tool_calls",+ "tableTo": "chat_voice_sessions","columnsFrom": ["company_id","session_id"],- "tableTo": "chat_voice_sessions","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"chat_voice_tool_calls_delivery_fk": {"name": "chat_voice_tool_calls_delivery_fk","tableFrom": "chat_voice_tool_calls",+ "tableTo": "chat_deliveries","columnsFrom": ["company_id","delivery_id"],- "tableTo": "chat_deliveries","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -15248,9 +15270,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cli_auth_challenges_approved_by_idx": {"name": "cli_auth_challenges_approved_by_idx",@@ -15263,9 +15285,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cli_auth_challenges_requested_company_idx": {"name": "cli_auth_challenges_requested_company_idx",@@ -15278,50 +15300,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"cli_auth_challenges_requested_company_id_companies_id_fk": {"name": "cli_auth_challenges_requested_company_id_companies_id_fk","tableFrom": "cli_auth_challenges",+ "tableTo": "companies","columnsFrom": ["requested_company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"cli_auth_challenges_approved_by_user_id_user_id_fk": {"name": "cli_auth_challenges_approved_by_user_id_user_id_fk","tableFrom": "cli_auth_challenges",+ "tableTo": "user","columnsFrom": ["approved_by_user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"cli_auth_challenges_board_api_key_id_board_api_keys_id_fk": {"name": "cli_auth_challenges_board_api_key_id_board_api_keys_id_fk","tableFrom": "cli_auth_challenges",+ "tableTo": "board_api_keys","columnsFrom": ["board_api_key_id"],- "tableTo": "board_api_keys","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -15478,9 +15500,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -15540,9 +15562,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_logos_asset_uq": {"name": "company_logos_asset_uq",@@ -15555,37 +15577,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_logos_company_id_companies_id_fk": {"name": "company_logos_company_id_companies_id_fk","tableFrom": "company_logos",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_logos_asset_id_assets_id_fk": {"name": "company_logos_asset_id_assets_id_fk","tableFrom": "company_logos",+ "tableTo": "assets","columnsFrom": ["asset_id"],- "tableTo": "assets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -15675,9 +15697,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_memberships_principal_status_idx": {"name": "company_memberships_principal_status_idx",@@ -15702,9 +15724,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_memberships_company_status_idx": {"name": "company_memberships_company_status_idx",@@ -15723,24 +15745,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_memberships_company_id_companies_id_fk": {"name": "company_memberships_company_id_companies_id_fk","tableFrom": "company_memberships",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -15823,28 +15845,28 @@"company_observability_company_id_companies_id_fk": {"name": "company_observability_company_id_companies_id_fk","tableFrom": "company_observability",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_observability_credentials_secret_id_company_secrets_id_fk": {"name": "company_observability_credentials_secret_id_company_secrets_id_fk","tableFrom": "company_observability",+ "tableTo": "company_secrets","columnsFrom": ["credentials_secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -15958,63 +15980,63 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_onboarding_seeds_company_id_companies_id_fk": {"name": "company_onboarding_seeds_company_id_companies_id_fk","tableFrom": "company_onboarding_seeds",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_onboarding_seeds_goal_id_goals_id_fk": {"name": "company_onboarding_seeds_goal_id_goals_id_fk","tableFrom": "company_onboarding_seeds",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_onboarding_seeds_agent_id_agents_id_fk": {"name": "company_onboarding_seeds_agent_id_agents_id_fk","tableFrom": "company_onboarding_seeds",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_onboarding_seeds_issue_id_issues_id_fk": {"name": "company_onboarding_seeds_issue_id_issues_id_fk","tableFrom": "company_onboarding_seeds",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -16124,9 +16146,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_bindings_secret_idx": {"name": "company_secret_bindings_secret_idx",@@ -16139,9 +16161,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_bindings_target_idx": {"name": "company_secret_bindings_target_idx",@@ -16166,9 +16188,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_bindings_target_path_uq": {"name": "company_secret_bindings_target_path_uq",@@ -16199,37 +16221,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_secret_bindings_company_id_companies_id_fk": {"name": "company_secret_bindings_company_id_companies_id_fk","tableFrom": "company_secret_bindings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"company_secret_bindings_secret_id_company_secrets_id_fk": {"name": "company_secret_bindings_secret_id_company_secrets_id_fk","tableFrom": "company_secret_bindings",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -16464,9 +16486,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_proposals_proposer_status_idx": {"name": "company_secret_proposals_proposer_status_idx",@@ -16485,9 +16507,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_proposals_expiry_idx": {"name": "company_secret_proposals_expiry_idx",@@ -16506,9 +16528,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_proposals_secret_proposal_idx": {"name": "company_secret_proposals_secret_proposal_idx",@@ -16521,9 +16543,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_proposals_interaction_idx": {"name": "company_secret_proposals_interaction_idx",@@ -16536,128 +16558,128 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_secret_proposals_company_id_companies_id_fk": {"name": "company_secret_proposals_company_id_companies_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"company_secret_proposals_secret_id_company_secrets_id_fk": {"name": "company_secret_proposals_secret_id_company_secrets_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secret_proposals_secret_proposal_id_company_secret_proposals_id_fk": {"name": "company_secret_proposals_secret_proposal_id_company_secret_proposals_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "company_secret_proposals","columnsFrom": ["secret_proposal_id"],- "tableTo": "company_secret_proposals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_proposals_target_id_agents_id_fk": {"name": "company_secret_proposals_target_id_agents_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "agents","columnsFrom": ["target_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_proposals_proposed_by_agent_id_agents_id_fk": {"name": "company_secret_proposals_proposed_by_agent_id_agents_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "agents","columnsFrom": ["proposed_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_proposals_origin_issue_id_issues_id_fk": {"name": "company_secret_proposals_origin_issue_id_issues_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "issues","columnsFrom": ["origin_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secret_proposals_origin_run_id_heartbeat_runs_id_fk": {"name": "company_secret_proposals_origin_run_id_heartbeat_runs_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "heartbeat_runs","columnsFrom": ["origin_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_proposals_interaction_id_issue_thread_interactions_id_fk": {"name": "company_secret_proposals_interaction_id_issue_thread_interactions_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "issue_thread_interactions","columnsFrom": ["interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secret_proposals_created_secret_id_company_secrets_id_fk": {"name": "company_secret_proposals_created_secret_id_company_secrets_id_fk","tableFrom": "company_secret_proposals",+ "tableTo": "company_secrets","columnsFrom": ["created_secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -16802,9 +16824,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_provider_configs_company_provider_idx": {"name": "company_secret_provider_configs_company_provider_idx",@@ -16823,9 +16845,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_provider_configs_default_uq": {"name": "company_secret_provider_configs_default_uq",@@ -16844,38 +16866,38 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_secret_provider_configs\".\"is_default\" = true",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"company_secret_provider_configs_company_id_companies_id_fk": {"name": "company_secret_provider_configs_company_id_companies_id_fk","tableFrom": "company_secret_provider_configs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_provider_configs_created_by_agent_id_agents_id_fk": {"name": "company_secret_provider_configs_created_by_agent_id_agents_id_fk","tableFrom": "company_secret_provider_configs",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -16988,9 +17010,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_versions_value_sha256_idx": {"name": "company_secret_versions_value_sha256_idx",@@ -17003,9 +17025,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_versions_fingerprint_idx": {"name": "company_secret_versions_fingerprint_idx",@@ -17018,9 +17040,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secret_versions_secret_version_uq": {"name": "company_secret_versions_secret_version_uq",@@ -17039,37 +17061,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_secret_versions_secret_id_company_secrets_id_fk": {"name": "company_secret_versions_secret_id_company_secrets_id_fk","tableFrom": "company_secret_versions",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secret_versions_created_by_agent_id_agents_id_fk": {"name": "company_secret_versions_created_by_agent_id_agents_id_fk","tableFrom": "company_secret_versions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -17254,9 +17276,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_company_scope_idx": {"name": "company_secrets_company_scope_idx",@@ -17275,9 +17297,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_company_owner_idx": {"name": "company_secrets_company_owner_idx",@@ -17296,9 +17318,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_user_definition_owner_idx": {"name": "company_secrets_user_definition_owner_idx",@@ -17323,9 +17345,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_company_provider_idx": {"name": "company_secrets_company_provider_idx",@@ -17344,9 +17366,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_instance_owner_key_uq": {"name": "company_secrets_instance_owner_key_uq",@@ -17377,10 +17399,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_secrets\".\"scope\" = 'instance' and \"company_secrets\".\"deleted_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"company_secrets_provider_config_idx": {"name": "company_secrets_provider_config_idx",@@ -17393,9 +17415,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_secrets_company_name_uq": {"name": "company_secrets_company_name_uq",@@ -17414,10 +17436,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_secrets\".\"scope\" = 'company' and \"company_secrets\".\"deleted_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"company_secrets_company_key_uq": {"name": "company_secrets_company_key_uq",@@ -17436,10 +17458,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_secrets\".\"scope\" = 'company' and \"company_secrets\".\"deleted_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"company_secrets_user_definition_owner_uq": {"name": "company_secrets_user_definition_owner_uq",@@ -17464,92 +17486,92 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_secrets\".\"scope\" = 'user' and \"company_secrets\".\"deleted_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"company_secrets_company_id_companies_id_fk": {"name": "company_secrets_company_id_companies_id_fk","tableFrom": "company_secrets",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"company_secrets_owner_plugin_id_plugins_id_fk": {"name": "company_secrets_owner_plugin_id_plugins_id_fk","tableFrom": "company_secrets",+ "tableTo": "plugins","columnsFrom": ["owner_plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_secrets_user_secret_definition_id_user_secret_definitions_id_fk": {"name": "company_secrets_user_secret_definition_id_user_secret_definitions_id_fk","tableFrom": "company_secrets",+ "tableTo": "user_secret_definitions","columnsFrom": ["user_secret_definition_id"],- "tableTo": "user_secret_definitions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secrets_provider_config_id_company_secret_provider_configs_id_fk": {"name": "company_secrets_provider_config_id_company_secret_provider_configs_id_fk","tableFrom": "company_secrets",+ "tableTo": "company_secret_provider_configs","columnsFrom": ["provider_config_id"],- "tableTo": "company_secret_provider_configs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secrets_created_by_agent_id_agents_id_fk": {"name": "company_secrets_created_by_agent_id_agents_id_fk","tableFrom": "company_secrets",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_secrets_company_id_owner_agent_id_agents_company_id_id_fk": {"name": "company_secrets_company_id_owner_agent_id_agents_company_id_id_fk","tableFrom": "company_secrets",+ "tableTo": "agents","columnsFrom": ["company_id","owner_agent_id"],- "tableTo": "agents","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -17619,15 +17641,15 @@"company_skill_policies_company_id_companies_id_fk": {"name": "company_skill_policies_company_id_companies_id_fk","tableFrom": "company_skill_policies",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -17666,15 +17688,15 @@"company_skill_import_budgets_company_id_companies_id_fk": {"name": "company_skill_import_budgets_company_id_companies_id_fk","tableFrom": "company_skill_import_budgets",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -17775,9 +17797,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_source_entries_company_skill_idx": {"name": "company_skill_source_entries_company_skill_idx",@@ -17796,50 +17818,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_source_entries_company_id_companies_id_fk": {"name": "company_skill_source_entries_company_id_companies_id_fk","tableFrom": "company_skill_source_entries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_source_entries_source_id_company_skill_sources_id_fk": {"name": "company_skill_source_entries_source_id_company_skill_sources_id_fk","tableFrom": "company_skill_source_entries",+ "tableTo": "company_skill_sources","columnsFrom": ["source_id"],- "tableTo": "company_skill_sources","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_source_entries_skill_id_company_skills_id_fk": {"name": "company_skill_source_entries_skill_id_company_skills_id_fk","tableFrom": "company_skill_source_entries",+ "tableTo": "company_skills","columnsFrom": ["skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18083,10 +18105,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_skill_sources\".\"removed_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"company_skill_sources_identity_ref_idx": {"name": "company_skill_sources_identity_ref_idx",@@ -18111,25 +18133,25 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_skill_sources\".\"removed_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"company_skill_sources_company_id_companies_id_fk": {"name": "company_skill_sources_company_id_companies_id_fk","tableFrom": "company_skill_sources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18294,9 +18316,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_skill_sources_source_project_idx": {"name": "project_skill_sources_source_project_idx",@@ -18321,9 +18343,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_skill_sources_sync_idx": {"name": "project_skill_sources_sync_idx",@@ -18348,63 +18370,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"project_skill_sources_company_id_companies_id_fk": {"name": "project_skill_sources_company_id_companies_id_fk","tableFrom": "project_skill_sources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_skill_sources_project_id_projects_id_fk": {"name": "project_skill_sources_project_id_projects_id_fk","tableFrom": "project_skill_sources",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_skill_sources_workspace_id_project_workspaces_id_fk": {"name": "project_skill_sources_workspace_id_project_workspaces_id_fk","tableFrom": "project_skill_sources",+ "tableTo": "project_workspaces","columnsFrom": ["workspace_id"],- "tableTo": "project_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"project_skill_sources_source_id_company_skill_sources_id_fk": {"name": "project_skill_sources_source_id_company_skill_sources_id_fk","tableFrom": "project_skill_sources",+ "tableTo": "company_skill_sources","columnsFrom": ["source_id"],- "tableTo": "company_skill_sources","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18505,9 +18527,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_comments_parent_idx": {"name": "company_skill_comments_parent_idx",@@ -18520,63 +18542,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_comments_company_id_companies_id_fk": {"name": "company_skill_comments_company_id_companies_id_fk","tableFrom": "company_skill_comments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_comments_company_skill_id_company_skills_id_fk": {"name": "company_skill_comments_company_skill_id_company_skills_id_fk","tableFrom": "company_skill_comments",+ "tableTo": "company_skills","columnsFrom": ["company_skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_comments_parent_comment_id_company_skill_comments_id_fk": {"name": "company_skill_comments_parent_comment_id_company_skill_comments_id_fk","tableFrom": "company_skill_comments",+ "tableTo": "company_skill_comments","columnsFrom": ["parent_comment_id"],- "tableTo": "company_skill_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skill_comments_author_agent_id_agents_id_fk": {"name": "company_skill_comments_author_agent_id_agents_id_fk","tableFrom": "company_skill_comments",+ "tableTo": "agents","columnsFrom": ["author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18640,24 +18662,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_repository_snapshots_company_id_companies_id_fk": {"name": "company_skill_repository_snapshots_company_id_companies_id_fk","tableFrom": "company_skill_repository_snapshots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18727,9 +18749,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_stars_skill_user_idx": {"name": "company_skill_stars_skill_user_idx",@@ -18748,9 +18770,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_stars_company_skill_created_idx": {"name": "company_skill_stars_company_skill_created_idx",@@ -18775,50 +18797,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_stars_company_id_companies_id_fk": {"name": "company_skill_stars_company_id_companies_id_fk","tableFrom": "company_skill_stars",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_stars_company_skill_id_company_skills_id_fk": {"name": "company_skill_stars_company_skill_id_company_skills_id_fk","tableFrom": "company_skill_stars",+ "tableTo": "company_skills","columnsFrom": ["company_skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_stars_agent_id_agents_id_fk": {"name": "company_skill_stars_agent_id_agents_id_fk","tableFrom": "company_skill_stars",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -18913,9 +18935,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_test_inputs_company_skill_active_idx": {"name": "company_skill_test_inputs_company_skill_active_idx",@@ -18940,37 +18962,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_test_inputs_company_id_companies_id_fk": {"name": "company_skill_test_inputs_company_id_companies_id_fk","tableFrom": "company_skill_test_inputs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_test_inputs_skill_id_company_skills_id_fk": {"name": "company_skill_test_inputs_skill_id_company_skills_id_fk","tableFrom": "company_skill_test_inputs",+ "tableTo": "company_skills","columnsFrom": ["skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -19083,50 +19105,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_test_run_templates_company_id_companies_id_fk": {"name": "company_skill_test_run_templates_company_id_companies_id_fk","tableFrom": "company_skill_test_run_templates",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_test_run_templates_created_by_agent_id_agents_id_fk": {"name": "company_skill_test_run_templates_created_by_agent_id_agents_id_fk","tableFrom": "company_skill_test_run_templates",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skill_test_run_templates_updated_by_agent_id_agents_id_fk": {"name": "company_skill_test_run_templates_updated_by_agent_id_agents_id_fk","tableFrom": "company_skill_test_run_templates",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -19316,9 +19338,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_test_runs_company_issue_idx": {"name": "company_skill_test_runs_company_issue_idx",@@ -19337,9 +19359,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_test_runs_company_input_created_idx": {"name": "company_skill_test_runs_company_input_created_idx",@@ -19364,9 +19386,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_test_runs_company_status_idx": {"name": "company_skill_test_runs_company_status_idx",@@ -19385,9 +19407,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_test_runs_company_harness_expires_idx": {"name": "company_skill_test_runs_company_harness_expires_idx",@@ -19406,89 +19428,89 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_test_runs_company_id_companies_id_fk": {"name": "company_skill_test_runs_company_id_companies_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_test_runs_skill_id_company_skills_id_fk": {"name": "company_skill_test_runs_skill_id_company_skills_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "company_skills","columnsFrom": ["skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_test_runs_input_id_company_skill_test_inputs_id_fk": {"name": "company_skill_test_runs_input_id_company_skill_test_inputs_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "company_skill_test_inputs","columnsFrom": ["input_id"],- "tableTo": "company_skill_test_inputs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skill_test_runs_skill_version_id_company_skill_versions_id_fk": {"name": "company_skill_test_runs_skill_version_id_company_skill_versions_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "company_skill_versions","columnsFrom": ["skill_version_id"],- "tableTo": "company_skill_versions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"company_skill_test_runs_agent_id_agents_id_fk": {"name": "company_skill_test_runs_agent_id_agents_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"company_skill_test_runs_issue_id_issues_id_fk": {"name": "company_skill_test_runs_issue_id_issues_id_fk","tableFrom": "company_skill_test_runs",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -19607,9 +19629,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skill_versions_skill_release_idx": {"name": "company_skill_versions_skill_release_idx",@@ -19628,10 +19650,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"company_skill_versions\".\"release_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"company_skill_versions_company_skill_created_idx": {"name": "company_skill_versions_company_skill_created_idx",@@ -19656,63 +19678,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skill_versions_company_id_companies_id_fk": {"name": "company_skill_versions_company_id_companies_id_fk","tableFrom": "company_skill_versions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_versions_company_skill_id_company_skills_id_fk": {"name": "company_skill_versions_company_skill_id_company_skills_id_fk","tableFrom": "company_skill_versions",+ "tableTo": "company_skills","columnsFrom": ["company_skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"company_skill_versions_repository_snapshot_id_company_skill_repository_snapshots_id_fk": {"name": "company_skill_versions_repository_snapshot_id_company_skill_repository_snapshots_id_fk","tableFrom": "company_skill_versions",+ "tableTo": "company_skill_repository_snapshots","columnsFrom": ["repository_snapshot_id"],- "tableTo": "company_skill_repository_snapshots","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"company_skill_versions_author_agent_id_agents_id_fk": {"name": "company_skill_versions_author_agent_id_agents_id_fk","tableFrom": "company_skill_versions",+ "tableTo": "agents","columnsFrom": ["author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -19948,9 +19970,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skills_company_name_idx": {"name": "company_skills_company_name_idx",@@ -19969,9 +19991,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skills_company_folder_idx": {"name": "company_skills_company_folder_idx",@@ -19990,9 +20012,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skills_company_categories_idx": {"name": "company_skills_company_categories_idx",@@ -20005,9 +20027,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"company_skills_company_sharing_scope_idx": {"name": "company_skills_company_sharing_scope_idx",@@ -20026,9 +20048,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skills_company_current_version_idx": {"name": "company_skills_company_current_version_idx",@@ -20047,9 +20069,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_skills_company_forked_from_idx": {"name": "company_skills_company_forked_from_idx",@@ -20068,76 +20090,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_skills_company_id_companies_id_fk": {"name": "company_skills_company_id_companies_id_fk","tableFrom": "company_skills",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"company_skills_folder_id_folders_id_fk": {"name": "company_skills_folder_id_folders_id_fk","tableFrom": "company_skills",+ "tableTo": "folders","columnsFrom": ["folder_id"],- "tableTo": "folders","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skills_forked_from_skill_id_company_skills_id_fk": {"name": "company_skills_forked_from_skill_id_company_skills_id_fk","tableFrom": "company_skills",+ "tableTo": "company_skills","columnsFrom": ["forked_from_skill_id"],- "tableTo": "company_skills","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skills_forked_from_company_id_companies_id_fk": {"name": "company_skills_forked_from_company_id_companies_id_fk","tableFrom": "company_skills",+ "tableTo": "companies","columnsFrom": ["forked_from_company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"company_skills_current_version_id_company_skill_versions_id_fk": {"name": "company_skills_current_version_id_company_skill_versions_id_fk","tableFrom": "company_skills",+ "tableTo": "company_skill_versions","columnsFrom": ["current_version_id"],- "tableTo": "company_skill_versions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -20272,9 +20294,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_transfer_runs_idempotency_direction_idx": {"name": "company_transfer_runs_idempotency_direction_idx",@@ -20293,9 +20315,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_transfer_runs_actor_status_idx": {"name": "company_transfer_runs_actor_status_idx",@@ -20314,24 +20336,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_transfer_runs_company_id_companies_id_fk": {"name": "company_transfer_runs_company_id_companies_id_fk","tableFrom": "company_transfer_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -20397,9 +20419,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_user_sidebar_preferences_user_idx": {"name": "company_user_sidebar_preferences_user_idx",@@ -20412,9 +20434,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"company_user_sidebar_preferences_company_user_uq": {"name": "company_user_sidebar_preferences_company_user_uq",@@ -20433,24 +20455,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"company_user_sidebar_preferences_company_id_companies_id_fk": {"name": "company_user_sidebar_preferences_company_id_companies_id_fk","tableFrom": "company_user_sidebar_preferences",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -20574,9 +20596,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"completion_contracts_issue_hash_uq": {"name": "completion_contracts_issue_hash_uq",@@ -20595,68 +20617,68 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"completion_contracts_company_id_companies_id_fk": {"name": "completion_contracts_company_id_companies_id_fk","tableFrom": "completion_contracts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"completion_contracts_issue_company_fk": {"name": "completion_contracts_issue_company_fk","tableFrom": "completion_contracts",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"completion_contracts_supersedes_owner_fk": {"name": "completion_contracts_supersedes_owner_fk","tableFrom": "completion_contracts",+ "tableTo": "completion_contracts","columnsFrom": ["company_id","issue_id","supersedes_contract_id"],- "tableTo": "completion_contracts","columnsTo": ["company_id","issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"completion_contracts_company_issue_id_uq": {"name": "completion_contracts_company_issue_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","issue_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -20794,9 +20816,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_event_deliveries_company_status_idx": {"name": "connection_event_deliveries_company_status_idx",@@ -20821,24 +20843,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"connection_event_deliveries_company_id_companies_id_fk": {"name": "connection_event_deliveries_company_id_companies_id_fk","tableFrom": "connection_event_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -20902,37 +20924,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"connection_intent_deliveries_interaction_id_issue_thread_interactions_id_fk": {"name": "connection_intent_deliveries_interaction_id_issue_thread_interactions_id_fk","tableFrom": "connection_intent_deliveries",+ "tableTo": "issue_thread_interactions","columnsFrom": ["interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_intent_deliveries_company_id_companies_id_fk": {"name": "connection_intent_deliveries_company_id_companies_id_fk","tableFrom": "connection_intent_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -21135,9 +21157,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_provider_request_idx": {"name": "cost_events_provider_request_idx",@@ -21162,9 +21184,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_project_occurred_idx": {"name": "cost_events_company_project_occurred_idx",@@ -21189,9 +21211,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_unpriced_idx": {"name": "cost_events_unpriced_idx",@@ -21216,10 +21238,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"cost_events\".\"cost_status\" = 'unpriced' and \"cost_events\".\"billing_type\" <> 'subscription_included'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"cost_events_data_quality_idx": {"name": "cost_events_data_quality_idx",@@ -21244,10 +21266,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"cost_events\".\"billing_type\" = 'unknown' or (\"cost_events\".\"cost_status\" = 'unpriced' and \"cost_events\".\"billing_type\" <> 'subscription_included')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"cost_events_company_occurred_idx": {"name": "cost_events_company_occurred_idx",@@ -21266,9 +21288,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_subscription_occurred_idx": {"name": "cost_events_company_subscription_occurred_idx",@@ -21293,9 +21315,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_agent_occurred_idx": {"name": "cost_events_company_agent_occurred_idx",@@ -21320,9 +21342,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_provider_occurred_idx": {"name": "cost_events_company_provider_occurred_idx",@@ -21347,9 +21369,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_biller_occurred_idx": {"name": "cost_events_company_biller_occurred_idx",@@ -21374,9 +21396,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"cost_events_company_heartbeat_run_idx": {"name": "cost_events_company_heartbeat_run_idx",@@ -21395,102 +21417,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"cost_events_company_id_companies_id_fk": {"name": "cost_events_company_id_companies_id_fk","tableFrom": "cost_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"cost_events_agent_id_agents_id_fk": {"name": "cost_events_agent_id_agents_id_fk","tableFrom": "cost_events",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"cost_events_issue_id_issues_id_fk": {"name": "cost_events_issue_id_issues_id_fk","tableFrom": "cost_events",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"cost_events_project_id_projects_id_fk": {"name": "cost_events_project_id_projects_id_fk","tableFrom": "cost_events",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"cost_events_goal_id_goals_id_fk": {"name": "cost_events_goal_id_goals_id_fk","tableFrom": "cost_events",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"cost_events_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "cost_events_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "cost_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"cost_events_subscription_id_ai_subscriptions_id_fk": {"name": "cost_events_subscription_id_ai_subscriptions_id_fk","tableFrom": "cost_events",+ "tableTo": "ai_subscriptions","columnsFrom": ["subscription_id"],- "tableTo": "ai_subscriptions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -21569,15 +21591,15 @@"company_decision_models_company_id_companies_id_fk": {"name": "company_decision_models_company_id_companies_id_fk","tableFrom": "company_decision_models",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -21773,9 +21795,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_invocations_pending_idx": {"name": "decision_invocations_pending_idx",@@ -21788,10 +21810,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"decision_invocations\".\"status\" = 'running'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"decision_invocations_cost_idx": {"name": "decision_invocations_cost_idx",@@ -21804,37 +21826,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_invocations_company_id_companies_id_fk": {"name": "decision_invocations_company_id_companies_id_fk","tableFrom": "decision_invocations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_invocations_cost_event_id_cost_events_id_fk": {"name": "decision_invocations_cost_event_id_cost_events_id_fk","tableFrom": "decision_invocations",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -21972,9 +21994,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_archive_notification_outbox_pending_idx": {"name": "decision_archive_notification_outbox_pending_idx",@@ -21993,37 +22015,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_archive_notification_outbox_company_id_companies_id_fk": {"name": "decision_archive_notification_outbox_company_id_companies_id_fk","tableFrom": "decision_archive_notification_outbox",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_archive_notification_outbox_origin_agent_id_agents_id_fk": {"name": "decision_archive_notification_outbox_origin_agent_id_agents_id_fk","tableFrom": "decision_archive_notification_outbox",+ "tableTo": "agents","columnsFrom": ["origin_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -22140,9 +22162,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_queue_items_company_source_idx": {"name": "decision_queue_items_company_source_idx",@@ -22167,78 +22189,78 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_queue_items_company_id_companies_id_fk": {"name": "decision_queue_items_company_id_companies_id_fk","tableFrom": "decision_queue_items",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_queue_items_added_by_agent_id_agents_id_fk": {"name": "decision_queue_items_added_by_agent_id_agents_id_fk","tableFrom": "decision_queue_items",+ "tableTo": "agents","columnsFrom": ["added_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_queue_items_added_by_run_id_heartbeat_runs_id_fk": {"name": "decision_queue_items_added_by_run_id_heartbeat_runs_id_fk","tableFrom": "decision_queue_items",+ "tableTo": "heartbeat_runs","columnsFrom": ["added_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_queue_items_added_by_agent_api_key_id_agent_api_keys_id_fk": {"name": "decision_queue_items_added_by_agent_api_key_id_agent_api_keys_id_fk","tableFrom": "decision_queue_items",+ "tableTo": "agent_api_keys","columnsFrom": ["added_by_agent_api_key_id"],- "tableTo": "agent_api_keys","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_queue_items_queue_company_fk": {"name": "decision_queue_items_queue_company_fk","tableFrom": "decision_queue_items",+ "tableTo": "decision_queues","columnsFrom": ["queue_id","company_id"],- "tableTo": "decision_queues","columnsTo": ["id","company_id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -22370,9 +22392,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_queues_company_updated_idx": {"name": "decision_queues_company_updated_idx",@@ -22391,74 +22413,74 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_queues_company_id_companies_id_fk": {"name": "decision_queues_company_id_companies_id_fk","tableFrom": "decision_queues",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_queues_created_by_agent_id_agents_id_fk": {"name": "decision_queues_created_by_agent_id_agents_id_fk","tableFrom": "decision_queues",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_queues_created_by_run_id_heartbeat_runs_id_fk": {"name": "decision_queues_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "decision_queues",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_queues_created_by_agent_api_key_id_agent_api_keys_id_fk": {"name": "decision_queues_created_by_agent_api_key_id_agent_api_keys_id_fk","tableFrom": "decision_queues",+ "tableTo": "agent_api_keys","columnsFrom": ["created_by_agent_api_key_id"],- "tableTo": "agent_api_keys","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"decision_queues_id_company_uq": {"name": "decision_queues_id_company_uq",+ "nullsNotDistinct": false,"columns": ["id","company_id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -22605,9 +22627,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_retention_company_archived_idx": {"name": "decision_retention_company_archived_idx",@@ -22626,50 +22648,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_retention_company_id_companies_id_fk": {"name": "decision_retention_company_id_companies_id_fk","tableFrom": "decision_retention",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_retention_archived_by_agent_id_agents_id_fk": {"name": "decision_retention_archived_by_agent_id_agents_id_fk","tableFrom": "decision_retention",+ "tableTo": "agents","columnsFrom": ["archived_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_retention_archived_by_run_id_heartbeat_runs_id_fk": {"name": "decision_retention_archived_by_run_id_heartbeat_runs_id_fk","tableFrom": "decision_retention",+ "tableTo": "heartbeat_runs","columnsFrom": ["archived_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -22812,9 +22834,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_triage_company_decide_by_idx": {"name": "decision_triage_company_decide_by_idx",@@ -22833,63 +22855,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_triage_company_id_companies_id_fk": {"name": "decision_triage_company_id_companies_id_fk","tableFrom": "decision_triage",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_triage_set_by_agent_id_agents_id_fk": {"name": "decision_triage_set_by_agent_id_agents_id_fk","tableFrom": "decision_triage",+ "tableTo": "agents","columnsFrom": ["set_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_triage_set_by_run_id_heartbeat_runs_id_fk": {"name": "decision_triage_set_by_run_id_heartbeat_runs_id_fk","tableFrom": "decision_triage",+ "tableTo": "heartbeat_runs","columnsFrom": ["set_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_triage_set_by_agent_api_key_id_agent_api_keys_id_fk": {"name": "decision_triage_set_by_agent_api_key_id_agent_api_keys_id_fk","tableFrom": "decision_triage",+ "tableTo": "agent_api_keys","columnsFrom": ["set_by_agent_api_key_id"],- "tableTo": "agent_api_keys","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -23029,9 +23051,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_triage_events_queue_created_idx": {"name": "decision_triage_events_queue_created_idx",@@ -23050,76 +23072,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_triage_events_company_id_companies_id_fk": {"name": "decision_triage_events_company_id_companies_id_fk","tableFrom": "decision_triage_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_triage_events_queue_id_decision_queues_id_fk": {"name": "decision_triage_events_queue_id_decision_queues_id_fk","tableFrom": "decision_triage_events",+ "tableTo": "decision_queues","columnsFrom": ["queue_id"],- "tableTo": "decision_queues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_triage_events_actor_agent_id_agents_id_fk": {"name": "decision_triage_events_actor_agent_id_agents_id_fk","tableFrom": "decision_triage_events",+ "tableTo": "agents","columnsFrom": ["actor_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_triage_events_actor_run_id_heartbeat_runs_id_fk": {"name": "decision_triage_events_actor_run_id_heartbeat_runs_id_fk","tableFrom": "decision_triage_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["actor_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_triage_events_agent_api_key_id_agent_api_keys_id_fk": {"name": "decision_triage_events_agent_api_key_id_agent_api_keys_id_fk","tableFrom": "decision_triage_events",+ "tableTo": "agent_api_keys","columnsFrom": ["agent_api_key_id"],- "tableTo": "agent_api_keys","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -23246,9 +23268,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_training_examples_issue_idx": {"name": "decision_training_examples_issue_idx",@@ -23261,9 +23283,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_training_examples_source_author_uq": {"name": "decision_training_examples_source_author_uq",@@ -23288,37 +23310,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_training_examples_company_id_companies_id_fk": {"name": "decision_training_examples_company_id_companies_id_fk","tableFrom": "decision_training_examples",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_training_examples_issue_id_issues_id_fk": {"name": "decision_training_examples_issue_id_issues_id_fk","tableFrom": "decision_training_examples",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -23400,63 +23422,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_bundles_company_id_companies_id_fk": {"name": "decision_bundles_company_id_companies_id_fk","tableFrom": "decision_bundles",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_bundles_origin_agent_id_agents_id_fk": {"name": "decision_bundles_origin_agent_id_agents_id_fk","tableFrom": "decision_bundles",+ "tableTo": "agents","columnsFrom": ["origin_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_bundles_origin_issue_id_issues_id_fk": {"name": "decision_bundles_origin_issue_id_issues_id_fk","tableFrom": "decision_bundles",+ "tableTo": "issues","columnsFrom": ["origin_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_bundles_origin_run_id_heartbeat_runs_id_fk": {"name": "decision_bundles_origin_run_id_heartbeat_runs_id_fk","tableFrom": "decision_bundles",+ "tableTo": "heartbeat_runs","columnsFrom": ["origin_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -23550,9 +23572,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_effect_executions_target_issue_idx": {"name": "decision_effect_executions_target_issue_idx",@@ -23565,50 +23587,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_effect_executions_decision_id_decisions_id_fk": {"name": "decision_effect_executions_decision_id_decisions_id_fk","tableFrom": "decision_effect_executions",+ "tableTo": "decisions","columnsFrom": ["decision_id"],- "tableTo": "decisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_effect_executions_target_issue_id_issues_id_fk": {"name": "decision_effect_executions_target_issue_id_issues_id_fk","tableFrom": "decision_effect_executions",+ "tableTo": "issues","columnsFrom": ["target_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decision_effect_executions_activity_log_id_activity_log_id_fk": {"name": "decision_effect_executions_activity_log_id_activity_log_id_fk","tableFrom": "decision_effect_executions",+ "tableTo": "activity_log","columnsFrom": ["activity_log_id"],- "tableTo": "activity_log","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -23652,9 +23674,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decision_target_issues_issue_idx": {"name": "decision_target_issues_issue_idx",@@ -23667,50 +23689,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"decision_target_issues_decision_id_decisions_id_fk": {"name": "decision_target_issues_decision_id_decisions_id_fk","tableFrom": "decision_target_issues",+ "tableTo": "decisions","columnsFrom": ["decision_id"],- "tableTo": "decisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_target_issues_issue_id_issues_id_fk": {"name": "decision_target_issues_issue_id_issues_id_fk","tableFrom": "decision_target_issues",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"decision_target_issues_company_id_companies_id_fk": {"name": "decision_target_issues_company_id_companies_id_fk","tableFrom": "decision_target_issues",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {@@ -23912,9 +23934,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decisions_bundle_idx": {"name": "decisions_bundle_idx",@@ -23927,9 +23949,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decisions_origin_issue_idx": {"name": "decisions_origin_issue_idx",@@ -23942,9 +23964,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"decisions_company_idempotency_uq": {"name": "decisions_company_idempotency_uq",@@ -23963,77 +23985,77 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"decisions\".\"idempotency_key\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"decisions_company_id_companies_id_fk": {"name": "decisions_company_id_companies_id_fk","tableFrom": "decisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decisions_bundle_id_decision_bundles_id_fk": {"name": "decisions_bundle_id_decision_bundles_id_fk","tableFrom": "decisions",+ "tableTo": "decision_bundles","columnsFrom": ["bundle_id"],- "tableTo": "decision_bundles","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"decisions_origin_agent_id_agents_id_fk": {"name": "decisions_origin_agent_id_agents_id_fk","tableFrom": "decisions",+ "tableTo": "agents","columnsFrom": ["origin_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decisions_origin_issue_id_issues_id_fk": {"name": "decisions_origin_issue_id_issues_id_fk","tableFrom": "decisions",+ "tableTo": "issues","columnsFrom": ["origin_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"decisions_origin_run_id_heartbeat_runs_id_fk": {"name": "decisions_origin_run_id_heartbeat_runs_id_fk","tableFrom": "decisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["origin_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -24157,9 +24179,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_anchor_snapshots_company_document_revision_idx": {"name": "document_annotation_anchor_snapshots_company_document_revision_idx",@@ -24184,76 +24206,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"document_annotation_anchor_snapshots_company_id_companies_id_fk": {"name": "document_annotation_anchor_snapshots_company_id_companies_id_fk","tableFrom": "document_annotation_anchor_snapshots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"document_annotation_anchor_snapshots_thread_id_document_annotation_threads_id_fk": {"name": "document_annotation_anchor_snapshots_thread_id_document_annotation_threads_id_fk","tableFrom": "document_annotation_anchor_snapshots",+ "tableTo": "document_annotation_threads","columnsFrom": ["thread_id"],- "tableTo": "document_annotation_threads","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_anchor_snapshots_document_id_documents_id_fk": {"name": "document_annotation_anchor_snapshots_document_id_documents_id_fk","tableFrom": "document_annotation_anchor_snapshots",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_anchor_snapshots_from_revision_id_document_revisions_id_fk": {"name": "document_annotation_anchor_snapshots_from_revision_id_document_revisions_id_fk","tableFrom": "document_annotation_anchor_snapshots",+ "tableTo": "document_revisions","columnsFrom": ["from_revision_id"],- "tableTo": "document_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_anchor_snapshots_to_revision_id_document_revisions_id_fk": {"name": "document_annotation_anchor_snapshots_to_revision_id_document_revisions_id_fk","tableFrom": "document_annotation_anchor_snapshots",+ "tableTo": "document_revisions","columnsFrom": ["to_revision_id"],- "tableTo": "document_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -24390,9 +24412,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_company_issue_created_at_idx": {"name": "document_annotation_comments_company_issue_created_at_idx",@@ -24417,9 +24439,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_company_routine_created_at_idx": {"name": "document_annotation_comments_company_routine_created_at_idx",@@ -24444,9 +24466,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_company_case_created_at_idx": {"name": "document_annotation_comments_company_case_created_at_idx",@@ -24471,9 +24493,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_company_document_created_at_idx": {"name": "document_annotation_comments_company_document_created_at_idx",@@ -24498,9 +24520,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_issue_comment_idx": {"name": "document_annotation_comments_issue_comment_idx",@@ -24513,9 +24535,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_comments_body_search_idx": {"name": "document_annotation_comments_body_search_idx",@@ -24529,128 +24551,128 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}}},"foreignKeys": {"document_annotation_comments_company_id_companies_id_fk": {"name": "document_annotation_comments_company_id_companies_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"document_annotation_comments_thread_id_document_annotation_threads_id_fk": {"name": "document_annotation_comments_thread_id_document_annotation_threads_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "document_annotation_threads","columnsFrom": ["thread_id"],- "tableTo": "document_annotation_threads","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_comments_issue_id_issues_id_fk": {"name": "document_annotation_comments_issue_id_issues_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_comments_routine_id_routines_id_fk": {"name": "document_annotation_comments_routine_id_routines_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_comments_case_id_cases_id_fk": {"name": "document_annotation_comments_case_id_cases_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_comments_document_id_documents_id_fk": {"name": "document_annotation_comments_document_id_documents_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_comments_author_agent_id_agents_id_fk": {"name": "document_annotation_comments_author_agent_id_agents_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "agents","columnsFrom": ["author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_comments_created_by_run_id_heartbeat_runs_id_fk": {"name": "document_annotation_comments_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_comments_issue_comment_id_issue_comments_id_fk": {"name": "document_annotation_comments_issue_comment_id_issue_comments_id_fk","tableFrom": "document_annotation_comments",+ "tableTo": "issue_comments","columnsFrom": ["issue_comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -24875,9 +24897,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_threads_company_issue_status_idx": {"name": "document_annotation_threads_company_issue_status_idx",@@ -24902,9 +24924,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_threads_company_routine_status_idx": {"name": "document_annotation_threads_company_routine_status_idx",@@ -24929,9 +24951,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_threads_company_case_status_idx": {"name": "document_annotation_threads_company_case_status_idx",@@ -24956,9 +24978,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_threads_company_current_revision_open_idx": {"name": "document_annotation_threads_company_current_revision_open_idx",@@ -24989,9 +25011,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_annotation_threads_company_anchor_state_idx": {"name": "document_annotation_threads_company_anchor_state_idx",@@ -25010,128 +25032,128 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"document_annotation_threads_company_id_companies_id_fk": {"name": "document_annotation_threads_company_id_companies_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"document_annotation_threads_issue_id_issues_id_fk": {"name": "document_annotation_threads_issue_id_issues_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_threads_routine_id_routines_id_fk": {"name": "document_annotation_threads_routine_id_routines_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_threads_case_id_cases_id_fk": {"name": "document_annotation_threads_case_id_cases_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "cases","columnsFrom": ["case_id"],- "tableTo": "cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_threads_document_id_documents_id_fk": {"name": "document_annotation_threads_document_id_documents_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_annotation_threads_original_revision_id_document_revisions_id_fk": {"name": "document_annotation_threads_original_revision_id_document_revisions_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "document_revisions","columnsFrom": ["original_revision_id"],- "tableTo": "document_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_threads_current_revision_id_document_revisions_id_fk": {"name": "document_annotation_threads_current_revision_id_document_revisions_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "document_revisions","columnsFrom": ["current_revision_id"],- "tableTo": "document_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_threads_created_by_agent_id_agents_id_fk": {"name": "document_annotation_threads_created_by_agent_id_agents_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_annotation_threads_resolved_by_agent_id_agents_id_fk": {"name": "document_annotation_threads_resolved_by_agent_id_agents_id_fk","tableFrom": "document_annotation_threads",+ "tableTo": "agents","columnsFrom": ["resolved_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -25219,9 +25241,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_memberships_company_user_document_uq": {"name": "document_memberships_company_user_document_uq",@@ -25246,37 +25268,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"document_memberships_company_id_companies_id_fk": {"name": "document_memberships_company_id_companies_id_fk","tableFrom": "document_memberships",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_memberships_document_id_documents_id_fk": {"name": "document_memberships_document_id_documents_id_fk","tableFrom": "document_memberships",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -25383,9 +25405,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"document_revisions_company_document_created_idx": {"name": "document_revisions_company_document_created_idx",@@ -25410,63 +25432,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"document_revisions_company_id_companies_id_fk": {"name": "document_revisions_company_id_companies_id_fk","tableFrom": "document_revisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_revisions_document_id_documents_id_fk": {"name": "document_revisions_document_id_documents_id_fk","tableFrom": "document_revisions",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"document_revisions_created_by_agent_id_agents_id_fk": {"name": "document_revisions_created_by_agent_id_agents_id_fk","tableFrom": "document_revisions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"document_revisions_created_by_run_id_heartbeat_runs_id_fk": {"name": "document_revisions_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "document_revisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -25605,9 +25627,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"documents_company_created_idx": {"name": "documents_company_created_idx",@@ -25626,9 +25648,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"documents_title_search_idx": {"name": "documents_title_search_idx",@@ -25642,9 +25664,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"documents_latest_body_search_idx": {"name": "documents_latest_body_search_idx",@@ -25658,63 +25680,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}}},"foreignKeys": {"documents_company_id_companies_id_fk": {"name": "documents_company_id_companies_id_fk","tableFrom": "documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"documents_created_by_agent_id_agents_id_fk": {"name": "documents_created_by_agent_id_agents_id_fk","tableFrom": "documents",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"documents_updated_by_agent_id_agents_id_fk": {"name": "documents_updated_by_agent_id_agents_id_fk","tableFrom": "documents",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"documents_locked_by_agent_id_agents_id_fk": {"name": "documents_locked_by_agent_id_agents_id_fk","tableFrom": "documents",+ "tableTo": "agents","columnsFrom": ["locked_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -25854,10 +25876,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"dot_agent_bindings\".\"revoked_at\" IS NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"dot_bindings_active_grant_uq": {"name": "dot_bindings_active_grant_uq",@@ -25870,10 +25892,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"dot_agent_bindings\".\"revoked_at\" IS NULL AND \"dot_agent_bindings\".\"grant_id\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"dot_bindings_pairing_code_uq": {"name": "dot_bindings_pairing_code_uq",@@ -25886,50 +25908,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"dot_agent_bindings_company_id_companies_id_fk": {"name": "dot_agent_bindings_company_id_companies_id_fk","tableFrom": "dot_agent_bindings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_agent_bindings_agent_id_agents_id_fk": {"name": "dot_agent_bindings_agent_id_agents_id_fk","tableFrom": "dot_agent_bindings",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_agent_bindings_grant_id_mcp_oauth_grants_id_fk": {"name": "dot_agent_bindings_grant_id_mcp_oauth_grants_id_fk","tableFrom": "dot_agent_bindings",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26022,9 +26044,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"dot_mailbox_binding_cursor_idx": {"name": "dot_mailbox_binding_cursor_idx",@@ -26049,50 +26071,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"dot_mailbox_items_company_id_companies_id_fk": {"name": "dot_mailbox_items_company_id_companies_id_fk","tableFrom": "dot_mailbox_items",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_mailbox_items_binding_id_dot_agent_bindings_id_fk": {"name": "dot_mailbox_items_binding_id_dot_agent_bindings_id_fk","tableFrom": "dot_mailbox_items",+ "tableTo": "dot_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "dot_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_mailbox_items_assignment_id_dot_runner_assignments_id_fk": {"name": "dot_mailbox_items_assignment_id_dot_runner_assignments_id_fk","tableFrom": "dot_mailbox_items",+ "tableTo": "dot_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "dot_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26242,9 +26264,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"dot_assignments_active_binding_uq": {"name": "dot_assignments_active_binding_uq",@@ -26257,10 +26279,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"dot_runner_assignments\".\"status\" IN ('offered', 'accepted')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"dot_assignments_company_idx": {"name": "dot_assignments_company_idx",@@ -26273,63 +26295,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"dot_runner_assignments_company_id_companies_id_fk": {"name": "dot_runner_assignments_company_id_companies_id_fk","tableFrom": "dot_runner_assignments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_runner_assignments_binding_id_dot_agent_bindings_id_fk": {"name": "dot_runner_assignments_binding_id_dot_agent_bindings_id_fk","tableFrom": "dot_runner_assignments",+ "tableTo": "dot_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "dot_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_runner_assignments_run_id_heartbeat_runs_id_fk": {"name": "dot_runner_assignments_run_id_heartbeat_runs_id_fk","tableFrom": "dot_runner_assignments",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_runner_assignments_agent_id_agents_id_fk": {"name": "dot_runner_assignments_agent_id_agents_id_fk","tableFrom": "dot_runner_assignments",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26443,37 +26465,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"dot_runner_operations_company_id_companies_id_fk": {"name": "dot_runner_operations_company_id_companies_id_fk","tableFrom": "dot_runner_operations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"dot_runner_operations_assignment_id_dot_runner_assignments_id_fk": {"name": "dot_runner_operations_assignment_id_dot_runner_assignments_id_fk","tableFrom": "dot_runner_operations",+ "tableTo": "dot_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "dot_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26540,17 +26562,17 @@"email_endpoints_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "email_endpoints_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "email_endpoints",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26663,9 +26685,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"email_messages_conversation_idx": {"name": "email_messages_conversation_idx",@@ -26690,41 +26712,41 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"email_messages_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "email_messages_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "email_messages",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"email_messages_company_id_conversation_id_chat_conversations_company_id_id_fk": {"name": "email_messages_company_id_conversation_id_chat_conversations_company_id_id_fk","tableFrom": "email_messages",+ "tableTo": "chat_conversations","columnsFrom": ["company_id","conversation_id"],- "tableTo": "chat_conversations","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -26810,42 +26832,42 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"email_sends\".\"outcome\" in ('queued', 'uncertain')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"email_sends_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {"name": "email_sends_company_id_endpoint_id_chat_endpoints_company_id_id_fk","tableFrom": "email_sends",+ "tableTo": "chat_endpoints","columnsFrom": ["company_id","endpoint_id"],- "tableTo": "chat_endpoints","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"email_sends_company_id_publication_id_chat_publications_company_id_id_fk": {"name": "email_sends_company_id_publication_id_chat_publications_company_id_id_fk","tableFrom": "email_sends",+ "tableTo": "chat_publications","columnsFrom": ["company_id","publication_id"],- "tableTo": "chat_publications","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -27000,9 +27022,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_setup_sessions_environment_active_uq": {"name": "environment_custom_image_setup_sessions_environment_active_uq",@@ -27015,10 +27037,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"environment_custom_image_setup_sessions\".\"status\" IN ('starting', 'waiting_for_user', 'capturing')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"environment_custom_image_setup_sessions_template_idx": {"name": "environment_custom_image_setup_sessions_template_idx",@@ -27031,9 +27053,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_setup_sessions_promoted_template_idx": {"name": "environment_custom_image_setup_sessions_promoted_template_idx",@@ -27046,9 +27068,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_setup_sessions_expires_idx": {"name": "environment_custom_image_setup_sessions_expires_idx",@@ -27061,9 +27083,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_setup_sessions_provider_lease_idx": {"name": "environment_custom_image_setup_sessions_provider_lease_idx",@@ -27082,76 +27104,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"environment_custom_image_setup_sessions_environment_id_environments_id_fk": {"name": "environment_custom_image_setup_sessions_environment_id_environments_id_fk","tableFrom": "environment_custom_image_setup_sessions",+ "tableTo": "environments","columnsFrom": ["environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"environment_custom_image_setup_sessions_template_id_environment_custom_image_templates_id_fk": {"name": "environment_custom_image_setup_sessions_template_id_environment_custom_image_templates_id_fk","tableFrom": "environment_custom_image_setup_sessions",+ "tableTo": "environment_custom_image_templates","columnsFrom": ["template_id"],- "tableTo": "environment_custom_image_templates","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_custom_image_setup_sessions_promoted_template_id_environment_custom_image_templates_id_fk": {"name": "environment_custom_image_setup_sessions_promoted_template_id_environment_custom_image_templates_id_fk","tableFrom": "environment_custom_image_setup_sessions",+ "tableTo": "environment_custom_image_templates","columnsFrom": ["promoted_template_id"],- "tableTo": "environment_custom_image_templates","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_custom_image_setup_sessions_environment_lease_id_environment_leases_id_fk": {"name": "environment_custom_image_setup_sessions_environment_lease_id_environment_leases_id_fk","tableFrom": "environment_custom_image_setup_sessions",+ "tableTo": "environment_leases","columnsFrom": ["environment_lease_id"],- "tableTo": "environment_leases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_custom_image_setup_sessions_started_by_agent_id_agents_id_fk": {"name": "environment_custom_image_setup_sessions_started_by_agent_id_agents_id_fk","tableFrom": "environment_custom_image_setup_sessions",+ "tableTo": "agents","columnsFrom": ["started_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -27284,9 +27306,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_templates_environment_provider_status_idx": {"name": "environment_custom_image_templates_environment_provider_status_idx",@@ -27311,9 +27333,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_templates_environment_active_uq": {"name": "environment_custom_image_templates_environment_active_uq",@@ -27326,10 +27348,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"environment_custom_image_templates\".\"status\" = 'active'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"environment_custom_image_templates_superseded_by_idx": {"name": "environment_custom_image_templates_superseded_by_idx",@@ -27342,9 +27364,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_custom_image_templates_last_used_idx": {"name": "environment_custom_image_templates_last_used_idx",@@ -27357,50 +27379,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"environment_custom_image_templates_environment_id_environments_id_fk": {"name": "environment_custom_image_templates_environment_id_environments_id_fk","tableFrom": "environment_custom_image_templates",+ "tableTo": "environments","columnsFrom": ["environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"environment_custom_image_templates_created_by_agent_id_agents_id_fk": {"name": "environment_custom_image_templates_created_by_agent_id_agents_id_fk","tableFrom": "environment_custom_image_templates",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_custom_image_templates_superseded_by_template_id_environment_custom_image_templates_id_fk": {"name": "environment_custom_image_templates_superseded_by_template_id_environment_custom_image_templates_id_fk","tableFrom": "environment_custom_image_templates",+ "tableTo": "environment_custom_image_templates","columnsFrom": ["superseded_by_template_id"],- "tableTo": "environment_custom_image_templates","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -27536,6 +27558,22 @@}},"indexes": {+ "environment_leases_retained_recovery_adoption_idx": {+ "name": "environment_leases_retained_recovery_adoption_idx",+ "columns": [+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"environment_leases\".\"lease_policy\" = 'retain_on_failure'\n and \"environment_leases\".\"heartbeat_run_id\" is not null\n and not (coalesce(\"environment_leases\".\"metadata\", '{}'::jsonb) ? 'systemRecoveryAdoption')",+ "concurrently": true,+ "method": "btree",+ "with": {}+ },"environment_leases_company_environment_status_idx": {"name": "environment_leases_company_environment_status_idx","columns": [@@ -27559,9 +27597,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_leases_company_execution_workspace_idx": {"name": "environment_leases_company_execution_workspace_idx",@@ -27580,9 +27618,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_leases_company_issue_idx": {"name": "environment_leases_company_issue_idx",@@ -27601,9 +27639,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_leases_heartbeat_run_idx": {"name": "environment_leases_heartbeat_run_idx",@@ -27616,9 +27654,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_leases_company_last_used_idx": {"name": "environment_leases_company_last_used_idx",@@ -27637,9 +27675,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environment_leases_provider_lease_idx": {"name": "environment_leases_provider_lease_idx",@@ -27652,76 +27690,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"environment_leases_company_id_companies_id_fk": {"name": "environment_leases_company_id_companies_id_fk","tableFrom": "environment_leases",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"environment_leases_environment_id_environments_id_fk": {"name": "environment_leases_environment_id_environments_id_fk","tableFrom": "environment_leases",+ "tableTo": "environments","columnsFrom": ["environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_leases_execution_workspace_id_execution_workspaces_id_fk": {"name": "environment_leases_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "environment_leases",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_leases_issue_id_issues_id_fk": {"name": "environment_leases_issue_id_issues_id_fk","tableFrom": "environment_leases",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"environment_leases_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "environment_leases_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "environment_leases",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -27814,9 +27852,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"environments_local_driver_idx": {"name": "environments_local_driver_idx",@@ -27829,10 +27867,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"environments\".\"driver\" = 'local'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"environments_managed_sandbox_idx": {"name": "environments_managed_sandbox_idx",@@ -27845,10 +27883,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"environments\".\"driver\" = 'sandbox' AND (\"environments\".\"metadata\" ->> 'managedByPaperclip')::boolean = true",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"environments_name_idx": {"name": "environments_name_idx",@@ -27861,9 +27899,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -28004,9 +28042,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspace_repositories_path_idx": {"name": "execution_workspace_repositories_path_idx",@@ -28025,9 +28063,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspace_repositories_request_idx": {"name": "execution_workspace_repositories_request_idx",@@ -28046,9 +28084,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspace_repositories_company_workspace_idx": {"name": "execution_workspace_repositories_company_workspace_idx",@@ -28067,50 +28105,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"execution_workspace_repositories_company_id_companies_id_fk": {"name": "execution_workspace_repositories_company_id_companies_id_fk","tableFrom": "execution_workspace_repositories",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk": {"name": "execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "execution_workspace_repositories",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"execution_workspace_repositories_requested_by_issue_id_issues_id_fk": {"name": "execution_workspace_repositories_requested_by_issue_id_issues_id_fk","tableFrom": "execution_workspace_repositories",+ "tableTo": "issues","columnsFrom": ["requested_by_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -28223,24 +28261,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"execution_workspace_repository_access_company_id_companies_id_fk": {"name": "execution_workspace_repository_access_company_id_companies_id_fk","tableFrom": "execution_workspace_repository_access",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -28317,24 +28355,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"execution_workspace_repository_roots_company_id_companies_id_fk": {"name": "execution_workspace_repository_roots_company_id_companies_id_fk","tableFrom": "execution_workspace_repository_roots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -28455,9 +28493,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspace_runtime_leases_company_owner_idx": {"name": "execution_workspace_runtime_leases_company_owner_idx",@@ -28476,9 +28514,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspace_runtime_leases_expires_at_idx": {"name": "execution_workspace_runtime_leases_expires_at_idx",@@ -28491,86 +28529,86 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"execution_workspace_runtime_leases_company_id_companies_id_fk": {"name": "execution_workspace_runtime_leases_company_id_companies_id_fk","tableFrom": "execution_workspace_runtime_leases",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"execution_workspace_runtime_leases_execution_workspace_id_execution_workspaces_id_fk": {"name": "execution_workspace_runtime_leases_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "execution_workspace_runtime_leases",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"execution_workspace_runtime_leases_owner_issue_id_issues_id_fk": {"name": "execution_workspace_runtime_leases_owner_issue_id_issues_id_fk","tableFrom": "execution_workspace_runtime_leases",+ "tableTo": "issues","columnsFrom": ["owner_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"execution_workspace_runtime_leases_owner_run_id_heartbeat_runs_id_fk": {"name": "execution_workspace_runtime_leases_owner_run_id_heartbeat_runs_id_fk","tableFrom": "execution_workspace_runtime_leases",+ "tableTo": "heartbeat_runs","columnsFrom": ["owner_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"execution_workspace_runtime_leases_owner_agent_id_agents_id_fk": {"name": "execution_workspace_runtime_leases_owner_agent_id_agents_id_fk","tableFrom": "execution_workspace_runtime_leases",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"execution_workspace_runtime_leases_execution_workspace_id_unique": {"name": "execution_workspace_runtime_leases_execution_workspace_id_unique",+ "nullsNotDistinct": false,"columns": ["execution_workspace_id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -28757,9 +28795,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspaces_company_project_workspace_status_idx": {"name": "execution_workspaces_company_project_workspace_status_idx",@@ -28784,9 +28822,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspaces_company_source_issue_idx": {"name": "execution_workspaces_company_source_issue_idx",@@ -28805,9 +28843,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspaces_company_last_used_idx": {"name": "execution_workspaces_company_last_used_idx",@@ -28826,9 +28864,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"execution_workspaces_company_branch_idx": {"name": "execution_workspaces_company_branch_idx",@@ -28847,76 +28885,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"execution_workspaces_company_id_companies_id_fk": {"name": "execution_workspaces_company_id_companies_id_fk","tableFrom": "execution_workspaces",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"execution_workspaces_project_id_projects_id_fk": {"name": "execution_workspaces_project_id_projects_id_fk","tableFrom": "execution_workspaces",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"execution_workspaces_project_workspace_id_project_workspaces_id_fk": {"name": "execution_workspaces_project_workspace_id_project_workspaces_id_fk","tableFrom": "execution_workspaces",+ "tableTo": "project_workspaces","columnsFrom": ["project_workspace_id"],- "tableTo": "project_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"execution_workspaces_source_issue_id_issues_id_fk": {"name": "execution_workspaces_source_issue_id_issues_id_fk","tableFrom": "execution_workspaces",+ "tableTo": "issues","columnsFrom": ["source_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"execution_workspaces_derived_from_execution_workspace_id_execution_workspaces_id_fk": {"name": "execution_workspaces_derived_from_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "execution_workspaces",+ "tableTo": "execution_workspaces","columnsFrom": ["derived_from_execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -29066,9 +29104,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_object_mentions_company_object_idx": {"name": "external_object_mentions_company_object_idx",@@ -29087,9 +29125,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_object_mentions_company_provider_idx": {"name": "external_object_mentions_company_provider_idx",@@ -29114,9 +29152,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_object_mentions_company_source_record_uq": {"name": "external_object_mentions_company_source_record_uq",@@ -29165,10 +29203,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"external_object_mentions\".\"source_record_id\" is not null and \"external_object_mentions\".\"canonical_identity_hash\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"external_object_mentions_company_source_null_record_uq": {"name": "external_object_mentions_company_source_null_record_uq",@@ -29211,64 +29249,64 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"external_object_mentions\".\"source_record_id\" is null and \"external_object_mentions\".\"canonical_identity_hash\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"external_object_mentions_company_id_companies_id_fk": {"name": "external_object_mentions_company_id_companies_id_fk","tableFrom": "external_object_mentions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"external_object_mentions_source_issue_id_issues_id_fk": {"name": "external_object_mentions_source_issue_id_issues_id_fk","tableFrom": "external_object_mentions",+ "tableTo": "issues","columnsFrom": ["source_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"external_object_mentions_object_id_external_objects_id_fk": {"name": "external_object_mentions_object_id_external_objects_id_fk","tableFrom": "external_object_mentions",+ "tableTo": "external_objects","columnsFrom": ["object_id"],- "tableTo": "external_objects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"external_object_mentions_created_by_plugin_id_plugins_id_fk": {"name": "external_object_mentions_created_by_plugin_id_plugins_id_fk","tableFrom": "external_object_mentions",+ "tableTo": "plugins","columnsFrom": ["created_by_plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -29500,9 +29538,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_objects_company_provider_status_idx": {"name": "external_objects_company_provider_status_idx",@@ -29527,9 +29565,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_objects_company_refresh_idx": {"name": "external_objects_company_refresh_idx",@@ -29548,9 +29586,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_objects_company_external_id_uq": {"name": "external_objects_company_external_id_uq",@@ -29581,9 +29619,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_objects_company_identity_uq": {"name": "external_objects_company_identity_uq",@@ -29614,37 +29652,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"external_objects_company_id_companies_id_fk": {"name": "external_objects_company_id_companies_id_fk","tableFrom": "external_objects",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"external_objects_plugin_id_plugins_id_fk": {"name": "external_objects_plugin_id_plugins_id_fk","tableFrom": "external_objects",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -29714,15 +29752,15 @@"company_fast_responses_company_id_companies_id_fk": {"name": "company_fast_responses_company_id_companies_id_fk","tableFrom": "company_fast_responses",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -29944,9 +29982,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"fast_response_requests_history_idx": {"name": "fast_response_requests_history_idx",@@ -29965,9 +30003,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"fast_response_requests_work_idx": {"name": "fast_response_requests_work_idx",@@ -29980,38 +30018,38 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"fast_response_requests\".\"status\" in ('pending', 'running')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"fast_response_requests_company_id_companies_id_fk": {"name": "fast_response_requests_company_id_companies_id_fk","tableFrom": "fast_response_requests",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"fast_response_requests_cost_event_id_cost_events_id_fk": {"name": "fast_response_requests_cost_event_id_cost_events_id_fk","tableFrom": "fast_response_requests",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -30206,9 +30244,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_exports_company_created_idx": {"name": "feedback_exports_company_created_idx",@@ -30227,9 +30265,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_exports_company_status_idx": {"name": "feedback_exports_company_status_idx",@@ -30254,9 +30292,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_exports_company_issue_idx": {"name": "feedback_exports_company_issue_idx",@@ -30281,9 +30319,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_exports_company_project_idx": {"name": "feedback_exports_company_project_idx",@@ -30308,9 +30346,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_exports_company_author_idx": {"name": "feedback_exports_company_author_idx",@@ -30335,63 +30373,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"feedback_exports_company_id_companies_id_fk": {"name": "feedback_exports_company_id_companies_id_fk","tableFrom": "feedback_exports",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"feedback_exports_feedback_vote_id_feedback_votes_id_fk": {"name": "feedback_exports_feedback_vote_id_feedback_votes_id_fk","tableFrom": "feedback_exports",+ "tableTo": "feedback_votes","columnsFrom": ["feedback_vote_id"],- "tableTo": "feedback_votes","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"feedback_exports_issue_id_issues_id_fk": {"name": "feedback_exports_issue_id_issues_id_fk","tableFrom": "feedback_exports",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"feedback_exports_project_id_projects_id_fk": {"name": "feedback_exports_project_id_projects_id_fk","tableFrom": "feedback_exports",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -30511,9 +30549,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_votes_issue_target_idx": {"name": "feedback_votes_issue_target_idx",@@ -30538,9 +30576,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_votes_author_idx": {"name": "feedback_votes_author_idx",@@ -30559,9 +30597,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"feedback_votes_company_target_author_idx": {"name": "feedback_votes_company_target_author_idx",@@ -30592,37 +30630,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"feedback_votes_company_id_companies_id_fk": {"name": "feedback_votes_company_id_companies_id_fk","tableFrom": "feedback_votes",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"feedback_votes_issue_id_issues_id_fk": {"name": "feedback_votes_issue_id_issues_id_fk","tableFrom": "feedback_votes",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -30833,9 +30871,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_occurred_idx": {"name": "finance_events_company_occurred_idx",@@ -30854,9 +30892,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_biller_occurred_idx": {"name": "finance_events_company_biller_occurred_idx",@@ -30881,9 +30919,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_kind_occurred_idx": {"name": "finance_events_company_kind_occurred_idx",@@ -30908,9 +30946,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_direction_occurred_idx": {"name": "finance_events_company_direction_occurred_idx",@@ -30935,9 +30973,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_heartbeat_run_idx": {"name": "finance_events_company_heartbeat_run_idx",@@ -30956,9 +30994,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"finance_events_company_cost_event_idx": {"name": "finance_events_company_cost_event_idx",@@ -30977,102 +31015,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"finance_events_company_id_companies_id_fk": {"name": "finance_events_company_id_companies_id_fk","tableFrom": "finance_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"finance_events_agent_id_agents_id_fk": {"name": "finance_events_agent_id_agents_id_fk","tableFrom": "finance_events",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"finance_events_issue_id_issues_id_fk": {"name": "finance_events_issue_id_issues_id_fk","tableFrom": "finance_events",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"finance_events_project_id_projects_id_fk": {"name": "finance_events_project_id_projects_id_fk","tableFrom": "finance_events",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"finance_events_goal_id_goals_id_fk": {"name": "finance_events_goal_id_goals_id_fk","tableFrom": "finance_events",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"finance_events_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "finance_events_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "finance_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"finance_events_cost_event_id_cost_events_id_fk": {"name": "finance_events_cost_event_id_cost_events_id_fk","tableFrom": "finance_events",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -31186,9 +31224,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"folders_company_kind_root_slug_uq": {"name": "folders_company_kind_root_slug_uq",@@ -31213,10 +31251,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"folders\".\"parent_id\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"folders_company_kind_parent_slug_uq": {"name": "folders_company_kind_parent_slug_uq",@@ -31247,10 +31285,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"folders\".\"parent_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"folders_company_kind_system_key_uq": {"name": "folders_company_kind_system_key_uq",@@ -31275,10 +31313,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"folders\".\"system_key\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"folders_company_kind_parent_position_idx": {"name": "folders_company_kind_parent_position_idx",@@ -31315,37 +31353,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"folders_company_id_companies_id_fk": {"name": "folders_company_id_companies_id_fk","tableFrom": "folders",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"folders_parent_id_folders_id_fk": {"name": "folders_parent_id_folders_id_fk","tableFrom": "folders",+ "tableTo": "folders","columnsFrom": ["parent_id"],- "tableTo": "folders","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -31436,50 +31474,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"goals_company_id_companies_id_fk": {"name": "goals_company_id_companies_id_fk","tableFrom": "goals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"goals_parent_id_goals_id_fk": {"name": "goals_parent_id_goals_id_fk","tableFrom": "goals",+ "tableTo": "goals","columnsFrom": ["parent_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"goals_owner_agent_id_agents_id_fk": {"name": "goals_owner_agent_id_agents_id_fk","tableFrom": "goals",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -31641,9 +31679,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"grok_dispatch_company_status_idx": {"name": "grok_dispatch_company_status_idx",@@ -31662,9 +31700,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"grok_dispatch_assignment_kind_idx": {"name": "grok_dispatch_assignment_kind_idx",@@ -31683,76 +31721,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"grok_bot_dispatches_company_id_companies_id_fk": {"name": "grok_bot_dispatches_company_id_companies_id_fk","tableFrom": "grok_bot_dispatches",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_dispatches_routine_id_grok_bot_routines_id_fk": {"name": "grok_bot_dispatches_routine_id_grok_bot_routines_id_fk","tableFrom": "grok_bot_dispatches",+ "tableTo": "grok_bot_routines","columnsFrom": ["routine_id"],- "tableTo": "grok_bot_routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_dispatches_binding_id_dot_agent_bindings_id_fk": {"name": "grok_bot_dispatches_binding_id_dot_agent_bindings_id_fk","tableFrom": "grok_bot_dispatches",+ "tableTo": "dot_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "dot_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_dispatches_grant_id_mcp_oauth_grants_id_fk": {"name": "grok_bot_dispatches_grant_id_mcp_oauth_grants_id_fk","tableFrom": "grok_bot_dispatches",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_dispatches_assignment_id_dot_runner_assignments_id_fk": {"name": "grok_bot_dispatches_assignment_id_dot_runner_assignments_id_fk","tableFrom": "grok_bot_dispatches",+ "tableTo": "dot_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "dot_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -31878,9 +31916,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"grok_routines_company_agent_idx": {"name": "grok_routines_company_agent_idx",@@ -31899,76 +31937,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"grok_bot_routines_company_id_companies_id_fk": {"name": "grok_bot_routines_company_id_companies_id_fk","tableFrom": "grok_bot_routines",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_routines_agent_id_agents_id_fk": {"name": "grok_bot_routines_agent_id_agents_id_fk","tableFrom": "grok_bot_routines",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_routines_binding_id_dot_agent_bindings_id_fk": {"name": "grok_bot_routines_binding_id_dot_agent_bindings_id_fk","tableFrom": "grok_bot_routines",+ "tableTo": "dot_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "dot_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"grok_bot_routines_secret_id_company_secrets_id_fk": {"name": "grok_bot_routines_secret_id_company_secrets_id_fk","tableFrom": "grok_bot_routines",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"grok_bot_routines_verified_grant_id_mcp_oauth_grants_id_fk": {"name": "grok_bot_routines_verified_grant_id_mcp_oauth_grants_id_fk","tableFrom": "grok_bot_routines",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["verified_grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -32103,9 +32141,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_run_events_run_source_event_uq": {"name": "heartbeat_run_events_run_source_event_uq",@@ -32124,10 +32162,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"heartbeat_run_events\".\"source_event_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_run_events_run_source_seq_uq": {"name": "heartbeat_run_events_run_source_seq_uq",@@ -32152,10 +32190,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"heartbeat_run_events\".\"source_instance_id\" is not null and \"heartbeat_run_events\".\"source_seq\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_run_events_company_run_idx": {"name": "heartbeat_run_events_company_run_idx",@@ -32174,9 +32212,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_run_events_company_created_idx": {"name": "heartbeat_run_events_company_created_idx",@@ -32195,50 +32233,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"heartbeat_run_events_company_id_companies_id_fk": {"name": "heartbeat_run_events_company_id_companies_id_fk","tableFrom": "heartbeat_run_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_run_events_run_id_heartbeat_runs_id_fk": {"name": "heartbeat_run_events_run_id_heartbeat_runs_id_fk","tableFrom": "heartbeat_run_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_run_events_agent_id_agents_id_fk": {"name": "heartbeat_run_events_agent_id_agents_id_fk","tableFrom": "heartbeat_run_events",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -32344,9 +32382,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_run_watchdog_decisions_company_run_snooze_idx": {"name": "heartbeat_run_watchdog_decisions_company_run_snooze_idx",@@ -32371,76 +32409,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"heartbeat_run_watchdog_decisions_company_id_companies_id_fk": {"name": "heartbeat_run_watchdog_decisions_company_id_companies_id_fk","tableFrom": "heartbeat_run_watchdog_decisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_run_watchdog_decisions_run_id_heartbeat_runs_id_fk": {"name": "heartbeat_run_watchdog_decisions_run_id_heartbeat_runs_id_fk","tableFrom": "heartbeat_run_watchdog_decisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"heartbeat_run_watchdog_decisions_evaluation_issue_id_issues_id_fk": {"name": "heartbeat_run_watchdog_decisions_evaluation_issue_id_issues_id_fk","tableFrom": "heartbeat_run_watchdog_decisions",+ "tableTo": "issues","columnsFrom": ["evaluation_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"heartbeat_run_watchdog_decisions_created_by_agent_id_agents_id_fk": {"name": "heartbeat_run_watchdog_decisions_created_by_agent_id_agents_id_fk","tableFrom": "heartbeat_run_watchdog_decisions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"heartbeat_run_watchdog_decisions_created_by_run_id_heartbeat_runs_id_fk": {"name": "heartbeat_run_watchdog_decisions_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "heartbeat_run_watchdog_decisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -32939,6 +32977,22 @@}},"indexes": {+ "heartbeat_runs_retained_recovery_adoption_idx": {+ "name": "heartbeat_runs_retained_recovery_adoption_idx",+ "columns": [+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"heartbeat_runs\".\"result_json\"->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'\n and not (coalesce(\"heartbeat_runs\".\"result_json\", '{}'::jsonb) ? 'systemRecoveryAdoption')\n and \"heartbeat_runs\".\"status\" in ('failed', 'interrupted', 'timed_out', 'cancelled', 'succeeded')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"heartbeat_runs_cost_accounting_pending_idx": {"name": "heartbeat_runs_cost_accounting_pending_idx","columns": [@@ -32956,10 +33010,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"heartbeat_runs\".\"cost_accounting_pending\" = true",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_runs_cost_data_quality_idx": {"name": "heartbeat_runs_cost_data_quality_idx",@@ -32972,8 +33026,8 @@},{"expression": "coalesce(\"finished_at\", \"created_at\") desc",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -32984,10 +33038,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"heartbeat_runs\".\"cost_accounting_pending\" = true and \"heartbeat_runs\".\"status\" in ('succeeded','failed','timed_out','cancelled','interrupted')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_runs_execution_status_delivery_idx": {"name": "heartbeat_runs_execution_status_delivery_idx",@@ -33000,10 +33054,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"heartbeat_runs\".\"execution_status_delivery_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_runs_execution_control_deadline_idx": {"name": "heartbeat_runs_execution_control_deadline_idx",@@ -33016,10 +33070,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"heartbeat_runs\".\"execution_control_deadline_at\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_runs_native_replacement_predecessor_uq": {"name": "heartbeat_runs_native_replacement_predecessor_uq",@@ -33038,10 +33092,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"heartbeat_runs\".\"scheduled_retry_reason\" = 'native_safe_replacement'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"heartbeat_runs_company_agent_started_idx": {"name": "heartbeat_runs_company_agent_started_idx",@@ -33066,9 +33120,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_issue_created_idx": {"name": "heartbeat_runs_company_issue_created_idx",@@ -33093,9 +33147,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_responsible_user_idx": {"name": "heartbeat_runs_company_responsible_user_idx",@@ -33120,9 +33174,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_liveness_idx": {"name": "heartbeat_runs_company_liveness_idx",@@ -33147,9 +33201,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_status_last_output_idx": {"name": "heartbeat_runs_company_status_last_output_idx",@@ -33174,9 +33228,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_status_process_started_idx": {"name": "heartbeat_runs_company_status_process_started_idx",@@ -33201,9 +33255,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_created_at_desc_idx": {"name": "heartbeat_runs_company_created_at_desc_idx",@@ -33222,9 +33276,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_ctx_issue_created_idx": {"name": "heartbeat_runs_company_ctx_issue_created_idx",@@ -33237,8 +33291,8 @@},{"expression": "(\"context_snapshot\" ->> 'issueId')",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -33249,9 +33303,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_ctx_task_created_idx": {"name": "heartbeat_runs_company_ctx_task_created_idx",@@ -33264,8 +33318,8 @@},{"expression": "(\"context_snapshot\" ->> 'taskId')",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -33276,9 +33330,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_ctx_taskkey_created_idx": {"name": "heartbeat_runs_company_ctx_taskkey_created_idx",@@ -33291,8 +33345,8 @@},{"expression": "(\"context_snapshot\" ->> 'taskKey')",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -33303,9 +33357,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"heartbeat_runs_company_ctx_paperclip_issue_created_idx": {"name": "heartbeat_runs_company_ctx_paperclip_issue_created_idx",@@ -33318,8 +33372,8 @@},{"expression": "(\"context_snapshot\" -> 'paperclipIssue' ->> 'id')",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -33330,9 +33384,9 @@}],"isUnique": false,- "with": {},+ "concurrently": true,"method": "btree",- "concurrently": true+ "with": {}},"heartbeat_runs_company_origin_issue_idx": {"name": "heartbeat_runs_company_origin_issue_idx",@@ -33345,104 +33399,104 @@},{"expression": "coalesce(\n \"native_issue_id\"::text,\n nullif(\"context_snapshot\"->>'issueId', ''),\n nullif(\"context_snapshot\"->>'taskId', ''),\n nullif(\"context_snapshot\"->>'taskKey', '')\n )",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"}],"isUnique": false,- "with": {},+ "concurrently": true,"method": "btree",- "concurrently": true+ "with": {}}},"foreignKeys": {"heartbeat_runs_company_id_companies_id_fk": {"name": "heartbeat_runs_company_id_companies_id_fk","tableFrom": "heartbeat_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_runs_agent_id_agents_id_fk": {"name": "heartbeat_runs_agent_id_agents_id_fk","tableFrom": "heartbeat_runs",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_runs_issue_id_issues_id_fk": {"name": "heartbeat_runs_issue_id_issues_id_fk","tableFrom": "heartbeat_runs",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk": {"name": "heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk","tableFrom": "heartbeat_runs",+ "tableTo": "agent_wakeup_requests","columnsFrom": ["wakeup_request_id"],- "tableTo": "agent_wakeup_requests","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"heartbeat_runs_retry_of_run_id_heartbeat_runs_id_fk": {"name": "heartbeat_runs_retry_of_run_id_heartbeat_runs_id_fk","tableFrom": "heartbeat_runs",+ "tableTo": "heartbeat_runs","columnsFrom": ["retry_of_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"heartbeat_runs_company_native_issue_id_uq": {"name": "heartbeat_runs_company_native_issue_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","native_issue_id","id"- ],- "nullsNotDistinct": false+ ]},"heartbeat_runs_company_native_issue_contract_id_uq": {"name": "heartbeat_runs_company_native_issue_contract_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","native_issue_id","id","completion_contract_id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -33536,9 +33590,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"inbox_dismissals_company_item_idx": {"name": "inbox_dismissals_company_item_idx",@@ -33557,9 +33611,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"inbox_dismissals_company_user_item_idx": {"name": "inbox_dismissals_company_user_item_idx",@@ -33584,24 +33638,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"inbox_dismissals_company_id_companies_id_fk": {"name": "inbox_dismissals_company_id_companies_id_fk","tableFrom": "inbox_dismissals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -33671,9 +33725,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grant_delegations_grant_agent_uq": {"name": "connection_grant_delegations_grant_agent_uq",@@ -33692,52 +33746,52 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"connection_grant_delegations_company_id_companies_id_fk": {"name": "connection_grant_delegations_company_id_companies_id_fk","tableFrom": "connection_grant_delegations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_grant_delegations_agent_id_agents_id_fk": {"name": "connection_grant_delegations_agent_id_agents_id_fk","tableFrom": "connection_grant_delegations",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_grant_delegations_company_grant_fk": {"name": "connection_grant_delegations_company_grant_fk","tableFrom": "connection_grant_delegations",+ "tableTo": "connection_grants","columnsFrom": ["company_id","grant_id"],- "tableTo": "connection_grants","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -33813,9 +33867,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grant_members_grant_subject_uq": {"name": "connection_grant_members_grant_subject_uq",@@ -33840,39 +33894,39 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"connection_grant_members_company_id_companies_id_fk": {"name": "connection_grant_members_company_id_companies_id_fk","tableFrom": "connection_grant_members",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_grant_members_company_grant_fk": {"name": "connection_grant_members_company_grant_fk","tableFrom": "connection_grant_members",+ "tableTo": "connection_grants","columnsFrom": ["company_id","grant_id"],- "tableTo": "connection_grants","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -34029,9 +34083,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grants_subject_user_idx": {"name": "connection_grants_subject_user_idx",@@ -34050,9 +34104,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grants_subject_agent_idx": {"name": "connection_grants_subject_agent_idx",@@ -34071,9 +34125,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grants_user_uq": {"name": "connection_grants_user_uq",@@ -34092,9 +34146,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grants_agent_uq": {"name": "connection_grants_agent_uq",@@ -34113,9 +34167,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_grants_default_uq": {"name": "connection_grants_default_uq",@@ -34128,90 +34182,90 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"connection_grants\".\"is_default\" = true and \"connection_grants\".\"kind\" = 'organization'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"connection_grants_company_id_companies_id_fk": {"name": "connection_grants_company_id_companies_id_fk","tableFrom": "connection_grants",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_grants_subject_agent_id_agents_id_fk": {"name": "connection_grants_subject_agent_id_agents_id_fk","tableFrom": "connection_grants",+ "tableTo": "agents","columnsFrom": ["subject_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_grants_created_by_agent_id_agents_id_fk": {"name": "connection_grants_created_by_agent_id_agents_id_fk","tableFrom": "connection_grants",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"connection_grants_revoked_by_agent_id_agents_id_fk": {"name": "connection_grants_revoked_by_agent_id_agents_id_fk","tableFrom": "connection_grants",+ "tableTo": "agents","columnsFrom": ["revoked_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"connection_grants_company_connection_fk": {"name": "connection_grants_company_connection_fk","tableFrom": "connection_grants",+ "tableTo": "tool_connections","columnsFrom": ["company_id","connection_id"],- "tableTo": "tool_connections","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"connection_grants_company_id_uq": {"name": "connection_grants_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -34381,9 +34435,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_token_issuances_connection_created_idx": {"name": "connection_token_issuances_connection_created_idx",@@ -34408,9 +34462,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_token_issuances_agent_connection_idx": {"name": "connection_token_issuances_agent_connection_idx",@@ -34441,9 +34495,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"connection_token_issuances_run_idx": {"name": "connection_token_issuances_run_idx",@@ -34462,102 +34516,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"connection_token_issuances_company_id_companies_id_fk": {"name": "connection_token_issuances_company_id_companies_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_token_issuances_application_id_tool_applications_id_fk": {"name": "connection_token_issuances_application_id_tool_applications_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"connection_token_issuances_connection_id_tool_connections_id_fk": {"name": "connection_token_issuances_connection_id_tool_connections_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_token_issuances_agent_id_agents_id_fk": {"name": "connection_token_issuances_agent_id_agents_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"connection_token_issuances_run_id_heartbeat_runs_id_fk": {"name": "connection_token_issuances_run_id_heartbeat_runs_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"connection_token_issuances_issue_id_issues_id_fk": {"name": "connection_token_issuances_issue_id_issues_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"connection_token_issuances_project_id_projects_id_fk": {"name": "connection_token_issuances_project_id_projects_id_fk","tableFrom": "connection_token_issuances",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -34631,24 +34685,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"instance_settings_default_environment_id_environments_id_fk": {"name": "instance_settings_default_environment_id_environments_id_fk","tableFrom": "instance_settings",+ "tableTo": "environments","columnsFrom": ["default_environment_id"],- "tableTo": "environments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -34714,9 +34768,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"instance_user_roles_role_idx": {"name": "instance_user_roles_role_idx",@@ -34729,9 +34783,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -34835,9 +34889,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"invites_company_invite_state_idx": {"name": "invites_company_invite_state_idx",@@ -34868,24 +34922,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"invites_company_id_companies_id_fk": {"name": "invites_company_id_companies_id_fk","tableFrom": "invites",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -34985,9 +35039,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_access_grants_issue_idx": {"name": "issue_access_grants_issue_idx",@@ -35006,37 +35060,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_access_grants_issue_id_issues_id_fk": {"name": "issue_access_grants_issue_id_issues_id_fk","tableFrom": "issue_access_grants",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_access_grants_granted_by_agent_id_agents_id_fk": {"name": "issue_access_grants_granted_by_agent_id_agents_id_fk","tableFrom": "issue_access_grants",+ "tableTo": "agents","columnsFrom": ["granted_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -35108,9 +35162,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_approvals_approval_idx": {"name": "issue_approvals_approval_idx",@@ -35123,9 +35177,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_approvals_company_idx": {"name": "issue_approvals_company_idx",@@ -35138,63 +35192,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_approvals_company_id_companies_id_fk": {"name": "issue_approvals_company_id_companies_id_fk","tableFrom": "issue_approvals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_approvals_issue_id_issues_id_fk": {"name": "issue_approvals_issue_id_issues_id_fk","tableFrom": "issue_approvals",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_approvals_approval_id_approvals_id_fk": {"name": "issue_approvals_approval_id_approvals_id_fk","tableFrom": "issue_approvals",+ "tableTo": "approvals","columnsFrom": ["approval_id"],- "tableTo": "approvals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_approvals_linked_by_agent_id_agents_id_fk": {"name": "issue_approvals_linked_by_agent_id_agents_id_fk","tableFrom": "issue_approvals",+ "tableTo": "agents","columnsFrom": ["linked_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {@@ -35285,9 +35339,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_attachments_issue_comment_idx": {"name": "issue_attachments_issue_comment_idx",@@ -35300,9 +35354,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_attachments_originating_run_idx": {"name": "issue_attachments_originating_run_idx",@@ -35315,9 +35369,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_attachments_asset_uq": {"name": "issue_attachments_asset_uq",@@ -35330,76 +35384,76 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_attachments_company_id_companies_id_fk": {"name": "issue_attachments_company_id_companies_id_fk","tableFrom": "issue_attachments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_attachments_issue_id_issues_id_fk": {"name": "issue_attachments_issue_id_issues_id_fk","tableFrom": "issue_attachments",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_attachments_asset_id_assets_id_fk": {"name": "issue_attachments_asset_id_assets_id_fk","tableFrom": "issue_attachments",+ "tableTo": "assets","columnsFrom": ["asset_id"],- "tableTo": "assets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_attachments_issue_comment_id_issue_comments_id_fk": {"name": "issue_attachments_issue_comment_id_issue_comments_id_fk","tableFrom": "issue_attachments",+ "tableTo": "issue_comments","columnsFrom": ["issue_comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_attachments_originating_run_id_heartbeat_runs_id_fk": {"name": "issue_attachments_originating_run_id_heartbeat_runs_id_fk","tableFrom": "issue_attachments",+ "tableTo": "heartbeat_runs","columnsFrom": ["originating_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -35585,9 +35639,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_comments_company_idx": {"name": "issue_comments_company_idx",@@ -35600,9 +35654,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_comments_company_issue_created_at_idx": {"name": "issue_comments_company_issue_created_at_idx",@@ -35627,9 +35681,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_comments_company_author_issue_created_at_idx": {"name": "issue_comments_company_author_issue_created_at_idx",@@ -35660,9 +35714,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_comments_body_search_idx": {"name": "issue_comments_body_search_idx",@@ -35676,148 +35730,148 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_comments_company_id_companies_id_fk": {"name": "issue_comments_company_id_companies_id_fk","tableFrom": "issue_comments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_comments_issue_id_issues_id_fk": {"name": "issue_comments_issue_id_issues_id_fk","tableFrom": "issue_comments",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_comments_author_agent_id_agents_id_fk": {"name": "issue_comments_author_agent_id_agents_id_fk","tableFrom": "issue_comments",+ "tableTo": "agents","columnsFrom": ["author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_comments_on_behalf_of_user_id_user_id_fk": {"name": "issue_comments_on_behalf_of_user_id_user_id_fk","tableFrom": "issue_comments",+ "tableTo": "user","columnsFrom": ["on_behalf_of_user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_comments_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_comments_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_comments",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_comments_derived_author_agent_id_agents_id_fk": {"name": "issue_comments_derived_author_agent_id_agents_id_fk","tableFrom": "issue_comments",+ "tableTo": "agents","columnsFrom": ["derived_author_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_comments_derived_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_comments_derived_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_comments",+ "tableTo": "heartbeat_runs","columnsFrom": ["derived_created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_comments_deleted_by_agent_id_agents_id_fk": {"name": "issue_comments_deleted_by_agent_id_agents_id_fk","tableFrom": "issue_comments",+ "tableTo": "agents","columnsFrom": ["deleted_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_comments_deleted_by_run_id_heartbeat_runs_id_fk": {"name": "issue_comments_deleted_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_comments",+ "tableTo": "heartbeat_runs","columnsFrom": ["deleted_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"issue_comments_client_request_uq": {"name": "issue_comments_client_request_uq",+ "nullsNotDistinct": false,"columns": ["issue_id","author_user_id","client_request_id"- ],- "nullsNotDistinct": false+ ]},"issue_comments_company_id_uq": {"name": "issue_comments_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -35879,9 +35933,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_create_idempotency_keys_issue_idx": {"name": "issue_create_idempotency_keys_issue_idx",@@ -35894,9 +35948,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_create_idempotency_keys_company_created_at_idx": {"name": "issue_create_idempotency_keys_company_created_at_idx",@@ -35915,37 +35969,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_create_idempotency_keys_company_id_companies_id_fk": {"name": "issue_create_idempotency_keys_company_id_companies_id_fk","tableFrom": "issue_create_idempotency_keys",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_create_idempotency_keys_issue_id_issues_id_fk": {"name": "issue_create_idempotency_keys_issue_id_issues_id_fk","tableFrom": "issue_create_idempotency_keys",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -36028,9 +36082,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_documents_document_uq": {"name": "issue_documents_document_uq",@@ -36043,9 +36097,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_documents_company_issue_updated_idx": {"name": "issue_documents_company_issue_updated_idx",@@ -36070,50 +36124,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_documents_company_id_companies_id_fk": {"name": "issue_documents_company_id_companies_id_fk","tableFrom": "issue_documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_documents_issue_id_issues_id_fk": {"name": "issue_documents_issue_id_issues_id_fk","tableFrom": "issue_documents",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_documents_document_id_documents_id_fk": {"name": "issue_documents_document_id_documents_id_fk","tableFrom": "issue_documents",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -36220,9 +36274,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_execution_decisions_stage_idx": {"name": "issue_execution_decisions_stage_idx",@@ -36247,63 +36301,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_execution_decisions_company_id_companies_id_fk": {"name": "issue_execution_decisions_company_id_companies_id_fk","tableFrom": "issue_execution_decisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_execution_decisions_issue_id_issues_id_fk": {"name": "issue_execution_decisions_issue_id_issues_id_fk","tableFrom": "issue_execution_decisions",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_execution_decisions_actor_agent_id_agents_id_fk": {"name": "issue_execution_decisions_actor_agent_id_agents_id_fk","tableFrom": "issue_execution_decisions",+ "tableTo": "agents","columnsFrom": ["actor_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_execution_decisions_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_execution_decisions_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_execution_decisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -36400,9 +36454,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_inbox_archives_company_user_idx": {"name": "issue_inbox_archives_company_user_idx",@@ -36421,9 +36475,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_inbox_archives_company_issue_user_idx": {"name": "issue_inbox_archives_company_issue_user_idx",@@ -36448,63 +36502,63 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_inbox_archives_company_id_companies_id_fk": {"name": "issue_inbox_archives_company_id_companies_id_fk","tableFrom": "issue_inbox_archives",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_inbox_archives_issue_id_issues_id_fk": {"name": "issue_inbox_archives_issue_id_issues_id_fk","tableFrom": "issue_inbox_archives",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_inbox_archives_archived_by_agent_id_agents_id_fk": {"name": "issue_inbox_archives_archived_by_agent_id_agents_id_fk","tableFrom": "issue_inbox_archives",+ "tableTo": "agents","columnsFrom": ["archived_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_inbox_archives_archived_by_run_id_heartbeat_runs_id_fk": {"name": "issue_inbox_archives_archived_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_inbox_archives",+ "tableTo": "heartbeat_runs","columnsFrom": ["archived_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -36560,9 +36614,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_labels_label_idx": {"name": "issue_labels_label_idx",@@ -36575,9 +36629,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_labels_company_idx": {"name": "issue_labels_company_idx",@@ -36590,50 +36644,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_labels_issue_id_issues_id_fk": {"name": "issue_labels_issue_id_issues_id_fk","tableFrom": "issue_labels",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_labels_label_id_labels_id_fk": {"name": "issue_labels_label_id_labels_id_fk","tableFrom": "issue_labels",+ "tableTo": "labels","columnsFrom": ["label_id"],- "tableTo": "labels","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_labels_company_id_companies_id_fk": {"name": "issue_labels_company_id_companies_id_fk","tableFrom": "issue_labels",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {@@ -36782,9 +36836,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_plan_decompositions_active_owner_idx": {"name": "issue_plan_decompositions_active_owner_idx",@@ -36803,10 +36857,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"issue_plan_decompositions\".\"status\" = 'in_flight'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issue_plan_decompositions_source_revision_uq": {"name": "issue_plan_decompositions_source_revision_uq",@@ -36831,89 +36885,89 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_plan_decompositions_company_id_companies_id_fk": {"name": "issue_plan_decompositions_company_id_companies_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_plan_decompositions_source_issue_id_issues_id_fk": {"name": "issue_plan_decompositions_source_issue_id_issues_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "issues","columnsFrom": ["source_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_plan_decompositions_accepted_plan_revision_id_document_revisions_id_fk": {"name": "issue_plan_decompositions_accepted_plan_revision_id_document_revisions_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "document_revisions","columnsFrom": ["accepted_plan_revision_id"],- "tableTo": "document_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_plan_decompositions_accepted_interaction_id_issue_thread_interactions_id_fk": {"name": "issue_plan_decompositions_accepted_interaction_id_issue_thread_interactions_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "issue_thread_interactions","columnsFrom": ["accepted_interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_plan_decompositions_owner_agent_id_agents_id_fk": {"name": "issue_plan_decompositions_owner_agent_id_agents_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_plan_decompositions_owner_run_id_heartbeat_runs_id_fk": {"name": "issue_plan_decompositions_owner_run_id_heartbeat_runs_id_fk","tableFrom": "issue_plan_decompositions",+ "tableTo": "heartbeat_runs","columnsFrom": ["owner_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -37053,9 +37107,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_question_response_deliveries_correlation_uq": {"name": "issue_question_response_deliveries_correlation_uq",@@ -37068,9 +37122,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_question_response_deliveries_pending_idx": {"name": "issue_question_response_deliveries_pending_idx",@@ -37089,9 +37143,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_question_response_deliveries_company_issue_idx": {"name": "issue_question_response_deliveries_company_issue_idx",@@ -37116,76 +37170,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_question_response_deliveries_company_id_companies_id_fk": {"name": "issue_question_response_deliveries_company_id_companies_id_fk","tableFrom": "issue_question_response_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_question_response_deliveries_issue_id_issues_id_fk": {"name": "issue_question_response_deliveries_issue_id_issues_id_fk","tableFrom": "issue_question_response_deliveries",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_question_response_deliveries_interaction_id_issue_thread_interactions_id_fk": {"name": "issue_question_response_deliveries_interaction_id_issue_thread_interactions_id_fk","tableFrom": "issue_question_response_deliveries",+ "tableTo": "issue_thread_interactions","columnsFrom": ["interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_question_response_deliveries_source_run_id_heartbeat_runs_id_fk": {"name": "issue_question_response_deliveries_source_run_id_heartbeat_runs_id_fk","tableFrom": "issue_question_response_deliveries",+ "tableTo": "heartbeat_runs","columnsFrom": ["source_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_question_response_deliveries_target_run_id_heartbeat_runs_id_fk": {"name": "issue_question_response_deliveries_target_run_id_heartbeat_runs_id_fk","tableFrom": "issue_question_response_deliveries",+ "tableTo": "heartbeat_runs","columnsFrom": ["target_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -37272,9 +37326,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_read_states_company_user_idx": {"name": "issue_read_states_company_user_idx",@@ -37293,9 +37347,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_read_states_company_issue_user_idx": {"name": "issue_read_states_company_issue_user_idx",@@ -37320,37 +37374,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_read_states_company_id_companies_id_fk": {"name": "issue_read_states_company_id_companies_id_fk","tableFrom": "issue_read_states",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_read_states_issue_id_issues_id_fk": {"name": "issue_read_states_issue_id_issues_id_fk","tableFrom": "issue_read_states",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -37528,6 +37582,71 @@}},"indexes": {+ "issue_recovery_actions_source_run_idx": {+ "name": "issue_recovery_actions_source_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"evidence\"->>'runId')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_system_recovery_due_idx": {+ "name": "issue_recovery_actions_system_recovery_due_idx",+ "columns": [+ {+ "expression": "(\"evidence\"#>'{systemRecovery,nextAttemptAt}')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue_recovery_actions\".\"evidence\" ? 'systemRecovery'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_system_recovery_adoption_idx": {+ "name": "issue_recovery_actions_system_recovery_adoption_idx",+ "columns": [+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "not (\"issue_recovery_actions\".\"evidence\" ? 'systemRecovery') and (\n \"issue_recovery_actions\".\"evidence\"->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'\n or \"issue_recovery_actions\".\"cause\" in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted')\n )",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"issue_recovery_actions_retained_workspace_recovery_idx": {"name": "issue_recovery_actions_retained_workspace_recovery_idx","columns": [@@ -37539,10 +37658,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\n (\"issue_recovery_actions\".\"evidence\"->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'\n or \"issue_recovery_actions\".\"cause\" in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted'))\n and (\"issue_recovery_actions\".\"evidence\"->'executionReconciliation' is null\n or \"issue_recovery_actions\".\"evidence\"#>>'{workspaceRecovery,status}' = 'recovered')\n ",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issue_recovery_actions_company_source_status_idx": {"name": "issue_recovery_actions_company_source_status_idx",@@ -37567,9 +37686,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_recovery_actions_company_owner_status_idx": {"name": "issue_recovery_actions_company_owner_status_idx",@@ -37594,9 +37713,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_recovery_actions_company_recovery_issue_idx": {"name": "issue_recovery_actions_company_recovery_issue_idx",@@ -37615,9 +37734,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_recovery_actions_active_source_uq": {"name": "issue_recovery_actions_active_source_uq",@@ -37636,10 +37755,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_recovery_actions\".\"status\" in ('active', 'escalated')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issue_recovery_actions_active_fingerprint_uq": {"name": "issue_recovery_actions_active_fingerprint_uq",@@ -37670,90 +37789,90 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_recovery_actions\".\"status\" in ('active', 'escalated')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"issue_recovery_actions_company_id_companies_id_fk": {"name": "issue_recovery_actions_company_id_companies_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_recovery_actions_source_issue_id_issues_id_fk": {"name": "issue_recovery_actions_source_issue_id_issues_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "issues","columnsFrom": ["source_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_recovery_actions_recovery_issue_id_issues_id_fk": {"name": "issue_recovery_actions_recovery_issue_id_issues_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "issues","columnsFrom": ["recovery_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_recovery_actions_owner_agent_id_agents_id_fk": {"name": "issue_recovery_actions_owner_agent_id_agents_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_recovery_actions_previous_owner_agent_id_agents_id_fk": {"name": "issue_recovery_actions_previous_owner_agent_id_agents_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "agents","columnsFrom": ["previous_owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_recovery_actions_return_owner_agent_id_agents_id_fk": {"name": "issue_recovery_actions_return_owner_agent_id_agents_id_fk","tableFrom": "issue_recovery_actions",+ "tableTo": "agents","columnsFrom": ["return_owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -37848,9 +37967,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_reference_mentions_company_target_issue_idx": {"name": "issue_reference_mentions_company_target_issue_idx",@@ -37869,9 +37988,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_reference_mentions_company_issue_pair_idx": {"name": "issue_reference_mentions_company_issue_pair_idx",@@ -37896,9 +38015,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_reference_mentions_company_source_mention_record_uq": {"name": "issue_reference_mentions_company_source_mention_record_uq",@@ -37935,10 +38054,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_reference_mentions\".\"source_record_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issue_reference_mentions_company_source_mention_null_record_uq": {"name": "issue_reference_mentions_company_source_mention_null_record_uq",@@ -37969,51 +38088,51 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_reference_mentions\".\"source_record_id\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"issue_reference_mentions_company_id_companies_id_fk": {"name": "issue_reference_mentions_company_id_companies_id_fk","tableFrom": "issue_reference_mentions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_reference_mentions_source_issue_id_issues_id_fk": {"name": "issue_reference_mentions_source_issue_id_issues_id_fk","tableFrom": "issue_reference_mentions",+ "tableTo": "issues","columnsFrom": ["source_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_reference_mentions_target_issue_id_issues_id_fk": {"name": "issue_reference_mentions_target_issue_id_issues_id_fk","tableFrom": "issue_reference_mentions",+ "tableTo": "issues","columnsFrom": ["target_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -38102,9 +38221,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_relations_company_related_issue_idx": {"name": "issue_relations_company_related_issue_idx",@@ -38123,9 +38242,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_relations_company_type_idx": {"name": "issue_relations_company_type_idx",@@ -38144,9 +38263,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_relations_company_edge_uq": {"name": "issue_relations_company_edge_uq",@@ -38177,63 +38296,63 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_relations_company_id_companies_id_fk": {"name": "issue_relations_company_id_companies_id_fk","tableFrom": "issue_relations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_relations_issue_id_issues_id_fk": {"name": "issue_relations_issue_id_issues_id_fk","tableFrom": "issue_relations",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_relations_related_issue_id_issues_id_fk": {"name": "issue_relations_related_issue_id_issues_id_fk","tableFrom": "issue_relations",+ "tableTo": "issues","columnsFrom": ["related_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_relations_created_by_agent_id_agents_id_fk": {"name": "issue_relations_created_by_agent_id_agents_id_fk","tableFrom": "issue_relations",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -38443,9 +38562,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_thread_interactions_company_issue_created_at_idx": {"name": "issue_thread_interactions_company_issue_created_at_idx",@@ -38470,9 +38589,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_thread_interactions_company_issue_status_idx": {"name": "issue_thread_interactions_company_issue_status_idx",@@ -38497,9 +38616,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_thread_interactions_company_issue_idempotency_uq": {"name": "issue_thread_interactions_company_issue_idempotency_uq",@@ -38524,10 +38643,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_thread_interactions\".\"idempotency_key\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issue_thread_interactions_source_comment_idx": {"name": "issue_thread_interactions_source_comment_idx",@@ -38540,9 +38659,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_thread_interactions_addressee_agent_idx": {"name": "issue_thread_interactions_addressee_agent_idx",@@ -38555,9 +38674,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_thread_interactions_addressee_user_idx": {"name": "issue_thread_interactions_addressee_user_idx",@@ -38570,115 +38689,115 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_thread_interactions_company_id_companies_id_fk": {"name": "issue_thread_interactions_company_id_companies_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_thread_interactions_issue_id_issues_id_fk": {"name": "issue_thread_interactions_issue_id_issues_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_thread_interactions_source_comment_id_issue_comments_id_fk": {"name": "issue_thread_interactions_source_comment_id_issue_comments_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "issue_comments","columnsFrom": ["source_comment_id"],- "tableTo": "issue_comments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_thread_interactions_source_run_id_heartbeat_runs_id_fk": {"name": "issue_thread_interactions_source_run_id_heartbeat_runs_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "heartbeat_runs","columnsFrom": ["source_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_thread_interactions_created_by_agent_id_agents_id_fk": {"name": "issue_thread_interactions_created_by_agent_id_agents_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_thread_interactions_addressee_agent_id_agents_id_fk": {"name": "issue_thread_interactions_addressee_agent_id_agents_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "agents","columnsFrom": ["addressee_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_thread_interactions_resolved_by_agent_id_agents_id_fk": {"name": "issue_thread_interactions_resolved_by_agent_id_agents_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "agents","columnsFrom": ["resolved_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_thread_interactions_resolved_by_run_id_heartbeat_runs_id_fk": {"name": "issue_thread_interactions_resolved_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_thread_interactions",+ "tableTo": "heartbeat_runs","columnsFrom": ["resolved_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -38810,9 +38929,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_tree_hold_members_company_issue_idx": {"name": "issue_tree_hold_members_company_issue_idx",@@ -38831,9 +38950,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_tree_hold_members_hold_depth_idx": {"name": "issue_tree_hold_members_hold_depth_idx",@@ -38852,89 +38971,89 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_tree_hold_members_company_id_companies_id_fk": {"name": "issue_tree_hold_members_company_id_companies_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_tree_hold_members_hold_id_issue_tree_holds_id_fk": {"name": "issue_tree_hold_members_hold_id_issue_tree_holds_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "issue_tree_holds","columnsFrom": ["hold_id"],- "tableTo": "issue_tree_holds","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_tree_hold_members_issue_id_issues_id_fk": {"name": "issue_tree_hold_members_issue_id_issues_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_tree_hold_members_parent_issue_id_issues_id_fk": {"name": "issue_tree_hold_members_parent_issue_id_issues_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "issues","columnsFrom": ["parent_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_tree_hold_members_assignee_agent_id_agents_id_fk": {"name": "issue_tree_hold_members_assignee_agent_id_agents_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "agents","columnsFrom": ["assignee_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_tree_hold_members_active_run_id_heartbeat_runs_id_fk": {"name": "issue_tree_hold_members_active_run_id_heartbeat_runs_id_fk","tableFrom": "issue_tree_hold_members",+ "tableTo": "heartbeat_runs","columnsFrom": ["active_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -39097,9 +39216,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_tree_holds_company_status_mode_idx": {"name": "issue_tree_holds_company_status_mode_idx",@@ -39124,89 +39243,89 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_tree_holds_company_id_companies_id_fk": {"name": "issue_tree_holds_company_id_companies_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_tree_holds_root_issue_id_issues_id_fk": {"name": "issue_tree_holds_root_issue_id_issues_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "issues","columnsFrom": ["root_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_tree_holds_created_by_agent_id_agents_id_fk": {"name": "issue_tree_holds_created_by_agent_id_agents_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_tree_holds_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_tree_holds_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_tree_holds_released_by_agent_id_agents_id_fk": {"name": "issue_tree_holds_released_by_agent_id_agents_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "agents","columnsFrom": ["released_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_tree_holds_released_by_run_id_heartbeat_runs_id_fk": {"name": "issue_tree_holds_released_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_tree_holds",+ "tableTo": "heartbeat_runs","columnsFrom": ["released_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -39375,9 +39494,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_watchdogs_company_status_idx": {"name": "issue_watchdogs_company_status_idx",@@ -39396,9 +39515,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_watchdogs_company_agent_idx": {"name": "issue_watchdogs_company_agent_idx",@@ -39417,9 +39536,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_watchdogs_company_watchdog_issue_uq": {"name": "issue_watchdogs_company_watchdog_issue_uq",@@ -39438,116 +39557,116 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issue_watchdogs\".\"watchdog_issue_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"issue_watchdogs_company_id_companies_id_fk": {"name": "issue_watchdogs_company_id_companies_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_watchdogs_issue_id_issues_id_fk": {"name": "issue_watchdogs_issue_id_issues_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_watchdogs_watchdog_agent_id_agents_id_fk": {"name": "issue_watchdogs_watchdog_agent_id_agents_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "agents","columnsFrom": ["watchdog_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_watchdogs_watchdog_issue_id_issues_id_fk": {"name": "issue_watchdogs_watchdog_issue_id_issues_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "issues","columnsFrom": ["watchdog_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_watchdogs_created_by_agent_id_agents_id_fk": {"name": "issue_watchdogs_created_by_agent_id_agents_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_watchdogs_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_watchdogs_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_watchdogs_updated_by_agent_id_agents_id_fk": {"name": "issue_watchdogs_updated_by_agent_id_agents_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_watchdogs_updated_by_run_id_heartbeat_runs_id_fk": {"name": "issue_watchdogs_updated_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_watchdogs",+ "tableTo": "heartbeat_runs","columnsFrom": ["updated_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -39717,9 +39836,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_work_products_company_execution_workspace_type_idx": {"name": "issue_work_products_company_execution_workspace_type_idx",@@ -39744,9 +39863,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_work_products_company_provider_external_id_idx": {"name": "issue_work_products_company_provider_external_id_idx",@@ -39771,9 +39890,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issue_work_products_company_updated_idx": {"name": "issue_work_products_company_updated_idx",@@ -39792,89 +39911,89 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"issue_work_products_company_id_companies_id_fk": {"name": "issue_work_products_company_id_companies_id_fk","tableFrom": "issue_work_products",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issue_work_products_project_id_projects_id_fk": {"name": "issue_work_products_project_id_projects_id_fk","tableFrom": "issue_work_products",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_work_products_issue_id_issues_id_fk": {"name": "issue_work_products_issue_id_issues_id_fk","tableFrom": "issue_work_products",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"issue_work_products_execution_workspace_id_execution_workspaces_id_fk": {"name": "issue_work_products_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "issue_work_products",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_work_products_runtime_service_id_workspace_runtime_services_id_fk": {"name": "issue_work_products_runtime_service_id_workspace_runtime_services_id_fk","tableFrom": "issue_work_products",+ "tableTo": "workspace_runtime_services","columnsFrom": ["runtime_service_id"],- "tableTo": "workspace_runtime_services","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issue_work_products_created_by_run_id_heartbeat_runs_id_fk": {"name": "issue_work_products_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "issue_work_products",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -40335,9 +40454,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_status_idx": {"name": "issues_company_status_idx",@@ -40356,9 +40475,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_harness_kind_idx": {"name": "issues_company_harness_kind_idx",@@ -40377,9 +40496,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_assignee_status_idx": {"name": "issues_company_assignee_status_idx",@@ -40404,9 +40523,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_assignee_user_status_idx": {"name": "issues_company_assignee_user_status_idx",@@ -40431,9 +40550,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_responsible_user_idx": {"name": "issues_company_responsible_user_idx",@@ -40452,9 +40571,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_parent_idx": {"name": "issues_company_parent_idx",@@ -40473,9 +40592,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_privacy_parent_idx": {"name": "issues_company_privacy_parent_idx",@@ -40494,9 +40613,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_privacy_root_idx": {"name": "issues_company_privacy_root_idx",@@ -40515,9 +40634,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_project_idx": {"name": "issues_company_project_idx",@@ -40536,9 +40655,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_origin_idx": {"name": "issues_company_origin_idx",@@ -40563,9 +40682,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_project_workspace_idx": {"name": "issues_company_project_workspace_idx",@@ -40584,9 +40703,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_execution_workspace_idx": {"name": "issues_company_execution_workspace_idx",@@ -40605,9 +40724,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_monitor_due_idx": {"name": "issues_company_monitor_due_idx",@@ -40626,9 +40745,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_updated_idx": {"name": "issues_company_updated_idx",@@ -40647,9 +40766,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_company_created_idx": {"name": "issues_company_created_idx",@@ -40668,9 +40787,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_open_normalized_title_created_idx": {"name": "issues_open_normalized_title_created_idx",@@ -40689,8 +40808,8 @@},{"expression": "lower(regexp_replace(btrim(\"title\"), '\\s+', ' ', 'g'))",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"},{@@ -40701,10 +40820,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"issues\".\"hidden_at\" is null and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_company_priority_idx": {"name": "issues_company_priority_idx",@@ -40723,9 +40842,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_identifier_idx": {"name": "issues_identifier_idx",@@ -40738,9 +40857,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"issues_title_search_idx": {"name": "issues_title_search_idx",@@ -40754,9 +40873,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"issues_identifier_search_idx": {"name": "issues_identifier_search_idx",@@ -40770,9 +40889,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"issues_description_search_idx": {"name": "issues_description_search_idx",@@ -40786,9 +40905,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}},"issues_open_routine_execution_uq": {"name": "issues_open_routine_execution_uq",@@ -40819,10 +40938,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'routine_execution'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"execution_run_id\" is not null\n and \"issues\".\"status\" in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_liveness_recovery_incident_uq": {"name": "issues_active_liveness_recovery_incident_uq",@@ -40847,10 +40966,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'harness_liveness_escalation'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_liveness_recovery_leaf_uq": {"name": "issues_active_liveness_recovery_leaf_uq",@@ -40875,10 +40994,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'harness_liveness_escalation'\n and \"issues\".\"origin_fingerprint\" <> 'default'\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_stale_run_evaluation_uq": {"name": "issues_active_stale_run_evaluation_uq",@@ -40903,10 +41022,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'stale_active_run_evaluation'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_task_watchdog_uq": {"name": "issues_active_task_watchdog_uq",@@ -40931,10 +41050,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'task_watchdog'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_productivity_review_uq": {"name": "issues_active_productivity_review_uq",@@ -40959,10 +41078,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'issue_productivity_review'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_active_stranded_issue_recovery_uq": {"name": "issues_active_stranded_issue_recovery_uq",@@ -40987,10 +41106,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'stranded_issue_recovery'\n and \"issues\".\"origin_id\" is not null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"status\" not in ('done', 'cancelled')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"issues_onboarding_first_task_uq": {"name": "issues_onboarding_first_task_uq",@@ -41003,192 +41122,192 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"issues\".\"origin_kind\" = 'onboarding_first_task'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"issues_company_id_companies_id_fk": {"name": "issues_company_id_companies_id_fk","tableFrom": "issues",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_conversation_agent_id_agents_id_fk": {"name": "issues_conversation_agent_id_agents_id_fk","tableFrom": "issues",+ "tableTo": "agents","columnsFrom": ["conversation_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_project_id_projects_id_fk": {"name": "issues_project_id_projects_id_fk","tableFrom": "issues",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_project_workspace_id_project_workspaces_id_fk": {"name": "issues_project_workspace_id_project_workspaces_id_fk","tableFrom": "issues",+ "tableTo": "project_workspaces","columnsFrom": ["project_workspace_id"],- "tableTo": "project_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issues_goal_id_goals_id_fk": {"name": "issues_goal_id_goals_id_fk","tableFrom": "issues",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_parent_id_issues_id_fk": {"name": "issues_parent_id_issues_id_fk","tableFrom": "issues",+ "tableTo": "issues","columnsFrom": ["parent_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_privacy_root_issue_id_issues_id_fk": {"name": "issues_privacy_root_issue_id_issues_id_fk","tableFrom": "issues",+ "tableTo": "issues","columnsFrom": ["privacy_root_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_privacy_parent_issue_id_issues_id_fk": {"name": "issues_privacy_parent_issue_id_issues_id_fk","tableFrom": "issues",+ "tableTo": "issues","columnsFrom": ["privacy_parent_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issues_assignee_agent_id_agents_id_fk": {"name": "issues_assignee_agent_id_agents_id_fk","tableFrom": "issues",+ "tableTo": "agents","columnsFrom": ["assignee_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_checkout_run_id_heartbeat_runs_id_fk": {"name": "issues_checkout_run_id_heartbeat_runs_id_fk","tableFrom": "issues",+ "tableTo": "heartbeat_runs","columnsFrom": ["checkout_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issues_execution_run_id_heartbeat_runs_id_fk": {"name": "issues_execution_run_id_heartbeat_runs_id_fk","tableFrom": "issues",+ "tableTo": "heartbeat_runs","columnsFrom": ["execution_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"issues_created_by_agent_id_agents_id_fk": {"name": "issues_created_by_agent_id_agents_id_fk","tableFrom": "issues",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"issues_execution_workspace_id_execution_workspaces_id_fk": {"name": "issues_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "issues",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"issues_company_id_uq": {"name": "issues_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -41357,9 +41476,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"join_requests_company_status_type_created_idx": {"name": "join_requests_company_status_type_created_idx",@@ -41390,9 +41509,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"join_requests_pending_human_user_uq": {"name": "join_requests_pending_human_user_uq",@@ -41411,10 +41530,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"requesting_user_id\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"join_requests_pending_human_email_uq": {"name": "join_requests_pending_human_email_uq",@@ -41427,57 +41546,57 @@},{"expression": "lower(\"request_email_snapshot\")",- "isExpression": true,"asc": true,+ "isExpression": true,"nulls": "last"}],"isUnique": true,- "with": {},- "method": "btree","where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"request_email_snapshot\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"join_requests_invite_id_invites_id_fk": {"name": "join_requests_invite_id_invites_id_fk","tableFrom": "join_requests",+ "tableTo": "invites","columnsFrom": ["invite_id"],- "tableTo": "invites","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"join_requests_company_id_companies_id_fk": {"name": "join_requests_company_id_companies_id_fk","tableFrom": "join_requests",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"join_requests_created_agent_id_agents_id_fk": {"name": "join_requests_created_agent_id_agents_id_fk","tableFrom": "join_requests",+ "tableTo": "agents","columnsFrom": ["created_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -41542,9 +41661,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"labels_company_name_idx": {"name": "labels_company_name_idx",@@ -41563,24 +41682,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"labels_company_id_companies_id_fk": {"name": "labels_company_id_companies_id_fk","tableFrom": "labels",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -41730,9 +41849,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"managed_agent_profiles_company_key_uq": {"name": "managed_agent_profiles_company_key_uq",@@ -41751,9 +41870,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"managed_agent_profiles_company_resource_uq": {"name": "managed_agent_profiles_company_resource_uq",@@ -41784,37 +41903,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"managed_agent_profiles_company_id_companies_id_fk": {"name": "managed_agent_profiles_company_id_companies_id_fk","tableFrom": "managed_agent_profiles",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"managed_agent_profiles_api_key_secret_id_company_secrets_id_fk": {"name": "managed_agent_profiles_api_key_secret_id_company_secrets_id_fk","tableFrom": "managed_agent_profiles",+ "tableTo": "company_secrets","columnsFrom": ["api_key_secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -42000,99 +42119,100 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"native_run_finalizations\".\"control_deadline_at\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"native_run_finalizations_company_id_companies_id_fk": {"name": "native_run_finalizations_company_id_companies_id_fk","tableFrom": "native_run_finalizations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_finalizations_issue_company_fk": {"name": "native_run_finalizations_issue_company_fk","tableFrom": "native_run_finalizations",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_finalizations_run_owner_fk": {"name": "native_run_finalizations_run_owner_fk","tableFrom": "native_run_finalizations",+ "tableTo": "heartbeat_runs","columnsFrom": ["company_id","issue_id","run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["company_id","native_issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_finalizations_result_owner_fk": {"name": "native_run_finalizations_result_owner_fk","tableFrom": "native_run_finalizations",+ "tableTo": "native_run_results","columnsFrom": ["company_id","issue_id","run_id","result_id"],- "tableTo": "native_run_results","columnsTo": ["company_id","issue_id","run_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_finalizations_assessment_owner_fk": {"name": "native_run_finalizations_assessment_owner_fk","tableFrom": "native_run_finalizations",+ "tableTo": "work_assessments","columnsFrom": ["company_id","issue_id","run_id","assessment_id"],- "tableTo": "work_assessments","columnsTo": ["company_id","issue_id","run_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_finalizations_decision_owner_fk": {"name": "native_run_finalizations_decision_owner_fk","tableFrom": "native_run_finalizations",+ "tableTo": "status_decisions","columnsFrom": ["company_id","issue_id",@@ -42100,7 +42220,6 @@"assessment_id","decision_id"],- "tableTo": "status_decisions","columnsTo": ["company_id","issue_id",@@ -42108,8 +42227,8 @@"assessment_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -42236,9 +42355,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"native_run_results_run_caller_result_uq": {"name": "native_run_results_run_caller_result_uq",@@ -42257,9 +42376,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"native_run_results_run_caller_dedupe_uq": {"name": "native_run_results_run_caller_dedupe_uq",@@ -42278,88 +42397,88 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"native_run_results_company_id_companies_id_fk": {"name": "native_run_results_company_id_companies_id_fk","tableFrom": "native_run_results",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_results_issue_company_fk": {"name": "native_run_results_issue_company_fk","tableFrom": "native_run_results",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_results_run_contract_owner_fk": {"name": "native_run_results_run_contract_owner_fk","tableFrom": "native_run_results",+ "tableTo": "heartbeat_runs","columnsFrom": ["company_id","issue_id","run_id","completion_contract_id"],- "tableTo": "heartbeat_runs","columnsTo": ["company_id","native_issue_id","id","completion_contract_id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"native_run_results_completion_contract_owner_fk": {"name": "native_run_results_completion_contract_owner_fk","tableFrom": "native_run_results",+ "tableTo": "completion_contracts","columnsFrom": ["company_id","issue_id","completion_contract_id"],- "tableTo": "completion_contracts","columnsTo": ["company_id","issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"native_run_results_company_issue_run_id_uq": {"name": "native_run_results_company_issue_run_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","issue_id","run_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -42477,9 +42596,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_automation_executions_company_case_idx": {"name": "pipeline_automation_executions_company_case_idx",@@ -42498,9 +42617,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_automation_executions_routine_idx": {"name": "pipeline_automation_executions_routine_idx",@@ -42513,9 +42632,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_automation_executions_execution_issue_idx": {"name": "pipeline_automation_executions_execution_issue_idx",@@ -42528,9 +42647,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_automation_executions_retry_of_execution_idx": {"name": "pipeline_automation_executions_retry_of_execution_idx",@@ -42543,63 +42662,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_automation_executions_company_id_companies_id_fk": {"name": "pipeline_automation_executions_company_id_companies_id_fk","tableFrom": "pipeline_automation_executions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_automation_executions_case_id_pipeline_cases_id_fk": {"name": "pipeline_automation_executions_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_automation_executions",+ "tableTo": "pipeline_cases","columnsFrom": ["case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_automation_executions_routine_id_routines_id_fk": {"name": "pipeline_automation_executions_routine_id_routines_id_fk","tableFrom": "pipeline_automation_executions",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_automation_executions_execution_issue_id_issues_id_fk": {"name": "pipeline_automation_executions_execution_issue_id_issues_id_fk","tableFrom": "pipeline_automation_executions",+ "tableTo": "issues","columnsFrom": ["execution_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -42675,9 +42794,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_blockers_blocked_by_idx": {"name": "pipeline_case_blockers_blocked_by_idx",@@ -42690,9 +42809,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_blockers_company_case_idx": {"name": "pipeline_case_blockers_company_case_idx",@@ -42711,50 +42830,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_case_blockers_company_id_companies_id_fk": {"name": "pipeline_case_blockers_company_id_companies_id_fk","tableFrom": "pipeline_case_blockers",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_blockers_case_id_pipeline_cases_id_fk": {"name": "pipeline_case_blockers_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_case_blockers",+ "tableTo": "pipeline_cases","columnsFrom": ["case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_blockers_blocked_by_case_id_pipeline_cases_id_fk": {"name": "pipeline_case_blockers_blocked_by_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_case_blockers",+ "tableTo": "pipeline_cases","columnsFrom": ["blocked_by_case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -42842,9 +42961,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_documents_document_uq": {"name": "pipeline_case_documents_document_uq",@@ -42857,9 +42976,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_documents_company_case_updated_idx": {"name": "pipeline_case_documents_company_case_updated_idx",@@ -42884,50 +43003,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_case_documents_company_id_companies_id_fk": {"name": "pipeline_case_documents_company_id_companies_id_fk","tableFrom": "pipeline_case_documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_documents_case_id_pipeline_cases_id_fk": {"name": "pipeline_case_documents_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_case_documents",+ "tableTo": "pipeline_cases","columnsFrom": ["case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_documents_document_id_documents_id_fk": {"name": "pipeline_case_documents_document_id_documents_id_fk","tableFrom": "pipeline_case_documents",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -43041,9 +43160,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_events_company_case_idx": {"name": "pipeline_case_events_company_case_idx",@@ -43062,76 +43181,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_case_events_company_id_companies_id_fk": {"name": "pipeline_case_events_company_id_companies_id_fk","tableFrom": "pipeline_case_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_events_case_id_pipeline_cases_id_fk": {"name": "pipeline_case_events_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_case_events",+ "tableTo": "pipeline_cases","columnsFrom": ["case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_events_actor_agent_id_agents_id_fk": {"name": "pipeline_case_events_actor_agent_id_agents_id_fk","tableFrom": "pipeline_case_events",+ "tableTo": "agents","columnsFrom": ["actor_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"pipeline_case_events_from_stage_id_pipeline_stages_id_fk": {"name": "pipeline_case_events_from_stage_id_pipeline_stages_id_fk","tableFrom": "pipeline_case_events",+ "tableTo": "pipeline_stages","columnsFrom": ["from_stage_id"],- "tableTo": "pipeline_stages","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"pipeline_case_events_to_stage_id_pipeline_stages_id_fk": {"name": "pipeline_case_events_to_stage_id_pipeline_stages_id_fk","tableFrom": "pipeline_case_events",+ "tableTo": "pipeline_stages","columnsFrom": ["to_stage_id"],- "tableTo": "pipeline_stages","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -43251,9 +43370,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_issue_links_issue_idx": {"name": "pipeline_case_issue_links_issue_idx",@@ -43266,9 +43385,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_issue_links_company_case_idx": {"name": "pipeline_case_issue_links_company_case_idx",@@ -43287,9 +43406,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_case_issue_links_automation_attempt_idx": {"name": "pipeline_case_issue_links_automation_attempt_idx",@@ -43302,50 +43421,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_case_issue_links_company_id_companies_id_fk": {"name": "pipeline_case_issue_links_company_id_companies_id_fk","tableFrom": "pipeline_case_issue_links",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_issue_links_case_id_pipeline_cases_id_fk": {"name": "pipeline_case_issue_links_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_case_issue_links",+ "tableTo": "pipeline_cases","columnsFrom": ["case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_case_issue_links_issue_id_issues_id_fk": {"name": "pipeline_case_issue_links_issue_id_issues_id_fk","tableFrom": "pipeline_case_issue_links",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -43587,9 +43706,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_parent_request_key_uq": {"name": "pipeline_cases_parent_request_key_uq",@@ -43608,10 +43727,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"pipeline_cases\".\"request_key\" is not null and \"pipeline_cases\".\"retired_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"pipeline_cases_company_idx": {"name": "pipeline_cases_company_idx",@@ -43624,9 +43743,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_pipeline_stage_idx": {"name": "pipeline_cases_pipeline_stage_idx",@@ -43645,9 +43764,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_parent_idx": {"name": "pipeline_cases_parent_idx",@@ -43660,9 +43779,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_automation_attempt_idx": {"name": "pipeline_cases_automation_attempt_idx",@@ -43675,9 +43794,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_retired_idx": {"name": "pipeline_cases_retired_idx",@@ -43696,9 +43815,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_cases_lease_expires_idx": {"name": "pipeline_cases_lease_expires_idx",@@ -43711,90 +43830,90 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"pipeline_cases\".\"lease_expires_at\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"pipeline_cases_company_id_companies_id_fk": {"name": "pipeline_cases_company_id_companies_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_cases_pipeline_id_pipelines_id_fk": {"name": "pipeline_cases_pipeline_id_pipelines_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "pipelines","columnsFrom": ["pipeline_id"],- "tableTo": "pipelines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_cases_stage_id_pipeline_stages_id_fk": {"name": "pipeline_cases_stage_id_pipeline_stages_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "pipeline_stages","columnsFrom": ["stage_id"],- "tableTo": "pipeline_stages","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"pipeline_cases_parent_case_id_pipeline_cases_id_fk": {"name": "pipeline_cases_parent_case_id_pipeline_cases_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "pipeline_cases","columnsFrom": ["parent_case_id"],- "tableTo": "pipeline_cases","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"pipeline_cases_lease_agent_id_agents_id_fk": {"name": "pipeline_cases_lease_agent_id_agents_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "agents","columnsFrom": ["lease_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"pipeline_cases_created_by_agent_id_agents_id_fk": {"name": "pipeline_cases_created_by_agent_id_agents_id_fk","tableFrom": "pipeline_cases",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -43886,9 +44005,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_documents_document_uq": {"name": "pipeline_documents_document_uq",@@ -43901,9 +44020,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_documents_company_pipeline_updated_idx": {"name": "pipeline_documents_company_pipeline_updated_idx",@@ -43928,50 +44047,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_documents_company_id_companies_id_fk": {"name": "pipeline_documents_company_id_companies_id_fk","tableFrom": "pipeline_documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_documents_pipeline_id_pipelines_id_fk": {"name": "pipeline_documents_pipeline_id_pipelines_id_fk","tableFrom": "pipeline_documents",+ "tableTo": "pipelines","columnsFrom": ["pipeline_id"],- "tableTo": "pipelines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_documents_document_id_documents_id_fk": {"name": "pipeline_documents_document_id_documents_id_fk","tableFrom": "pipeline_documents",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44061,9 +44180,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_stages_pipeline_position_idx": {"name": "pipeline_stages_pipeline_position_idx",@@ -44082,24 +44201,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_stages_pipeline_id_pipelines_id_fk": {"name": "pipeline_stages_pipeline_id_pipelines_id_fk","tableFrom": "pipeline_stages",+ "tableTo": "pipelines","columnsFrom": ["pipeline_id"],- "tableTo": "pipelines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44187,9 +44306,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_transitions_pipeline_from_idx": {"name": "pipeline_transitions_pipeline_from_idx",@@ -44208,9 +44327,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipeline_transitions_pipeline_to_idx": {"name": "pipeline_transitions_pipeline_to_idx",@@ -44229,50 +44348,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipeline_transitions_pipeline_id_pipelines_id_fk": {"name": "pipeline_transitions_pipeline_id_pipelines_id_fk","tableFrom": "pipeline_transitions",+ "tableTo": "pipelines","columnsFrom": ["pipeline_id"],- "tableTo": "pipelines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_transitions_from_stage_id_pipeline_stages_id_fk": {"name": "pipeline_transitions_from_stage_id_pipeline_stages_id_fk","tableFrom": "pipeline_transitions",+ "tableTo": "pipeline_stages","columnsFrom": ["from_stage_id"],- "tableTo": "pipeline_stages","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipeline_transitions_to_stage_id_pipeline_stages_id_fk": {"name": "pipeline_transitions_to_stage_id_pipeline_stages_id_fk","tableFrom": "pipeline_transitions",+ "tableTo": "pipeline_stages","columnsFrom": ["to_stage_id"],- "tableTo": "pipeline_stages","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44380,9 +44499,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipelines_company_idx": {"name": "pipelines_company_idx",@@ -44395,9 +44514,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"pipelines_company_project_idx": {"name": "pipelines_company_project_idx",@@ -44416,50 +44535,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"pipelines_company_id_companies_id_fk": {"name": "pipelines_company_id_companies_id_fk","tableFrom": "pipelines",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"pipelines_project_id_projects_id_fk": {"name": "pipelines_project_id_projects_id_fk","tableFrom": "pipelines",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"pipelines_created_by_agent_id_agents_id_fk": {"name": "pipelines_created_by_agent_id_agents_id_fk","tableFrom": "pipelines",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44538,9 +44657,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_company_settings_plugin_idx": {"name": "plugin_company_settings_plugin_idx",@@ -44553,9 +44672,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_company_settings_company_plugin_uq": {"name": "plugin_company_settings_company_plugin_uq",@@ -44574,37 +44693,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_company_settings_company_id_companies_id_fk": {"name": "plugin_company_settings_company_id_companies_id_fk","tableFrom": "plugin_company_settings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_company_settings_plugin_id_plugins_id_fk": {"name": "plugin_company_settings_plugin_id_plugins_id_fk","tableFrom": "plugin_company_settings",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44682,37 +44801,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_config_plugin_id_plugins_id_fk": {"name": "plugin_config_plugin_id_plugins_id_fk","tableFrom": "plugin_config",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_config_company_id_companies_id_fk": {"name": "plugin_config_company_id_companies_id_fk","tableFrom": "plugin_config",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44791,9 +44910,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_database_namespaces_namespace_idx": {"name": "plugin_database_namespaces_namespace_idx",@@ -44806,9 +44925,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_database_namespaces_status_idx": {"name": "plugin_database_namespaces_status_idx",@@ -44821,24 +44940,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_database_namespaces_plugin_id_plugins_id_fk": {"name": "plugin_database_namespaces_plugin_id_plugins_id_fk","tableFrom": "plugin_database_namespaces",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -44940,9 +45059,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_entities_company_idx": {"name": "plugin_entities_company_idx",@@ -44955,9 +45074,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_entities_type_idx": {"name": "plugin_entities_type_idx",@@ -44970,9 +45089,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_entities_scope_idx": {"name": "plugin_entities_scope_idx",@@ -44991,50 +45110,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_entities_plugin_id_plugins_id_fk": {"name": "plugin_entities_plugin_id_plugins_id_fk","tableFrom": "plugin_entities",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_entities_company_id_companies_id_fk": {"name": "plugin_entities_company_id_companies_id_fk","tableFrom": "plugin_entities",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"plugin_entities_external_idx": {"name": "plugin_entities_external_idx",+ "nullsNotDistinct": true,"columns": ["company_id","plugin_id","entity_type","external_id"- ],- "nullsNotDistinct": true+ ]}},"policies": {},@@ -45134,9 +45253,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_job_runs_plugin_idx": {"name": "plugin_job_runs_plugin_idx",@@ -45149,9 +45268,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_job_runs_company_idx": {"name": "plugin_job_runs_company_idx",@@ -45164,9 +45283,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_job_runs_status_idx": {"name": "plugin_job_runs_status_idx",@@ -45179,50 +45298,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_job_runs_job_id_plugin_jobs_id_fk": {"name": "plugin_job_runs_job_id_plugin_jobs_id_fk","tableFrom": "plugin_job_runs",+ "tableTo": "plugin_jobs","columnsFrom": ["job_id"],- "tableTo": "plugin_jobs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_job_runs_plugin_id_plugins_id_fk": {"name": "plugin_job_runs_plugin_id_plugins_id_fk","tableFrom": "plugin_job_runs",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_job_runs_company_id_companies_id_fk": {"name": "plugin_job_runs_company_id_companies_id_fk","tableFrom": "plugin_job_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -45306,9 +45425,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_jobs_next_run_idx": {"name": "plugin_jobs_next_run_idx",@@ -45321,9 +45440,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_jobs_unique_idx": {"name": "plugin_jobs_unique_idx",@@ -45342,24 +45461,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_jobs_plugin_id_plugins_id_fk": {"name": "plugin_jobs_plugin_id_plugins_id_fk","tableFrom": "plugin_jobs",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -45404,37 +45523,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_lifecycle_acknowledgments_plugin_id_plugins_id_fk": {"name": "plugin_lifecycle_acknowledgments_plugin_id_plugins_id_fk","tableFrom": "plugin_lifecycle_acknowledgments",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_lifecycle_acknowledgments_event_id_resource_lifecycle_events_id_fk": {"name": "plugin_lifecycle_acknowledgments_event_id_resource_lifecycle_events_id_fk","tableFrom": "plugin_lifecycle_acknowledgments",+ "tableTo": "resource_lifecycle_events","columnsFrom": ["event_id"],- "tableTo": "resource_lifecycle_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {@@ -45519,9 +45638,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_logs_company_idx": {"name": "plugin_logs_company_idx",@@ -45534,9 +45653,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_logs_level_idx": {"name": "plugin_logs_level_idx",@@ -45549,37 +45668,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_logs_plugin_id_plugins_id_fk": {"name": "plugin_logs_plugin_id_plugins_id_fk","tableFrom": "plugin_logs",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_logs_company_id_companies_id_fk": {"name": "plugin_logs_company_id_companies_id_fk","tableFrom": "plugin_logs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -45669,9 +45788,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_managed_resources_plugin_idx": {"name": "plugin_managed_resources_plugin_idx",@@ -45684,9 +45803,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_managed_resources_resource_idx": {"name": "plugin_managed_resources_resource_idx",@@ -45705,9 +45824,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_managed_resources_company_plugin_resource_uq": {"name": "plugin_managed_resources_company_plugin_resource_uq",@@ -45738,37 +45857,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_managed_resources_company_id_companies_id_fk": {"name": "plugin_managed_resources_company_id_companies_id_fk","tableFrom": "plugin_managed_resources",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_managed_resources_plugin_id_plugins_id_fk": {"name": "plugin_managed_resources_plugin_id_plugins_id_fk","tableFrom": "plugin_managed_resources",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -45868,9 +45987,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_migrations_plugin_idx": {"name": "plugin_migrations_plugin_idx",@@ -45883,9 +46002,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_migrations_status_idx": {"name": "plugin_migrations_status_idx",@@ -45898,24 +46017,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_migrations_plugin_id_plugins_id_fk": {"name": "plugin_migrations_plugin_id_plugins_id_fk","tableFrom": "plugin_migrations",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -45998,38 +46117,38 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_state_plugin_id_plugins_id_fk": {"name": "plugin_state_plugin_id_plugins_id_fk","tableFrom": "plugin_state",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"plugin_state_unique_entry_idx": {"name": "plugin_state_unique_entry_idx",+ "nullsNotDistinct": true,"columns": ["plugin_id","scope_kind","scope_id","namespace","state_key"- ],- "nullsNotDistinct": true+ ]}},"policies": {},@@ -46135,9 +46254,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_webhook_deliveries_company_idx": {"name": "plugin_webhook_deliveries_company_idx",@@ -46150,9 +46269,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_webhook_deliveries_status_idx": {"name": "plugin_webhook_deliveries_status_idx",@@ -46165,9 +46284,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugin_webhook_deliveries_key_idx": {"name": "plugin_webhook_deliveries_key_idx",@@ -46180,37 +46299,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"plugin_webhook_deliveries_plugin_id_plugins_id_fk": {"name": "plugin_webhook_deliveries_plugin_id_plugins_id_fk","tableFrom": "plugin_webhook_deliveries",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"plugin_webhook_deliveries_company_id_companies_id_fk": {"name": "plugin_webhook_deliveries_company_id_companies_id_fk","tableFrom": "plugin_webhook_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -46320,9 +46439,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"plugins_status_idx": {"name": "plugins_status_idx",@@ -46335,9 +46454,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -46439,9 +46558,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"principal_permission_grants_company_permission_idx": {"name": "principal_permission_grants_company_permission_idx",@@ -46460,24 +46579,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"principal_permission_grants_company_id_companies_id_fk": {"name": "principal_permission_grants_company_id_companies_id_fk","tableFrom": "principal_permission_grants",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -46553,9 +46672,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_access_members_subject_lookup_idx": {"name": "project_access_members_subject_lookup_idx",@@ -46586,37 +46705,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"project_access_members_company_id_companies_id_fk": {"name": "project_access_members_company_id_companies_id_fk","tableFrom": "project_access_members",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_access_members_project_id_projects_id_fk": {"name": "project_access_members_project_id_projects_id_fk","tableFrom": "project_access_members",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -46679,9 +46798,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_goals_goal_idx": {"name": "project_goals_goal_idx",@@ -46694,9 +46813,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_goals_company_idx": {"name": "project_goals_company_idx",@@ -46709,50 +46828,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"project_goals_project_id_projects_id_fk": {"name": "project_goals_project_id_projects_id_fk","tableFrom": "project_goals",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_goals_goal_id_goals_id_fk": {"name": "project_goals_goal_id_goals_id_fk","tableFrom": "project_goals",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_goals_company_id_companies_id_fk": {"name": "project_goals_company_id_companies_id_fk","tableFrom": "project_goals",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {@@ -46844,9 +46963,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_memberships_company_user_starred_idx": {"name": "project_memberships_company_user_starred_idx",@@ -46871,9 +46990,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_memberships_project_idx": {"name": "project_memberships_project_idx",@@ -46886,9 +47005,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_memberships_company_user_project_uq": {"name": "project_memberships_company_user_project_uq",@@ -46913,37 +47032,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"project_memberships_company_id_companies_id_fk": {"name": "project_memberships_company_id_companies_id_fk","tableFrom": "project_memberships",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"project_memberships_project_id_projects_id_fk": {"name": "project_memberships_project_id_projects_id_fk","tableFrom": "project_memberships",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -47095,9 +47214,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_workspaces_project_primary_idx": {"name": "project_workspaces_project_primary_idx",@@ -47116,9 +47235,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_workspaces_project_source_type_idx": {"name": "project_workspaces_project_source_type_idx",@@ -47137,9 +47256,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_workspaces_company_shared_key_idx": {"name": "project_workspaces_company_shared_key_idx",@@ -47158,9 +47277,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"project_workspaces_project_remote_ref_idx": {"name": "project_workspaces_project_remote_ref_idx",@@ -47185,37 +47304,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"project_workspaces_company_id_companies_id_fk": {"name": "project_workspaces_company_id_companies_id_fk","tableFrom": "project_workspaces",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"project_workspaces_project_id_projects_id_fk": {"name": "project_workspaces_project_id_projects_id_fk","tableFrom": "project_workspaces",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -47366,9 +47485,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"projects_company_personal_owner_uq": {"name": "projects_company_personal_owner_uq",@@ -47387,51 +47506,51 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"projects\".\"personal_owner_user_id\" is not null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"projects_company_id_companies_id_fk": {"name": "projects_company_id_companies_id_fk","tableFrom": "projects",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"projects_goal_id_goals_id_fk": {"name": "projects_goal_id_goals_id_fk","tableFrom": "projects",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"projects_lead_agent_id_agents_id_fk": {"name": "projects_lead_agent_id_agents_id_fk","tableFrom": "projects",+ "tableTo": "agents","columnsFrom": ["lead_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -47558,9 +47677,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"provider_trace_records_expiry_idx": {"name": "provider_trace_records_expiry_idx",@@ -47579,9 +47698,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"provider_trace_records_company_created_idx": {"name": "provider_trace_records_company_created_idx",@@ -47600,37 +47719,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"provider_trace_records_company_id_companies_id_fk": {"name": "provider_trace_records_company_id_companies_id_fk","tableFrom": "provider_trace_records",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"provider_trace_records_run_id_heartbeat_runs_id_fk": {"name": "provider_trace_records_run_id_heartbeat_runs_id_fk","tableFrom": "provider_trace_records",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -47741,9 +47860,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"remote_agent_profiles_company_key_uq": {"name": "remote_agent_profiles_company_key_uq",@@ -47762,24 +47881,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"remote_agent_profiles_company_id_companies_id_fk": {"name": "remote_agent_profiles_company_id_companies_id_fk","tableFrom": "remote_agent_profiles",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -47807,15 +47926,15 @@"primaryKey": true,"notNull": true,"identity": {+ "type": "always","name": "resource_lifecycle_events_id_seq",+ "schema": "public","increment": "1",+ "startWith": "1","minValue": "1","maxValue": "9223372036854775807",- "startWith": "1","cache": "1",- "cycle": false,- "schema": "public",- "type": "always"+ "cycle": false}},"company_id": {@@ -47874,10 +47993,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"resource_lifecycle_events\".\"action\" = 'create'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"resource_lifecycle_events_company_idx": {"name": "resource_lifecycle_events_company_idx",@@ -47896,9 +48015,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"resource_lifecycle_events_resource_order_idx": {"name": "resource_lifecycle_events_resource_order_idx",@@ -47929,24 +48048,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"resource_lifecycle_events_company_id_companies_id_fk": {"name": "resource_lifecycle_events_company_id_companies_id_fk","tableFrom": "resource_lifecycle_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -48038,9 +48157,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_documents_document_uq": {"name": "routine_documents_document_uq",@@ -48053,9 +48172,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_documents_company_routine_updated_idx": {"name": "routine_documents_company_routine_updated_idx",@@ -48080,50 +48199,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routine_documents_company_id_companies_id_fk": {"name": "routine_documents_company_id_companies_id_fk","tableFrom": "routine_documents",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"routine_documents_routine_id_routines_id_fk": {"name": "routine_documents_routine_id_routines_id_fk","tableFrom": "routine_documents",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_documents_document_id_documents_id_fk": {"name": "routine_documents_document_id_documents_id_fk","tableFrom": "routine_documents",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -48241,9 +48360,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_revisions_company_routine_created_idx": {"name": "routine_revisions_company_routine_created_idx",@@ -48268,9 +48387,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_revisions_company_responsible_user_idx": {"name": "routine_revisions_company_responsible_user_idx",@@ -48295,76 +48414,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routine_revisions_company_id_companies_id_fk": {"name": "routine_revisions_company_id_companies_id_fk","tableFrom": "routine_revisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_revisions_routine_id_routines_id_fk": {"name": "routine_revisions_routine_id_routines_id_fk","tableFrom": "routine_revisions",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_revisions_restored_from_revision_id_routine_revisions_id_fk": {"name": "routine_revisions_restored_from_revision_id_routine_revisions_id_fk","tableFrom": "routine_revisions",+ "tableTo": "routine_revisions","columnsFrom": ["restored_from_revision_id"],- "tableTo": "routine_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_revisions_created_by_agent_id_agents_id_fk": {"name": "routine_revisions_created_by_agent_id_agents_id_fk","tableFrom": "routine_revisions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_revisions_created_by_run_id_heartbeat_runs_id_fk": {"name": "routine_revisions_created_by_run_id_heartbeat_runs_id_fk","tableFrom": "routine_revisions",+ "tableTo": "heartbeat_runs","columnsFrom": ["created_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -48515,9 +48634,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_revision_idx": {"name": "routine_runs_revision_idx",@@ -48530,9 +48649,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_company_responsible_user_idx": {"name": "routine_runs_company_responsible_user_idx",@@ -48557,9 +48676,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_trigger_idx": {"name": "routine_runs_trigger_idx",@@ -48578,9 +48697,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_dispatch_fingerprint_idx": {"name": "routine_runs_dispatch_fingerprint_idx",@@ -48599,9 +48718,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_linked_issue_idx": {"name": "routine_runs_linked_issue_idx",@@ -48614,9 +48733,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_runs_trigger_idempotency_idx": {"name": "routine_runs_trigger_idempotency_idx",@@ -48635,76 +48754,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routine_runs_company_id_companies_id_fk": {"name": "routine_runs_company_id_companies_id_fk","tableFrom": "routine_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_runs_routine_id_routines_id_fk": {"name": "routine_runs_routine_id_routines_id_fk","tableFrom": "routine_runs",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_runs_trigger_id_routine_triggers_id_fk": {"name": "routine_runs_trigger_id_routine_triggers_id_fk","tableFrom": "routine_runs",+ "tableTo": "routine_triggers","columnsFrom": ["trigger_id"],- "tableTo": "routine_triggers","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_runs_routine_revision_id_routine_revisions_id_fk": {"name": "routine_runs_routine_revision_id_routine_revisions_id_fk","tableFrom": "routine_runs",+ "tableTo": "routine_revisions","columnsFrom": ["routine_revision_id"],- "tableTo": "routine_revisions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_runs_linked_issue_id_issues_id_fk": {"name": "routine_runs_linked_issue_id_issues_id_fk","tableFrom": "routine_runs",+ "tableTo": "issues","columnsFrom": ["linked_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -48892,9 +49011,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_triggers_company_kind_idx": {"name": "routine_triggers_company_kind_idx",@@ -48913,9 +49032,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_triggers_next_run_idx": {"name": "routine_triggers_next_run_idx",@@ -48928,9 +49047,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_triggers_public_id_idx": {"name": "routine_triggers_public_id_idx",@@ -48943,9 +49062,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routine_triggers_public_id_uq": {"name": "routine_triggers_public_id_uq",@@ -48958,76 +49077,76 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routine_triggers_company_id_companies_id_fk": {"name": "routine_triggers_company_id_companies_id_fk","tableFrom": "routine_triggers",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_triggers_routine_id_routines_id_fk": {"name": "routine_triggers_routine_id_routines_id_fk","tableFrom": "routine_triggers",+ "tableTo": "routines","columnsFrom": ["routine_id"],- "tableTo": "routines","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_triggers_secret_id_company_secrets_id_fk": {"name": "routine_triggers_secret_id_company_secrets_id_fk","tableFrom": "routine_triggers",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_triggers_created_by_agent_id_agents_id_fk": {"name": "routine_triggers_created_by_agent_id_agents_id_fk","tableFrom": "routine_triggers",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routine_triggers_updated_by_agent_id_agents_id_fk": {"name": "routine_triggers_updated_by_agent_id_agents_id_fk","tableFrom": "routine_triggers",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -49091,37 +49210,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routine_webhook_test_receipts_company_id_companies_id_fk": {"name": "routine_webhook_test_receipts_company_id_companies_id_fk","tableFrom": "routine_webhook_test_receipts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routine_webhook_test_receipts_trigger_id_routine_triggers_id_fk": {"name": "routine_webhook_test_receipts_trigger_id_routine_triggers_id_fk","tableFrom": "routine_webhook_test_receipts",+ "tableTo": "routine_triggers","columnsFrom": ["trigger_id"],- "tableTo": "routine_triggers","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -49345,9 +49464,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routines_company_assignee_idx": {"name": "routines_company_assignee_idx",@@ -49366,9 +49485,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routines_company_project_idx": {"name": "routines_company_project_idx",@@ -49387,9 +49506,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routines_company_folder_idx": {"name": "routines_company_folder_idx",@@ -49408,9 +49527,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routines_company_responsible_user_idx": {"name": "routines_company_responsible_user_idx",@@ -49429,9 +49548,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"routines_company_origin_idx": {"name": "routines_company_origin_idx",@@ -49456,115 +49575,115 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"routines_company_id_companies_id_fk": {"name": "routines_company_id_companies_id_fk","tableFrom": "routines",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routines_project_id_projects_id_fk": {"name": "routines_project_id_projects_id_fk","tableFrom": "routines",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"routines_folder_id_folders_id_fk": {"name": "routines_folder_id_folders_id_fk","tableFrom": "routines",+ "tableTo": "folders","columnsFrom": ["folder_id"],- "tableTo": "folders","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routines_goal_id_goals_id_fk": {"name": "routines_goal_id_goals_id_fk","tableFrom": "routines",+ "tableTo": "goals","columnsFrom": ["goal_id"],- "tableTo": "goals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routines_parent_issue_id_issues_id_fk": {"name": "routines_parent_issue_id_issues_id_fk","tableFrom": "routines",+ "tableTo": "issues","columnsFrom": ["parent_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routines_assignee_agent_id_agents_id_fk": {"name": "routines_assignee_agent_id_agents_id_fk","tableFrom": "routines",+ "tableTo": "agents","columnsFrom": ["assignee_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"routines_created_by_agent_id_agents_id_fk": {"name": "routines_created_by_agent_id_agents_id_fk","tableFrom": "routines",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"routines_updated_by_agent_id_agents_id_fk": {"name": "routines_updated_by_agent_id_agents_id_fk","tableFrom": "routines",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -49677,9 +49796,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"run_identity_contexts_run_correlation_idx": {"name": "run_identity_contexts_run_correlation_idx",@@ -49698,9 +49817,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"run_identity_contexts_company_run_idx": {"name": "run_identity_contexts_company_run_idx",@@ -49719,24 +49838,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"run_identity_contexts_company_id_companies_id_fk": {"name": "run_identity_contexts_company_id_companies_id_fk","tableFrom": "run_identity_contexts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -49800,50 +49919,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"runner_api_response_reservations_company_id_companies_id_fk": {"name": "runner_api_response_reservations_company_id_companies_id_fk","tableFrom": "runner_api_response_reservations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"runner_api_response_reservations_run_id_heartbeat_runs_id_fk": {"name": "runner_api_response_reservations_run_id_heartbeat_runs_id_fk","tableFrom": "runner_api_response_reservations",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"runner_api_response_reservations_asset_id_assets_id_fk": {"name": "runner_api_response_reservations_asset_id_assets_id_fk","tableFrom": "runner_api_response_reservations",+ "tableTo": "assets","columnsFrom": ["asset_id"],- "tableTo": "assets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -50010,9 +50129,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"secret_access_events_secret_created_idx": {"name": "secret_access_events_secret_created_idx",@@ -50031,9 +50150,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"secret_access_events_user_definition_created_idx": {"name": "secret_access_events_user_definition_created_idx",@@ -50052,9 +50171,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"secret_access_events_company_credential_owner_idx": {"name": "secret_access_events_company_credential_owner_idx",@@ -50079,9 +50198,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"secret_access_events_consumer_idx": {"name": "secret_access_events_consumer_idx",@@ -50106,9 +50225,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"secret_access_events_run_idx": {"name": "secret_access_events_run_idx",@@ -50121,89 +50240,89 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"secret_access_events_company_id_companies_id_fk": {"name": "secret_access_events_company_id_companies_id_fk","tableFrom": "secret_access_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"secret_access_events_secret_id_company_secrets_id_fk": {"name": "secret_access_events_secret_id_company_secrets_id_fk","tableFrom": "secret_access_events",+ "tableTo": "company_secrets","columnsFrom": ["secret_id"],- "tableTo": "company_secrets","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"secret_access_events_user_secret_definition_id_user_secret_definitions_id_fk": {"name": "secret_access_events_user_secret_definition_id_user_secret_definitions_id_fk","tableFrom": "secret_access_events",+ "tableTo": "user_secret_definitions","columnsFrom": ["user_secret_definition_id"],- "tableTo": "user_secret_definitions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"secret_access_events_issue_id_issues_id_fk": {"name": "secret_access_events_issue_id_issues_id_fk","tableFrom": "secret_access_events",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"secret_access_events_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "secret_access_events_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "secret_access_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"secret_access_events_plugin_id_plugins_id_fk": {"name": "secret_access_events_plugin_id_plugins_id_fk","tableFrom": "secret_access_events",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -50304,9 +50423,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"smoke_run_steps_company_path_idx": {"name": "smoke_run_steps_company_path_idx",@@ -50325,37 +50444,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"smoke_run_steps_company_id_companies_id_fk": {"name": "smoke_run_steps_company_id_companies_id_fk","tableFrom": "smoke_run_steps",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"smoke_run_steps_run_id_smoke_runs_id_fk": {"name": "smoke_run_steps_run_id_smoke_runs_id_fk","tableFrom": "smoke_run_steps",+ "tableTo": "smoke_runs","columnsFrom": ["run_id"],- "tableTo": "smoke_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -50447,9 +50566,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"smoke_runs_company_status_idx": {"name": "smoke_runs_company_status_idx",@@ -50468,24 +50587,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"smoke_runs_company_id_companies_id_fk": {"name": "smoke_runs_company_id_companies_id_fk","tableFrom": "smoke_runs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -50625,9 +50744,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"status_card_updates_generation_issue_idx": {"name": "status_card_updates_generation_issue_idx",@@ -50640,50 +50759,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"status_card_updates_card_id_status_cards_id_fk": {"name": "status_card_updates_card_id_status_cards_id_fk","tableFrom": "status_card_updates",+ "tableTo": "status_cards","columnsFrom": ["card_id"],- "tableTo": "status_cards","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"status_card_updates_generation_issue_id_issues_id_fk": {"name": "status_card_updates_generation_issue_id_issues_id_fk","tableFrom": "status_card_updates",+ "tableTo": "issues","columnsFrom": ["generation_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_card_updates_run_id_heartbeat_runs_id_fk": {"name": "status_card_updates_run_id_heartbeat_runs_id_fk","tableFrom": "status_card_updates",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -50916,9 +51035,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"status_cards_company_next_eval_idx": {"name": "status_cards_company_next_eval_idx",@@ -50937,102 +51056,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"status_cards_company_id_companies_id_fk": {"name": "status_cards_company_id_companies_id_fk","tableFrom": "status_cards",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"status_cards_created_by_agent_id_agents_id_fk": {"name": "status_cards_created_by_agent_id_agents_id_fk","tableFrom": "status_cards",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_cards_query_compiled_by_agent_id_agents_id_fk": {"name": "status_cards_query_compiled_by_agent_id_agents_id_fk","tableFrom": "status_cards",+ "tableTo": "agents","columnsFrom": ["query_compiled_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_cards_agent_id_agents_id_fk": {"name": "status_cards_agent_id_agents_id_fk","tableFrom": "status_cards",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_cards_document_id_documents_id_fk": {"name": "status_cards_document_id_documents_id_fk","tableFrom": "status_cards",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_cards_generating_issue_id_issues_id_fk": {"name": "status_cards_generating_issue_id_issues_id_fk","tableFrom": "status_cards",+ "tableTo": "issues","columnsFrom": ["generating_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"status_cards_archived_by_agent_id_agents_id_fk": {"name": "status_cards_archived_by_agent_id_agents_id_fk","tableFrom": "status_cards",+ "tableTo": "agents","columnsFrom": ["archived_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -51171,9 +51290,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"status_decision_effects_company_idempotency_uq": {"name": "status_decision_effects_company_idempotency_uq",@@ -51192,56 +51311,56 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"status_decision_effects_company_id_companies_id_fk": {"name": "status_decision_effects_company_id_companies_id_fk","tableFrom": "status_decision_effects",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"status_decision_effects_issue_company_fk": {"name": "status_decision_effects_issue_company_fk","tableFrom": "status_decision_effects",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"status_decision_effects_decision_owner_fk": {"name": "status_decision_effects_decision_owner_fk","tableFrom": "status_decision_effects",+ "tableTo": "status_decisions","columnsFrom": ["company_id","issue_id","decision_id"],- "tableTo": "status_decisions","columnsTo": ["company_id","issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -51378,9 +51497,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"status_decisions_company_assessment_uq": {"name": "status_decisions_company_assessment_uq",@@ -51399,9 +51518,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"status_decisions_company_issue_digest_uq": {"name": "status_decisions_company_issue_digest_uq",@@ -51426,98 +51545,98 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"status_decisions_company_id_companies_id_fk": {"name": "status_decisions_company_id_companies_id_fk","tableFrom": "status_decisions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"status_decisions_issue_company_fk": {"name": "status_decisions_issue_company_fk","tableFrom": "status_decisions",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"status_decisions_assessment_owner_fk": {"name": "status_decisions_assessment_owner_fk","tableFrom": "status_decisions",+ "tableTo": "work_assessments","columnsFrom": ["company_id","issue_id","run_id","assessment_id"],- "tableTo": "work_assessments","columnsTo": ["company_id","issue_id","run_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"status_decisions_supersedes_owner_fk": {"name": "status_decisions_supersedes_owner_fk","tableFrom": "status_decisions",+ "tableTo": "status_decisions","columnsFrom": ["company_id","issue_id","supersedes_decision_id"],- "tableTo": "status_decisions","columnsTo": ["company_id","issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"status_decisions_company_issue_id_uq": {"name": "status_decisions_company_issue_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","issue_id","id"- ],- "nullsNotDistinct": false+ ]},"status_decisions_company_issue_run_assessment_id_uq": {"name": "status_decisions_company_issue_run_assessment_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","issue_id","run_id","assessment_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -51629,9 +51748,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"summary_slots_company_scope_idx": {"name": "summary_slots_company_scope_idx",@@ -51656,9 +51775,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"summary_slots_company_generating_issue_idx": {"name": "summary_slots_company_generating_issue_idx",@@ -51677,9 +51796,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"summary_slots_company_updated_idx": {"name": "summary_slots_company_updated_idx",@@ -51698,76 +51817,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"summary_slots_company_id_companies_id_fk": {"name": "summary_slots_company_id_companies_id_fk","tableFrom": "summary_slots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"summary_slots_document_id_documents_id_fk": {"name": "summary_slots_document_id_documents_id_fk","tableFrom": "summary_slots",+ "tableTo": "documents","columnsFrom": ["document_id"],- "tableTo": "documents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"summary_slots_generating_issue_id_issues_id_fk": {"name": "summary_slots_generating_issue_id_issues_id_fk","tableFrom": "summary_slots",+ "tableTo": "issues","columnsFrom": ["generating_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"summary_slots_last_generated_by_agent_id_agents_id_fk": {"name": "summary_slots_last_generated_by_agent_id_agents_id_fk","tableFrom": "summary_slots",+ "tableTo": "agents","columnsFrom": ["last_generated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"summary_slots_company_scope_slot_uq": {"name": "summary_slots_company_scope_slot_uq",+ "nullsNotDistinct": true,"columns": ["company_id","scope_kind","scope_id","slot_key"- ],- "nullsNotDistinct": true+ ]}},"policies": {},@@ -51897,9 +52016,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_access_audit_connection_idx": {"name": "tool_access_audit_connection_idx",@@ -51912,9 +52031,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_access_audit_gateway_idx": {"name": "tool_access_audit_gateway_idx",@@ -51933,76 +52052,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_access_audit_events_company_id_companies_id_fk": {"name": "tool_access_audit_events_company_id_companies_id_fk","tableFrom": "tool_access_audit_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_access_audit_events_gateway_id_tool_mcp_gateways_id_fk": {"name": "tool_access_audit_events_gateway_id_tool_mcp_gateways_id_fk","tableFrom": "tool_access_audit_events",+ "tableTo": "tool_mcp_gateways","columnsFrom": ["gateway_id"],- "tableTo": "tool_mcp_gateways","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_access_audit_events_gateway_token_id_tool_mcp_gateway_tokens_id_fk": {"name": "tool_access_audit_events_gateway_token_id_tool_mcp_gateway_tokens_id_fk","tableFrom": "tool_access_audit_events",+ "tableTo": "tool_mcp_gateway_tokens","columnsFrom": ["gateway_token_id"],- "tableTo": "tool_mcp_gateway_tokens","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_access_audit_events_connection_id_tool_connections_id_fk": {"name": "tool_access_audit_events_connection_id_tool_connections_id_fk","tableFrom": "tool_access_audit_events",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_access_audit_events_catalog_entry_id_tool_catalog_entries_id_fk": {"name": "tool_access_audit_events_catalog_entry_id_tool_catalog_entries_id_fk","tableFrom": "tool_access_audit_events",+ "tableTo": "tool_catalog_entries","columnsFrom": ["catalog_entry_id"],- "tableTo": "tool_catalog_entries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -52071,63 +52190,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_action_deliveries_action_request_id_tool_action_requests_id_fk": {"name": "tool_action_deliveries_action_request_id_tool_action_requests_id_fk","tableFrom": "tool_action_deliveries",+ "tableTo": "tool_action_requests","columnsFrom": ["action_request_id"],- "tableTo": "tool_action_requests","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_action_deliveries_company_id_companies_id_fk": {"name": "tool_action_deliveries_company_id_companies_id_fk","tableFrom": "tool_action_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_action_deliveries_issue_id_issues_id_fk": {"name": "tool_action_deliveries_issue_id_issues_id_fk","tableFrom": "tool_action_deliveries",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_action_deliveries_interaction_id_issue_thread_interactions_id_fk": {"name": "tool_action_deliveries_interaction_id_issue_thread_interactions_id_fk","tableFrom": "tool_action_deliveries",+ "tableTo": "issue_thread_interactions","columnsFrom": ["interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -52295,9 +52414,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_action_requests_invocation_idx": {"name": "tool_action_requests_invocation_idx",@@ -52310,9 +52429,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_action_requests_issue_idx": {"name": "tool_action_requests_issue_idx",@@ -52331,115 +52450,115 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_action_requests_company_id_companies_id_fk": {"name": "tool_action_requests_company_id_companies_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_action_requests_invocation_id_tool_invocations_id_fk": {"name": "tool_action_requests_invocation_id_tool_invocations_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "tool_invocations","columnsFrom": ["invocation_id"],- "tableTo": "tool_invocations","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_action_requests_issue_id_issues_id_fk": {"name": "tool_action_requests_issue_id_issues_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_action_requests_interaction_id_issue_thread_interactions_id_fk": {"name": "tool_action_requests_interaction_id_issue_thread_interactions_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "issue_thread_interactions","columnsFrom": ["interaction_id"],- "tableTo": "issue_thread_interactions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_action_requests_approval_id_approvals_id_fk": {"name": "tool_action_requests_approval_id_approvals_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "approvals","columnsFrom": ["approval_id"],- "tableTo": "approvals","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_action_requests_requested_by_agent_id_agents_id_fk": {"name": "tool_action_requests_requested_by_agent_id_agents_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "agents","columnsFrom": ["requested_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_action_requests_resolved_by_agent_id_agents_id_fk": {"name": "tool_action_requests_resolved_by_agent_id_agents_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "agents","columnsFrom": ["resolved_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_action_requests_decided_by_agent_id_agents_id_fk": {"name": "tool_action_requests_decided_by_agent_id_agents_id_fk","tableFrom": "tool_action_requests",+ "tableTo": "agents","columnsFrom": ["decided_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -52554,9 +52673,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_applications_company_status_idx": {"name": "tool_applications_company_status_idx",@@ -52575,9 +52694,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_applications_company_name_uq": {"name": "tool_applications_company_name_uq",@@ -52596,9 +52715,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_applications_company_key_uq": {"name": "tool_applications_company_key_uq",@@ -52617,50 +52736,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_applications_company_id_companies_id_fk": {"name": "tool_applications_company_id_companies_id_fk","tableFrom": "tool_applications",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_applications_plugin_id_plugins_id_fk": {"name": "tool_applications_plugin_id_plugins_id_fk","tableFrom": "tool_applications",+ "tableTo": "plugins","columnsFrom": ["plugin_id"],- "tableTo": "plugins","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_applications_owner_agent_id_agents_id_fk": {"name": "tool_applications_owner_agent_id_agents_id_fk","tableFrom": "tool_applications",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -52955,9 +53074,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_call_events_run_idx": {"name": "tool_call_events_run_idx",@@ -52976,9 +53095,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_call_events_issue_idx": {"name": "tool_call_events_issue_idx",@@ -52997,9 +53116,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_call_events_invocation_idx": {"name": "tool_call_events_invocation_idx",@@ -53012,9 +53131,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_call_events_gateway_idx": {"name": "tool_call_events_gateway_idx",@@ -53033,167 +53152,167 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_call_events_company_id_companies_id_fk": {"name": "tool_call_events_company_id_companies_id_fk","tableFrom": "tool_call_events",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_call_events_agent_id_agents_id_fk": {"name": "tool_call_events_agent_id_agents_id_fk","tableFrom": "tool_call_events",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_run_id_heartbeat_runs_id_fk": {"name": "tool_call_events_run_id_heartbeat_runs_id_fk","tableFrom": "tool_call_events",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_issue_id_issues_id_fk": {"name": "tool_call_events_issue_id_issues_id_fk","tableFrom": "tool_call_events",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_gateway_id_tool_mcp_gateways_id_fk": {"name": "tool_call_events_gateway_id_tool_mcp_gateways_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_mcp_gateways","columnsFrom": ["gateway_id"],- "tableTo": "tool_mcp_gateways","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_gateway_token_id_tool_mcp_gateway_tokens_id_fk": {"name": "tool_call_events_gateway_token_id_tool_mcp_gateway_tokens_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_mcp_gateway_tokens","columnsFrom": ["gateway_token_id"],- "tableTo": "tool_mcp_gateway_tokens","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_application_id_tool_applications_id_fk": {"name": "tool_call_events_application_id_tool_applications_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_connection_id_tool_connections_id_fk": {"name": "tool_call_events_connection_id_tool_connections_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_catalog_entry_id_tool_catalog_entries_id_fk": {"name": "tool_call_events_catalog_entry_id_tool_catalog_entries_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_catalog_entries","columnsFrom": ["catalog_entry_id"],- "tableTo": "tool_catalog_entries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_invocation_id_tool_invocations_id_fk": {"name": "tool_call_events_invocation_id_tool_invocations_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_invocations","columnsFrom": ["invocation_id"],- "tableTo": "tool_invocations","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_action_request_id_tool_action_requests_id_fk": {"name": "tool_call_events_action_request_id_tool_action_requests_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_action_requests","columnsFrom": ["action_request_id"],- "tableTo": "tool_action_requests","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_call_events_runtime_slot_id_tool_runtime_slots_id_fk": {"name": "tool_call_events_runtime_slot_id_tool_runtime_slots_id_fk","tableFrom": "tool_call_events",+ "tableTo": "tool_runtime_slots","columnsFrom": ["runtime_slot_id"],- "tableTo": "tool_runtime_slots","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -53406,9 +53525,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_catalog_entries_application_idx": {"name": "tool_catalog_entries_application_idx",@@ -53421,9 +53540,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_catalog_entries_connection_idx": {"name": "tool_catalog_entries_connection_idx",@@ -53436,9 +53555,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_catalog_entries_company_status_idx": {"name": "tool_catalog_entries_company_status_idx",@@ -53457,9 +53576,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_catalog_entries_connection_name_uq": {"name": "tool_catalog_entries_connection_name_uq",@@ -53478,63 +53597,63 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_catalog_entries_company_id_companies_id_fk": {"name": "tool_catalog_entries_company_id_companies_id_fk","tableFrom": "tool_catalog_entries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_catalog_entries_application_id_tool_applications_id_fk": {"name": "tool_catalog_entries_application_id_tool_applications_id_fk","tableFrom": "tool_catalog_entries",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_catalog_entries_connection_id_tool_connections_id_fk": {"name": "tool_catalog_entries_connection_id_tool_connections_id_fk","tableFrom": "tool_catalog_entries",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_catalog_entries_reviewed_by_agent_id_agents_id_fk": {"name": "tool_catalog_entries_reviewed_by_agent_id_agents_id_fk","tableFrom": "tool_catalog_entries",+ "tableTo": "agents","columnsFrom": ["reviewed_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -53641,39 +53760,39 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_connection_app_snapshots_company_id_companies_id_fk": {"name": "tool_connection_app_snapshots_company_id_companies_id_fk","tableFrom": "tool_connection_app_snapshots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_connection_app_snapshots_company_connection_fk": {"name": "tool_connection_app_snapshots_company_connection_fk","tableFrom": "tool_connection_app_snapshots",+ "tableTo": "tool_connections","columnsFrom": ["company_id","connection_id"],- "tableTo": "tool_connections","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -53794,39 +53913,39 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_connection_app_syncs_company_id_companies_id_fk": {"name": "tool_connection_app_syncs_company_id_companies_id_fk","tableFrom": "tool_connection_app_syncs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_connection_app_syncs_company_connection_fk": {"name": "tool_connection_app_syncs_company_connection_fk","tableFrom": "tool_connection_app_syncs",+ "tableTo": "tool_connections","columnsFrom": ["company_id","connection_id"],- "tableTo": "tool_connections","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -53914,9 +54033,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_connection_installs_connection_idx": {"name": "tool_connection_installs_connection_idx",@@ -53935,9 +54054,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_connection_installs_target_uq": {"name": "tool_connection_installs_target_uq",@@ -53968,50 +54087,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_connection_installs_company_id_companies_id_fk": {"name": "tool_connection_installs_company_id_companies_id_fk","tableFrom": "tool_connection_installs",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_connection_installs_connection_id_tool_connections_id_fk": {"name": "tool_connection_installs_connection_id_tool_connections_id_fk","tableFrom": "tool_connection_installs",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_connection_installs_created_by_agent_id_agents_id_fk": {"name": "tool_connection_installs_created_by_agent_id_agents_id_fk","tableFrom": "tool_connection_installs",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -54238,9 +54357,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_connections_application_idx": {"name": "tool_connections_application_idx",@@ -54253,9 +54372,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_connections_company_enabled_idx": {"name": "tool_connections_company_enabled_idx",@@ -54274,9 +54393,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_connections_company_uid_uq": {"name": "tool_connections_company_uid_uq",@@ -54295,61 +54414,61 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_connections_company_id_companies_id_fk": {"name": "tool_connections_company_id_companies_id_fk","tableFrom": "tool_connections",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_connections_application_id_tool_applications_id_fk": {"name": "tool_connections_application_id_tool_applications_id_fk","tableFrom": "tool_connections",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"tool_connections_created_by_agent_id_agents_id_fk": {"name": "tool_connections_created_by_agent_id_agents_id_fk","tableFrom": "tool_connections",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"tool_connections_company_id_uq": {"name": "tool_connections_company_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -54470,9 +54589,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_rate_limit_counters_window_uq": {"name": "tool_gateway_rate_limit_counters_window_uq",@@ -54497,24 +54616,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_gateway_rate_limit_counters_company_id_companies_id_fk": {"name": "tool_gateway_rate_limit_counters_company_id_companies_id_fk","tableFrom": "tool_gateway_rate_limit_counters",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -54663,9 +54782,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_sessions_company_agent_idx": {"name": "tool_gateway_sessions_company_agent_idx",@@ -54684,9 +54803,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_sessions_company_expires_idx": {"name": "tool_gateway_sessions_company_expires_idx",@@ -54705,9 +54824,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_sessions_run_idx": {"name": "tool_gateway_sessions_run_idx",@@ -54726,9 +54845,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_sessions_issue_idx": {"name": "tool_gateway_sessions_issue_idx",@@ -54747,9 +54866,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_gateway_sessions_gateway_idx": {"name": "tool_gateway_sessions_gateway_idx",@@ -54768,102 +54887,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_gateway_sessions_company_id_companies_id_fk": {"name": "tool_gateway_sessions_company_id_companies_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_gateway_sessions_agent_id_agents_id_fk": {"name": "tool_gateway_sessions_agent_id_agents_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_gateway_sessions_run_id_heartbeat_runs_id_fk": {"name": "tool_gateway_sessions_run_id_heartbeat_runs_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_gateway_sessions_issue_id_issues_id_fk": {"name": "tool_gateway_sessions_issue_id_issues_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_gateway_sessions_project_id_projects_id_fk": {"name": "tool_gateway_sessions_project_id_projects_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_gateway_sessions_gateway_id_tool_mcp_gateways_id_fk": {"name": "tool_gateway_sessions_gateway_id_tool_mcp_gateways_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "tool_mcp_gateways","columnsFrom": ["gateway_id"],- "tableTo": "tool_mcp_gateways","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_gateway_sessions_gateway_token_id_tool_mcp_gateway_tokens_id_fk": {"name": "tool_gateway_sessions_gateway_token_id_tool_mcp_gateway_tokens_id_fk","tableFrom": "tool_gateway_sessions",+ "tableTo": "tool_mcp_gateway_tokens","columnsFrom": ["gateway_token_id"],- "tableTo": "tool_mcp_gateway_tokens","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -55178,9 +55297,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_invocations_run_idx": {"name": "tool_invocations_run_idx",@@ -55199,9 +55318,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_invocations_issue_idx": {"name": "tool_invocations_issue_idx",@@ -55220,9 +55339,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_invocations_gateway_idx": {"name": "tool_invocations_gateway_idx",@@ -55241,9 +55360,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_invocations_company_idempotency_uq": {"name": "tool_invocations_company_idempotency_uq",@@ -55262,128 +55381,128 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_invocations_company_id_companies_id_fk": {"name": "tool_invocations_company_id_companies_id_fk","tableFrom": "tool_invocations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_invocations_agent_id_agents_id_fk": {"name": "tool_invocations_agent_id_agents_id_fk","tableFrom": "tool_invocations",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_issue_id_issues_id_fk": {"name": "tool_invocations_issue_id_issues_id_fk","tableFrom": "tool_invocations",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_run_id_heartbeat_runs_id_fk": {"name": "tool_invocations_run_id_heartbeat_runs_id_fk","tableFrom": "tool_invocations",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_gateway_id_tool_mcp_gateways_id_fk": {"name": "tool_invocations_gateway_id_tool_mcp_gateways_id_fk","tableFrom": "tool_invocations",+ "tableTo": "tool_mcp_gateways","columnsFrom": ["gateway_id"],- "tableTo": "tool_mcp_gateways","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_gateway_token_id_tool_mcp_gateway_tokens_id_fk": {"name": "tool_invocations_gateway_token_id_tool_mcp_gateway_tokens_id_fk","tableFrom": "tool_invocations",+ "tableTo": "tool_mcp_gateway_tokens","columnsFrom": ["gateway_token_id"],- "tableTo": "tool_mcp_gateway_tokens","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_application_id_tool_applications_id_fk": {"name": "tool_invocations_application_id_tool_applications_id_fk","tableFrom": "tool_invocations",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_connection_id_tool_connections_id_fk": {"name": "tool_invocations_connection_id_tool_connections_id_fk","tableFrom": "tool_invocations",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_invocations_catalog_entry_id_tool_catalog_entries_id_fk": {"name": "tool_invocations_catalog_entry_id_tool_catalog_entries_id_fk","tableFrom": "tool_invocations",+ "tableTo": "tool_catalog_entries","columnsFrom": ["catalog_entry_id"],- "tableTo": "tool_catalog_entries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -55549,9 +55668,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateway_tokens_expiry_idx": {"name": "tool_mcp_gateway_tokens_expiry_idx",@@ -55570,9 +55689,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateway_tokens_gateway_idx": {"name": "tool_mcp_gateway_tokens_gateway_idx",@@ -55591,9 +55710,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateway_tokens_subject_idx": {"name": "tool_mcp_gateway_tokens_subject_idx",@@ -55618,9 +55737,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateway_tokens_company_expires_idx": {"name": "tool_mcp_gateway_tokens_company_expires_idx",@@ -55639,63 +55758,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_mcp_gateway_tokens_company_id_companies_id_fk": {"name": "tool_mcp_gateway_tokens_company_id_companies_id_fk","tableFrom": "tool_mcp_gateway_tokens",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_mcp_gateway_tokens_gateway_id_tool_mcp_gateways_id_fk": {"name": "tool_mcp_gateway_tokens_gateway_id_tool_mcp_gateways_id_fk","tableFrom": "tool_mcp_gateway_tokens",+ "tableTo": "tool_mcp_gateways","columnsFrom": ["gateway_id"],- "tableTo": "tool_mcp_gateways","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_mcp_gateway_tokens_expiry_override_by_agent_id_agents_id_fk": {"name": "tool_mcp_gateway_tokens_expiry_override_by_agent_id_agents_id_fk","tableFrom": "tool_mcp_gateway_tokens",+ "tableTo": "agents","columnsFrom": ["expiry_override_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_mcp_gateway_tokens_created_by_agent_id_agents_id_fk": {"name": "tool_mcp_gateway_tokens_created_by_agent_id_agents_id_fk","tableFrom": "tool_mcp_gateway_tokens",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -55890,9 +56009,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateways_company_status_idx": {"name": "tool_mcp_gateways_company_status_idx",@@ -55911,9 +56030,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateways_profile_idx": {"name": "tool_mcp_gateways_profile_idx",@@ -55932,9 +56051,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateways_public_id_uq": {"name": "tool_mcp_gateways_public_id_uq",@@ -55947,9 +56066,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateways_company_slug_uq": {"name": "tool_mcp_gateways_company_slug_uq",@@ -55968,9 +56087,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_mcp_gateways_company_name_uq": {"name": "tool_mcp_gateways_company_name_uq",@@ -55989,102 +56108,102 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_mcp_gateways_company_id_companies_id_fk": {"name": "tool_mcp_gateways_company_id_companies_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_mcp_gateways_profile_id_tool_profiles_id_fk": {"name": "tool_mcp_gateways_profile_id_tool_profiles_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "tool_profiles","columnsFrom": ["profile_id"],- "tableTo": "tool_profiles","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "restrict"+ "onDelete": "restrict",+ "onUpdate": "no action"},"tool_mcp_gateways_agent_id_agents_id_fk": {"name": "tool_mcp_gateways_agent_id_agents_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_mcp_gateways_project_id_projects_id_fk": {"name": "tool_mcp_gateways_project_id_projects_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_mcp_gateways_issue_id_issues_id_fk": {"name": "tool_mcp_gateways_issue_id_issues_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_mcp_gateways_approval_issue_id_issues_id_fk": {"name": "tool_mcp_gateways_approval_issue_id_issues_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "issues","columnsFrom": ["approval_issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_mcp_gateways_created_by_agent_id_agents_id_fk": {"name": "tool_mcp_gateways_created_by_agent_id_agents_id_fk","tableFrom": "tool_mcp_gateways",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -56201,9 +56320,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_oauth_states_connection_idx": {"name": "tool_oauth_states_connection_idx",@@ -56216,9 +56335,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_oauth_states_actor_idx": {"name": "tool_oauth_states_actor_idx",@@ -56237,9 +56356,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_oauth_states_subject_agent_idx": {"name": "tool_oauth_states_subject_agent_idx",@@ -56258,9 +56377,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_oauth_states_expires_at_idx": {"name": "tool_oauth_states_expires_at_idx",@@ -56273,50 +56392,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_oauth_states_company_id_companies_id_fk": {"name": "tool_oauth_states_company_id_companies_id_fk","tableFrom": "tool_oauth_states",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_oauth_states_connection_id_tool_connections_id_fk": {"name": "tool_oauth_states_connection_id_tool_connections_id_fk","tableFrom": "tool_oauth_states",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_oauth_states_subject_agent_id_agents_id_fk": {"name": "tool_oauth_states_subject_agent_id_agents_id_fk","tableFrom": "tool_oauth_states",+ "tableTo": "agents","columnsFrom": ["subject_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -56438,9 +56557,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_policies_company_type_idx": {"name": "tool_policies_company_type_idx",@@ -56459,9 +56578,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_policies_company_name_uq": {"name": "tool_policies_company_name_uq",@@ -56480,37 +56599,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_policies_company_id_companies_id_fk": {"name": "tool_policies_company_id_companies_id_fk","tableFrom": "tool_policies",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_policies_created_by_agent_id_agents_id_fk": {"name": "tool_policies_created_by_agent_id_agents_id_fk","tableFrom": "tool_policies",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -56619,9 +56738,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profile_bindings_target_profile_uq": {"name": "tool_profile_bindings_target_profile_uq",@@ -56652,50 +56771,50 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_profile_bindings_company_id_companies_id_fk": {"name": "tool_profile_bindings_company_id_companies_id_fk","tableFrom": "tool_profile_bindings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_bindings_profile_id_tool_profiles_id_fk": {"name": "tool_profile_bindings_profile_id_tool_profiles_id_fk","tableFrom": "tool_profile_bindings",+ "tableTo": "tool_profiles","columnsFrom": ["profile_id"],- "tableTo": "tool_profiles","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_bindings_created_by_agent_id_agents_id_fk": {"name": "tool_profile_bindings_created_by_agent_id_agents_id_fk","tableFrom": "tool_profile_bindings",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -56809,9 +56928,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profile_entries_application_idx": {"name": "tool_profile_entries_application_idx",@@ -56830,9 +56949,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profile_entries_connection_idx": {"name": "tool_profile_entries_connection_idx",@@ -56851,9 +56970,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profile_entries_catalog_entry_idx": {"name": "tool_profile_entries_catalog_entry_idx",@@ -56872,76 +56991,76 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_profile_entries_company_id_companies_id_fk": {"name": "tool_profile_entries_company_id_companies_id_fk","tableFrom": "tool_profile_entries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_entries_profile_id_tool_profiles_id_fk": {"name": "tool_profile_entries_profile_id_tool_profiles_id_fk","tableFrom": "tool_profile_entries",+ "tableTo": "tool_profiles","columnsFrom": ["profile_id"],- "tableTo": "tool_profiles","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_entries_application_id_tool_applications_id_fk": {"name": "tool_profile_entries_application_id_tool_applications_id_fk","tableFrom": "tool_profile_entries",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_entries_connection_id_tool_connections_id_fk": {"name": "tool_profile_entries_connection_id_tool_connections_id_fk","tableFrom": "tool_profile_entries",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_profile_entries_catalog_entry_id_tool_catalog_entries_id_fk": {"name": "tool_profile_entries_catalog_entry_id_tool_catalog_entries_id_fk","tableFrom": "tool_profile_entries",+ "tableTo": "tool_catalog_entries","columnsFrom": ["catalog_entry_id"],- "tableTo": "tool_catalog_entries","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -57045,9 +57164,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profiles_company_key_uq": {"name": "tool_profiles_company_key_uq",@@ -57066,9 +57185,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_profiles_company_name_uq": {"name": "tool_profiles_company_name_uq",@@ -57087,24 +57206,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_profiles_company_id_companies_id_fk": {"name": "tool_profiles_company_id_companies_id_fk","tableFrom": "tool_profiles",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -57211,9 +57330,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_rate_limit_counters_window_uq": {"name": "tool_rate_limit_counters_window_uq",@@ -57250,37 +57369,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_rate_limit_counters_company_id_companies_id_fk": {"name": "tool_rate_limit_counters_company_id_companies_id_fk","tableFrom": "tool_rate_limit_counters",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_rate_limit_counters_policy_id_tool_policies_id_fk": {"name": "tool_rate_limit_counters_policy_id_tool_policies_id_fk","tableFrom": "tool_rate_limit_counters",+ "tableTo": "tool_policies","columnsFrom": ["policy_id"],- "tableTo": "tool_policies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -57364,9 +57483,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_runtime_metric_counters_bucket_uq": {"name": "tool_runtime_metric_counters_bucket_uq",@@ -57391,24 +57510,24 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_runtime_metric_counters_company_id_companies_id_fk": {"name": "tool_runtime_metric_counters_company_id_companies_id_fk","tableFrom": "tool_runtime_metric_counters",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -57634,9 +57753,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_runtime_slots_connection_idx": {"name": "tool_runtime_slots_connection_idx",@@ -57649,9 +57768,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_runtime_slots_execution_workspace_idx": {"name": "tool_runtime_slots_execution_workspace_idx",@@ -57670,9 +57789,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_runtime_slots_slot_key_uq": {"name": "tool_runtime_slots_slot_key_uq",@@ -57691,89 +57810,89 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_runtime_slots_company_id_companies_id_fk": {"name": "tool_runtime_slots_company_id_companies_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_runtime_slots_application_id_tool_applications_id_fk": {"name": "tool_runtime_slots_application_id_tool_applications_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "tool_applications","columnsFrom": ["application_id"],- "tableTo": "tool_applications","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_runtime_slots_connection_id_tool_connections_id_fk": {"name": "tool_runtime_slots_connection_id_tool_connections_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "tool_connections","columnsFrom": ["connection_id"],- "tableTo": "tool_connections","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_runtime_slots_project_workspace_id_project_workspaces_id_fk": {"name": "tool_runtime_slots_project_workspace_id_project_workspaces_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "project_workspaces","columnsFrom": ["project_workspace_id"],- "tableTo": "project_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_runtime_slots_execution_workspace_id_execution_workspaces_id_fk": {"name": "tool_runtime_slots_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"tool_runtime_slots_issue_id_issues_id_fk": {"name": "tool_runtime_slots_issue_id_issues_id_fk","tableFrom": "tool_runtime_slots",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -57896,9 +58015,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_stdio_command_templates_company_status_idx": {"name": "tool_stdio_command_templates_company_status_idx",@@ -57917,9 +58036,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"tool_stdio_command_templates_company_key_uq": {"name": "tool_stdio_command_templates_company_key_uq",@@ -57938,37 +58057,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"tool_stdio_command_templates_company_id_companies_id_fk": {"name": "tool_stdio_command_templates_company_id_companies_id_fk","tableFrom": "tool_stdio_command_templates",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"tool_stdio_command_templates_created_by_agent_id_agents_id_fk": {"name": "tool_stdio_command_templates_created_by_agent_id_agents_id_fk","tableFrom": "tool_stdio_command_templates",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -58046,9 +58165,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_company_preferences_primary_agent_idx": {"name": "user_company_preferences_primary_agent_idx",@@ -58061,37 +58180,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"user_company_preferences_company_id_companies_id_fk": {"name": "user_company_preferences_company_id_companies_id_fk","tableFrom": "user_company_preferences",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"user_company_preferences_primary_agent_id_agents_id_fk": {"name": "user_company_preferences_primary_agent_id_agents_id_fk","tableFrom": "user_company_preferences",+ "tableTo": "agents","columnsFrom": ["primary_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -58170,9 +58289,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_inbox_agent_policies_allowed_agent_ids_idx": {"name": "user_inbox_agent_policies_allowed_agent_ids_idx",@@ -58185,24 +58304,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "gin",- "concurrently": false+ "with": {}}},"foreignKeys": {"user_inbox_agent_policies_company_id_companies_id_fk": {"name": "user_inbox_agent_policies_company_id_companies_id_fk","tableFrom": "user_inbox_agent_policies",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -58317,9 +58436,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_declarations_definition_idx": {"name": "user_secret_declarations_definition_idx",@@ -58332,9 +58451,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_declarations_target_idx": {"name": "user_secret_declarations_target_idx",@@ -58359,9 +58478,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_declarations_company_required_idx": {"name": "user_secret_declarations_company_required_idx",@@ -58380,9 +58499,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_declarations_target_path_uq": {"name": "user_secret_declarations_target_path_uq",@@ -58413,9 +58532,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_declarations_required_override_idx": {"name": "user_secret_declarations_required_override_idx",@@ -58434,38 +58553,38 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"user_secret_declarations\".\"allow_missing_override\" = true",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"user_secret_declarations_company_id_companies_id_fk": {"name": "user_secret_declarations_company_id_companies_id_fk","tableFrom": "user_secret_declarations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"user_secret_declarations_user_secret_definition_id_user_secret_definitions_id_fk": {"name": "user_secret_declarations_user_secret_definition_id_user_secret_definitions_id_fk","tableFrom": "user_secret_declarations",+ "tableTo": "user_secret_definitions","columnsFrom": ["user_secret_definition_id"],- "tableTo": "user_secret_definitions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -58611,9 +58730,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_definitions_company_provider_idx": {"name": "user_secret_definitions_company_provider_idx",@@ -58632,9 +58751,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_definitions_provider_config_idx": {"name": "user_secret_definitions_provider_config_idx",@@ -58647,9 +58766,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"user_secret_definitions_company_key_uq": {"name": "user_secret_definitions_company_key_uq",@@ -58668,64 +58787,64 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"user_secret_definitions\".\"deleted_at\" is null",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"user_secret_definitions_company_id_companies_id_fk": {"name": "user_secret_definitions_company_id_companies_id_fk","tableFrom": "user_secret_definitions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"user_secret_definitions_provider_config_id_company_secret_provider_configs_id_fk": {"name": "user_secret_definitions_provider_config_id_company_secret_provider_configs_id_fk","tableFrom": "user_secret_definitions",+ "tableTo": "company_secret_provider_configs","columnsFrom": ["provider_config_id"],- "tableTo": "company_secret_provider_configs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"user_secret_definitions_created_by_agent_id_agents_id_fk": {"name": "user_secret_definitions_created_by_agent_id_agents_id_fk","tableFrom": "user_secret_definitions",+ "tableTo": "agents","columnsFrom": ["created_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"user_secret_definitions_updated_by_agent_id_agents_id_fk": {"name": "user_secret_definitions_updated_by_agent_id_agents_id_fk","tableFrom": "user_secret_definitions",+ "tableTo": "agents","columnsFrom": ["updated_by_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -58785,9 +58904,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -58942,137 +59061,137 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"work_assessments_company_id_companies_id_fk": {"name": "work_assessments_company_id_companies_id_fk","tableFrom": "work_assessments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_trigger_actor_company_id_companies_id_fk": {"name": "work_assessments_trigger_actor_company_id_companies_id_fk","tableFrom": "work_assessments",+ "tableTo": "companies","columnsFrom": ["trigger_actor_company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_issue_company_fk": {"name": "work_assessments_issue_company_fk","tableFrom": "work_assessments",+ "tableTo": "issues","columnsFrom": ["company_id","issue_id"],- "tableTo": "issues","columnsTo": ["company_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_run_owner_fk": {"name": "work_assessments_run_owner_fk","tableFrom": "work_assessments",+ "tableTo": "heartbeat_runs","columnsFrom": ["company_id","issue_id","run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["company_id","native_issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_contract_owner_fk": {"name": "work_assessments_contract_owner_fk","tableFrom": "work_assessments",+ "tableTo": "completion_contracts","columnsFrom": ["company_id","issue_id","contract_id"],- "tableTo": "completion_contracts","columnsTo": ["company_id","issue_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_result_owner_fk": {"name": "work_assessments_result_owner_fk","tableFrom": "work_assessments",+ "tableTo": "native_run_results","columnsFrom": ["company_id","issue_id","run_id","result_id"],- "tableTo": "native_run_results","columnsTo": ["company_id","issue_id","run_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"work_assessments_supersedes_owner_fk": {"name": "work_assessments_supersedes_owner_fk","tableFrom": "work_assessments",+ "tableTo": "work_assessments","columnsFrom": ["company_id","issue_id","run_id","supersedes_assessment_id"],- "tableTo": "work_assessments","columnsTo": ["company_id","issue_id","run_id","id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {"work_assessments_company_issue_run_id_uq": {"name": "work_assessments_company_issue_run_id_uq",+ "nullsNotDistinct": false,"columns": ["company_id","issue_id","run_id","id"- ],- "nullsNotDistinct": false+ ]}},"policies": {},@@ -59251,9 +59370,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_operations_company_workspace_started_idx": {"name": "workspace_operations_company_workspace_started_idx",@@ -59278,9 +59397,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_operations_company_workspace_issue_started_idx": {"name": "workspace_operations_company_workspace_issue_started_idx",@@ -59311,63 +59430,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"workspace_operations_company_id_companies_id_fk": {"name": "workspace_operations_company_id_companies_id_fk","tableFrom": "workspace_operations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"workspace_operations_execution_workspace_id_execution_workspaces_id_fk": {"name": "workspace_operations_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "workspace_operations",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk": {"name": "workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk","tableFrom": "workspace_operations",+ "tableTo": "heartbeat_runs","columnsFrom": ["heartbeat_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_operations_issue_id_issues_id_fk": {"name": "workspace_operations_issue_id_issues_id_fk","tableFrom": "workspace_operations",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -59590,9 +59709,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_runtime_services_company_execution_workspace_status_idx": {"name": "workspace_runtime_services_company_execution_workspace_status_idx",@@ -59617,9 +59736,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_runtime_services_company_project_status_idx": {"name": "workspace_runtime_services_company_project_status_idx",@@ -59644,9 +59763,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_runtime_services_run_idx": {"name": "workspace_runtime_services_run_idx",@@ -59659,9 +59778,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"workspace_runtime_services_company_updated_idx": {"name": "workspace_runtime_services_company_updated_idx",@@ -59680,102 +59799,102 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"workspace_runtime_services_company_id_companies_id_fk": {"name": "workspace_runtime_services_company_id_companies_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"},"workspace_runtime_services_project_id_projects_id_fk": {"name": "workspace_runtime_services_project_id_projects_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "projects","columnsFrom": ["project_id"],- "tableTo": "projects","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_runtime_services_project_workspace_id_project_workspaces_id_fk": {"name": "workspace_runtime_services_project_workspace_id_project_workspaces_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "project_workspaces","columnsFrom": ["project_workspace_id"],- "tableTo": "project_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_runtime_services_execution_workspace_id_execution_workspaces_id_fk": {"name": "workspace_runtime_services_execution_workspace_id_execution_workspaces_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "execution_workspaces","columnsFrom": ["execution_workspace_id"],- "tableTo": "execution_workspaces","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_runtime_services_issue_id_issues_id_fk": {"name": "workspace_runtime_services_issue_id_issues_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "issues","columnsFrom": ["issue_id"],- "tableTo": "issues","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_runtime_services_owner_agent_id_agents_id_fk": {"name": "workspace_runtime_services_owner_agent_id_agents_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "agents","columnsFrom": ["owner_agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"},"workspace_runtime_services_started_by_run_id_heartbeat_runs_id_fk": {"name": "workspace_runtime_services_started_by_run_id_heartbeat_runs_id_fk","tableFrom": "workspace_runtime_services",+ "tableTo": "heartbeat_runs","columnsFrom": ["started_by_run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -59923,9 +60042,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_attachment_upload_expiry_idx": {"name": "mcp_attachment_upload_expiry_idx",@@ -59938,50 +60057,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_attachment_uploads_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_attachment_uploads_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_attachment_uploads",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_attachment_uploads_company_id_companies_id_fk": {"name": "mcp_attachment_uploads_company_id_companies_id_fk","tableFrom": "mcp_attachment_uploads",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_attachment_uploads_user_id_user_id_fk": {"name": "mcp_attachment_uploads_user_id_user_id_fk","tableFrom": "mcp_attachment_uploads",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60057,9 +60176,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_event_admissions_grant_idx": {"name": "mcp_event_admissions_grant_idx",@@ -60072,9 +60191,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_event_admissions_company_idx": {"name": "mcp_event_admissions_company_idx",@@ -60087,37 +60206,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_event_admissions_company_id_companies_id_fk": {"name": "mcp_event_admissions_company_id_companies_id_fk","tableFrom": "mcp_event_admissions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_event_admissions_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_event_admissions_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_event_admissions",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60206,9 +60325,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_event_deliveries_activity_uq": {"name": "mcp_event_deliveries_activity_uq",@@ -60227,9 +60346,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_event_deliveries_due_idx": {"name": "mcp_event_deliveries_due_idx",@@ -60242,24 +60361,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_event_deliveries_subscription_id_mcp_event_subscriptions_id_fk": {"name": "mcp_event_deliveries_subscription_id_mcp_event_subscriptions_id_fk","tableFrom": "mcp_event_deliveries",+ "tableTo": "mcp_event_subscriptions","columnsFrom": ["subscription_id"],- "tableTo": "mcp_event_subscriptions","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60370,9 +60489,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_event_subscriptions_company_idx": {"name": "mcp_event_subscriptions_company_idx",@@ -60385,37 +60504,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_event_subscriptions_company_id_companies_id_fk": {"name": "mcp_event_subscriptions_company_id_companies_id_fk","tableFrom": "mcp_event_subscriptions",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_event_subscriptions_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_event_subscriptions_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_event_subscriptions",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60495,9 +60614,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_file_ticket_grant_idx": {"name": "mcp_file_ticket_grant_idx",@@ -60510,50 +60629,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_file_tickets_company_id_companies_id_fk": {"name": "mcp_file_tickets_company_id_companies_id_fk","tableFrom": "mcp_file_tickets",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_file_tickets_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_file_tickets_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_file_tickets",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_file_tickets_upload_id_mcp_attachment_uploads_id_fk": {"name": "mcp_file_tickets_upload_id_mcp_attachment_uploads_id_fk","tableFrom": "mcp_file_tickets",+ "tableTo": "mcp_attachment_uploads","columnsFrom": ["upload_id"],- "tableTo": "mcp_attachment_uploads","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60660,9 +60779,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_mutation_receipts_company_idx": {"name": "mcp_mutation_receipts_company_idx",@@ -60675,50 +60794,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_mutation_receipts_company_id_companies_id_fk": {"name": "mcp_mutation_receipts_company_id_companies_id_fk","tableFrom": "mcp_mutation_receipts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_mutation_receipts_user_id_user_id_fk": {"name": "mcp_mutation_receipts_user_id_user_id_fk","tableFrom": "mcp_mutation_receipts",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_mutation_receipts_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_mutation_receipts_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_mutation_receipts",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -60884,9 +61003,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_oauth_user_code_uq": {"name": "mcp_oauth_user_code_uq",@@ -60899,9 +61018,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_oauth_device_expiry_idx": {"name": "mcp_oauth_device_expiry_idx",@@ -60914,37 +61033,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_oauth_device_requests_client_id_mcp_oauth_clients_id_fk": {"name": "mcp_oauth_device_requests_client_id_mcp_oauth_clients_id_fk","tableFrom": "mcp_oauth_device_requests",+ "tableTo": "mcp_oauth_clients","columnsFrom": ["client_id"],- "tableTo": "mcp_oauth_clients","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_oauth_device_requests_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_oauth_device_requests_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_oauth_device_requests",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61039,63 +61158,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_oauth_grants_company_id_companies_id_fk": {"name": "mcp_oauth_grants_company_id_companies_id_fk","tableFrom": "mcp_oauth_grants",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_oauth_grants_user_id_user_id_fk": {"name": "mcp_oauth_grants_user_id_user_id_fk","tableFrom": "mcp_oauth_grants",+ "tableTo": "user","columnsFrom": ["user_id"],- "tableTo": "user","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_oauth_grants_client_id_mcp_oauth_clients_id_fk": {"name": "mcp_oauth_grants_client_id_mcp_oauth_clients_id_fk","tableFrom": "mcp_oauth_grants",+ "tableTo": "mcp_oauth_clients","columnsFrom": ["client_id"],- "tableTo": "mcp_oauth_clients","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_oauth_grants_agent_id_agents_id_fk": {"name": "mcp_oauth_grants_agent_id_agents_id_fk","tableFrom": "mcp_oauth_grants",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61140,9 +61259,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {},@@ -61254,9 +61373,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_oauth_requests_expiry_idx": {"name": "mcp_oauth_requests_expiry_idx",@@ -61269,37 +61388,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_oauth_requests_client_id_mcp_oauth_clients_id_fk": {"name": "mcp_oauth_requests_client_id_mcp_oauth_clients_id_fk","tableFrom": "mcp_oauth_requests",+ "tableTo": "mcp_oauth_clients","columnsFrom": ["client_id"],- "tableTo": "mcp_oauth_clients","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"mcp_oauth_requests_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_oauth_requests_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_oauth_requests",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61369,9 +61488,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_oauth_tokens_grant_idx": {"name": "mcp_oauth_tokens_grant_idx",@@ -61384,9 +61503,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"mcp_oauth_tokens_expiry_idx": {"name": "mcp_oauth_tokens_expiry_idx",@@ -61399,24 +61518,24 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"mcp_oauth_tokens_grant_id_mcp_oauth_grants_id_fk": {"name": "mcp_oauth_tokens_grant_id_mcp_oauth_grants_id_fk","tableFrom": "mcp_oauth_tokens",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61549,9 +61668,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"external_holds_agent_idx": {"name": "external_holds_agent_idx",@@ -61570,37 +61689,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"external_agent_holds_company_id_companies_id_fk": {"name": "external_agent_holds_company_id_companies_id_fk","tableFrom": "external_agent_holds",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"external_agent_holds_agent_id_agents_id_fk": {"name": "external_agent_holds_agent_id_agents_id_fk","tableFrom": "external_agent_holds",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61813,10 +61932,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"muse_agent_bindings\".\"revoked_at\" IS NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"muse_bindings_ticket_uq": {"name": "muse_bindings_ticket_uq",@@ -61829,9 +61948,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"muse_bindings_active_grant_uq": {"name": "muse_bindings_active_grant_uq",@@ -61844,51 +61963,51 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"muse_agent_bindings\".\"revoked_at\" IS NULL AND \"muse_agent_bindings\".\"grant_id\" IS NOT NULL",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}}},"foreignKeys": {"muse_agent_bindings_company_id_companies_id_fk": {"name": "muse_agent_bindings_company_id_companies_id_fk","tableFrom": "muse_agent_bindings",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_agent_bindings_agent_id_agents_id_fk": {"name": "muse_agent_bindings_agent_id_agents_id_fk","tableFrom": "muse_agent_bindings",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_agent_bindings_grant_id_mcp_oauth_grants_id_fk": {"name": "muse_agent_bindings_grant_id_mcp_oauth_grants_id_fk","tableFrom": "muse_agent_bindings",+ "tableTo": "mcp_oauth_grants","columnsFrom": ["grant_id"],- "tableTo": "mcp_oauth_grants","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "set null"+ "onDelete": "set null",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -61982,9 +62101,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"muse_credentials_binding_idx": {"name": "muse_credentials_binding_idx",@@ -62003,37 +62122,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_credentials_company_id_companies_id_fk": {"name": "muse_credentials_company_id_companies_id_fk","tableFrom": "muse_credentials",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_credentials_binding_id_muse_agent_bindings_id_fk": {"name": "muse_credentials_binding_id_muse_agent_bindings_id_fk","tableFrom": "muse_credentials",+ "tableTo": "muse_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "muse_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -62121,37 +62240,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_idle_receipts_company_id_companies_id_fk": {"name": "muse_idle_receipts_company_id_companies_id_fk","tableFrom": "muse_idle_receipts",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_idle_receipts_binding_id_muse_agent_bindings_id_fk": {"name": "muse_idle_receipts_binding_id_muse_agent_bindings_id_fk","tableFrom": "muse_idle_receipts",+ "tableTo": "muse_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "muse_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -62251,9 +62370,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"muse_input_source_uq": {"name": "muse_input_source_uq",@@ -62272,37 +62391,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_input_deliveries_company_id_companies_id_fk": {"name": "muse_input_deliveries_company_id_companies_id_fk","tableFrom": "muse_input_deliveries",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_input_deliveries_assignment_id_muse_runner_assignments_id_fk": {"name": "muse_input_deliveries_assignment_id_muse_runner_assignments_id_fk","tableFrom": "muse_input_deliveries",+ "tableTo": "muse_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "muse_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -62408,9 +62527,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"muse_mailbox_cursor_idx": {"name": "muse_mailbox_cursor_idx",@@ -62435,50 +62554,50 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_mailbox_items_company_id_companies_id_fk": {"name": "muse_mailbox_items_company_id_companies_id_fk","tableFrom": "muse_mailbox_items",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_mailbox_items_binding_id_muse_agent_bindings_id_fk": {"name": "muse_mailbox_items_binding_id_muse_agent_bindings_id_fk","tableFrom": "muse_mailbox_items",+ "tableTo": "muse_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "muse_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_mailbox_items_assignment_id_muse_runner_assignments_id_fk": {"name": "muse_mailbox_items_assignment_id_muse_runner_assignments_id_fk","tableFrom": "muse_mailbox_items",+ "tableTo": "muse_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "muse_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -62610,37 +62729,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_receiver_contact_buckets_company_id_companies_id_fk": {"name": "muse_receiver_contact_buckets_company_id_companies_id_fk","tableFrom": "muse_receiver_contact_buckets",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_receiver_contact_buckets_binding_id_muse_agent_bindings_id_fk": {"name": "muse_receiver_contact_buckets_binding_id_muse_agent_bindings_id_fk","tableFrom": "muse_receiver_contact_buckets",+ "tableTo": "muse_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "muse_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -62809,9 +62928,9 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"muse_assignments_live_binding_uq": {"name": "muse_assignments_live_binding_uq",@@ -62824,10 +62943,10 @@}],"isUnique": true,- "with": {},- "method": "btree","where": "\"muse_runner_assignments\".\"status\" IN ('offered','claimed','accepted')",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"muse_assignments_company_idx": {"name": "muse_assignments_company_idx",@@ -62840,63 +62959,63 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_runner_assignments_company_id_companies_id_fk": {"name": "muse_runner_assignments_company_id_companies_id_fk","tableFrom": "muse_runner_assignments",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_runner_assignments_binding_id_muse_agent_bindings_id_fk": {"name": "muse_runner_assignments_binding_id_muse_agent_bindings_id_fk","tableFrom": "muse_runner_assignments",+ "tableTo": "muse_agent_bindings","columnsFrom": ["binding_id"],- "tableTo": "muse_agent_bindings","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_runner_assignments_run_id_heartbeat_runs_id_fk": {"name": "muse_runner_assignments_run_id_heartbeat_runs_id_fk","tableFrom": "muse_runner_assignments",+ "tableTo": "heartbeat_runs","columnsFrom": ["run_id"],- "tableTo": "heartbeat_runs","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_runner_assignments_agent_id_agents_id_fk": {"name": "muse_runner_assignments_agent_id_agents_id_fk","tableFrom": "muse_runner_assignments",+ "tableTo": "agents","columnsFrom": ["agent_id"],- "tableTo": "agents","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -63004,37 +63123,37 @@}],"isUnique": true,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"muse_runner_operations_company_id_companies_id_fk": {"name": "muse_runner_operations_company_id_companies_id_fk","tableFrom": "muse_runner_operations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"muse_runner_operations_assignment_id_muse_runner_assignments_id_fk": {"name": "muse_runner_operations_assignment_id_muse_runner_assignments_id_fk","tableFrom": "muse_runner_operations",+ "tableTo": "muse_runner_assignments","columnsFrom": ["assignment_id"],- "tableTo": "muse_runner_assignments","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -63092,15 +63211,15 @@"company_prompt_injection_prevention_company_id_companies_id_fk": {"name": "company_prompt_injection_prevention_company_id_companies_id_fk","tableFrom": "company_prompt_injection_prevention",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -63314,9 +63433,9 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}},"prompt_injection_invocations_pending_idx": {"name": "prompt_injection_invocations_pending_idx",@@ -63329,10 +63448,10 @@}],"isUnique": false,- "with": {},- "method": "btree","where": "\"prompt_injection_invocations\".\"status\" = 'running'",- "concurrently": false+ "concurrently": false,+ "method": "btree",+ "with": {}},"prompt_injection_invocations_cost_idx": {"name": "prompt_injection_invocations_cost_idx",@@ -63345,37 +63464,37 @@}],"isUnique": false,- "with": {},+ "concurrently": false,"method": "btree",- "concurrently": false+ "with": {}}},"foreignKeys": {"prompt_injection_invocations_company_id_companies_id_fk": {"name": "prompt_injection_invocations_company_id_companies_id_fk","tableFrom": "prompt_injection_invocations",+ "tableTo": "companies","columnsFrom": ["company_id"],- "tableTo": "companies","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "cascade"+ "onDelete": "cascade",+ "onUpdate": "no action"},"prompt_injection_invocations_cost_event_id_cost_events_id_fk": {"name": "prompt_injection_invocations_cost_event_id_cost_events_id_fk","tableFrom": "prompt_injection_invocations",+ "tableTo": "cost_events","columnsFrom": ["cost_event_id"],- "tableTo": "cost_events","columnsTo": ["id"],- "onUpdate": "no action",- "onDelete": "no action"+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -63396,21 +63515,21 @@},"enums": {},"schemas": {},- "views": {},"sequences": {"public.chat_telegram_draft_ids": {"name": "chat_telegram_draft_ids",+ "schema": "public","increment": "1",+ "startWith": "1","minValue": "1","maxValue": "2147483647",- "startWith": "1","cache": "1",- "cycle": false,- "schema": "public"+ "cycle": false}},"roles": {},"policies": {},+ "views": {},"_meta": {"columns": {},"schemas": {},diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex 2eac75ef2e..235a6f765c 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -2570,6 +2570,13 @@"when": 1792514266649,"tag": "0368_abandoned_bucky","breakpoints": true+ },+ {+ "idx": 369,+ "version": "7",+ "when": 1792541385924,+ "tag": "0369_late_logan",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/agent_wakeup_requests.ts b/packages/db/src/schema/agent_wakeup_requests.tsindex ee84a39520..fc7feaed02 100644--- a/packages/db/src/schema/agent_wakeup_requests.ts+++ b/packages/db/src/schema/agent_wakeup_requests.ts@@ -46,6 +46,9 @@ export const agentWakeupRequests = pgTable(.defaultNow(),},(table) => ({+ taskRetryIdempotencyUq: uniqueIndex("agent_wakeup_requests_task_retry_idempotency_uq")+ .on(table.companyId, table.idempotencyKey)+ .where(sql`${table.idempotencyKey} LIKE 'task-retry:%'`),companyAgentStatusIdx: index("agent_wakeup_requests_company_agent_status_idx",).on(table.companyId, table.agentId, table.status),diff --git a/packages/db/src/schema/environment_leases.ts b/packages/db/src/schema/environment_leases.tsindex 87819eabc7..948d372f23 100644--- a/packages/db/src/schema/environment_leases.ts+++ b/packages/db/src/schema/environment_leases.ts@@ -1,4 +1,5 @@import { index, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";+import { sql } from "drizzle-orm";import { companies } from "./companies.js";import { environments } from "./environments.js";import { executionWorkspaces } from "./execution_workspaces.js";@@ -36,6 +37,10 @@ export const environmentLeases = pgTable(updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ retainedRecoveryAdoptionIdx: index("environment_leases_retained_recovery_adoption_idx")+ .on(table.heartbeatRunId).concurrently().where(sql`${table.leasePolicy} = 'retain_on_failure'+ and ${table.heartbeatRunId} is not null+ and not (coalesce(${table.metadata}, '{}'::jsonb) ? 'systemRecoveryAdoption')`),companyEnvironmentStatusIdx: index("environment_leases_company_environment_status_idx").on(table.companyId,table.environmentId,diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.tsindex 39af2c33a3..903b2a5249 100644--- a/packages/db/src/schema/heartbeat_runs.ts+++ b/packages/db/src/schema/heartbeat_runs.ts@@ -111,6 +111,10 @@ export const heartbeatRuns = pgTable(updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ retainedRecoveryAdoptionIdx: index("heartbeat_runs_retained_recovery_adoption_idx")+ .on(table.id).where(sql`${table.resultJson}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ and not (coalesce(${table.resultJson}, '{}'::jsonb) ? 'systemRecoveryAdoption')+ and ${table.status} in ('failed', 'interrupted', 'timed_out', 'cancelled', 'succeeded')`),scopeBindingCheck: check("heartbeat_runs_scope_binding_check",sql`(${table.scopeKind} = 'company' AND ${table.issueId} IS NULL)diff --git a/packages/db/src/schema/issue_recovery_actions.ts b/packages/db/src/schema/issue_recovery_actions.tsindex dad3be2c95..67e03e39d4 100644--- a/packages/db/src/schema/issue_recovery_actions.ts+++ b/packages/db/src/schema/issue_recovery_actions.ts@@ -44,6 +44,17 @@ export const issueRecoveryActions = pgTable(updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ sourceRunIdx: index("issue_recovery_actions_source_run_idx")+ .on(table.companyId, table.sourceIssueId, sql`(${table.evidence}->>'runId')`),+ systemRecoveryDueIdx: index("issue_recovery_actions_system_recovery_due_idx")+ .on(sql`(${table.evidence}#>'{systemRecovery,nextAttemptAt}')`, table.id)+ .where(sql`${table.evidence} ? 'systemRecovery'`),+ systemRecoveryAdoptionIdx: index("issue_recovery_actions_system_recovery_adoption_idx")+ .on(table.id)+ .where(sql`not (${table.evidence} ? 'systemRecovery') and (+ ${table.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ or ${table.cause} in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted')+ )`),retainedWorkspaceRecoveryIdx: index("issue_recovery_actions_retained_workspace_recovery_idx").on(table.id).where(sql`(${table.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'or ${table.cause} in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted'))diff --git a/packages/paperclip-runner/src/provider-events.test.ts b/packages/paperclip-runner/src/provider-events.test.tsindex 043399c5e5..a35c21179f 100644--- a/packages/paperclip-runner/src/provider-events.test.ts+++ b/packages/paperclip-runner/src/provider-events.test.ts@@ -87,6 +87,7 @@ describe("provider-neutral events", () => {const [event] = canonicalProviderEventsFromCodex(method, params);expect(event.eventType).toBe("provider.notice.recorded");expect(event.payload.summary).toBe(expected);+ expect(event.payload.userActionable).toBe(false);expect(validatePrpEvent(envelope(event)).ok).toBe(true);}}diff --git a/packages/paperclip-runner/src/provider-events.ts b/packages/paperclip-runner/src/provider-events.tsindex c453173370..a20ac855af 100644--- a/packages/paperclip-runner/src/provider-events.ts+++ b/packages/paperclip-runner/src/provider-events.ts@@ -987,7 +987,10 @@ export function canonicalProviderEventsFromCodex(? "environment": "turn",recoverable: method !== "error",- userActionable: method === "error" || method === "warning",+ // Provider severity does not establish a decision the task user can+ // make. Authentication, approval and model-choice actions have typed+ // admission paths; generic runtime notices remain diagnostics.+ userActionable: false,summary: [params.summary, params.message, params.details].map((value) => text(value).trim()).find(Boolean)?.slice(0, 4000) || "Provider notice",diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex ed30d7c210..bf465cb2f8 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1955,6 +1955,7 @@ export {isValidExistingBranchName,retryWorkspaceExportSchema,recoverWorkspaceSchema,+ taskRetrySchema,reconstructWorkspaceSchema,resumeWorkspaceFinalizationSchema,issueReviewRequestSchema,@@ -2750,7 +2751,7 @@ export {} from "./runtime-exposure/loopback-bind.js";export { ACCOUNT_HANDLE_MAX_LENGTH, toAccountHandle } from "./account-handle.js";export type { ExecutionContinuationEnvelope } from "./types/execution-continuation.js";-export type { ExecutionProjection, ExecutionReconciliation, ExecutionBlocker } from "./types/execution-projection.js";+export type { ExecutionProjection, ExecutionReconciliation, ExecutionBlocker, TaskInterruptionPresentation } from "./types/execution-projection.js";export { EXECUTION_RECONCILIATION_CAUSES, requiresExecutionReconciliation } from "./types/execution-projection.js";export * from "./types/voice-sessions.js";diff --git a/packages/shared/src/types/execution-continuation.ts b/packages/shared/src/types/execution-continuation.tsindex d6f587764c..0546b3b470 100644--- a/packages/shared/src/types/execution-continuation.ts+++ b/packages/shared/src/types/execution-continuation.ts@@ -58,6 +58,9 @@ export interface ExecutionContinuationEnvelope {operationId: string;result: unknown;}>;+ /** Verified snapshots attached separately to the new workspace. Paths are+ * relative to the new working directory and include a provenance record. */+ recoveredFiles?: Array<{ operationId: string; sourceRunId: string; path: string }>;unresolvedInteractionIds: string[];coverage: {kind: "full_task_history" | "task_history_delta";diff --git a/packages/shared/src/types/execution-projection.ts b/packages/shared/src/types/execution-projection.tsindex 277cdec820..23c7d3d688 100644--- a/packages/shared/src/types/execution-projection.ts+++ b/packages/shared/src/types/execution-projection.ts@@ -96,3 +96,15 @@ export interface ExecutionReconciliation {interveningExecutions?: Array<{ runId: string; recoveryActionId: string; evidenceSha256: string }>;};}+/** A task-level view of one interruption. Diagnostics keep the underlying runs+ * and recovery records; ordinary product surfaces render this projection. */+export interface TaskInterruptionPresentation {+ intentId: string | null;+ responsibility: "system" | "user";+ state: "working" | "retry_scheduled" | "failed" | "waiting_for_user" | "resolved";+ nextRetryAt: string | null;+ canRetry: boolean;+ userAction: "approval" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | null;+ sourceRunIds: string[];+ observedRunId: string | null;+}diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.tsindex e7a48e065d..c5a9d6c227 100644--- a/packages/shared/src/types/issue.ts+++ b/packages/shared/src/types/issue.ts@@ -1,6 +1,6 @@import type { ChatProvider } from "./chat-channels.js";import type { TaskWorkspaceIntent, TaskWorkspacePendingSelection } from "./task-workspace.js";-import type { ExecutionProjection, ExecutionBlocker } from "./execution-projection.js";+import type { ExecutionProjection, ExecutionBlocker, TaskInterruptionPresentation } from "./execution-projection.js";import type {IssueCommentAuthorType,IssueCommentMetadataRowType,@@ -927,6 +927,7 @@ export interface Issue {activeRecoveryAction?: IssueRecoveryAction | null;successfulRunHandoff?: SuccessfulRunHandoffState | null;executionBlocker?: ExecutionBlocker | null;+ interruption?: TaskInterruptionPresentation | null;watchdog?: IssueWatchdogSummary | null;scheduledRetry?: IssueScheduledRetry | null;liveDescendantCount?: number;@@ -993,6 +994,7 @@ export type CompactIssue = Pick<| "createdAt"| "updatedAt"> & {+ interruption?: TaskInterruptionPresentation | null;labelIds?: string[];labels?: IssueLabel[];blockedBy?: IssueRelationIssueSummary[];@@ -1159,6 +1161,8 @@ export interface IssueCommentMetadataSection {export interface IssueCommentMetadata {version: 1;+ /** Producer-classified diagnostics; task interruption UI owns system repair. */+ recoveryResponsibility?: "system" | "user";/** Inbound channel attribution; never an authorization input. */sourceChannel?: ChatProvider;sourceRunId?: string | null;diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.tsindex acaaeec307..9b2f1a83b2 100644--- a/packages/shared/src/validators/index.ts+++ b/packages/shared/src/validators/index.ts@@ -443,6 +443,7 @@ export {isValidExistingBranchName,retryWorkspaceExportSchema,recoverWorkspaceSchema,+ taskRetrySchema,reconstructWorkspaceSchema,resumeWorkspaceFinalizationSchema,issueReviewRequestSchema,diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.tsindex b45597f2ad..9e42c7b118 100644--- a/packages/shared/src/validators/issue.ts+++ b/packages/shared/src/validators/issue.ts@@ -582,6 +582,11 @@ export const retryWorkspaceExportSchema = z.object({repairNote: z.string().trim().min(20).max(12000),}).strict();+export const taskRetrySchema = z.object({+ idempotencyKey: z.string().guid(),+ observedRunId: z.string().guid().nullable(),+}).strict();+export const recoverWorkspaceSchema = z.object({actionId: z.string().guid(),runId: z.string().guid(),@@ -1082,6 +1087,7 @@ export const issueCommentMetadataSectionSchema = zexport const issueCommentMetadataSchema = z.object({version: z.literal(1),+ recoveryResponsibility: z.enum(["system", "user"]).optional(),sourceChannel: z.enum(CHAT_PROVIDERS).optional(),sourceRunId: z.string().guid().nullable().optional(),authorizationReason: zdiff --git a/server/scripts/workspace-recovery-provider.test.mjs b/server/scripts/workspace-recovery-provider.test.mjsnew file mode 100644index 0000000000..a9902ae580--- /dev/null+++ b/server/scripts/workspace-recovery-provider.test.mjs@@ -0,0 +1,188 @@+// Opt-in provider qualification, separate from the cheap default suite:+// PAPERCLIP_RECOVERY_LIVE=1 DAYTONA_API_KEY=... PAPERCLIP_DAYTONA_SDK_PATH=...+// PAPERCLIP_RECOVERY_IMAGE=ghcr.io/...@sha256:... vitest run --config vitest.config.ts scripts/workspace-recovery-provider.test.mjs+import { randomUUID, createHash } from "node:crypto";+import { spawn } from "node:child_process";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { eq } from "drizzle-orm";+import { expect, it, vi } from "vitest";+import { agents, companies, createDb, environmentLeases, environments, heartbeatRuns, issueRecoveryActions,+ issues, workspaceOperations } from "@paperclipai/db";+import { NOOP_PLUGIN_TRACER } from "@paperclipai/plugin-sdk";+import { startEmbeddedPostgresTestDatabase } from "../src/__tests__/helpers/embedded-postgres.js";+import { readSystemRecovery } from "../src/services/system-recovery-state.js";+import { recoverRetainedWorkspace } from "../src/services/workspace-recovery.js";+import { attachPreservedWorkspaceSnapshots } from "../src/services/workspace-recovery-snapshot.js";+import { performSyncOut } from "../../packages/plugins/sandbox-providers/daytona/src/file-sync.js";++const boundary = vi.hoisted(() => ({ target: null }));+vi.mock("../src/services/environment-execution-target.js", () => ({+ resolveEnvironmentExecutionTarget: async () => boundary.target,+}));+vi.mock("../../packages/plugins/sandbox-providers/daytona/src/plugin.js", () => ({+ getPluginTracer: () => NOOP_PLUGIN_TRACER,+}));++const live = process.env.PAPERCLIP_RECOVERY_LIVE === "1";+const worker = process.env.PAPERCLIP_RECOVERY_WORKER;+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");+const quote = value => `'${value.replaceAll("'", "'\\''")}'`;+async function client() {+ const modulePath = process.env.PAPERCLIP_DAYTONA_SDK_PATH;+ if (!modulePath || !process.env.DAYTONA_API_KEY) throw new Error("Explicit Daytona qualification settings are required");+ const { Daytona } = await import(/* @vite-ignore */ pathToFileURL(modulePath).href);+ return new Daytona({ apiKey: process.env.DAYTONA_API_KEY, requestTimeoutMs: 120_000 });+}++it.skipIf(!live || !worker)("provider controller", async () => {+ const f = JSON.parse(await readFile(process.env.PAPERCLIP_RECOVERY_FIXTURE, "utf8"));+ process.env.PAPERCLIP_STORAGE_LOCAL_DIR = path.join(f.directory, "storage");+ const db = createDb(f.connectionString);+ try {+ const sandbox = await (await client()).get(f.providerLeaseId);+ const download = sandbox.fs.downloadFiles.bind(sandbox.fs);+ sandbox.fs.downloadFiles = async (...args) => {+ const result = await download(...args);+ if (worker === "interrupt") {+ // Interrupt after the real provider transfer and before host extraction.+ // The controller joins its work and stops the export-only sandbox before+ // exiting; an unjoined hard crash is separately fenced by ownership tests.+ await writeFile(path.join(f.directory, "interrupted"), "archive received; extraction interrupted");+ throw new Error("qualification_export_interrupted");+ }+ return result;+ };+ boundary.target = { kind: "remote", transport: "sandbox", providerKey: "daytona", leaseId: f.leaseId,+ remoteCwd: f.remoteCwd, timeoutMs: 120_000,+ runner: {+ syncIn: async () => { throw new Error("Recovery must not upload into the retained source"); },+ execute: async input => {+ const startedAt = new Date().toISOString();+ const result = await sandbox.process.executeCommand([input.command, ...(input.args ?? [])].map(quote).join(" "),+ input.cwd, input.env, 120);+ return { exitCode: result.exitCode, stdout: result.result, stderr: "", timedOut: false,+ signal: null, pid: null, startedAt };+ },+ syncOut: operations => performSyncOut({ sandbox, operations, remoteDir: f.remoteCwd, timeoutSeconds: 120 }),+ } };+ const environmentRuntime = {+ resumeRunLease: async () => {+ await sandbox.start(120); await sandbox.refreshData();+ if (sandbox.state !== "started") throw new Error("Provider did not confirm start");+ return { providerLeaseId: sandbox.id, metadata: { remoteCwd: f.remoteCwd } };+ },+ retryPendingSandboxTeardown: async () => {+ await sandbox.stop(120); await sandbox.refreshData();+ if (sandbox.state !== "stopped") throw new Error("Provider did not confirm stop");+ return { providerLeaseId: sandbox.id, state: "stopped" };+ },+ };+ await recoverRetainedWorkspace({ db, ...f, environmentRuntime });+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));+ const state = readSystemRecovery(action.evidence);+ expect(state?.state).toBe(worker === "interrupt" ? "scheduled" : "complete");+ await writeFile(path.join(f.directory, `${worker}.json`), JSON.stringify(state));+ } finally { await db.$client.end(); }+}, 300_000);++it.skipIf(!live || Boolean(worker))("preserves provider files across an interrupted export and controller restart without restarting the old agent", async () => {+ const image = process.env.PAPERCLIP_RECOVERY_IMAGE;+ if (!image?.includes("@sha256:")) throw new Error("An immutable qualification image is required");+ const directory = await mkdtemp(path.join(os.tmpdir(), "paperclip-provider-recovery-"));+ const priorHome = process.env.PAPERCLIP_HOME;+ process.env.PAPERCLIP_HOME = path.join(directory, "home");+ const priorStorage = process.env.PAPERCLIP_STORAGE_LOCAL_DIR;+ process.env.PAPERCLIP_STORAGE_LOCAL_DIR = path.join(directory, "storage");+ const database = await startEmbeddedPostgresTestDatabase("provider-recovery-");+ const db = createDb(database.connectionString);+ const daytona = await client();+ let sandbox;+ const evidence = { image, interrupted: false, restored: false, oldAgentStarts: null, externalOperations: null,+ prematureCleanup: false, controllerProcesses: [], snapshotCount: 0 };+ try {+ sandbox = await daytona.create({ image, autoStopInterval: 10, autoArchiveInterval: 60,+ resources: { cpu: 2, memory: 4, disk: 10 }, labels: { purpose: "paperclip-recovery-qualification" } }, { timeout: 300 });+ const remoteCwd = "/tmp/paperclip-recovery-fixture";+ await sandbox.process.executeCommand(`mkdir -p ${remoteCwd}`, undefined, undefined, 30);+ await sandbox.process.createSession("old-agent");+ await sandbox.process.executeSessionCommand("old-agent", {+ command: `sh -c ${quote(`echo start >> ${remoteCwd}/agent-starts; echo published >> ${remoteCwd}/external-operations; printf 'saved work\\n' > ${remoteCwd}/saved.txt; while :; do sleep 1; done`)}`,+ runAsync: true,+ });+ await expect.poll(async () => (await sandbox.process.executeCommand(`cat ${remoteCwd}/saved.txt`, undefined, undefined, 30)).result)+ .toContain("saved work");+ const companyId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), actionId = randomUUID(), agentId = randomUUID();+ await db.insert(companies).values({ id: companyId, name: "Disposable provider qualification", issuePrefix: "LIVE" });+ await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" });+ await db.insert(issues).values({ id: issueId, companyId, title: "Disposable preservation fixture", status: "blocked", assigneeAgentId: agentId });+ await db.insert(heartbeatRuns).values({ id: runId, companyId, issueId, agentId, status: "failed", runtimeMode: "legacy",+ contextSnapshot: { issueId }, finishedAt: new Date() });+ const [environment] = await db.insert(environments).values({ name: runId, driver: "sandbox" }).returning();+ const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId,+ environmentId: environment.id, provider: "daytona", providerLeaseId: sandbox.id,+ leasePolicy: "retain_on_failure", status: "released", releasedAt: new Date(),+ metadata: { remoteCwd, driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true } }).returning();+ const recovery = { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] };+ await db.update(heartbeatRuns).set({ resultJson: { workspaceRestoreRecovery: recovery, workspaceRestoreFailure: "restore_failed" } })+ .where(eq(heartbeatRuns.id, runId));+ await db.insert(issueRecoveryActions).values({ id: actionId, companyId, sourceIssueId: issueId,+ kind: "active_run_watchdog", ownerType: "system", fingerprint: runId, nextAction: "",+ cause: "legacy_execution_requires_reconciliation", evidence: { runId, workspaceRestoreRecovery: recovery } });+ const fixture = path.join(directory, "fixture.json");+ await writeFile(fixture, JSON.stringify({ connectionString: database.connectionString, companyId, issueId, runId, actionId,+ leaseId: lease.id, providerLeaseId: sandbox.id, remoteCwd, directory }), { mode: 0o600 });+ async function runController(phase) {+ const child = spawn(process.execPath, [path.join(root, "node_modules/vitest/vitest.mjs"), "run", "--config", "vitest.config.ts",+ "scripts/workspace-recovery-provider.test.mjs", "-t", "provider controller"], {+ cwd: path.join(root, "server"), env: { ...process.env, PAPERCLIP_RECOVERY_WORKER: phase, PAPERCLIP_RECOVERY_FIXTURE: fixture },+ stdio: ["ignore", "pipe", "pipe"],+ });+ evidence.controllerProcesses.push(child.pid);+ // Keep provider/auth diagnostics off the terminal. Only the bounded,+ // scrubbed verdict is published by the parent.+ let output = "";+ child.stdout.on("data", data => { output += data; });+ child.stderr.on("data", data => { output += data; });+ const code = await new Promise(resolve => child.on("exit", resolve));+ if (code !== 0) {+ await writeFile(path.join(directory, `${phase}.log`), output, { mode: 0o600 });+ throw new Error(`Provider controller ${phase} failed; protected log: ${directory}/${phase}.log`);+ }+ }+ await runController("interrupt");+ evidence.interrupted = Boolean(await readFile(path.join(directory, "interrupted"), "utf8"));+ const failed = JSON.parse(await readFile(path.join(directory, "interrupt.json"), "utf8"));+ expect(failed.attempts).toBe(1);+ // Honor the production persisted backoff; the probe never replenishes it.+ if (failed.nextAttemptAt > Date.now()) await new Promise(resolve => setTimeout(resolve, failed.nextAttemptAt - Date.now() + 10));+ await runController("resume");+ const finished = JSON.parse(await readFile(path.join(directory, "resume.json"), "utf8"));+ expect(finished.attempts).toBe(2);+ const fresh = path.join(directory, "fresh"); await mkdir(fresh);+ const attached = await attachPreservedWorkspaceSnapshots({ db, companyId, issueId, sourceRunIds: [runId], cwd: fresh });+ const files = path.join(attached[0].path, "files");+ expect(await readFile(path.join(files, "saved.txt"), "utf8")).toBe("saved work\n");+ evidence.oldAgentStarts = (await readFile(path.join(files, "agent-starts"), "utf8")).trim().split("\n").length;+ evidence.externalOperations = (await readFile(path.join(files, "external-operations"), "utf8")).trim().split("\n").length;+ expect(evidence.oldAgentStarts).toBe(1); expect(evidence.externalOperations).toBe(1);+ const operations = await db.select().from(workspaceOperations).where(eq(workspaceOperations.heartbeatRunId, runId));+ evidence.snapshotCount = operations.filter(op => op.phase === "workspace_recovery_snapshot" && op.status === "succeeded").length;+ expect(evidence.snapshotCount).toBe(1);+ await sandbox.refreshData(); expect(sandbox.state).toBe("stopped");+ const [retained] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id));+ expect(retained.providerLeaseId).toBe(sandbox.id); expect(retained.metadata.workspaceRecoveryCleanup).toBeUndefined();+ evidence.restored = true;+ evidence.savedFileSha256 = createHash("sha256").update(await readFile(path.join(files, "saved.txt"))).digest("hex");+ } finally {+ // This test owns the disposable source. Production recovery never destroys it.+ if (sandbox) await sandbox.delete(120);+ if (process.env.PAPERCLIP_RECOVERY_EVIDENCE) await writeFile(process.env.PAPERCLIP_RECOVERY_EVIDENCE, JSON.stringify(evidence, null, 2));+ await db.$client.end(); await database.cleanup();+ if (priorHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = priorHome;+ if (priorStorage === undefined) delete process.env.PAPERCLIP_STORAGE_LOCAL_DIR; else process.env.PAPERCLIP_STORAGE_LOCAL_DIR = priorStorage;+ if (evidence.restored) await rm(directory, { recursive: true, force: true });+ }+}, 900_000);diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.tsindex d0a0678ff8..310c779895 100644--- a/server/src/__tests__/chat-channels.integration.test.ts+++ b/server/src/__tests__/chat-channels.integration.test.ts@@ -1,4 +1,5 @@import { idleWorkSnapshot } from "../services/task-admission.js";+import { requestTaskRetry } from "../services/task-retry.js";import { stageReceiptReactionRemovals } from "../services/chat-receipt-reactions.js";import type { Db } from "@paperclipai/db";import * as activityLogModule from "../services/activity-log.js";@@ -10090,6 +10091,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {.expect(400);});+it.each([{provider: "slack" as const,@@ -60827,6 +60829,75 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {},);+ it.each(["stopped", "real_queue", "unknown_executor", "source_edited", "cancelled_stopped", "cancelled_unknown"] as const)(+ "admits ordinary chat task Retry with a missing checkpoint only after containment: %s", async kind => {+ const context = await failedChatRetryFixture("telegram", undefined, kind === "real_queue");+ try {+ await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: context.issue.id,+ nativePhase: "terminal_failure", errorCode: "runner_remote_process_identity_unavailable",+ runnerProfileJson: {},+ ...(kind.startsWith("cancelled_") ? { status: "cancelled" } : {}),+ }).where(eq(heartbeatRuns.id, context.runId));+ await db.insert(nativeRunFinalizations).values({ companyId: context.fixture.companyId,+ issueId: context.issue.id, runId: context.runId, phase: "terminal_failure" });+ const exact = { companyId: context.fixture.companyId, issueId: context.issue.id,+ agentId: context.fixture.assignedAgentId, failedRunId: context.runId, initiatedByUserId: "owner-user" };+ await expect(db.transaction(tx => context.service.prepareFailedChatRunRetry(tx, exact)))+ .rejects.toMatchObject({ details: { code: "chat_failed_run_retry_not_authorized" } });+ if (kind !== "unknown_executor" && kind !== "cancelled_unknown") await db.insert(heartbeatRunEvents).values({+ companyId: context.fixture.companyId, agentId: context.fixture.assignedAgentId, runId: context.runId,+ seq: 1, eventType: "native.local_process_stopped", payload: { processPid: 999999999, processGroupId: null },+ });+ const request = { db, companyId: context.fixture.companyId, issueId: context.issue.id,+ actorId: "owner-user", actorSource: "cloud_tenant", observedRunId: context.runId, idempotencyKey: randomUUID(),+ prepareChatRetry: context.service.prepareFailedChatRunRetry };+ const receipt = await requestTaskRetry(request);+ expect(receipt.chatActionId).toBeTruthy();+ expect((await requestTaskRetry(request)).requestId).toBe(receipt.requestId);+ if (kind === "source_edited") await db.update(issueComments).set({ body: "Changed source", updatedAt: new Date() })+ .where(eq(issueComments.id, String(context.action.payload.commentId)));+ if (kind === "real_queue") {+ // Exercise the real dispatch transaction while another live run+ // occupies capacity. This test makes no provider-execution claim.+ await db.update(agents).set({ adapterType: "paperclip_runner", status: "running",+ runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } })+ .where(eq(agents.id, context.fixture.assignedAgentId));+ await db.insert(heartbeatRuns).values({ companyId: context.fixture.companyId,+ agentId: context.fixture.assignedAgentId, status: "running", startedAt: new Date() });+ context.wakeup.mockImplementation(heartbeatService(db).wakeup);+ }+ const outcome = await context.service.processFailedChatRunRetry(receipt.chatActionId!);+ if (kind === "stopped" || kind === "real_queue" || kind === "cancelled_stopped") {+ expect(outcome).toMatchObject({ status: "queued" });+ const [wake] = await readAgentWakeupRequestsById(receipt.chatActionId!);+ expect(wake, JSON.stringify({+ action: (await db.select().from(chatActions).where(eq(chatActions.id, receipt.chatActionId!)))[0],+ wakeResult: await context.wakeup.mock.results.at(-1)?.value,+ })).toBeDefined();+ expect(wake).toMatchObject({ requestedByActorType: context.receipt.requestedByActorType,+ requestedByActorId: context.receipt.requestedByActorId,+ payload: { wakeCommentIds: [context.action.payload.commentId], retryOfRunId: context.runId } });+ if (kind === "real_queue") {+ const [intent] = await readAgentWakeupRequestsById(receipt.requestId!);+ expect(intent).toMatchObject({ status: "coalesced", runId: wake.runId });+ expect(wake.runId).toBeTruthy();+ const [successor] = await readHeartbeatRunsById(wake.runId!);+ expect(successor).toMatchObject({ status: "queued", contextSnapshot: {+ taskRetryRequestId: receipt.requestId, forceFreshSession: true,+ chatFailedRunRetry: { actionId: receipt.chatActionId },+ } });+ await context.service.processFailedChatRunRetry(receipt.chatActionId!);+ expect((await readHeartbeatRunsByCompanyId(context.fixture.companyId))+ .filter(run => run.contextSnapshot?.taskRetryRequestId === receipt.requestId)).toHaveLength(1);+ }+ } else {+ expect(outcome).toMatchObject({ status: "failed" });+ expect(await readAgentWakeupRequestsById(receipt.chatActionId!)).toHaveLength(0);+ }+ } finally { await context.service.shutdown(); }+ },+ );+it.each(["bootstrap","checkpoint",diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.tsindex 01d2dfc330..b4faf3b74d 100644--- a/server/src/__tests__/heartbeat-process-recovery.test.ts+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts@@ -11704,7 +11704,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {const heartbeat = heartbeatService(db);await heartbeat.reconcileStrandedAssignedIssues();- await heartbeat.promoteDueScheduledRetries(new Date(Date.now() + 31_000));+ const scheduledRun = (await selectRecoveryRunsByAgent(agentId))+ .find((row) => row.status === "scheduled_retry");+ expect(scheduledRun?.scheduledRetryAt).toBeInstanceOf(Date);+ await heartbeat.promoteDueScheduledRetries(scheduledRun!.scheduledRetryAt!);await heartbeat.resumeQueuedRuns();// The continuation is produced by completion; wait for that durable boundary.await heartbeat.drainActiveRunExecutions();@@ -11802,7 +11805,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {const heartbeat = heartbeatService(db);await heartbeat.reconcileStrandedAssignedIssues();- await heartbeat.promoteDueScheduledRetries(new Date(Date.now() + 31_000));+ const scheduledRun = (await selectRecoveryRunsByAgent(agentId))+ .find((row) => row.status === "scheduled_retry");+ expect(scheduledRun?.scheduledRetryAt).toBeInstanceOf(Date);+ await heartbeat.promoteDueScheduledRetries(scheduledRun!.scheduledRetryAt!);await heartbeat.resumeQueuedRuns();const retryRun = await waitForValue(async () => {diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.tsindex 941aaf16ed..826fe78ec3 100644--- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts+++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts@@ -120,6 +120,7 @@ const mockHeartbeatService = vi.hoisted(() => ({getRun: vi.fn(async () => null),getActiveRunForAgent: vi.fn(async () => null),cancelRun: vi.fn(async () => null),+ resumeTaskRetry: vi.fn(async () => undefined),}));const mockRunnerGoalService = vi.hoisted(() => ({projection: vi.fn(async () => null),@@ -163,9 +164,22 @@ const mockObserveCrossIssueInfluence = vi.hoisted(() => vi.fn(async () => null))const mockRetryWorkspaceExport = vi.hoisted(() => vi.fn());const mockRequestWorkspaceRecovery = vi.hoisted(() => vi.fn());+const mockRequestTaskRetry = vi.hoisted(() => vi.fn());+const mockGetExperimental = vi.hoisted(() => vi.fn());const mockResumeWorkspaceFinalization = vi.hoisted(() => vi.fn());function registerRouteMocks() {+ vi.doMock("../services/instance-settings.js", async () => {+ const actual = await vi.importActual<typeof import("../services/instance-settings.js")>("../services/instance-settings.js");+ return { ...actual, instanceSettingsService: (...args: Parameters<typeof actual.instanceSettingsService>) => ({+ ...actual.instanceSettingsService(...args), getExperimental: mockGetExperimental,+ }) };+ });+ vi.doMock("../services/task-retry.js", () => ({ requestTaskRetry: mockRequestTaskRetry }));+ vi.doMock("../services/task-interruption-presentation.js", () => ({+ taskInterruptionPresentation: vi.fn(async () => null),+ taskInterruptionPresentations: vi.fn(async () => new Map()),+ }));vi.doMock("../services/native-runtime/native-workspace-owner-recovery.js", () => ({ resumeNativeWorkspaceAfterOwnerStop: mockResumeWorkspaceFinalization }));vi.doMock("../services/native-runtime/native-workspace-export-retry.js", () => ({ retryNativeWorkspaceExport: mockRetryWorkspaceExport }));vi.doMock("../services/workspace-recovery.js", () => ({ requestWorkspaceRecovery: mockRequestWorkspaceRecovery }));@@ -254,6 +268,7 @@ function registerRouteMocks() {goalService: () => ({}),heartbeatService: () => mockHeartbeatService,instanceSettingsService: () => ({+ getExperimental: mockGetExperimental,get: vi.fn(async () => ({id: "instance-settings-1",general: {@@ -481,6 +496,8 @@ describe("agent issue mutation checkout ownership", () => {mockIssueTreeControlService.getActivePauseHoldGate.mockReset().mockResolvedValue(null);mockChatRunRetries.prepareFailedChatRunRetry.mockReset();mockChatRunRetries.processFailedChatRunRetry.mockReset();+ mockRequestTaskRetry.mockReset().mockResolvedValue({ requestId: recoveryActionId, accepted: true, stale: false });+ mockGetExperimental.mockReset().mockResolvedValue({ enableAgentChat: true });mockAccessService.canUser.mockReset();mockAccessService.decide.mockReset();mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({@@ -853,6 +870,50 @@ describe("agent issue mutation checkout ownership", () => {}));});+ it("admits ordinary Retry only for a board actor with task mutation permission", async () => {+ const body = { idempotencyKey: recoveryActionId, observedRunId: ownerRunId };+ const deniedAgent = await request(createApp(peerActor())).post(`/api/issues/${issueId}/retry`).send(body);+ expect(deniedAgent.status).toBe(403);+ expect(mockRequestTaskRetry).not.toHaveBeenCalled();+ mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({+ allowed: input.action !== "issue:mutate", action: input.action, reason: "test_gate", explanation: "Task is read-only.",+ }));+ const deniedReader = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send(body);+ expect(deniedReader.status).toBe(403);+ expect(mockRequestTaskRetry).not.toHaveBeenCalled();+ mockAccessService.decide.mockResolvedValue({ allowed: true, reason: "allow_test", explanation: "Allowed." });+ const accepted = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send(body);+ expect(accepted.status, JSON.stringify(accepted.body)).toBe(202);+ expect(mockRequestTaskRetry).toHaveBeenCalledWith(expect.objectContaining({+ companyId, issueId, actorId: "board-user", actorSource: "local_implicit", ...body,+ }));+ });++ it("rejects client-selected workspace strategy and certifications on ordinary Retry", async () => {+ const response = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send({+ idempotencyKey: recoveryActionId, observedRunId: ownerRunId,+ forceFreshSession: true, workspaceRepairEvidence: { verified: true },+ });+ expect(response.status).toBe(400);+ expect(mockRequestTaskRetry).not.toHaveBeenCalled();+ });++ it.each([+ { owner: "another-user", enabled: true, status: 403 },+ { owner: "board-user", enabled: false, status: 404 },+ { owner: "board-user", enabled: true, status: 202 },+ ])("gates Agent Chat task Retry by owner and feature ($owner, $enabled)", async ({ owner, enabled, status }) => {+ mockIssueService.getById.mockResolvedValue(makeIssue({+ conversationAgentId: ownerAgentId, conversationUserId: owner,+ }));+ mockGetExperimental.mockResolvedValue({ enableAgentChat: enabled });+ const response = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send({+ idempotencyKey: recoveryActionId, observedRunId: ownerRunId,+ });+ expect(response.status, JSON.stringify(response.body)).toBe(status);+ expect(mockRequestTaskRetry).toHaveBeenCalledTimes(status === 202 ? 1 : 0);+ });+it.each([["patch", (app: express.Express) => request(app).patch(`/api/issues/${issueId}`).send({ title: "Blocked" })],["delete", (app: express.Express) => request(app).delete(`/api/issues/${issueId}`)],diff --git a/server/src/__tests__/issues-goal-context-routes.test.ts b/server/src/__tests__/issues-goal-context-routes.test.tsindex b061bb3832..863509c312 100644--- a/server/src/__tests__/issues-goal-context-routes.test.ts+++ b/server/src/__tests__/issues-goal-context-routes.test.ts@@ -99,6 +99,11 @@ const mockDb = vi.hoisted(() => ({execute: vi.fn(),}));+vi.mock("../services/task-interruption-presentation.js", () => ({+ taskInterruptionPresentation: vi.fn(async () => null),+ taskInterruptionPresentations: vi.fn(async () => new Map()),+}));+vi.mock("../services/index.js", () => ({companyService: () => ({getById: vi.fn(async () => ({ id: "company-1" })),diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.tsindex f471307c5b..f63add3c1d 100644--- a/server/src/__tests__/tool-gateway.test.ts+++ b/server/src/__tests__/tool-gateway.test.ts@@ -7,6 +7,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport {activityLog,agents,+ agentWakeupRequests,companySecretBindings,companySecrets,companySecretVersions,@@ -580,6 +581,7 @@ describeEmbeddedPostgres("tool gateway acceptance", () => {await db.delete(companySecrets);await db.delete(userSecretDefinitions);await db.delete(issueThreadInteractions);+ await db.delete(agentWakeupRequests);await db.delete(heartbeatRuns);await db.delete(issues);await db.delete(projects);@@ -1385,6 +1387,40 @@ describeEmbeddedPostgres("tool gateway acceptance", () => {});});+ it("fences an uncertain upstream mutation after fresh Retry while allowing independent reads", async () => {+ const company = await createCompany(db);+ const agent = await createAgent(db, company.id);+ const { issue, run } = await createIssueAndRun(db, company.id, agent.id);+ const remote = await createRemoteMcpTool(db, company.id);+ await allowAllToolsForAgent(db, company.id, agent.id);+ const gateway = createTestToolGatewayService(db);+ const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });+ const tool = (await gateway.listToolsForSession(session.token))+ .find(item => item.connectionId === remote.connection.id)!;+ const [source] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id,+ issueId: issue.id, status: "failed", createdAt: new Date(Date.now() - 60_000) }).returning();+ const intentId = randomUUID();+ await db.insert(agentWakeupRequests).values({ id: intentId, companyId: company.id, agentId: agent.id,+ runId: run.id, source: "on_demand", reason: "task_retry", status: "coalesced",+ requestedByActorType: "user", requestedByActorId: "board",+ payload: { issueId: issue.id, taskRetry: { schema: "paperclip.task-retry.v1",+ generationId: intentId, sourceRunId: source.id, actorId: "board", strategy: "fresh_isolated_workspace" } } });+ const [uncertain] = await db.insert(toolInvocations).values({ companyId: company.id,+ issueId: issue.id, runId: source.id, agentId: agent.id, connectionId: remote.connection.id,+ toolName: tool.name, riskLevel: "write", status: "timed_out", startedAt: new Date() }).returning();+ const fetcher = vi.spyOn(globalThis, "fetch");+ try {+ await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name,+ idempotencyKey: randomUUID(), parameters: { key: "new-key", value: "do not repeat" } }))+ .rejects.toMatchObject({ status: 409, reasonCode: "recovery_effect_outcome_unresolved" });+ expect(fetcher).not.toHaveBeenCalled();+ expect(await gateway.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:add",+ parameters: { a: 2, b: 3 } })).toMatchObject({ status: "completed", result: { content: "5" } });+ const [retained] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, uncertain.id));+ expect(retained.status).toBe("timed_out");+ } finally { fetcher.mockRestore(); }+ });+it("filters discovery, executes a remote HTTP fixture, and audits run and issue links", async () => {const company = await createCompany(db);const agent = await createAgent(db, company.id);diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.tsindex 164f553edd..7ea94ad547 100644--- a/server/src/routes/issues.ts+++ b/server/src/routes/issues.ts@@ -1,3 +1,4 @@+import { taskInterruptionPresentation, taskInterruptionPresentations } from "../services/task-interruption-presentation.js";import { parseObject } from "../adapters/utils.js";import { prepareRestrictedWorkspaceRetry } from "../services/restricted-workspace-retry.js";import { issueSummariesQuerySchema, type IssueSummary } from "@paperclipai/shared";@@ -100,6 +101,7 @@ import {resolveIssueRecoveryActionSchema,retryWorkspaceExportSchema,recoverWorkspaceSchema,+ taskRetrySchema,resumeWorkspaceFinalizationSchema,runnerGoalActionRequestSchema,feedbackTargetTypeSchema,@@ -2934,6 +2936,7 @@ function toCompactIssue(issue: any): CompactIssue {? { isUnreadForMe: issue.isUnreadForMe }: {}),activeRecoveryAction: issue.activeRecoveryAction ?? null,+ interruption: issue.interruption ?? null,successfulRunHandoff: issue.successfulRunHandoff ?? null,};}@@ -8517,6 +8520,7 @@ export function issueRoutes(: await filterIssuesForActor(req, rawResult);const result = await redactIssueRelationEdgesOnRows(req, companyId, visibleRows);const issueIds = result.map((issue) => issue.id);+ const interruptions = await taskInterruptionPresentations(db, companyId, result);if (compactView) {const [handoffStates, recoveryActionByIssue] = await Promise.all([listSuccessfulRunHandoffStates(db, companyId, issueIds),@@ -8542,6 +8546,7 @@ export function issueRoutes(toCompactIssue({...issue,activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,+ interruption: interruptions.get(issue.id) ?? null,successfulRunHandoff: handoffStates.get(issue.id) ?? null,}),);@@ -8578,6 +8583,7 @@ export function issueRoutes(...issue,successfulRunHandoff: handoffStates.get(issue.id) ?? null,activeRecoveryAction: recoveryActionByIssue.get(issue.id) ?? null,+ interruption: interruptions.get(issue.id) ?? null,})),};},@@ -9325,6 +9331,7 @@ export function issueRoutes(...(reviewAttention ? { reviewAttention } : {}),successfulRunHandoff: successfulRunHandoffStates.get(issue.id) ?? null,executionBlocker,+ interruption: await taskInterruptionPresentation(db, issue),scheduledRetry,activeRecoveryAction: revalidatedActiveRecoveryAction,blockedBy: visibleRelations.blockedBy,@@ -9498,6 +9505,30 @@ export function issueRoutes(});});+ router.post("/issues/:id/retry", validate(taskRetrySchema), async (req, res) => {+ assertBoard(req);+ const issue = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found");+ if (!issue || !(await assertIssueReadAllowed(req, res, issue))) return;+ const decision = await decideIssueAccess(req, issue, "issue:mutate");+ if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));+ if (issue.conversationAgentId) {+ if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled");+ if (!req.actor.userId || req.actor.userId !== issue.conversationUserId)+ throw forbidden("Only the conversation owner can retry a chat run");+ }+ const { requestTaskRetry } = await import("../services/task-retry.js");+ const receipt = await requestTaskRetry({ db, companyId: issue.companyId, issueId: issue.id,+ ...req.body, actorId: getActorInfo(req).actorId, actorSource: req.actor.source,+ prepareChatRetry: opts.chatRunRetries?.prepareFailedChatRunRetry });+ res.status(receipt.accepted ? 202 : 200).json({ ...receipt, presentation: await taskInterruptionPresentation(db, issue) });+ // The receipt commits before dispatch. Maintenance redelivers it after a+ // crash or a lost response; this nudge only reduces perceived latency.+ if (receipt.chatActionId) void opts.chatRunRetries?.processFailedChatRunRetry(receipt.chatActionId).catch(err =>+ logger.warn({ err, issueId: issue.id }, "Connected task Retry remains queued"));+ else if (receipt.accepted && receipt.requestId) void heartbeat.resumeTaskRetry(issue.companyId, receipt.requestId).catch(err =>+ logger.warn({ err, issueId: issue.id }, "Task Retry remains queued"));+ });+router.post("/issues/:id/recovery-actions/recover-workspace", validate(recoverWorkspaceSchema), async (req, res) => {assertBoard(req);const issue = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found");diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.tsindex 610236fa74..99680b5c28 100644--- a/server/src/routes/openapi.ts+++ b/server/src/routes/openapi.ts@@ -250,6 +250,7 @@ import {createAcceptedPlanDecompositionSchema,resolveIssueRecoveryActionSchema,recoverWorkspaceSchema,+ taskRetrySchema,retryWorkspaceExportSchema,reconstructWorkspaceSchema,resumeWorkspaceFinalizationSchema,@@ -1388,6 +1389,7 @@ const browserUseOperations = [] as const;const BOARD_ONLY_OPERATIONS = new Set([+ "POST /api/issues/{id}/retry","GET /api/companies/{companyId}/prompt-injection-prevention","PUT /api/companies/{companyId}/prompt-injection-prevention","GET /api/companies/{companyId}/prompt-injection-prevention/models",@@ -10703,6 +10705,15 @@ registerCurrentRoute({summary: "List issue recovery actions",});+registerCurrentRoute({+ method: "post",+ path: "/api/issues/{id}/retry",+ tags: ["issues"],+ summary: "Request one durable task retry from current input and preserved results",+ body: taskRetrySchema,+ responses: { 200: r.ok(), 202: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },+});+registerCurrentRoute({method: "post",path: "/api/issues/{id}/recovery-actions/recover-workspace",diff --git a/server/src/services/chat-channels/failed-run-retry.ts b/server/src/services/chat-channels/failed-run-retry.tsindex ae041ef925..a25bcb27df 100644--- a/server/src/services/chat-channels/failed-run-retry.ts+++ b/server/src/services/chat-channels/failed-run-retry.ts@@ -1,4 +1,5 @@import { continuingTeamsFilePublication, type ContinuingTeamsFileTransfer } from "./microsoft-teams/file-transfer-source.js";+import { readTaskChatRetryIntent, taskChatRetryExecutionStopped } from "./task-retry-authority.js";import { notifyChatActionWork, notifyChatPublicationWork } from "../chat-work-notifications.js";import { FAILED_RUN_RETRY_STALE_MS, dueChatAction } from "../chat-action-work.js";@@ -546,6 +547,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptitx: DbOrTransaction,source: Pick<FailedChatRetrySource, "failedRunId" | "issueId" | "agentId">,companyId: string,+ taskRetryIntentId?: string,) {const [run] = await tx.select()@@ -559,6 +561,14 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti).for("share", { noWait: true });if (!run) throw failedChatRetryDenied();+ if (taskRetryIntentId) {+ if (!await readTaskChatRetryIntent(tx as unknown as Db, { companyId, issueId: source.issueId,+ agentId: source.agentId, sourceRunId: run.id, intentId: taskRetryIntentId })) throw failedChatRetryDenied();+ if (await taskChatRetryExecutionStopped(tx as unknown as Db, run)) return;+ // A still-live/unknown executor remains held. The exact pre-provider+ // proof below can establish a never-started native attempt.+ if (run.runtimeMode !== "native") throw failedChatRetryDenied();+ }if (run.runtimeMode !== "native") return;const { coordinator, leases, retiredOwner } =await failedNativeRetryCoordinator(tx, run, source.issueId);@@ -634,6 +644,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptiretryActionId?: string;runId?: string;publication?: boolean;+ taskRetryIntentId?: string;/** Internal selector for already committed output, never retry admission. */committedResponse?: {resultId: string;@@ -691,9 +702,10 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti!failedRun ||!failedRun.wakeupRequestId ||(!input.committedResponse &&- (!["failed", "timed_out"].includes(failedRun.status) ||+ (!(["failed", "timed_out"].includes(failedRun.status) ||+ (input.taskRetryIntentId && failedRun.status === "cancelled")) ||!failedRun.finishedAt)) ||- (!input.committedResponse &&+ (!input.committedResponse && !input.taskRetryIntentId &&failedRun.runtimeMode !== "native" &&!([@@ -708,7 +720,11 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti["backlog", "done", "cancelled"].includes(issue.status)))throw failedChatRetryDenied();- if (failedRun.runtimeMode === "native" && !input.committedResponse)+ if (input.taskRetryIntentId && !await readTaskChatRetryIntent(tx as unknown as Db, {+ companyId: input.companyId, issueId: issue.id, agentId: input.agentId,+ sourceRunId: failedRun.id, intentId: input.taskRetryIntentId,+ })) throw failedChatRetryDenied();+ if (failedRun.runtimeMode === "native" && !input.committedResponse && !input.taskRetryIntentId)await failedNativeRetryCoordinator(tx, failedRun, issue.id);const context = failedRun.contextSnapshot ?? {};const provider = CHAT_PROVIDERS.find(@@ -899,6 +915,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti...input,failedRunId: priorIntent.payload.failedRunId,committedResponse: undefined,+ taskRetryIntentId: typeof priorIntent.payload.taskRetryIntentId === "string"+ ? priorIntent.payload.taskRetryIntentId : undefined,},ancestors,);@@ -1222,10 +1240,12 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptiagentId: string;failedRunId: string;initiatedByUserId: string;+ retryIntentId?: string;},): Promise<{ actionId: string; issueId: string }> {- const source = await failedChatRetrySource(tx, input);- const providerActionId = `failed-run-retry:${source.failedRunId}`;+ const source = await failedChatRetrySource(tx, { ...input, taskRetryIntentId: input.retryIntentId });+ const providerActionId = input.retryIntentId+ ? `task-retry:${input.retryIntentId}` : `failed-run-retry:${source.failedRunId}`;const [existing] = await tx.select().from(chatActions)@@ -1245,7 +1265,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptithrow failedChatRetryDenied();return { actionId: existing.id, issueId: input.issueId };}- await assertFailedNativeRetryState(tx, source, input.companyId);+ if (!input.retryIntentId) await assertFailedNativeRetryState(tx, source, input.companyId);const [busy] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)@@ -1277,6 +1297,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptiversion: 1,...source,initiatedByUserId: input.initiatedByUserId,+ ...(input.retryIntentId ? { taskRetryIntentId: input.retryIntentId } : {}),},status: "issued",result: { code: "failed_chat_retry_queued", attemptCount: 0 },@@ -1331,7 +1352,13 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpticonst source = await failedChatRetrySource(tx, {...input,failedRunId: snapshot.payload.failedRunId,+ taskRetryIntentId: typeof snapshot.payload.taskRetryIntentId === "string"+ ? snapshot.payload.taskRetryIntentId : undefined,});+ if (typeof snapshot.payload.taskRetryIntentId === "string" && !await readTaskChatRetryIntent(tx as unknown as Db, {+ companyId: input.companyId, issueId: input.issueId, agentId: input.agentId,+ sourceRunId: source.failedRunId, intentId: snapshot.payload.taskRetryIntentId, chatActionId: snapshot.id,+ })) throw failedChatRetryDenied();const [intent] = await tx.select().from(chatActions)@@ -1408,7 +1435,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti...input,retryActionId: input.wakeupRequestId,});- await assertFailedNativeRetryState(tx, source, input.companyId);+ await assertFailedNativeRetryState(tx, source, input.companyId,+ typeof source.intent.payload.taskRetryIntentId === "string" ? source.intent.payload.taskRetryIntentId : undefined);const context = input.contextSnapshot;const hint = context.chatFailedRunRetry as| Record<string, unknown>@@ -1423,6 +1451,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptihint?.version !== 1 ||hint.actionId !== source.intent.id ||hint.failedRunId !== source.failedRunId ||+ (typeof source.intent.payload.taskRetryIntentId === "string" &&+ (context.taskRetryRequestId !== source.intent.payload.taskRetryIntentId || context.forceFreshSession !== true)) ||!Array.isArray(context.externalAttachmentOmissions) ||JSON.stringify(context.externalAttachmentOmissions.map((entry) =>@@ -1562,6 +1592,10 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptiif (!existing.length) {const context = {issueId: source.issueId,+ ...(typeof claimed.payload.taskRetryIntentId === "string" ? {+ taskRetryRequestId: claimed.payload.taskRetryIntentId, forceFreshSession: true,+ previousRunId: source.failedRunId,+ } : {}),taskKey: source.taskKey,source: `chat:${source.provider}`,wakeCommentId: source.commentIds.at(-1)!,@@ -1584,6 +1618,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptipayload: context,contextSnapshot: context,allowRunCoalescing: false,+ ...(typeof claimed.payload.taskRetryIntentId === "string"+ ? { taskRetryRequestId: claimed.payload.taskRetryIntentId } : {}),requestedByActorType: source.requestedByActorType,requestedByActorId: source.requestedByActorId,durableChatRequest: createDurableChatWakeupRequest({@@ -1602,6 +1638,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOptitx,current,claimed.companyId,+ typeof claimed.payload.taskRetryIntentId === "string" ? claimed.payload.taskRetryIntentId : undefined,);},}),diff --git a/server/src/services/chat-channels/task-retry-authority.ts b/server/src/services/chat-channels/task-retry-authority.tsnew file mode 100644index 0000000000..f0bcc91afc--- /dev/null+++ b/server/src/services/chat-channels/task-retry-authority.ts@@ -0,0 +1,45 @@+import { and, eq, sql } from "drizzle-orm";+import { agentWakeupRequests, environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";+import { readTaskRetryIntent } from "../task-retry.js";+import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession, recordedLocalExecutionStopped } from "../native-local-process-stop.js";+import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js";+import { adapterExecutionControls } from "../adapter-execution-control.js";++/** This receipt changes the workspace strategy, never the external principal,+ * accepted inbound batch, publication scope, or current conversation access. */+export async function readTaskChatRetryIntent(db: Db, input: {+ companyId: string; issueId: string; agentId: string; sourceRunId: string;+ intentId: string; chatActionId?: string;+}) {+ const [wake] = await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, input.intentId),+ eq(agentWakeupRequests.agentId, input.agentId), eq(agentWakeupRequests.reason, "task_retry"),+ eq(agentWakeupRequests.requestedByActorType, "user"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,+ sql`${agentWakeupRequests.idempotencyKey} like 'task-retry:%'`,+ ));+ const intent = readTaskRetryIntent(wake?.payload);+ return wake && intent && intent.generationId === wake.id && !intent.canonicalIntentId &&+ intent.sourceRunId === input.sourceRunId && intent.actorId === wake.requestedByActorId &&+ (!input.chatActionId || intent.chatActionId === input.chatActionId)+ ? { wake, intent } : null;+}++/** An unusable checkpoint does not prevent an isolated attempt. The old+ * executor must still be contained; a terminal database row is insufficient. */+export async function taskChatRetryExecutionStopped(db: Db, run: typeof heartbeatRuns.$inferSelect) {+ if (adapterExecutionControls.has(run.id) ||+ (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) return false;+ const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(+ eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id),+ )).for("share", { noWait: true });+ if (coordinator && (coordinator.leaseOwner || coordinator.resultId || coordinator.failureDetail?.successorRunId ||+ !["terminal_failure", "committed"].includes(coordinator.phase))) return false;+ const leases = await db.select().from(environmentLeases).where(and(+ eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),+ )).for("share", { noWait: true });+ if (leases.some(lease => lease.provider !== "local")) return leases.every(hasRemoteTerminationReceipt);+ return await recordedLocalExecutionStopped(db, run) ||+ await hasNativeLocalProcessStop(db, run.companyId, run.id) ||+ await hasHistoricalSuspendedNativeSession(db, run);+}diff --git a/server/src/services/durable-chat-wakeup.ts b/server/src/services/durable-chat-wakeup.tsindex c00ad561b1..62324a15ec 100644--- a/server/src/services/durable-chat-wakeup.ts+++ b/server/src/services/durable-chat-wakeup.ts@@ -116,7 +116,7 @@ export async function authorizeFailedChatRunRetryWake(): Promise<boolean> {const action = input.wakeupRequestId? await tx- .select({ companyId: chatActions.companyId, kind: chatActions.kind })+ .select({ companyId: chatActions.companyId, kind: chatActions.kind, payload: chatActions.payload }).from(chatActions).where(eq(chatActions.id, input.wakeupRequestId)).limit(1)@@ -144,7 +144,9 @@ export async function authorizeFailedChatRunRetryWake(!(selector as Record<string, unknown>).failedRunId ||(selector as Record<string, unknown>).failedRunId !==input.contextSnapshot.retryOfRunId ||- input.contextSnapshot.forceFreshSession === true ||+ (input.contextSnapshot.forceFreshSession === true &&+ (typeof action.payload.taskRetryIntentId !== "string" ||+ input.contextSnapshot.taskRetryRequestId !== action.payload.taskRetryIntentId)) ||["resumeFromRunId", "resumeSessionParams", "resumeSessionDisplayId"].some((key) => Object.hasOwn(input.contextSnapshot, key),)diff --git a/server/src/services/execution-continuation.ts b/server/src/services/execution-continuation.tsindex e6cb691c21..53f1f47981 100644--- a/server/src/services/execution-continuation.ts+++ b/server/src/services/execution-continuation.ts@@ -393,7 +393,20 @@ export async function buildExecutionContinuation(input: {sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is not null`,input.runId ? eq(agentWakeupRequests.runId, input.runId) : undefined,)) : [];- const authorization = continuationAuthorizations.find(value => failedRunId+ const taskRetryId = string(explicitContinuation.taskRetryRequestId);+ const [taskRetryWake] = taskRetryId && z.string().guid().safeParse(taskRetryId).success+ ? await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.id, taskRetryId),+ eq(agentWakeupRequests.agentId, input.agentId), eq(agentWakeupRequests.reason, "task_retry"),+ eq(agentWakeupRequests.requestedByActorType, "user"), eq(agentWakeupRequests.status, "coalesced"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,+ input.runId ? eq(agentWakeupRequests.runId, input.runId) : undefined,+ )) : [];+ const authorization = continuationAuthorizations.find(value => taskRetryId+ ? value.taskRetryRequestId === taskRetryId && taskRetryWake?.runId === value.runId &&+ taskRetryWake.requestedByActorId === value.actorId &&+ object(taskRetryWake.payload?.taskRetry).sourceRunId === value.previousRunId+ : failedRunId? value.failedRunId === failedRunId && retryWakes.some(wake =>wake.runId === value.runId && wake.requestedByActorId === value.actorId &&priorRuns.some(run => run.id === wake.runId && run.retryOfRunId === failedRunId))diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.tsindex f5ea0dfc87..3323bceb93 100644--- a/server/src/services/execution-recovery-resolution.ts+++ b/server/src/services/execution-recovery-resolution.ts@@ -25,6 +25,7 @@ import { parseIssueExecutionState } from "./issue-execution-policy.js";import { isSupersededConversationRun } from "./agent-conversations.js";import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";+import { readSystemRecovery } from "./system-recovery-state.js";/** An operator records observed outcomes; this is not permission to blindly retry. */export async function validateExecutionReconciliation(input: {@@ -351,6 +352,7 @@ export async function settleUnrecoverableExecutions(// Keep their evidence and record the policy change in the task's activity log.const obsoleteConversationHold = and(conversationRecoveryActionPredicate(),+ sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`,or(inArray(issueRecoveryActions.status, ["active", "escalated"]),sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`,@@ -412,6 +414,7 @@ export async function settleUnrecoverableExecutions(.where(and(not(conversationRecoveryActionPredicate()!),+ sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`,inArray(issueRecoveryActions.status, ["active", "escalated"]),eq(issueRecoveryActions.kind, "active_run_watchdog"),inArray(issueRecoveryActions.cause, [@@ -494,6 +497,10 @@ export async function settleUnrecoverableExecutions())return;+ // Adoption transfers maintenance to the retained-workspace owner.+ // This compatibility resolver must not close its hold or relabel it+ // as a user repair merely because old return-owner metadata is absent.+ if (readSystemRecovery(action.evidence)) return;// Give durable native recovery its chance; never preempt a resume,// replacement, result finalizer, or still-owned execution.if (diff --git a/server/src/services/explicit-native-continuation.test.ts b/server/src/services/explicit-native-continuation.test.tsindex ad7c352d71..854c5784b9 100644--- a/server/src/services/explicit-native-continuation.test.ts+++ b/server/src/services/explicit-native-continuation.test.ts@@ -1,4 +1,7 @@import { legacyControllerBootId } from "./legacy-controller-lease.js";+import { execFile } from "node:child_process";+import os from "node:os";+import { createSystemRecovery, failSystemRecovery, SystemRecoveryFailure } from "./system-recovery-state.js";import { instanceSettingsService } from "./instance-settings.js";import { createPostgresWakeQueueAdapter } from "../modules/wake-queue/adapters/postgres.js";import { createReleaseIssueExecution } from "../modules/wake-queue/application/use-cases.js";@@ -54,6 +57,48 @@ const support = await getEmbeddedPostgresTestSupport();actorType: "user", actorId: "board", reason: "issue_commented" };}type Fixture = Awaited<ReturnType<typeof seed>>;+ it("automatically admits a saved historical local message once after isolated fallback becomes eligible", async () => {+ const f = await seed();+ const processStartedAt = new Date();+ const child = execFile(process.execPath, ["-e", "process.exit(0)"]);+ await new Promise(resolve => child.on("exit", resolve));+ await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.sourceRunId));+ const [source] = await db.update(heartbeatRuns).set({+ runtimeMode: "legacy", nativeIssueId: null, issueId: f.issueId,+ processPid: child.pid, processGroupId: null, processStartedAt,+ runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } },+ resultJson: { workspaceRestoreFailure: "restore_failed" },+ }).where(eq(heartbeatRuns.id, f.sourceRunId)).returning();+ await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: source.id, agentId: f.agentId,+ eventType: "native.process_identity_recorded", stream: "system", level: "info",+ message: "Test child exited", payload: { targetKind: "local", hostname: os.hostname(),+ processPid: child.pid, processGroupId: null, processStartedAt: processStartedAt.toISOString() } });+ await db.update(issueRecoveryActions).set({ status: "active", ownerType: "system",+ cause: "legacy_execution_requires_reconciliation", returnOwnerAgentId: f.agentId,+ evidence: { runId: source.id, systemRecovery: failSystemRecovery(createSystemRecovery(source.id),+ new SystemRecoveryFailure("historical_source_missing", "use_alternative_strategy")) },+ }).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));+ // Keep execution queued so this admission test does not invoke a provider.+ await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" });+ const [wake] = await db.insert(agentWakeupRequests).values({+ companyId: f.companyId, agentId: f.agentId, source: "on_demand", reason: "issue_commented",+ requestedByActorType: "user", requestedByActorId: "board", status: "deferred_issue_execution",+ payload: { issueId: f.issueId, commentId: f.commentId, _paperclipWakeContext: {+ issueId: f.issueId, wakeReason: "issue_commented", wakeCommentId: f.commentId, wakeCommentIds: [f.commentId],+ } },+ }).returning();+ const service = heartbeatService(db);+ await service.resumeRemoteStopComments(source);+ await service.resumeRemoteStopComments(source);+ const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));+ expect(receipt).toMatchObject({ status: "coalesced" });+ const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),+ sql`${heartbeatRuns.contextSnapshot}->>'wakeCommentId' = ${f.commentId}`));+ expect(runs).toHaveLength(1);+ expect(runs[0].contextSnapshot?.explicitUserContinuation).toMatchObject({+ readiness: { mode: "fresh_isolated_workspace", retryIntentId: wake.id, sourceRunId: source.id },+ });+ }, 30_000);it.each(["handoff", "foreign_task", "running_source", "different_owner", "mention", "interaction", "chat"])("adopts former-owner comments only during an authorized handoff (%s)", async kind => {const f = await seed(), nextAgentId = randomUUID(), queueId = randomUUID();await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.tsindex 4b14a4ca46..c449167dd0 100644--- a/server/src/services/explicit-native-continuation.ts+++ b/server/src/services/explicit-native-continuation.ts@@ -1,3 +1,6 @@+import { canSelectFreshWorkspace, type ContinuationReadiness } from "./fresh-workspace-continuation.js";+import { readTaskRetryIntent } from "./task-retry.js";+import { readSystemRecovery } from "./system-recovery-state.js";import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";import { hasVerifiedWorkspaceRepair } from "./workspace-recovery-receipt.js";import { createHash } from "node:crypto";@@ -5,7 +8,7 @@ import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";import { canContinueCancelledRun } from "./run-cancellation.js";import { readQueuedInteractionResponse } from "./queued-interaction-response.js";import { isCancelledNativeStartup } from "./cancelled-native-startup.js";-import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession } from "./native-local-process-stop.js";+import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession, recordedLocalExecutionStopped } from "./native-local-process-stop.js";import { completeTerminatedRemoteNativeSessionCleanup } from "../vendor/paperclip-runner/index.js";import { hasRemoteTerminationReceipt, remoteLeaseCleanupScope } from "./remote-execution-termination.js";import { z } from "zod";@@ -78,24 +81,33 @@ export async function admitExplicitNativeContinuation(input: {actorType: string | null | undefined; actorId: string | null | undefined;reason: string | null; commentId: string | null; successorRunId: string;failedRunId?: string | null;+ taskRetryRequestId?: string;/** Server-recorded board intent to send an existing legacy message queue. */queuedCommentInterruptId?: string;/** Internal delivery of an unconsumed, user-authored saved queue entry. */queuedCommentRequestId?: string;dryRun?: boolean;onBlocked?: (reason: string, message: string) => void;-}): Promise<{ previousRunId: string; commentId: string | null; failedRunId?: string } | null> {+}): Promise<{ previousRunId: string; commentId: string | null; failedRunId?: string; taskRetryRequestId?: string; readiness?: ContinuationReadiness } | null> {const { db, companyId, issueId, agentId, actorId, commentId } = input;const blocked = (reason: string, message: string) => { input.onBlocked?.(reason, message); return null; };if (input.actorType !== "user" || !actorId) return null;const retry = input.reason === "retry_failed_run" &&z.string().guid().safeParse(input.failedRunId).success;- if (!retry && !input.queuedCommentInterruptId && (!commentId || !z.string().guid().safeParse(commentId).success ||+ if (!retry && !input.taskRetryRequestId && !input.queuedCommentInterruptId && (!commentId || !z.string().guid().safeParse(commentId).success ||!["issue_commented", "issue_reopened_via_comment"].includes(input.reason ?? ""))) return null;const [task] = await db.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId),));if (!task || task.assigneeAgentId !== agentId || ["done", "cancelled"].includes(task.status)) return null;+ const [retryWake] = input.taskRetryRequestId ? await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.id, input.taskRetryRequestId),+ eq(agentWakeupRequests.agentId, agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),+ eq(agentWakeupRequests.requestedByActorType, "user"), eq(agentWakeupRequests.requestedByActorId, actorId),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,+ )) : [];+ const taskRetry = readTaskRetryIntent(retryWake?.payload);+ if (input.taskRetryRequestId && (!taskRetry || taskRetry.generationId !== retryWake?.id || taskRetry.actorId !== actorId)) return null;const [interruptQueue] = input.queuedCommentInterruptId ? await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.id, input.queuedCommentInterruptId),eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.agentId, agentId),@@ -127,14 +139,14 @@ export async function admitExplicitNativeContinuation(input: {if (undelivered.at(-1) !== commentId) return null;partiallyDeliveredQueue = undelivered.length !== ids.length;}- const [comment] = retry || response ? [] : await db.select().from(issueComments).where(and(+ const [comment] = retry || taskRetry || response ? [] : await db.select().from(issueComments).where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId),eq(issueComments.id, commentId!), eq(issueComments.authorType, "user"),queuedInterrupt ? undefined : eq(issueComments.authorUserId, actorId), isNull(issueComments.createdByRunId),isNull(issueComments.deletedAt),));- if (!retry && !response && !comment?.body.trim()) return null;- const authorizedAt = response?.comment.createdAt ?? comment?.createdAt ?? new Date();+ if (!retry && !taskRetry && !response && !comment?.body.trim()) return null;+ const authorizedAt = response?.comment.createdAt ?? comment?.createdAt ?? retryWake?.requestedAt ?? new Date();const [agent] = await db.select().from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, agentId)));if (!agent || (!isConversationAdapter(agent.adapterType) && agent.adapterType !== "paperclip_runner")) return null;if (queuedInterrupt && !isConversationAdapter(agent.adapterType) && !response?.source.requiresFreshSession) return null;@@ -150,9 +162,6 @@ export async function admitExplicitNativeContinuation(input: {if (!actions.length) return null;const blocker = await getExecutionBlocker(db, companyId, issueId);if (blocker && blocker.recoveryActionId === null) return null;- if (blocker?.workspaceRepairRequired && ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"].includes(blocker.cause)) {- return blocked("workspace_reconstruction_required", "Recover the saved files or record reconstruction before continuing. Your message is saved.");- }const [pendingInteraction] = await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(eq(issueThreadInteractions.companyId, companyId), eq(issueThreadInteractions.issueId, issueId),eq(issueThreadInteractions.status, "pending"),@@ -165,6 +174,8 @@ export async function admitExplicitNativeContinuation(input: {if (pendingInteraction || pendingApproval) return blocked("decision_pending", "A pending approval or question must be resolved before this message can start.");const sources: Run[] = [];+ let readiness: ContinuationReadiness | undefined;+ const freshSources = new Map<string, string>();const stoppedSessions: Array<{ evidence: Record<string, unknown>; retire: () => boolean }> = [];const cancelledStartupIds = new Set<string>();for (const action of actions) {@@ -175,17 +186,20 @@ export async function admitExplicitNativeContinuation(input: {eq(heartbeatRuns.companyId, companyId), sql`${heartbeatRuns.id}::text = ${runId}`,));if (!run || run.agentId !== agentId || !terminal.includes(run.status) ||- (run.nativeIssueId ?? run.contextSnapshot?.issueId) !== issueId ||+ (run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId) !== issueId ||!run.finishedAt) return blocked("source_unavailable", "The previous execution has not finished or its owner changed. Your message is saved.");if (!queuedInterrupt && !queuedRequest && authorizedAt <= run.finishedAt) return blocked("message_predates_stop", "This message arrived before the previous run stopped. Send a new message to continue.");if (adapterExecutionControls.has(run.id)) return blocked("execution_settling", "Waiting for the previous run to stop. Your message will start automatically.");const unusedAdmission = run.status === "cancelled" && !run.startedAt &&run.errorCode === "execution_reconciliation_required" &&!run.processPid && !run.processGroupId && !run.nativeSessionId;+ const freshIntent = await canSelectFreshWorkspace({ db, companyId, issueId, agentId, actorId,+ sourceRunId: run.id, evidence: action.evidence, taskRetryRequestId: input.taskRetryRequestId,+ queuedRequestId: input.queuedCommentRequestId });const legacyUserTurn = run.runtimeMode === "legacy" &&action.cause === "legacy_execution_requires_reconciliation" &&(isConversationAdapter(agent.adapterType) ||- (agent.adapterType === "paperclip_runner" && await hasVerifiedWorkspaceRepair(db, run)));+ (agent.adapterType === "paperclip_runner" && (freshIntent || await hasVerifiedWorkspaceRepair(db, run))));// Saved input is a request for a new turn, never permission to undo an// operator Stop or redeliver a message already consumed by this run.if (queuedRequest && !queuedInterrupt && (run.contextSnapshot?.wakeCommentId === commentId ||@@ -211,13 +225,23 @@ export async function admitExplicitNativeContinuation(input: {if (!lockedRun || lockedRun.status !== run.status || lockedRun.agentId !== run.agentId ||lockedRun.finishedAt?.getTime() !== run.finishedAt.getTime()) return null;run = lockedRun;+ if (coordinator && coordinator.phase !== "committed" && coordinator.resultId &&+ readSystemRecovery(action.evidence)) {+ const [completedResult] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(+ eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issueId),+ eq(nativeRunResults.runId, run.id), eq(nativeRunResults.id, coordinator.resultId),+ eq(nativeRunResults.schemaStatus, "accepted"),+ sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`,+ )).limit(1);+ if (completedResult) return blocked("finalizing_saved_result", "Paperclip is finishing the saved result.");+ }// A repaired export no longer blocks execution. Its machine receipt still// binds the saved user turn; finalized file state alone is insufficient.if (["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"].includes(action.cause)- && !await hasVerifiedWorkspaceRepair(db, run)) return blocked("workspace_repair_required",+ && !freshIntent && !await hasVerifiedWorkspaceRepair(db, run)) return blocked("workspace_repair_required","Paperclip is recovering saved work before continuing. Your message is saved.");if ((run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive" || hasRequiredWorkspaceRecovery(run.resultJson))- && !await hasVerifiedWorkspaceRepair(db, run)) {+ && !freshIntent && !await hasVerifiedWorkspaceRepair(db, run)) {return blocked("workspace_repair_required", "Paperclip is recovering saved work before continuing. Your message is saved.");}const cancelledStartup = await isCancelledNativeStartup(db, run, coordinator);@@ -272,6 +296,8 @@ export async function admitExplicitNativeContinuation(input: {} else {if (leases.some(lease => !lease.releasedAt || lease.cleanupStatus === "failed")) return blocked("local_cleanup", "Waiting for the previous environment to finish cleanup. Your message will start automatically.");if (!unusedAdmission && !cancelledStartup) {+ if (freshIntent && (run.processPid || run.processGroupId) && !await recordedLocalExecutionStopped(db, run))+ return blocked("process_identity_missing", "Paperclip is verifying that the previous session stopped.");// A missing process identity is not evidence that a provider exited.if (!run.processPid && !run.processGroupId &&!await hasNativeLocalProcessStop(db, companyId, run.id) &&@@ -288,11 +314,18 @@ export async function admitExplicitNativeContinuation(input: {if (!stopped) return blocked("local_cleanup", "Waiting for the previous provider and its tools to stop. Your message is saved.");stoppedSessions.push(stopped);}+ if (freshIntent && !await hasVerifiedWorkspaceRepair(db, run)) {+ freshSources.set(run.id, freshIntent);+ readiness = { mode: "fresh_isolated_workspace", retryIntentId: freshIntent, sourceRunId: run.id,+ retainedSourceIds: [...new Set([...(readiness?.mode === "fresh_isolated_workspace" ? readiness.retainedSourceIds : []),+ ...leases.map(lease => lease.id)])] };+ }sources.push(run);}const nativeSources = sources.filter(run => run.runtimeMode === "native");const executedSources = sources.filter(run => run.runtimeMode === "native" || run.errorCode !== "execution_reconciliation_required" || run.startedAt);- if (!executedSources.length || (retry && !sources.some(run => run.id === input.failedRunId))) return null;+ if (!executedSources.length || (retry && !sources.some(run => run.id === input.failedRunId)) ||+ (taskRetry && !sources.some(run => run.id === taskRetry.sourceRunId))) return null;const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),or(eq(heartbeatRuns.nativeIssueId, issueId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`),@@ -305,7 +338,9 @@ export async function admitExplicitNativeContinuation(input: {await buildExecutionContinuation({ db, companyId, issueId, agentId,context: { previousRunId: previous.id, wakeCommentId: commentId },summary: null, exposeLowTrustRaw: false });- if (input.dryRun) return { previousRunId: previous.id, commentId, ...(retry ? { failedRunId: input.failedRunId! } : {}) };+ const continuation = { previousRunId: previous.id, commentId, ...(retry ? { failedRunId: input.failedRunId! } : {}),+ ...(taskRetry ? { taskRetryRequestId: input.taskRetryRequestId! } : {}), ...(readiness ? { readiness } : {}) };+ if (input.dryRun) return continuation;for (const stopped of stoppedSessions) {if (!stopped.retire()) return blocked("local_cleanup", "The previous provider cleanup changed. Your message is saved.");await appendHeartbeatRunEvent(db, {@@ -315,7 +350,7 @@ export async function admitExplicitNativeContinuation(input: {payload: stopped.evidence,});}- const authorization = { actorId, commentId, ...(response ? { interactionId: response.source.interactionId } : {}), ...(retry ? { failedRunId: input.failedRunId } : {}),+ const authorization = { ...continuation, actorId, commentId, ...(response ? { interactionId: response.source.interactionId } : {}), ...(retry ? { failedRunId: input.failedRunId } : {}),...(comment ? { commentUpdatedAt: comment.updatedAt.toISOString(),commentBodyHash: createHash("sha256").update(comment.body).digest("hex") } : {}),...(queuedInterrupt ? { queuedCommentInterruptId: input.queuedCommentInterruptId } : {}),@@ -342,6 +377,10 @@ export async function admitExplicitNativeContinuation(input: {resolutionNote: "The user continued after the prior execution stopped. No action outcomes were inferred.",wakePolicy: null, monitorPolicy: null,evidence: { ...action.evidence, explicitUserContinuation: authorization,+ ...(freshSources.has(String(action.evidence.runId)) && readSystemRecovery(action.evidence) ? {+ systemRecovery: { ...readSystemRecovery(action.evidence)!,+ revision: readSystemRecovery(action.evidence)!.revision + 1, freshAttemptRunId: input.successorRunId },+ } : {}),...(action.evidence.automaticRecovery ? { automaticRecovery: {...(action.evidence.automaticRecovery as Record<string, unknown>), replay: "explicit_user_continuation",} } : {}),@@ -353,7 +392,14 @@ export async function admitExplicitNativeContinuation(input: {details: { continuation: retry ? "explicit_user_retry" : "explicit_user_message", ...authorization,recoveryActionIds: actions.map(action => action.id), previousRunIds: sources.map(run => run.id) },});- return { previousRunId: previous.id, commentId, ...(retry ? { failedRunId: input.failedRunId! } : {}) };+ if (readiness) await persistActivity(db, { companyId, actorType: "system", actorId: "task-recovery",+ action: "issue.fresh_workspace_selected", entityType: "issue", entityId: issueId,+ details: { ...readiness, runId: input.successorRunId } });+ if (input.taskRetryRequestId) await db.update(agentWakeupRequests).set({+ payload: sql`jsonb_set(${agentWakeupRequests.payload}, '{taskRetry,strategy}',+ ${JSON.stringify(readiness?.mode === "fresh_isolated_workspace" ? "fresh_isolated_workspace" : "continue")}::jsonb)`,+ }).where(and(eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.id, input.taskRetryRequestId)));+ return continuation;}/** Re-admit a bounded automatic retry without lending it its parent's receipt.diff --git a/server/src/services/fresh-workspace-continuation.ts b/server/src/services/fresh-workspace-continuation.tsnew file mode 100644index 0000000000..9cb59b0a9a--- /dev/null+++ b/server/src/services/fresh-workspace-continuation.ts@@ -0,0 +1,125 @@+import { and, eq, sql } from "drizzle-orm";+import { agentWakeupRequests, environmentLeases, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";+import { verifiedWorkspaceRepairReceipt } from "./workspace-recovery-receipt.js";+import { persistActivity } from "./activity-log.js";+import { readSystemRecovery } from "./system-recovery-state.js";+import { readTaskRetryIntent } from "./task-retry.js";+import { z } from "zod";++export type ContinuationReadiness =+ | { mode: "resume_preserved_workspace"; preservationReceiptId: string }+ | { mode: "fresh_isolated_workspace"; retryIntentId: string; sourceRunId: string; retainedSourceIds: string[] };+const freshReadinessSchema = z.object({+ mode: z.literal("fresh_isolated_workspace"), retryIntentId: z.string().uuid(),+ sourceRunId: z.string().uuid(), retainedSourceIds: z.array(z.string().uuid()),+});++/** This chooses a strategy, never establishes termination or effect safety.+ * Admission verifies those independently before it can persist this receipt. */+export async function canSelectFreshWorkspace(input: {+ db: Db; companyId: string; issueId: string; agentId: string; actorId: string;+ sourceRunId: string; evidence: Record<string, unknown>; taskRetryRequestId?: string;+ queuedRequestId?: string;+}): Promise<string | null> {+ const system = readSystemRecovery(input.evidence);+ const requestId = input.taskRetryRequestId ?? input.queuedRequestId;+ if (!requestId || !system || system.sourceRunId !== input.sourceRunId || system.freshAttemptRunId) return null;+ if (system.providerCooldownAt !== null && system.providerCooldownAt > Date.now()) return null;+ const [wake] = await input.db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, requestId),+ eq(agentWakeupRequests.agentId, input.agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,+ ));+ if (!wake) return null;+ if (input.taskRetryRequestId) {+ const retry = readTaskRetryIntent(wake.payload);+ if (retry?.generationId !== wake.id || retry.sourceRunId !== input.sourceRunId ||+ retry.actorId !== input.actorId || wake.requestedByActorId !== input.actorId) return null;+ return wake.id;+ }+ const [source] = await input.db.select({ context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.sourceRunId),+ ));+ const recoveryPolicy = source?.context?.automaticRecovery as Record<string, unknown> | undefined;+ if (recoveryPolicy?.allowFreshWorkspace === false) return null;+ // Saved input can use the automatic fallback only after maintenance settled.+ // A pending export keeps its current attempt; it cannot spawn another agent.+ return ["complete", "exhausted"].includes(system.state) ? wake.id : null;+}++/** Preparation trusts the committed admission receipt, not a raw wake payload. */+export async function readFreshWorkspaceReadiness(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,+ "id" | "companyId" | "agentId" | "issueId" | "nativeIssueId" | "contextSnapshot">): Promise<ContinuationReadiness | null> {+ const issueId = run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId;+ if (typeof issueId !== "string") return null;+ const [action] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId),+ sql`${issueRecoveryActions.evidence}#>>'{explicitUserContinuation,runId}' = ${run.id}`,+ sql`${issueRecoveryActions.evidence}#>>'{explicitUserContinuation,readiness,mode}' = 'fresh_isolated_workspace'`,+ sql`${issueRecoveryActions.evidence}->>'runId' = ${issueRecoveryActions.evidence}#>>'{explicitUserContinuation,readiness,sourceRunId}'`,+ )).limit(1);+ if (!action) {+ // Normal dispatch can admit a retry after a pre-provider failure without a+ // recovery hold. The committed wake is its authority. It still needs an+ // independent directory: falling back to the agent's configured cwd would+ // reopen the original source after a failed fresh attempt.+ const [wake] = await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId),+ eq(agentWakeupRequests.runId, run.id), eq(agentWakeupRequests.reason, "task_retry"),+ eq(agentWakeupRequests.status, "coalesced"), eq(agentWakeupRequests.requestedByActorType, "user"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,+ )).limit(1);+ const intent = readTaskRetryIntent(wake?.payload);+ if (!wake || !intent || intent.canonicalIntentId ||+ intent.generationId !== wake.id || intent.actorId !== wake.requestedByActorId ||+ run.contextSnapshot?.taskRetryRequestId !== wake.id ||+ !["evaluate", "continue", "fresh_isolated_workspace"].includes(intent.strategy)) return null;+ if (intent.chatActionId) {+ const [chatWake] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId),+ eq(agentWakeupRequests.id, intent.chatActionId), eq(agentWakeupRequests.runId, run.id),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,+ ));+ if (!chatWake || (run.contextSnapshot?.chatFailedRunRetry as Record<string, unknown> | undefined)?.actionId !== chatWake.id)+ return null;+ }+ const [source] = await db.select().from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId),+ eq(heartbeatRuns.id, intent.sourceRunId), sql`coalesce(${heartbeatRuns.nativeIssueId}::text,+ ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`,+ )).limit(1);+ if (!source) throw new Error("Fresh retry source changed");+ if (intent.strategy !== "fresh_isolated_workspace") {+ const preservationReceiptId = await verifiedWorkspaceRepairReceipt(db, source);+ if (preservationReceiptId) return { mode: "resume_preserved_workspace", preservationReceiptId };+ }+ const leases = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(+ eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, source.id),+ ));+ const readiness: ContinuationReadiness = { mode: "fresh_isolated_workspace",+ retryIntentId: wake.id, sourceRunId: source.id, retainedSourceIds: leases.map(lease => lease.id) };+ await db.transaction(async tx => {+ const changed = await tx.update(agentWakeupRequests).set({+ payload: sql`jsonb_set(${agentWakeupRequests.payload}, '{taskRetry,strategy}', '"fresh_isolated_workspace"'::jsonb)`,+ }).where(and(eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.runId, run.id),+ sql`${agentWakeupRequests.payload}#>>'{taskRetry,strategy}' in ('evaluate', 'continue')`)).returning({ id: agentWakeupRequests.id });+ if (changed.length) await persistActivity(tx as unknown as Db, { companyId: run.companyId,+ actorType: "system", actorId: "task-recovery", action: "issue.fresh_workspace_selected",+ entityType: "issue", entityId: issueId, runId: run.id, details: { ...readiness } });+ });+ return readiness;+ }+ const authorization = action?.evidence.explicitUserContinuation as Record<string, unknown> | undefined;+ const parsed = freshReadinessSchema.safeParse(authorization?.readiness);+ if (!parsed.success) return null;+ const readiness = parsed.data;+ if (action?.evidence.runId !== readiness.sourceRunId ||+ readSystemRecovery(action.evidence)?.freshAttemptRunId !== run.id) return null;+ const [wake] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.id, readiness.retryIntentId),+ eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.runId, run.id),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,+ )).limit(1);+ if (!wake) throw new Error("Fresh workspace admission lost its input receipt");+ return readiness;+}diff --git a/server/src/services/fresh-workspace-seed.ts b/server/src/services/fresh-workspace-seed.tsnew file mode 100644index 0000000000..2e9c6d032f--- /dev/null+++ b/server/src/services/fresh-workspace-seed.ts@@ -0,0 +1,68 @@+import { execFile as execFileCallback } from "node:child_process";+import { lstat, mkdtemp, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";+import path from "node:path";+import { promisify } from "node:util";+import { materializeIsolatedTaskDirectory } from "./isolated-task-directory.js";++const execFile = promisify(execFileCallback);+const gitOptions = { timeout: 120_000, maxBuffer: 1024 * 1024 };++/** Seed from committed objects, never from a possibly changing old directory.+ * --no-local also prevents shared objects/hardlinks and copied Git authority.+ * The caller authorizes the source before calling this function. */+export async function materializeFreshWorkspaceSeed(input: {+ companyId: string; issueId: string; runId: string; sourceCwd: string; baseRef?: string | null; repoUrl?: string | null;+ beforeCopy?(sourceCwd: string, targetCwd: string): Promise<void>;+}) {+ const root = await materializeIsolatedTaskDirectory({+ companyId: input.companyId, issueId: input.issueId, attemptId: input.runId,+ });+ const destination = path.join(root, "workspace");+ const receiptPath = path.join(root, "seed.json");+ const existing = await lstat(destination).catch((error: NodeJS.ErrnoException) => {+ if (error.code !== "ENOENT") throw error;+ return null;+ });+ if (existing) {+ if (!existing.isDirectory() || existing.isSymbolicLink() || await realpath(destination) !== destination)+ throw new Error("Fresh workspace identity changed");+ const receiptStat = await lstat(receiptPath);+ if (!receiptStat.isFile() || receiptStat.isSymbolicLink()) throw new Error("Fresh workspace seed receipt changed");+ const receipt = JSON.parse(await readFile(receiptPath, "utf8"));+ if (receipt.runId !== input.runId || receipt.companyId !== input.companyId || receipt.issueId !== input.issueId)+ throw new Error("Fresh workspace seed receipt changed");+ return destination;+ }+ const staging = await mkdtemp(path.join(root, ".seed-"));+ try {+ await input.beforeCopy?.(input.sourceCwd, destination);+ const probe = await execFile("git", ["-C", input.sourceCwd, "rev-parse", "--git-dir"],+ { ...gitOptions, env: { ...process.env, LC_ALL: "C" } })+ .then(() => true, (error: { code?: number; stderr?: string }) => {+ if (error.code === 128 && error.stderr?.startsWith("fatal: not a git repository")) return false;+ // Permission, corruption and transport failures are not permission to+ // replace a recorded repository with an empty workspace.+ throw error;+ });+ let commit: string | null = null;+ if (probe) {+ const ref = input.baseRef || "HEAD";+ const resolved = await execFile("git", ["-C", input.sourceCwd, "rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], gitOptions);+ commit = resolved.stdout.trim();+ if (!/^[a-f0-9]{40,64}$/.test(commit)) throw new Error("Invalid fresh workspace seed commit");+ await execFile("git", ["clone", "--no-local", "--no-checkout", "--", input.sourceCwd, staging], gitOptions);+ await execFile("git", ["-C", staging, "-c", "core.hooksPath=/dev/null", "checkout", "--detach", commit], gitOptions);+ // The old local directory is not a publication target for this attempt.+ await execFile("git", ["-C", staging, "remote", "remove", "origin"], gitOptions);+ if (input.repoUrl) await execFile("git", ["-C", staging, "remote", "add", "origin", input.repoUrl], gitOptions);+ }+ await writeFile(receiptPath, JSON.stringify({+ schema: "paperclip.fresh-workspace-seed.v1", companyId: input.companyId,+ issueId: input.issueId, runId: input.runId, commit,+ }), { mode: 0o600 });+ await rename(staging, destination);+ return destination;+ } finally {+ await rm(staging, { recursive: true, force: true });+ }+}diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex e787fec903..a07388ed2a 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -1,3 +1,4 @@+import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js";import { promptInjectionPreventionService } from "./prompt-injection-prevention.js";import { createHeartbeatAgentStatus } from "./heartbeat/agent-status.js";import { heartbeatExternalProvider, nativeRuntimeHasInstructionFilesystem } from "./heartbeat/external-provider.js";@@ -2195,7 +2196,8 @@ export function heartbeatService(const externalProvider = heartbeatExternalProvider({ run, agent });const [taskWorkspaceIntentRow] = issueId && !externalProvider ? await db.select({ intent: issues.workspaceSelection }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))) : [];- const runtimeWorkspaceSelectionEnabled = !externalProvider && taskWorkspaceRuntimeSelectionEnabled({ legacyUiEnabled: isolatedWorkspacesEnabled, hasTypedSelection: Boolean(taskWorkspaceIntentRow?.intent), hasBinding: Boolean(issueContext?.executionWorkspaceId) });+ const freshWorkspace = await readFreshWorkspaceReadiness(db, run);+ const runtimeWorkspaceSelectionEnabled = !externalProvider && (freshWorkspace?.mode === "fresh_isolated_workspace" || taskWorkspaceRuntimeSelectionEnabled({ legacyUiEnabled: isolatedWorkspacesEnabled, hasTypedSelection: Boolean(taskWorkspaceIntentRow?.intent), hasBinding: Boolean(issueContext?.executionWorkspaceId) }));const parsedIssueExecutionWorkspaceSettings =parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings,@@ -2508,8 +2510,8 @@ export function heartbeatService(legacyUseProjectWorkspace:issueAssigneeOverrides?.useProjectWorkspace ?? null,});- const requestedExecutionWorkspaceMode =- trustPreset.kind === "low_trust_review" &&+ const requestedExecutionWorkspaceMode = freshWorkspace?.mode === "fresh_isolated_workspace"+ ? "isolated_workspace" : trustPreset.kind === "low_trust_review" &&resolvedExecutionWorkspaceMode === "shared_workspace"? "isolated_workspace": resolvedExecutionWorkspaceMode;@@ -2526,9 +2528,8 @@ export function heartbeatService(description: issueContext.description,projectId: issueContext.projectId,projectWorkspaceId: issueContext.projectWorkspaceId,- executionWorkspaceId: issueContext.executionWorkspaceId,- executionWorkspacePreference:- issueContext.executionWorkspacePreference,+ executionWorkspaceId: freshWorkspace?.mode === "fresh_isolated_workspace" ? null : issueContext.executionWorkspaceId,+ executionWorkspacePreference: freshWorkspace?.mode === "fresh_isolated_workspace" ? "create_new" : issueContext.executionWorkspacePreference,}: null;const storedLedgerScope = parseObject(parseObject(run.usageJson).ledgerScope);@@ -2583,7 +2584,7 @@ export function heartbeatService(} = await timePreparation("environment_selection", () => selectHeartbeatEnvironment(db, {run, agent,task: { issueRef, issueContext, issueId, context, executionProjectId, workspaceProjectContext, boundSourceWorkspace,- hasSelectedWorkspaceSource: Boolean(selectedWorkspaceSource), taskWorkspaceIntent: taskWorkspaceIntentRow?.intent ?? null, responsibleUserId },+ freshWorkspace, hasSelectedWorkspaceSource: Boolean(selectedWorkspaceSource), taskWorkspaceIntent: taskWorkspaceIntentRow?.intent ?? null, responsibleUserId },policy: {trustPreset, requestedExecutionWorkspaceMode, isolatedWorkspacesEnabled: runtimeWorkspaceSelectionEnabled,projectExecutionWorkspacePolicy, issueExecutionWorkspaceSettings,@@ -2661,6 +2662,7 @@ export function heartbeatService(responsibleUserId,previousSessionParams,workspaceSelection: taskWorkspaceIntentRow?.intent ?? null,+ freshWorkspace,},policy: {trustPreset,@@ -4079,6 +4081,7 @@ export function heartbeatService(releaseEnvironmentLeasesForRun,resumeRemoteStopComments,+ resumeTaskRetry: runControl.resumeTaskRetry,resumeQueuedCommentInterrupt,resumeExecutionWaitComments,diff --git a/server/src/services/heartbeat/environment-selection.ts b/server/src/services/heartbeat/environment-selection.tsindex 1e92b2b0bc..f8e001e5c1 100644--- a/server/src/services/heartbeat/environment-selection.ts+++ b/server/src/services/heartbeat/environment-selection.ts@@ -40,6 +40,7 @@ export interface HeartbeatEnvironmentSelectionInput {agent: Pick<typeof agents.$inferSelect,"id" | "companyId" | "adapterType" | "adapterConfig" | "defaultEnvironmentId">;task: {+ freshWorkspace?: import("../fresh-workspace-continuation.js").ContinuationReadiness | null;issueRef: Pick<Issue, "id" | "projectWorkspaceId" | "executionWorkspaceId" | "executionWorkspacePreference"> | null;issueContext: Pick<Issue, "assigneeAgentId" | "executionWorkspaceSettings"> | null;issueId: string | null;@@ -102,6 +103,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnvironconst isDotRun = heartbeatExternalProvider({ run, agent }) !== null;const persistedNativeExecutionWorkspaceId =persistedNativeExecutionInput?.binding.executionWorkspaceId ?? null;+ const fresh = input.task.freshWorkspace?.mode === "fresh_isolated_workspace";const requestedExecutionWorkspaceId = isDotRun ? null :persistedNativeExecutionWorkspaceId ??readNonEmptyString(issueRef?.executionWorkspaceId);@@ -260,6 +262,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnvironcompanyId: agent.companyId,agentId: agent.id,issueId,+ ...(fresh ? { freshAttemptId: run.id } : {}),admittedCwd: nativeExecutionUsesTaskWorkspace(persistedNativeExecutionInput)? persistedNativeExecutionInput.workspace.cwd : null,});@@ -440,7 +443,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnvironpreserveImplicitDefaultSettings: ["project", "task_default"].includes(taskWorkspaceIntent.source) });}const explicitTaskDirectory = !isDotRun && taskWorkspaceIntent?.selection.kind === "task_directory";- const useIsolatedTaskDirectory = !isDotRun && issueRef !== null && shouldUseIsolatedTaskDirectory({+ const useIsolatedTaskDirectory = !isDotRun && issueRef !== null && ((fresh && !workspaceProjectContext?.hasWorkspace && !issueRef.projectWorkspaceId) || shouldUseIsolatedTaskDirectory({trustPreset: trustPreset.kind,environmentDriver: selectedEnvironmentForConfig?.driver ?? null,mode: requestedExecutionWorkspaceMode,@@ -452,7 +455,7 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnvironprojectExecutionWorkspacePolicy?.workspaceStrategy,issueExecutionWorkspaceSettings?.workspaceStrategy,],- });+ }));return {persistedRunnerProfile,persistedNativeExecutionInput,diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.tsindex 61a9c3087c..abb2f520ba 100644--- a/server/src/services/heartbeat/queue.ts+++ b/server/src/services/heartbeat/queue.ts@@ -1,3 +1,5 @@+import { authorizationService } from "../authorization.js";+import { assertTaskRetryConversationAllowed, readTaskRetryIntent, retireSupersededTaskRetry } from "../task-retry.js";import { withExternalAdmissionGuard, assertNoExternalOverlap } from "../../modules/external-agents/index.js";import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js";import { normalizeAgentNameKey } from "./retries.js";@@ -2138,6 +2140,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeif (payload) {delete payload.queuedCommentInterrupt;delete payload.manualUserWake;+ delete payload.taskRetry;}if (opts.manualUserWake) {if (opts.requestedByActorType !== "user" || !opts.requestedByActorId || opts.failedRunId) {@@ -2167,6 +2170,28 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependelet issueId =readNonEmptyString(enrichedContextSnapshot.issueId) ?? issueIdFromPayload;if (executionReconciliationWake && !issueId) return null;+ const durableRequest = opts.durableChatRequest;+ let taskRetryActorId: string | null = null;+ if (opts.taskRetryRequestId) {+ const [receipt] = await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.id, opts.taskRetryRequestId), eq(agentWakeupRequests.agentId, agentId),+ eq(agentWakeupRequests.status, "deferred_issue_execution"),+ eq(agentWakeupRequests.requestedByActorType, "user"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId ?? ""}`,+ ));+ const retry = readTaskRetryIntent(receipt?.payload);+ if (!receipt || retry?.generationId !== receipt.id || retry.canonicalIntentId ||+ retry.actorId !== receipt.requestedByActorId) return null;+ const chatRetry = retry.chatActionId && durableRequest?.id === retry.chatActionId &&+ durableRequest.failedRunRetry?.failedRunId === retry.sourceRunId;+ if (retry.chatActionId ? !chatRetry :+ opts.requestedByActorType !== "user" || retry.actorId !== opts.requestedByActorId) return null;+ taskRetryActorId = retry.actorId;+ enrichedContextSnapshot.forceFreshSession = true;+ enrichedContextSnapshot.previousRunId = retry.sourceRunId;+ enrichedContextSnapshot.taskRetryRequestId = receipt.id;+ }+let agent = await getAgent(agentId);if (!agent) throw notFound("Agent not found");@@ -2180,6 +2205,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeif (reason === "issue_comment_mentioned" || enrichedContextSnapshot.wakeReason === "issue_comment_mentioned") return null;if (issueId) {const conversation = await getIssueExecutionContext(agent.companyId, issueId);+ if (taskRetryActorId && conversation) await assertTaskRetryConversationAllowed(db, conversation, taskRetryActorId);if (reason === "issue_children_completed" && conversation?.originKind === "onboarding_first_task") enrichedContextSnapshot.onboardingCompletion = true;if (isConversation(conversation)) {if (opts.manualUserWake && conversation!.conversationUserId !== opts.requestedByActorId) {@@ -2188,7 +2214,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeif (isConversationExecutionWake(conversation, reason ?? readNonEmptyString(enrichedContextSnapshot.wakeReason))) return null;if (agent.id !== conversation!.conversationAgentId) return null;if (!(await instanceSettings.getExperimental()).enableAgentChat) return null;- if (!wakeCommentId && isWaitingConversation(conversation) && !hasInteractionContinuationWakeContext(enrichedContextSnapshot) && reason !== CHAT_COMPLETION_WAKE_REASON) return null;+ if (!wakeCommentId && !opts.taskRetryRequestId && isWaitingConversation(conversation) && !hasInteractionContinuationWakeContext(enrichedContextSnapshot) && reason !== CHAT_COMPLETION_WAKE_REASON) return null;}}if (agent.adapterType === "paperclip_runner") {@@ -2239,7 +2265,6 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende}}- const durableRequest = opts.durableChatRequest;const caseRequest = opts.durableCaseHandoffRequest;const waitForCaseAdmission = (reason: string, message: string): never => {// The case ledger is the outbox. Roll back this admission attempt rather@@ -2248,7 +2273,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende};let caseReceipt: { id: string; requestedAt: Date } | undefined;if (caseRequest) {- if (opts.durableChatRequest || opts.durableDotRequest || opts.durableMuseRequest || source !== "assignment" || reason !== "case_handoff")+ if (opts.taskRetryRequestId || opts.durableChatRequest || opts.durableDotRequest || opts.durableMuseRequest || source !== "assignment" || reason !== "case_handoff")throw conflict("Invalid case handoff wake authority");const [handoff] = await db.select().from(caseHandoffs).where(and(eq(caseHandoffs.id, caseRequest.handoffId),eq(caseHandoffs.companyId, agent.companyId), eq(caseHandoffs.issueId, caseRequest.issueId),@@ -2781,11 +2806,22 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende));// The issue lock serializes cleanup callbacks and periodic workers.// An adopted, discarded, or edited receipt is no longer authority.- if (!pending || (!(wakeCommentId && queuedCommentIdsFromWakePayload(pending.payload).includes(wakeCommentId)) &&+ if (!pending || (!opts.taskRetryRequestId && !(wakeCommentId && queuedCommentIdsFromWakePayload(pending.payload).includes(wakeCommentId)) &&!(opts.queuedCommentInterruptId && await readQueuedInteractionResponse(tx as unknown as Db,agent.companyId, issueId, pending.payload)))) {return { kind: "deferred" as const };}+ if (opts.taskRetryRequestId) {+ const retry = readTaskRetryIntent(pending.payload);+ if (pending.id !== opts.taskRetryRequestId || retry?.generationId !== pending.id || retry.chatActionId ||+ retry.actorId !== opts.requestedByActorId || retry.sourceRunId !== enrichedContextSnapshot.previousRunId)+ return { kind: "deferred" as const };+ const permission = await authorizationService(tx as unknown as Db).decide({+ actor: { type: "board", userId: retry.actorId, source: retry.actorSource }, action: "issue:mutate",+ resource: { type: "issue", companyId: agent.companyId, issueId },+ });+ if (!permission.allowed) return { kind: "deferred" as const };+ }if (opts.queuedCommentRequestId) {const ids = await undeliveredLegacyUserCommentIds(tx as unknown as Db,agent.companyId, issueId, agentId, queuedCommentIdsFromWakePayload(pending.payload));@@ -2928,6 +2964,21 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeif (issueId !== durableRequest.issueId)throw new Error("chat_inbound_wakeup_binding_denied");await durableRequest.authorize(tx as unknown as Db);+ if (opts.taskRetryRequestId) {+ const [retryWake] = await tx.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, agent.companyId), eq(agentWakeupRequests.id, opts.taskRetryRequestId),+ eq(agentWakeupRequests.agentId, agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),+ )).for("update");+ const retry = readTaskRetryIntent(retryWake?.payload);+ if (!failedChatRetry || retry?.chatActionId !== durableRequest.id ||+ retry.actorId !== taskRetryActorId || retry.sourceRunId !== durableRequest.failedRunRetry?.failedRunId)+ throw new FailedChatRunRetryAuthorizationError();+ const permission = await authorizationService(tx as unknown as Db).decide({+ actor: { type: "board", userId: retry.actorId, source: retry.actorSource }, action: "issue:mutate",+ resource: { type: "issue", companyId: agent.companyId, issueId },+ });+ if (!permission.allowed) return { kind: "deferred" as const };+ }} else {if (source === "on_demand" &&@@ -3026,6 +3077,13 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependereturn { kind: "skipped" as const };}+ if (taskRetryActorId) {+ await assertTaskRetryConversationAllowed(tx as unknown as Db, issue, taskRetryActorId);+ if (await retireSupersededTaskRetry(tx as unknown as Db, {+ companyId: issue.companyId, issueId: issue.id, requestId: opts.taskRetryRequestId!,+ sourceRunId: readNonEmptyString(enrichedContextSnapshot.previousRunId)!,+ })) return { kind: "deferred" as const };+ }const issueStateGuard = opts.issueStateGuard;const activeMonitorRun = issueStateGuard?.monitorNextCheckAt === undefined ? null: await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(@@ -3275,11 +3333,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende&& executionBlocker.recoveryActionId === enrichedContextSnapshot.recoveryActionId;if (executionBlocker && !ownsReconstructionContinuation && !(await admitExplicitNativeContinuation({db: tx as unknown as Db, companyId: issue.companyId, issueId: issue.id,- agentId, actorType: opts.requestedByActorType, actorId: opts.requestedByActorId,- reason: durableRequest && !failedChatRetry ? "issue_commented" : reason,+ agentId, actorType: taskRetryActorId ? "user" : opts.requestedByActorType, actorId: taskRetryActorId ?? opts.requestedByActorId,+ reason: taskRetryActorId ? "task_retry" : durableRequest && !failedChatRetry ? "issue_commented" : reason,commentId: wakeCommentId ?? null, failedRunId: opts.failedRunId, successorRunId: explicitContinuationRunId,queuedCommentInterruptId: opts.queuedCommentInterruptId,queuedCommentRequestId: opts.queuedCommentRequestId,+ taskRetryRequestId: opts.taskRetryRequestId,dryRun: true,onBlocked: (reason, message) => { continuationWait = { reason, message }; },}))) return deferBlockedExecution(executionBlocker);@@ -4074,11 +4133,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeconst explicitContinuation = await admitExplicitNativeContinuation({db: tx as unknown as Db, companyId: issue.companyId, issueId: issue.id,- agentId, actorType: opts.requestedByActorType, actorId: opts.requestedByActorId,- reason: durableRequest && !failedChatRetry ? "issue_commented" : reason,+ agentId, actorType: taskRetryActorId ? "user" : opts.requestedByActorType, actorId: taskRetryActorId ?? opts.requestedByActorId,+ reason: taskRetryActorId ? "task_retry" : durableRequest && !failedChatRetry ? "issue_commented" : reason,commentId: wakeCommentId ?? null, failedRunId: opts.failedRunId, successorRunId: explicitContinuationRunId,queuedCommentInterruptId: opts.queuedCommentInterruptId,queuedCommentRequestId: opts.queuedCommentRequestId,+ taskRetryRequestId: opts.taskRetryRequestId,});if (!explicitContinuation && executionBlocker && !ownsReconstructionContinuation) return deferBlockedExecution(executionBlocker);if (explicitContinuation) {@@ -4135,7 +4195,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDependeinArray(agentWakeupRequests.agentId, handoffSource ? [agentId, handoffSource.agentId] : [agentId]),eq(agentWakeupRequests.status, "deferred_issue_execution"),sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`,- canCoalesceComments ? undefined : eq(agentWakeupRequests.id, executionWaitRequestId!),+ canCoalesceComments || opts.taskRetryRequestId ? undefined : eq(agentWakeupRequests.id, executionWaitRequestId!),),).orderBy(asc(agentWakeupRequests.requestedAt))@@ -4167,7 +4227,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende...queuedCommentIdsFromRunContext(enrichedContextSnapshot),]),];- if (opts.queuedCommentRequestId || handoffSource) {+ if (opts.queuedCommentRequestId || opts.taskRetryRequestId || handoffSource) {adoptedCommentIds = await undeliveredLegacyUserCommentIds(tx as unknown as Db,agent.companyId, issueId, agentId, adoptedCommentIds);}@@ -4223,6 +4283,14 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende}).where(eq(agentWakeupRequests.id, wakeupRequest.id));+ if (failedChatRetry && opts.taskRetryRequestId) {+ await tx.update(agentWakeupRequests).set({+ status: "coalesced", runId: newRun.id, finishedAt: new Date(), updatedAt: new Date(),+ }).where(and(eq(agentWakeupRequests.companyId, issue.companyId),+ eq(agentWakeupRequests.id, opts.taskRetryRequestId),+ eq(agentWakeupRequests.status, "deferred_issue_execution")));+ }+if (adoptedComments.length) {await tx.update(agentWakeupRequests)diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.tsindex 1eb6625e20..329a4da756 100644--- a/server/src/services/heartbeat/retries.ts+++ b/server/src/services/heartbeat/retries.ts@@ -1,4 +1,5 @@import { deriveTaskKeyWithHeartbeatFallback } from "./run-state.js";+import { infrastructureRetryDelayMs } from "../system-recovery-state.js";import {WORKSPACE_VALIDATION_FAILURE_CODE,isWorkspaceValidationFailedRun,@@ -113,11 +114,9 @@ export interface HeartbeatRetryDependencies {}export const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS = [- 30_000, 30_000,+ 30_000, 60_000,] as const;-const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_JITTER_RATIO = 0;-const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_REASON = "transient_failure";const BOUNDED_TRANSIENT_HEARTBEAT_RETRY_WAKE_REASON = "transient_failure_retry";@@ -354,10 +353,7 @@ export function computeBoundedTransientHeartbeatRetrySchedule(if (!Number.isInteger(attempt) || attempt <= 0) return null;const baseDelayMs = BOUNDED_TRANSIENT_HEARTBEAT_RETRY_DELAYS_MS[attempt - 1];if (typeof baseDelayMs !== "number") return null;- const sample = Math.min(1, Math.max(0, random()));- const jitterMultiplier =- 1 + (sample * 2 - 1) * BOUNDED_TRANSIENT_HEARTBEAT_RETRY_JITTER_RATIO;- const delayMs = Math.max(1_000, Math.round(baseDelayMs * jitterMultiplier));+ const delayMs = infrastructureRetryDelayMs(attempt, random());return {attempt,baseDelayMs,diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.tsindex d672594c57..343832733f 100644--- a/server/src/services/heartbeat/run-control.ts+++ b/server/src/services/heartbeat/run-control.ts@@ -1,3 +1,5 @@+import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js";+import { recordedLocalExecutionStopped } from "../native-local-process-stop.js";import { isHeartbeatRunTerminalStatus } from "./run-lifecycle.js";import { pendingCaseHandoffForRun, cancelCaseHandoffsForIssue, isCaseHandoffSourceReleased } from "./case-handoff-lifecycle.js";import { publishActivity, type ActivityPublication } from "../activity-log.js";@@ -445,7 +447,8 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunContawait isCancelledNativeStartup(db, run, preparationCoordinator);if (run.runtimeMode !== "native" && !cancelledPreparation &&parseObject(run.resultJson?.startupCancellation).beforeNativeSelection !== true &&- !(await remoteExecutionHasStopped(db, run.companyId, run.id))) return;+ !(await remoteExecutionHasStopped(db, run.companyId, run.id)) &&+ !(await recordedLocalExecutionStopped(db, run))) return;const issueId = run.nativeIssueId ?? (typeof run.contextSnapshot?.issueId === "string" ? run.contextSnapshot.issueId : null);if (!issueId) return;const currentRun = run.runtimeMode === "native" ? await getRun(run.id, { includeExecutionEvidence: true }) : null;@@ -475,6 +478,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont)).orderBy(asc(agentWakeupRequests.requestedAt)).limit(50);for (const wake of pending) {if (wake.idempotencyKey?.startsWith("chat-inbound:")) continue;+ if (readTaskRetryIntent(wake.payload)) { await resumeTaskRetry(wake.companyId, wake.id); continue; }let payload = parseObject(wake.payload);if (payload.queuedCommentInterrupt) {await resumeQueuedCommentInterrupt(wake.companyId, wake.id);@@ -514,7 +518,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunContconst admitted = await admitExplicitNativeContinuation({ db, companyId: run.companyId, issueId,agentId: run.agentId, actorType: wake.requestedByActorType, actorId: requestedByActorId,reason, commentId, successorRunId: randomUUID(), dryRun: true,- ...((run.runtimeMode === "native" || cancelledPreparation) ? { queuedCommentRequestId: wake.id } : {}),+ queuedCommentRequestId: wake.id,onBlocked: (reason, message) => { wait = { reason, message }; },});if (!admitted) {@@ -532,7 +536,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunContawait enqueueWakeup(run.agentId, { source: wake.source as WakeupOptions["source"], triggerDetail: (wake.triggerDetail ?? undefined) as WakeupOptions["triggerDetail"],reason, payload, contextSnapshot: context,requestedByActorType: "user", requestedByActorId,- ...((run.runtimeMode === "native" || cancelledPreparation) ? { queuedCommentRequestId: wake.id } : {}),+ queuedCommentRequestId: wake.id,idempotencyKey: `remote-stop-comment:${run.id}:${wake.id}` }, wake.id);break;}@@ -658,8 +662,42 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont}, queueId);}+ async function resumeTaskRetry(companyId: string, requestId: string) {+ if ((await getSchedulingSuppression()).suppressed) return;+ const [wake] = await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.id, requestId),+ eq(agentWakeupRequests.status, "deferred_issue_execution"), eq(agentWakeupRequests.reason, "task_retry"),+ eq(agentWakeupRequests.requestedByActorType, "user"),+ ));+ const intent = readTaskRetryIntent(wake?.payload);+ if (!wake || !intent || intent.chatActionId || intent.canonicalIntentId || intent.generationId !== wake.id ||+ intent.actorId !== wake.requestedByActorId) return;+ const issueId = readNonEmptyString(wake.payload?.issueId);+ if (!issueId) return;+ await enqueueWakeup(wake.agentId, { source: "on_demand", triggerDetail: "manual", reason: "task_retry",+ requestedByActorType: "user", requestedByActorId: intent.actorId, taskRetryRequestId: wake.id,+ payload: { issueId }, contextSnapshot: { issueId, triggeredBy: "board", actorId: intent.actorId,+ responsibleUserId: intent.actorId },+ issueStateGuard: { assigneeAgentId: wake.agentId, statuses: ["todo", "in_progress", "in_review", "blocked"] },+ idempotencyKey: `task-retry-dispatch:${wake.id}` }, wake.id);+ }+async function resumeExecutionWaitComments() {if ((await getSchedulingSuppression()).suppressed) return;+ await reconcileTaskChatRetryReceipts(db);+ const retries = await db.select({ id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId })+ .from(agentWakeupRequests).innerJoin(issues, and(eq(issues.companyId, agentWakeupRequests.companyId),+ sql`${issues.id}::text = ${agentWakeupRequests.payload}->>'issueId'`,+ eq(issues.assigneeAgentId, agentWakeupRequests.agentId)))+ .innerJoin(companies, and(eq(companies.id, issues.companyId), eq(companies.status, "active")))+ .where(and(eq(agentWakeupRequests.reason, "task_retry"), eq(agentWakeupRequests.status, "deferred_issue_execution"),+ sql`${agentWakeupRequests.payload}->'taskRetry'->>'chatActionId' is null`,+ notInArray(issues.status, ["done", "cancelled"])))+ .orderBy(asc(agentWakeupRequests.updatedAt)).limit(50);+ for (const retry of retries) {+ await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(eq(agentWakeupRequests.id, retry.id));+ await resumeTaskRetry(retry.companyId, retry.id).catch(err => logger.warn({ err, requestId: retry.id }, "Task retry dispatch deferred"));+ }const waits = await db.select({ wake: agentWakeupRequests }).from(agentWakeupRequests).innerJoin(issues, and(eq(issues.companyId, agentWakeupRequests.companyId),@@ -1413,6 +1451,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunContresumeExecutionWaitComments,resumeQueuedCommentInterrupt,resumeSavedLegacyComments,+ resumeTaskRetry,cancelActiveForAgentInternal,cancelInvocationsForAgentsInternal,};diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.tsindex 6081dca8d6..f71639247e 100644--- a/server/src/services/heartbeat/run-lifecycle.ts+++ b/server/src/services/heartbeat/run-lifecycle.ts@@ -1,3 +1,4 @@+import os from "node:os";import {DEFERRED_WAKE_CONTEXT_KEY,EXECUTION_PATH_HEARTBEAT_RUN_STATUSES,@@ -577,10 +578,13 @@ export async function persistHeartbeatRunProcessMetadata(.where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null);- if (run?.runtimeMode === "native") await appendHeartbeatRunEvent(tx as unknown as Db, {+ if (run) await appendHeartbeatRunEvent(tx as unknown as Db, {companyId: run.companyId, runId, agentId: run.agentId,eventType: PROCESS_IDENTITY_RECORDED, stream: "system", level: "info",message: "Process identity recorded; prior stop evidence no longer applies.",+ payload: { targetKind: meta.targetKind ?? "local", hostname: os.hostname(),+ processPid: meta.pid, processGroupId: meta.processGroupId,+ processStartedAt: run.processStartedAt?.toISOString() ?? null },});return run;});diff --git a/server/src/services/heartbeat/run-preparation.ts b/server/src/services/heartbeat/run-preparation.tsindex dd28eb2882..7c635e5cba 100644--- a/server/src/services/heartbeat/run-preparation.ts+++ b/server/src/services/heartbeat/run-preparation.ts@@ -830,6 +830,8 @@ export interface WakeupOptions {queuedCommentInterruptId?: string;/** Internal delivery of an existing undelivered user comment. */queuedCommentRequestId?: string;+ /** Internal delivery of the authenticated task-level Retry receipt. */+ taskRetryRequestId?: string;/** Exact failed run selected by an authenticated board Retry request. */failedRunId?: string | null;durableChatRequest?: DurableChatWakeupRequest;diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.tsindex a4d6225e7d..490190dd3e 100644--- a/server/src/services/heartbeat/workspace-preparation.test.ts+++ b/server/src/services/heartbeat/workspace-preparation.test.ts@@ -129,6 +129,62 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",const readRun = (id: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)).then(rows => rows[0]!);const leases = (id: string) => db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, id));+ it("keeps plugin-owned storage untouched when a fresh attempt cannot import preserved files", async () => {+ const { input, source, issue } = await fixture(true);+ await db.update(projects).set({ executionWorkspacePolicy: {+ enabled: true, storageProviderPluginId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ } }).where(eq(projects.id, issue.projectId!));+ input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,+ sourceRunId: input.run.id, retainedSourceIds: [] };+ const call = vi.fn();+ input.services.workspaceWorkers = { getWorker: () => ({ supportedMethods: ["workspaceOperation"] }), call } as any;+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({+ resultJson: { reason: "fresh_workspace_storage_unsupported" },+ });+ expect(call).not.toHaveBeenCalled();+ expect(await leases(input.run.id)).toHaveLength(0);+ expect((await readIssue(issue.id)).executionWorkspaceId).toBeNull();+ expect(await readFile(join(source, "README.md"), "utf8")).toBe("source content\n");+ });++ it("a fresh retry creates independent files and Git storage instead of reopening a configured task branch", async () => {+ const { input, source, issue } = await fixture(true);+ const original = await prepareHeartbeatWorkspace(db, input);+ await writeFile(join(original.executionWorkspace.cwd, "unpublished.txt"), "keep the old work\n");+ const [nextRun] = await db.insert(heartbeatRuns).values({ companyId: input.run.companyId,+ agentId: input.agent.id, issueId: issue.id, scopeKind: "issue", status: "running", runtimeMode: "legacy" }).returning();+ input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: nextRun.id,+ sourceRunId: input.run.id, retainedSourceIds: [] };+ input.run = nextRun;+ input.task.issueRef = { ...issue, executionWorkspaceId: null, executionWorkspacePreference: "create_new" };+ const replacement = await prepareHeartbeatWorkspace(db, input);+ expect(replacement.persistedExecutionWorkspace!.id).not.toBe(original.persistedExecutionWorkspace!.id);+ expect(replacement.executionWorkspace.cwd).not.toBe(original.executionWorkspace.cwd);+ expect(replacement.executionWorkspace.cwd).not.toBe(source);+ expect(await readFile(join(replacement.executionWorkspace.cwd, "README.md"), "utf8")).toBe("source content\n");+ expect(await readFile(join(original.executionWorkspace.cwd, "unpublished.txt"), "utf8")).toBe("keep the old work\n");+ const common = await execFile("git", ["-C", replacement.executionWorkspace.cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"]);+ expect(common.stdout.trim()).toBe(join(replacement.executionWorkspace.cwd, ".git"));+ await expect(access(join(replacement.executionWorkspace.cwd, "unpublished.txt"))).rejects.toThrow();+ expect((await readIssue(issue.id)).executionWorkspaceId).toBe(replacement.persistedExecutionWorkspace!.id);+ }, 30_000);++ it("starts a fresh clean task directory without treating it as a Git source", async () => {+ const { input, source, issue } = await fixture();+ input.policy.useIsolatedTaskDirectory = true;+ input.policy.effectiveExecutionWorkspaceMode = "isolated_workspace";+ input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";+ input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,+ sourceRunId: input.run.id, retainedSourceIds: [] };+ const prepared = await prepareHeartbeatWorkspace(db, input);+ expect(prepared.executionWorkspace.cwd).toContain("/isolated-workspace-attempts/");+ expect(prepared.executionWorkspace.cwd).toContain(`/${input.run.id}`);+ expect(prepared.executionWorkspace.cwd).not.toBe(source);+ await expect(access(join(prepared.executionWorkspace.cwd, "README.md"))).rejects.toThrow();+ expect(await readFile(join(source, "README.md"), "utf8")).toBe("source content\n");+ expect((await readIssue(issue.id)).executionWorkspaceId).toBe(prepared.persistedExecutionWorkspace!.id);+ });+async function reuse(input: HeartbeatWorkspacePreparationInput, workspace: NonNullable<Awaited<ReturnType<typeof prepareHeartbeatWorkspace>>["persistedExecutionWorkspace"]>) {input.reuse.requestedShouldReuseExisting = true;input.reuse.existingExecutionWorkspace = workspace;diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.tsindex 8109302b82..a0b4fae0ff 100644--- a/server/src/services/heartbeat/workspace-preparation.ts+++ b/server/src/services/heartbeat/workspace-preparation.ts@@ -1,3 +1,6 @@+import { attachPreservedWorkspaceSnapshots } from "../workspace-recovery-snapshot.js";+import { materializeFreshWorkspaceSeed } from "../fresh-workspace-seed.js";+import { assertTaskWorkspaceExecutionAccess } from "../task-workspace-access.js";import { preparePluginWorkspace, type WorkspaceWorkers } from "../plugin-workspaces.js";import { readWorkspaceProviderBinding } from "@paperclipai/shared";import { nativeExecutionUsesTaskWorkspace } from "./external-provider.js";@@ -24,7 +27,7 @@ import path from "node:path";import { CONTROLLER_PROVISION_COPY_ONLY, workspaceRequiresCopyOnlyProvisioning } from "../workspace-host-provision.js";import { and, asc, eq } from "drizzle-orm";import { type ExecutionWorkspace } from "@paperclipai/shared";-import { heartbeatRuns, issues, projectWorkspaces } from "@paperclipai/db";+import { heartbeatRuns, issues, projects, projectWorkspaces } from "@paperclipai/db";import { getStartupTracer } from "../../instrumentation.js";import { createHostDuplexObservabilityRecorder } from "../duplex-observability-recorder.js";import { incrementToolRuntimeMetricCounter } from "../tool-runtime-metrics.js";@@ -97,6 +100,7 @@ export interface HeartbeatWorkspacePreparationInput {context: Record<string, unknown>;responsibleUserId: string | null;previousSessionParams: Record<string, unknown> | null;+ freshWorkspace?: import("../fresh-workspace-continuation.js").ContinuationReadiness | null;workspaceSelection?: import("@paperclipai/shared").TaskWorkspaceIntent | null;};policy: {@@ -160,6 +164,7 @@ export async function prepareHeartbeatWorkspace(db: Db, input: HeartbeatWorkspacasync function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspacePreparationInput) {const { run, agent, controllerLease, nativeRunnerPreparationSpans } = input;+ const fresh = input.task.freshWorkspace?.mode === "fresh_isolated_workspace";const timeWorkspace = createHeartbeatPreparationTiming(run.id);const {issueRef,@@ -198,6 +203,10 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspaceisDotRun,runOptions,} = input.reuse;+ // An ordinary clean task directory already has a new per-attempt identity.+ // It is not a repository source and must not pass through Git copy admission.+ const freshNeedsSeed = fresh && !isDotRun && !useIsolatedTaskDirectory &&+ !(nativeChatWorkspaceScope && !nativeChatWorkspaceScope.projectId);const {envOrchestrator,executionWorkspacesSvc,@@ -244,6 +253,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspaceconst cwd = await materializeIsolatedTaskDirectory({companyId: agent.companyId,issueId: issueRef.id,+ ...(input.task.freshWorkspace?.mode === "fresh_isolated_workspace" ? { attemptId: run.id } : {}),});if (reusableExistingExecutionWorkspace && (reusableExistingExecutionWorkspace.companyId !== agent.companyId ||@@ -342,6 +352,20 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace},}));const hostProvisionDriver = selectedEnvironmentForConfig?.driver ?? lowTrustPreflightEnvironmentDriver;+ if (fresh && !isDotRun) {+ const [project] = resolvedWorkspace.projectId ? await db.select({+ policy: projects.executionWorkspacePolicy,+ }).from(projects).where(and(eq(projects.id, resolvedWorkspace.projectId),+ eq(projects.companyId, agent.companyId))) : [];+ const sourceWorkspace = reusableExistingExecutionWorkspace ?? existingExecutionWorkspace;+ if (sourceWorkspace?.providerType === "plugin" ||+ readWorkspaceProviderBinding(sourceWorkspace?.metadata) ||+ project?.policy?.storageProviderPluginId) {+ throw new WorkspaceValidationFailure("A fresh attempt is unavailable for this workspace storage provider. The existing workspace is retained.", {+ reason: "fresh_workspace_storage_unsupported",+ });+ }+ }const pluginPrepared = isDotRun ? null : await preparePluginWorkspace(db, input.services.workspaceWorkers, {companyId: agent.companyId, projectId: resolvedWorkspace.projectId, projectWorkspaceId: resolvedWorkspace.workspaceId,issueId, runId: run.id, agentId: agent.id, responsibleUserId,@@ -367,7 +391,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspaceconst skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh";const hostExecutionWorkspaceConfig = isDotRun ? {} :stripHostWorkspaceProvision({- config: mergedConfig,+ config: fresh ? { ...mergedConfig, workspaceStrategy: { type: "project_primary" } } : mergedConfig,skipHostProvision,});const executionWorkspaceBase = {@@ -510,6 +534,26 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspaceagentId: agent.id,},);+ if (freshNeedsSeed && issueId) {+ await controllerLease.assertOwned();+ const verifySourceAccess = async () => {+ await assertTaskWorkspaceExecutionAccess(db, {+ type: "agent", source: "agent_jwt", companyId: agent.companyId,+ agentId: agent.id, runId: run.id,+ onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId,+ }, agent.companyId, { issueId });+ };+ const cwd = await materializeFreshWorkspaceSeed({+ companyId: agent.companyId, issueId, runId: run.id, sourceCwd: executionWorkspaceBase.baseCwd,+ repoUrl: executionWorkspaceBase.repoUrl,+ baseRef: readNonEmptyString(parseObject(mergedConfig.workspaceStrategy).baseRef) ?? executionWorkspaceBase.repoRef,+ beforeCopy: verifySourceAccess,+ });+ await verifySourceAccess();+ executionWorkspaceBase.baseCwd = cwd;+ resolvedWorkspace.cwd = cwd;+ await controllerLease.assertOwned();+ }const {executionWorkspace,reusedExecutionWorkspace,@@ -625,6 +669,20 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace}),},));+ if (input.task.freshWorkspace?.mode === "fresh_isolated_workspace" && issueId) {+ const snapshots = await attachPreservedWorkspaceSnapshots({ db, companyId: agent.companyId,+ issueId, sourceRunIds: [input.task.freshWorkspace.sourceRunId], cwd: executionWorkspace.cwd });+ const recoveredFiles = snapshots.map(snapshot => ({ ...snapshot, path: path.relative(executionWorkspace.cwd, snapshot.path) }));+ context.recoveredWorkspaceFiles = recoveredFiles;+ const continuation = context.executionContinuation as import("@paperclipai/shared").ExecutionContinuationEnvelope | null;+ if (continuation) {+ continuation.recoveredFiles = recoveredFiles;+ // The wake was assembled before filesystem preparation. Update that same+ // server-authored envelope so every adapter receives the verified paths.+ const wake = context.paperclipWake as Record<string, unknown> | undefined;+ if (wake) wake.executionContinuation = continuation;+ }+ }const resolvedProjectId =reusableExistingExecutionWorkspace? reusableExistingExecutionWorkspace.projectIddiff --git a/server/src/services/isolated-task-directory.ts b/server/src/services/isolated-task-directory.tsindex be34c930c8..9b0298cfe2 100644--- a/server/src/services/isolated-task-directory.ts+++ b/server/src/services/isolated-task-directory.ts@@ -25,16 +25,19 @@ export function shouldUseIsolatedTaskDirectory(input: {export async function materializeIsolatedTaskDirectory(input: {companyId: string;issueId: string;+ attemptId?: string;}): Promise<string> {// Files belong to the task, so reassignment preserves the same workspace.- const identities = [input.companyId, input.issueId];+ const identities = [input.companyId, input.issueId, ...(input.attemptId ? [input.attemptId] : [])];if (identities.some((value) => !/^[a-zA-Z0-9_-]+$/.test(value))) {throw new Error("Invalid isolated task workspace identity");}const root = resolvePaperclipInstanceRoot();await mkdir(root, { recursive: true });let cwd = await realpath(root);- for (const segment of ["isolated-workspaces", ...identities]) {+ // A retry is a sibling namespace, never a descendant of the retained root.+ // An old copyback operation must not be able to overwrite its replacement.+ for (const segment of [input.attemptId ? "isolated-workspace-attempts" : "isolated-workspaces", ...identities]) {cwd = path.join(cwd, segment);await mkdir(cwd, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {if (error.code !== "EEXIST") throw error;diff --git a/server/src/services/issue-recovery-actions.ts b/server/src/services/issue-recovery-actions.tsindex 5c466963dd..5351722b19 100644--- a/server/src/services/issue-recovery-actions.ts+++ b/server/src/services/issue-recovery-actions.ts@@ -408,7 +408,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {.update(issueRecoveryActions).set({status: "escalated",- ownerType: "board",+ ownerType: existing.ownerType === "system" || input.ownerType === "system" ? "system" : "board",ownerAgentId: null,ownerUserId: null,previousOwnerAgentId:diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.tsindex 29cbafdf0b..235aeb878c 100644--- a/server/src/services/native-local-process-stop.ts+++ b/server/src/services/native-local-process-stop.ts@@ -1,6 +1,7 @@import { and, desc, eq, inArray, isNull } from "drizzle-orm";import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";+import os from "node:os";export const PROCESS_START_REQUESTED = "native.process_start_requested";export const PROCESS_IDENTITY_RECORDED = "native.process_identity_recorded";@@ -15,6 +16,21 @@ function absent(pid: number): boolean {}}+/** A fresh workspace is not process containment. Bind an OS observation to+ * the original host, process birth, and launch event before accepting it. */+export async function recordedLocalExecutionStopped(db: Db, run: typeof heartbeatRuns.$inferSelect) {+ const [identity] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(+ eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),+ eq(heartbeatRunEvents.eventType, PROCESS_IDENTITY_RECORDED), isNull(heartbeatRunEvents.sourceEventId),+ )).orderBy(desc(heartbeatRunEvents.seq)).limit(1);+ const recorded = identity?.payload;+ if (recorded?.targetKind !== "local" || recorded.hostname !== os.hostname() ||+ recorded.processPid !== run.processPid || recorded.processGroupId !== run.processGroupId ||+ !run.processStartedAt || recorded.processStartedAt !== run.processStartedAt.toISOString()) return false;+ return Boolean(run.processPid && absent(run.processPid) &&+ (!run.processGroupId || absent(-run.processGroupId)));+}+/*** Preserve the host's observation before recovery clears the process fields.* Call in the same transaction as that compare-and-set. Never inspect remotediff --git a/server/src/services/native-runtime/native-chat-workspace.test.ts b/server/src/services/native-runtime/native-chat-workspace.test.tsindex 00705ae557..dccfe22c14 100644--- a/server/src/services/native-runtime/native-chat-workspace.test.ts+++ b/server/src/services/native-runtime/native-chat-workspace.test.ts@@ -170,6 +170,21 @@ describe("native external chat workspace boundary", () => {).rejects.toThrow("native_chat_workspace_issue_unavailable");});+ it("keeps an admitted fresh chat attempt separate from the original task root", async () => {+ const freshAttemptId = "01000000-0000-4000-8000-000000000090";+ const original = await materializeNativeChatTaskRoot(scopeA);+ await writeFile(path.join(original, "retained.txt"), "retained original");+ const fresh = (await findNativeChatWorkspaceScope(db, { ...scopeInput(issueA), freshAttemptId }))!;+ const directory = await materializeNativeChatTaskRoot(fresh);+ expect(directory).toBe(path.join(instanceRoot, "isolated-workspace-attempts", companyId, issueA, freshAttemptId));+ expect(path.relative(original, directory).startsWith("..")).toBe(true);+ expect(await readdir(directory)).toEqual([]);+ expect(nativeChatWorkspaceCwd(fresh, null, false)).toBe(directory);+ expect(await readFile(path.join(original, "retained.txt"), "utf8")).toBe("retained original");+ expect(nativeChatWorkspaceCwd({ ...fresh, taskRoot: path.join(original, "attempts", freshAttemptId, "escape") }, null, false)).toBeNull();+ expect(nativeChatWorkspaceCwd({ ...fresh, taskRoot: path.join(instanceRoot, "isolated-workspace-attempts", companyId, issueB, freshAttemptId) }, null, false)).toBeNull();+ });+it("does not expose another active task's staged inbound files or register its generated file", async () => {const [rootA, rootB] = await Promise.all([materializeNativeChatTaskRoot(scopeA),diff --git a/server/src/services/native-runtime/native-chat-workspace.ts b/server/src/services/native-runtime/native-chat-workspace.tsindex e943281858..ee513babf5 100644--- a/server/src/services/native-runtime/native-chat-workspace.ts+++ b/server/src/services/native-runtime/native-chat-workspace.ts@@ -11,6 +11,7 @@ export type NativeChatWorkspaceScope = {projectId: string | null;instanceRoot: string;taskRoot: string;+ freshAttemptId?: string;};function segment(value: string): string {@@ -31,6 +32,8 @@ export async function findNativeChatWorkspaceScope(issueId: string | null;instanceRoot?: string;admittedCwd?: string | null;+ /** Supplied only after validating a committed fresh-attempt receipt. */+ freshAttemptId?: string;},): Promise<NativeChatWorkspaceScope | null> {if (@@ -76,15 +79,21 @@ export async function findNativeChatWorkspaceScope(const instanceRoot = await realpath(input.instanceRoot ?? resolvePaperclipInstanceRoot(),);+ const projectId = issue.boundWorkspaceId ? issue.boundProjectId : issue.selection?.selection.kind === "task_directory"+ ? null : issue.configuredProjectId ?? (issue.hasConfiguredDefault ? issue.projectId : null);return {companyId: input.companyId,agentId: input.agentId,issueId: issue.id,- projectId: issue.boundWorkspaceId ? issue.boundProjectId : issue.selection?.selection.kind === "task_directory" ? null : issue.configuredProjectId ?? (issue.hasConfiguredDefault ? issue.projectId : null),+ projectId,+ ...(input.freshAttemptId ? { freshAttemptId: input.freshAttemptId } : {}),instanceRoot,// This must be a sibling of agent homes, not a child readable by an old// provider thread whose immutable permission root is the entire agent home.- taskRoot: issue.boundSourceIssueId === issue.id && issue.boundCwd+ taskRoot: input.freshAttemptId+ ? path.join(instanceRoot, "isolated-workspace-attempts", segment(input.companyId), segment(issue.id),+ segment(input.freshAttemptId), ...(projectId ? ["workspace"] : []))+ : issue.boundSourceIssueId === issue.id && issue.boundCwd? issue.boundCwd : input.admittedCwd ?? path.join(instanceRoot, "isolated-workspaces", segment(input.companyId), segment(issue.id)),};}@@ -104,7 +113,11 @@ function isNativeChatTaskRoot(scope: NativeChatWorkspaceScope): boolean {const relative = path.relative(scope.instanceRoot, scope.taskRoot);const allowedTask = path.join("isolated-workspaces", segment(scope.companyId), segment(scope.issueId));const legacyParts = relative.split(path.sep);- return relative === allowedTask || (+ const attempt = relative.split(path.sep);+ const isolatedAttempt = (attempt.length === 4 || (attempt.length === 5 && attempt[4] === "workspace")) &&+ attempt[0] === "isolated-workspace-attempts" && attempt[1] === scope.companyId &&+ attempt[2] === scope.issueId && /^[0-9a-f-]{36}$/i.test(attempt[3]!);+ return relative === allowedTask || isolatedAttempt || (legacyParts.length === 4 && legacyParts[0] === "chat-workspaces" &&legacyParts[1] === scope.companyId && /^[a-zA-Z0-9_-]+$/.test(legacyParts[2]!) && legacyParts[3] === scope.issueId);@@ -116,6 +129,7 @@ export function nativeChatWorkspaceCwd(workspace: NativeChatProjectWorkspace | null,reuseExisting: boolean,): string | null {+ if (scope.freshAttemptId && workspace === null && isNativeChatTaskRoot(scope)) return scope.taskRoot;if (!scope.projectId) return isNativeChatTaskRoot(scope) && (workspace === null || (workspace.companyId === scope.companyId && workspace.sourceIssueId === scope.issueId &&workspace.projectId === null && workspace.cwd === scope.taskRoot && ["active", "idle"].includes(workspace.status)@@ -127,7 +141,8 @@ export function nativeChatWorkspaceCwd(workspace.projectId !== scope.projectId ||workspace.sourceIssueId !== scope.issueId ||workspace.mode !== "isolated_workspace" ||- workspace.strategyType !== "git_worktree" ||+ !(workspace.strategyType === "git_worktree" ||+ (workspace.strategyType === "project_primary" && workspace.cwd === scope.taskRoot && isNativeChatTaskRoot(scope))) ||!["active", "idle"].includes(workspace.status) ||!workspace.cwd ||!path.isAbsolute(workspace.cwd) ||diff --git a/server/src/services/native-runtime/native-workspace-finalization-ownership.ts b/server/src/services/native-runtime/native-workspace-finalization-ownership.tsindex 1dfae78fe9..7f02ae9cfb 100644--- a/server/src/services/native-runtime/native-workspace-finalization-ownership.ts+++ b/server/src/services/native-runtime/native-workspace-finalization-ownership.ts@@ -103,10 +103,16 @@ export async function withNativeWorkspaceFinalizationOwnership<T>(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, run.issueId),eq(issueRecoveryActions.id, input.retainedRepairActionId),)).for("update");+ const continuation = repair?.evidence.explicitUserContinuation as {+ runId?: string; readiness?: { mode?: string; sourceRunId?: string };+ } | undefined;+ const independentRun = continuation?.readiness?.mode === "fresh_isolated_workspace"+ && continuation.readiness.sourceRunId === input.runId ? continuation.runId : undefined;return currentRun && issue && repair && repair.evidence.runId === currentRun.id&& repair.evidence.workspaceRecovery && !coordinator?.leaseOwner&& ["failed", "interrupted", "timed_out", "cancelled", "succeeded"].includes(currentRun.status)- && !issue.executionRunId && !issue.checkoutRunId ? repair : null;+ && (!issue.executionRunId || issue.executionRunId === independentRun)+ && (!issue.checkoutRunId || issue.checkoutRunId === independentRun) ? repair : null;}return coordinator && issue && currentRun ? currentNativeWorkspaceRecoveryResult(db, {companyId: input.companyId, coordinator, issue, run: currentRun,diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.tsindex 04da59cca1..0f358561f4 100644--- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts+++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts@@ -1,3 +1,4 @@+import { priorRecoveryApiReceipt } from "../recovery-effect-receipts.js";import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";import { caseHandoffService } from "../case-handoffs.js";import { caseIdForApiCapture, createNativeCaseSchema, executeNativeCaseTool, NATIVE_CASE_OPERATIONS } from "./native-case-tools.js";@@ -894,6 +895,15 @@ export class PaperclipRunnerToolAuthority {const locked = await this.#lockAuthorizedMutationContext(tx as unknown as Db);const resultJson = record(locked.run.resultJson);const receipts = record(resultJson.apiToolReceipts);+ const inherited = await priorRecoveryApiReceipt(tx as unknown as Db, { companyId: this.binding.companyId,+ issueId: this.binding.issueId, runId: this.binding.runId, operationId: operation.operationId, digest });+ if (inherited) {+ if (inherited.encryptedResult) {+ const text = await getSecretProvider("local_encrypted").resolveVersion({ material: record(inherited.encryptedResult), externalRef: null });+ return { result: JSON.parse(text) as unknown };+ }+ return { result: inherited.result };+ }const existing = record(receipts[key]);if (receipts[key]) {if (existing.digest !== digest) throw badRequest("API call id was reused with different arguments");diff --git a/server/src/services/native-runtime/runner-api.integration.test.ts b/server/src/services/native-runtime/runner-api.integration.test.tsindex d85f67f280..4285af716c 100644--- a/server/src/services/native-runtime/runner-api.integration.test.ts+++ b/server/src/services/native-runtime/runner-api.integration.test.ts@@ -3,7 +3,8 @@ import { randomUUID } from "node:crypto";import { chmod, writeFile, symlink, mkdir, open } from "node:fs/promises";import { join, dirname } from "node:path";import { eq } from "drizzle-orm";-import { agents, assets, documents, heartbeatRuns, issues, projects, routineDocuments, routines, runnerApiResponseReservations, companySkills, companyMemberships, principalPermissionGrants } from "@paperclipai/db";+import { agents, agentWakeupRequests, assets, documents, heartbeatRuns, issues, projects, routineDocuments, routines, runnerApiResponseReservations, companySkills, companyMemberships, principalPermissionGrants } from "@paperclipai/db";+import { initializeRunIdentity } from "../run-identity.js";import { beforeAll, afterAll, beforeEach, afterEach, describe, expect, it, vi } from "vitest";import { secretService } from "../secrets.js";import { authorizationService } from "../authorization.js";@@ -581,6 +582,88 @@ else if(m.id!==undefined) send({id:m.id,result:{}});expect((await fixture.snapshot()).projects.some(p => p.name === "Uncertain")).toBe(false);});+ it.each([403, 422])("a deliberate retry can execute an exact mutation previously rejected with %s", async status => {+ const fixture = await server.fixture();+ const args = { operationId: "POST /api/companies/{companyId}/projects", body: { name: "Authorized on retry" } };+ const rejected = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(Response.json({ error: "Rejected before mutation" }, { status }));+ try {+ expect(await fixture.authority.execute({ tool: "call_api", callId: "rejected", arguments: args }))+ .toMatchObject({ ok: false, status });+ } finally { rejected.mockRestore(); }+ await server.db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() })+ .where(eq(heartbeatRuns.id, fixture.runId));+ const id = randomUUID(), intentId = randomUUID();+ await server.db.insert(heartbeatRuns).values({ id, companyId: fixture.companyId, agentId: fixture.agentId,+ status: "running", runtimeMode: "native", nativeIssueId: fixture.issueId, responsibleUserId: fixture.responsibleUserId,+ contextSnapshot: { issueId: fixture.issueId, previousRunId: fixture.runId } });+ await server.db.update(issues).set({ executionRunId: id }).where(eq(issues.id, fixture.issueId));+ await server.db.insert(agentWakeupRequests).values({ id: intentId, companyId: fixture.companyId,+ agentId: fixture.agentId, runId: id, source: "on_demand", reason: "task_retry", status: "coalesced",+ requestedByActorType: "user", requestedByActorId: fixture.responsibleUserId ?? "board",+ payload: { issueId: fixture.issueId, taskRetry: { schema: "paperclip.task-retry.v1", generationId: intentId,+ sourceRunId: fixture.runId, actorId: fixture.responsibleUserId ?? "board", strategy: "fresh_isolated_workspace" } } });+ if (fixture.responsibleUserId) await initializeRunIdentity(server.db, { companyId: fixture.companyId, runId: id,+ issueId: fixture.issueId, responsibleUserId: fixture.responsibleUserId, cause: "instruction" });+ const authority = new PaperclipRunnerToolAuthority(server.db, { ...fixture, runId: id });+ const network = vi.spyOn(globalThis, "fetch");+ try {+ const result = await authority.execute({ tool: "call_api", callId: "accepted-retry", arguments: args });+ expect(result).toMatchObject({ ok: true, status: 201 });+ expect(await authority.execute({ tool: "call_api", callId: "accepted-retry", arguments: args })).toEqual(result);+ expect(network).toHaveBeenCalledTimes(1);+ } finally { network.mockRestore(); }+ expect((await fixture.snapshot()).projects.filter(project => project.name === "Authorized on retry")).toHaveLength(1);+ });++ it.each(["task_retry", "automatic_successor"])("%s reuses the completed effect and fences a different unresolved effect across run identities", async mode => {+ const fixture = await server.fixture();+ const args = { operationId: "POST /api/companies/{companyId}/projects", body: { name: "Already created" } };+ const completed = await fixture.authority.execute({ tool: "call_api", callId: "first-publication", arguments: args });+ expect(completed).toMatchObject({ status: 201 });+ const [original] = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));+ await server.db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(),+ resultJson: { ...original.resultJson, apiToolReceipts: { ...(original.resultJson?.apiToolReceipts as object),+ unresolved: { operationId: "POST /api/companies/{companyId}/routines", state: "pending", digest: "unknown" } } },+ }).where(eq(heartbeatRuns.id, fixture.runId));+ let id = randomUUID();+ const intentId = randomUUID();+ await server.db.insert(heartbeatRuns).values({ id, companyId: fixture.companyId, agentId: fixture.agentId,+ status: "running", runtimeMode: "native", nativeIssueId: fixture.issueId, responsibleUserId: fixture.responsibleUserId,+ contextSnapshot: { issueId: fixture.issueId, previousRunId: fixture.runId } });+ await server.db.update(issues).set({ executionRunId: id }).where(eq(issues.id, fixture.issueId));+ await server.db.insert(agentWakeupRequests).values({ id: intentId, companyId: fixture.companyId,+ agentId: fixture.agentId, runId: id, source: "on_demand", reason: "task_retry", status: "coalesced",+ requestedByActorType: "user", requestedByActorId: fixture.responsibleUserId ?? "board",+ payload: { issueId: fixture.issueId, taskRetry: { schema: "paperclip.task-retry.v1", generationId: intentId,+ sourceRunId: fixture.runId, actorId: fixture.responsibleUserId ?? "board", strategy: "fresh_isolated_workspace" } } });+ if (mode === "automatic_successor") {+ const parentId = id;+ id = randomUUID();+ await server.db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() })+ .where(eq(heartbeatRuns.id, parentId));+ await server.db.insert(heartbeatRuns).values({ id, companyId: fixture.companyId, agentId: fixture.agentId,+ status: "running", runtimeMode: "native", nativeIssueId: fixture.issueId, retryOfRunId: parentId,+ responsibleUserId: fixture.responsibleUserId, invocationSource: "automation", contextSnapshot: { issueId: fixture.issueId } });+ await server.db.update(issues).set({ executionRunId: id }).where(eq(issues.id, fixture.issueId));+ }+ if (fixture.responsibleUserId) await initializeRunIdentity(server.db, { companyId: fixture.companyId, runId: id,+ issueId: fixture.issueId, responsibleUserId: fixture.responsibleUserId, cause: "instruction" });+ const authority = new PaperclipRunnerToolAuthority(server.db, { ...fixture, runId: id });+ const network = vi.spyOn(globalThis, "fetch");+ try {+ expect(await authority.execute({ tool: "call_api", callId: "replacement-publication", arguments: args })).toEqual(completed);+ expect(await authority.execute({ tool: "call_api", callId: "uncertain-other-operation", arguments: {+ operationId: "POST /api/companies/{companyId}/routines", body: { title: "Uncertain", assigneeAgentId: fixture.agentId },+ } })).toMatchObject({ outcome: "unknown", error: "api_outcome_unknown" });+ expect(network).not.toHaveBeenCalled();+ expect(await authority.execute({ tool: "call_api", callId: "independent-read", arguments: {+ operationId: "GET /api/companies/{companyId}/projects",+ } })).toMatchObject({ status: 200 });+ expect(network).toHaveBeenCalledTimes(1);+ } finally { network.mockRestore(); }+ expect((await fixture.snapshot()).projects.filter(project => project.name === "Already created")).toHaveLength(1);+ });+it("revalidates the active run after reading an upload", async () => {const fixture = await server.fixture();const original = server.storage.getObject.bind(server.storage);diff --git a/server/src/services/preserved-result-finalization.ts b/server/src/services/preserved-result-finalization.tsnew file mode 100644index 0000000000..6073896fee--- /dev/null+++ b/server/src/services/preserved-result-finalization.ts@@ -0,0 +1,63 @@+import { and, desc, eq, gte, ne, or, sql } from "drizzle-orm";+import { agentWakeupRequests, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";+import { readSystemRecovery } from "./system-recovery-state.js";++/** Re-enter the existing finalizer only after preservation. This does not+ * recreate a result, grant an executor budget, or apply it over newer work. */+export async function resumePreservedResultFinalization(db: Db, companyId: string, runId: string) {+ return db.transaction(async tx => {+ const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(+ eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, runId),+ )).for("update");+ if (!coordinator?.resultId || coordinator.phase !== "terminal_failure" || coordinator.leaseOwner ||+ coordinator.failureDetail?.successorRunId) return false;+ const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, companyId),+ eq(issues.id, coordinator.issueId))).for("update");+ const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),+ eq(heartbeatRuns.id, runId))).for("update");+ if (!issue || !run || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status) ||+ issue.executionRunId || issue.checkoutRunId) return false;+ const [newer] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, companyId), ne(heartbeatRuns.id, runId),+ or(eq(heartbeatRuns.issueId, issue.id), eq(heartbeatRuns.nativeIssueId, issue.id),+ sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`),+ gte(heartbeatRuns.createdAt, run.createdAt),+ )).limit(1);+ if (newer) return false;+ const [result] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(+ eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issue.id),+ eq(nativeRunResults.runId, runId), eq(nativeRunResults.id, coordinator.resultId),+ eq(nativeRunResults.schemaStatus, "accepted"),+ sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`,+ ));+ const [action] = await tx.select().from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issue.id),+ sql`${issueRecoveryActions.evidence}->>'runId' = ${runId}`,+ )).orderBy(desc(issueRecoveryActions.createdAt)).limit(1);+ const recovery = readSystemRecovery(action?.evidence);+ if (!result || recovery?.state !== "complete" || !recovery.preservationOperationIds.length) return false;+ const [intent] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.agentId, run.agentId),+ eq(agentWakeupRequests.status, "deferred_issue_execution"), eq(agentWakeupRequests.reason, "task_retry"),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`,+ sql`${agentWakeupRequests.payload}#>>'{taskRetry,sourceRunId}' = ${runId}`,+ )).orderBy(desc(agentWakeupRequests.requestedAt)).limit(1);+ const generationId = intent?.id ?? recovery.generationId;+ if (coordinator.recoveryHistory.some(entry => entry.kind === "preserved_result_finalization" &&+ entry.generationId === generationId)) return false;+ await tx.update(nativeRunFinalizations).set({+ phase: coordinator.assessmentId ? "arbitrating" : "workspace_finalizing",+ nextAttemptAt: new Date(), failureCode: null, failureDetail: null, updatedAt: new Date(),+ recoveryHistory: [...coordinator.recoveryHistory, {+ kind: "preserved_result_finalization", generationId,+ resultId: result.id, previousFailureCode: coordinator.failureCode,+ previousFailureDetail: coordinator.failureDetail, at: new Date().toISOString(),+ }],+ }).where(eq(nativeRunFinalizations.runId, runId));+ if (intent) await tx.update(agentWakeupRequests).set({+ status: "coalesced", runId, finishedAt: new Date(), updatedAt: new Date(),+ payload: sql`jsonb_set(${agentWakeupRequests.payload}, '{taskRetry,strategy}', '"finalize_result"'::jsonb)`,+ }).where(eq(agentWakeupRequests.id, intent.id));+ return true;+ });+}diff --git a/server/src/services/recovery-effect-receipts.ts b/server/src/services/recovery-effect-receipts.tsnew file mode 100644index 0000000000..a9456768dc--- /dev/null+++ b/server/src/services/recovery-effect-receipts.ts@@ -0,0 +1,79 @@+import { and, eq, sql, ne, or, inArray } from "drizzle-orm";+import { heartbeatRuns, toolInvocations, type Db } from "@paperclipai/db";+import { getSecretProvider } from "../secrets/provider-registry.js";+import { recoveryRunAncestry } from "./recovery-run-ancestry.js";++const record = (value: unknown): Record<string, unknown> =>+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};++/** Generic upstream tools have no common authoritative result-query protocol.+ * Preserve their uncertain mutation fence across recovery. Exact publication+ * protocols can reconcile through their existing owner instead. No transcript+ * assertion or new call/idempotency key clears an old uncertain operation. */+export async function unresolvedRecoveryToolInvocation(db: Db, input: {+ companyId: string; issueId: string; runId: string; connectionId: string;+ toolName: string; risk: string;+}): Promise<string | null> {+ if (input.risk === "read") return null;+ const ancestry = await recoveryRunAncestry({ db, companyId: input.companyId,+ issueId: input.issueId, sourceRunIds: [input.runId] });+ if (!ancestry.some(source => source.id !== input.runId)) return null;+ const [prior] = await db.select({ id: toolInvocations.id }).from(toolInvocations)+ .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, toolInvocations.runId),+ eq(heartbeatRuns.companyId, input.companyId)))+ .where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.issueId, input.issueId),+ eq(toolInvocations.connectionId, input.connectionId), eq(toolInvocations.toolName, input.toolName),+ ne(toolInvocations.runId, input.runId),+ sql`${toolInvocations.riskLevel} is distinct from 'read'`,+ inArray(toolInvocations.status, ["executing", "failed", "timed_out"]),+ sql`${toolInvocations.startedAt} is not null`,+ sql`${heartbeatRuns.createdAt} < (select created_at from heartbeat_runs+ where id = ${input.runId} and company_id = ${input.companyId})`,+ )).limit(1);+ return prior?.id ?? null;+}++/** Keep the mutation fence across provider/session replacement. Read operations+ * and unrelated operations remain available for authoritative reconciliation. */+export async function priorRecoveryApiReceipt(db: Db, input: {+ companyId: string; issueId: string; runId: string; operationId: string; digest: string;+}): Promise<Record<string, unknown> | null> {+ // Start at the current run so persisted automatic retry edges inherit the+ // same protection as a deliberate Retry or explicit continuation receipt.+ const ancestry = new Set((await recoveryRunAncestry({ db, companyId: input.companyId,+ issueId: input.issueId, sourceRunIds: [input.runId] }))+ .map(source => source.id).filter(id => id !== input.runId));+ if (!ancestry.size) return null;+ const sources = await db.select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, input.companyId),+ sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text,+ ${heartbeatRuns.contextSnapshot}->>'issueId') = ${input.issueId}`,+ ne(heartbeatRuns.id, input.runId),+ or(inArray(heartbeatRuns.id, [...ancestry]),+ sql`${heartbeatRuns.createdAt} < (select created_at from heartbeat_runs where id = ${input.runId})`)));+ let completed: Record<string, unknown> | null = null;+ for (const source of sources) {+ for (const receipt of Object.values(record(source.result?.apiToolReceipts)).map(record)) {+ if (receipt.operationId !== input.operationId) continue;+ const result = receipt.encryptedResult+ ? record(JSON.parse(await getSecretProvider("local_encrypted").resolveVersion({ material: record(receipt.encryptedResult), externalRef: null })))+ : record(receipt.result);+ if (receipt.state !== "completed" || result.outcome === "unknown" || result.error === "api_outcome_unknown") {+ return { state: "pending", result: { ok: false, status: null, error: "api_outcome_unknown",+ outcome: "unknown", guidance: "Reconcile the existing operation before repeating it. Independent work and reads remain available." } };+ }+ // A completed HTTP request is not necessarily a completed effect. A+ // definite client rejection may be retried after the user fixes its cause.+ // Preserve the transport owner's uncertainty classification above.+ if (result.ok === false && typeof result.status === "number" &&+ result.status >= 400 && result.status < 500 && result.status !== 408) continue;+ if (result.ok !== true) return { state: "pending", result: { ok: false, status: null,+ error: "api_outcome_unknown", outcome: "unknown",+ guidance: "Reconcile the existing operation before repeating it. Independent work and reads remain available." } };+ // Successful effects belong to their original intent, not every later+ // request on this task. Uncertain effects above retain their wider fence.+ if (ancestry.has(source.id) && receipt.digest === input.digest) completed = receipt;+ }+ }+ return completed;+}diff --git a/server/src/services/recovery-observability.ts b/server/src/services/recovery-observability.tsindex 7e866cdb8a..66304c31f2 100644--- a/server/src/services/recovery-observability.ts+++ b/server/src/services/recovery-observability.ts@@ -1,3 +1,4 @@+import { historicalRecoveryCounts } from "./workspace-recovery-backfill.js";import { and, eq, gte, sql } from "drizzle-orm";import type { Db } from "@paperclipai/db";import { heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db";@@ -52,6 +53,7 @@ export type RecoveryHandoffSummary = {/** Original agent recovered its own issue (owner == original assignee). */selfRecovery: number;boardOwned: number;+ systemOwned: number;activeTakeovers: number;/** handedBack / (handedBack + ownerCompleted); null when no resolved takeovers. */handedBackRatio: number | null;@@ -72,6 +74,7 @@ export type RecoveryCauseRouting = {};export type RecoveryObservabilityReport = {+ historicalRecovery: Awaited<ReturnType<typeof historicalRecoveryCounts>>;companyId: string;generatedAt: string;window: { weeks: number; since: string };@@ -88,10 +91,12 @@ export type HandoffClass =| "handed_back"| "owner_completed"| "board_owned"+ | "system_owned"| "active"| "other";type RecoveryActionFacts = {+ ownerType?: string;status: string;outcome: string | null;ownerAgentId: string | null;@@ -114,6 +119,7 @@ const TERMINAL_ISSUE_STATUSES = new Set(["done"]);* doing the work becomes rare".*/export function classifyRecoveryHandoff(facts: RecoveryActionFacts): HandoffClass {+ if (facts.ownerType === "system") return "system_owned";if (ACTIVE_STATUSES.has(facts.status)) return "active";if (!facts.ownerAgentId) return "board_owned";// Original agent recovered its own issue — the ideal per-cause routing, not a takeover.@@ -256,6 +262,7 @@ export function recoveryObservabilityService(db: Db) {status: issueRecoveryActions.status,outcome: issueRecoveryActions.outcome,ownerAgentId: issueRecoveryActions.ownerAgentId,+ ownerType: issueRecoveryActions.ownerType,returnOwnerAgentId: issueRecoveryActions.returnOwnerAgentId,finalAssigneeAgentId: issues.assigneeAgentId,finalIssueStatus: issues.status,@@ -276,6 +283,7 @@ export function recoveryObservabilityService(db: Db) {otherTakeover: 0,selfRecovery: 0,boardOwned: 0,+ systemOwned: 0,activeTakeovers: 0,handedBackRatio: null,ownerCompletedRatio: null,@@ -323,6 +331,10 @@ export function recoveryObservabilityService(db: Db) {if (row.status === "cancelled" && row.outcome !== "false_positive") routing.cancelled += 1;switch (klass) {+ case "system_owned":+ handoff.systemOwned += 1;+ if (ACTIVE_STATUSES.has(row.status)) routing.active += 1;+ break;case "self_recovery":handoff.selfRecovery += 1;if (row.status === "resolved") routing.retriedByOriginalSucceeded += 1;@@ -366,6 +378,7 @@ export function recoveryObservabilityService(db: Db) {byCause,handoff,perCauseRouting,+ historicalRecovery: await historicalRecoveryCounts(db, companyId),};}diff --git a/server/src/services/recovery-run-ancestry.ts b/server/src/services/recovery-run-ancestry.tsnew file mode 100644index 0000000000..cc171faa8f--- /dev/null+++ b/server/src/services/recovery-run-ancestry.ts@@ -0,0 +1,41 @@+import { sql } from "drizzle-orm";+import { agentWakeupRequests, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db";+import { canonicalExecutionUuid } from "./execution-identity.js";++/** Only committed predecessor edges can carry preserved work into a retry. */+export async function recoveryRunAncestry(input: {+ db: Db; companyId: string; issueId: string; sourceRunIds: string[];+}) {+ // Follow committed predecessor receipts, not transcript paths. UNION makes+ // cycles and duplicate receipts finite; every edge retains company/task scope.+ return input.db.execute<{ id: string }>(sql`+ with recursive sources(id) as (+ select r.id from ${heartbeatRuns} r+ where r.company_id = ${input.companyId}+ and coalesce(r.native_issue_id::text, r.issue_id::text, r.context_snapshot->>'issueId') = ${input.issueId}+ and r.id in (select ${canonicalExecutionUuid(sql`value`)}+ from jsonb_array_elements_text(${JSON.stringify(input.sourceRunIds)}::jsonb))+ union+ select predecessor.id from sources s+ join ${heartbeatRuns} current_run on current_run.id = s.id+ cross join lateral (+ select current_run.retry_of_run_id::text as id+ union+ select w.payload#>>'{taskRetry,sourceRunId}' from ${agentWakeupRequests} w+ where w.company_id = ${input.companyId} and w.run_id = s.id+ and w.reason = 'task_retry' and w.status = 'coalesced'+ and w.requested_by_actor_type = 'user' and w.payload->>'issueId' = ${input.issueId}+ and w.payload#>>'{taskRetry,schema}' = 'paperclip.task-retry.v1'+ and w.payload#>>'{taskRetry,generationId}' = w.id::text+ union+ select a.evidence->>'runId' from ${issueRecoveryActions} a+ where a.company_id = ${input.companyId} and a.source_issue_id = ${input.issueId}+ and a.evidence#>>'{explicitUserContinuation,runId}' = s.id::text+ ) edge+ join ${heartbeatRuns} predecessor on predecessor.id = ${canonicalExecutionUuid(sql`edge.id`)}+ and predecessor.company_id = ${input.companyId}+ and coalesce(predecessor.native_issue_id::text, predecessor.issue_id::text,+ predecessor.context_snapshot->>'issueId') = ${input.issueId}+ ) select id from sources+ `);+}diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.tsindex 101114042f..c4f9e4f834 100644--- a/server/src/services/recovery/stranded-notice.ts+++ b/server/src/services/recovery/stranded-notice.ts@@ -264,6 +264,9 @@ export function buildStrandedRecoveryEscalationNotice(input: {presentation: systemNoticePresentation({ tone: seed?.tone ?? "danger", title }),metadata: {version: 1,+ recoveryResponsibility: input.recoveryCause === "configuration_incomplete" ||+ ["provider_quota", "claude_auth_required", "acpx_auth_required"].includes(input.sourceRun?.errorCode ?? "")+ ? "user" : "system",sourceRunId: input.sourceRun?.id ?? null,sections,},diff --git a/server/src/services/sandbox-stop-and-retain.ts b/server/src/services/sandbox-stop-and-retain.tsindex 659a7bdc5e..86fabf4a84 100644--- a/server/src/services/sandbox-stop-and-retain.ts+++ b/server/src/services/sandbox-stop-and-retain.ts@@ -76,6 +76,15 @@ export async function prepareSandboxStopAndRetain(db: Db, lease: Lease) {return prepareStopAndRetain(db, lease, "active");}+/** Historical release rows can lack a stop receipt. Re-inspect the exact+ * recorded allocation using stop-only dispatch; never infer that it stopped. */+export async function prepareHistoricalSandboxStopVerification(db: Db, lease: typeof environmentLeases.$inferSelect) {+ if (lease.status !== "released" || !lease.heartbeatRunId || !lease.providerLeaseId ||+ !["retain_on_failure", "ephemeral"].includes(lease.leasePolicy) || lease.metadata?.pendingCleanupInFlight === true)+ return null;+ return prepareStopAndRetain(db, lease, "released");+}+/** A repair-only resume invalidates the old stop receipt atomically. This is* separate from ordinary release; a released timestamp alone cannot grant it. */export async function prepareStoppedSandboxForRecovery(db: Db, lease: typeof environmentLeases.$inferSelect) {diff --git a/server/src/services/system-recovery-state.test.ts b/server/src/services/system-recovery-state.test.tsnew file mode 100644index 0000000000..cab57be263--- /dev/null+++ b/server/src/services/system-recovery-state.test.ts@@ -0,0 +1,58 @@+import { randomUUID } from "node:crypto";+import { describe, expect, it } from "vitest";+import { createSystemRecovery, failSystemRecovery, readSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "./system-recovery-state.js";++describe("durable system recovery budget", () => {+ it("makes six attempts with exponential delays that survive serialization and exhaustion", () => {+ let state = createSystemRecovery(randomUUID());+ let now = 1_000;+ for (let attempt = 0; attempt < 6; attempt++) {+ state = reserveSystemRecoveryAttempt(state, now)!;+ expect(state.attempts).toBe(attempt + 1);+ state = failSystemRecovery(state, new SystemRecoveryFailure("export_interrupted", "retry_transient"), { now });+ state = readSystemRecovery(JSON.parse(JSON.stringify({ systemRecovery: state })))!;+ if (attempt < 5) {+ const base = 30_000 * 2 ** attempt;+ expect(state.nextAttemptAt! - now).toBeGreaterThanOrEqual(base * 0.8);+ expect(state.nextAttemptAt! - now).toBeLessThanOrEqual(base * 1.2);+ expect(reserveSystemRecoveryAttempt(state, state.nextAttemptAt! - 1)).toBeNull();+ now = state.nextAttemptAt!;+ }+ }+ expect(state.state).toBe("exhausted");+ expect(state.retriesUsed).toBe(5);+ expect(reserveSystemRecoveryAttempt(state, now + 1_000_000)).toBeNull();+ });+ it("never retries ahead of a provider cooldown or after the generation deadline", () => {+ const state = reserveSystemRecoveryAttempt(createSystemRecovery(randomUUID()), 0)!;+ const later = failSystemRecovery(state, new SystemRecoveryFailure("provider_unavailable", "retry_transient"),+ { now: 0, retryAfterAt: 120_000 });+ expect(later.nextAttemptAt).toBe(120_000);+ expect(reserveSystemRecoveryAttempt(later, 30 * 60_000)).toBeNull();+ expect(failSystemRecovery(state, new SystemRecoveryFailure("provider_unavailable", "retry_transient"),+ { now: 0, retryAfterAt: 31 * 60_000 }).state).toBe("exhausted");+ });+ it("reconciles a recorded attempt after restart without spending another retry", () => {+ const running = reserveSystemRecoveryAttempt(createSystemRecovery(randomUUID()), 0)!;+ const restarted = readSystemRecovery(JSON.parse(JSON.stringify({ systemRecovery: running })))!;+ expect(reserveSystemRecoveryAttempt(restarted, 60_000)).toMatchObject({+ attemptId: running.attemptId, attempts: 1, retriesUsed: 0,+ });+ });+ it("keeps an invalid ownership binding out of the physical retry loop", () => {+ const state = failSystemRecovery(createSystemRecovery(randomUUID()),+ new SystemRecoveryFailure("source_binding_invalid", "service_required"));+ expect(state).toMatchObject({ state: "exhausted", nextAttemptAt: null,+ failure: { code: "source_binding_invalid", retryClass: "service_required" } });+ });+ it("reads prior incident metadata without losing the local recovery budget or failure", () => {+ const state = failSystemRecovery(createSystemRecovery(randomUUID()),+ new SystemRecoveryFailure("source_unavailable", "service_required"), { now: 1_000 });+ const restored = readSystemRecovery({ systemRecovery: { ...state,+ incident: { status: "pending", id: null, attempts: 2, nextDeliveryAt: 60_000 },+ }, recoveryIncidentDelivery: { attempts: 2, nextAttemptAt: 60_000 } });+ expect(restored).toEqual(state);+ expect(reserveSystemRecoveryAttempt(restored!, 61_000)).toBeNull();+ });++});diff --git a/server/src/services/system-recovery-state.ts b/server/src/services/system-recovery-state.tsnew file mode 100644index 0000000000..5dd8fdd5ae--- /dev/null+++ b/server/src/services/system-recovery-state.ts@@ -0,0 +1,104 @@+import { createHash, randomUUID } from "node:crypto";+import { z } from "zod";++export const SYSTEM_RECOVERY_POLICY_VERSION = 1;+export const SYSTEM_RECOVERY_MAX_RETRIES = 5;+export const SYSTEM_RECOVERY_WINDOW_MS = 30 * 60_000;+export function infrastructureRetryDelayMs(retryNumber: number, sample: number) {+ return Math.round(30_000 * 2 ** (retryNumber - 1) * (0.8 + Math.min(1, Math.max(0, sample)) * 0.4));+}++export const recoveryFailureCodes = [+ "historical_source_missing", "source_binding_invalid", "allocation_ownership_ambiguous",+ "agent_stop_unconfirmed", "copyback_stop_unconfirmed", "workspace_writer_active",+ "provider_unavailable", "export_interrupted", "archive_unsafe", "snapshot_verification_failed",+ "source_unavailable", "effect_unresolved",+] as const;+export type RecoveryFailureCode = typeof recoveryFailureCodes[number];+export const recoveryRetryClasses = [+ "retry_transient", "recheck_evidence", "use_alternative_strategy", "service_required", "user_action_required",+] as const;+export type RecoveryRetryClass = typeof recoveryRetryClasses[number];++export class SystemRecoveryFailure extends Error {+ constructor(readonly code: RecoveryFailureCode, readonly retryClass: RecoveryRetryClass, message = code) {+ super(message);+ }+}++export const systemRecoverySchema = z.object({+ schema: z.literal("paperclip.system-recovery.v1"),+ policyVersion: z.literal(SYSTEM_RECOVERY_POLICY_VERSION),+ sourceRunId: z.string().uuid(),+ revision: z.number().int().nonnegative(),+ generationId: z.string().uuid(),+ intentId: z.string().uuid().nullable(),+ phase: z.enum(["verify_execution", "preserve_files", "reconcile_effects", "settle_result_or_dispatch"]),+ state: z.enum(["scheduled", "running", "awaiting_evidence", "exhausted", "complete"]),+ attemptId: z.string().uuid().nullable(),+ attempts: z.number().int().nonnegative(),+ retriesUsed: z.number().int().min(0).max(SYSTEM_RECOVERY_MAX_RETRIES),+ firstFailureAt: z.number().nullable(),+ nextAttemptAt: z.number().nullable(),+ deadlineAt: z.number().nullable(),+ providerCooldownAt: z.number().nullable().default(null),+ failure: z.object({+ code: z.enum(recoveryFailureCodes),+ retryClass: z.enum(recoveryRetryClasses),+ evidenceFingerprint: z.string(),+ }).nullable(),+ preservationOperationIds: z.array(z.string().uuid()),+ freshAttemptRunId: z.string().uuid().nullable(),+});+export type SystemRecoveryState = z.infer<typeof systemRecoverySchema>;++export function readSystemRecovery(evidence: Record<string, unknown> | null | undefined): SystemRecoveryState | null {+ const parsed = systemRecoverySchema.safeParse(evidence?.systemRecovery);+ return parsed.success ? parsed.data : null;+}++/** New generations require new intent or one-time policy adoption, never a sweep. */+export function createSystemRecovery(sourceRunId: string, intentId: string | null = null): SystemRecoveryState {+ return {+ schema: "paperclip.system-recovery.v1", policyVersion: SYSTEM_RECOVERY_POLICY_VERSION,+ sourceRunId, revision: 0, generationId: intentId ?? randomUUID(), intentId,+ phase: "verify_execution", state: "scheduled", attemptId: null, attempts: 0, retriesUsed: 0,+ firstFailureAt: null, nextAttemptAt: null, deadlineAt: null, providerCooldownAt: null, failure: null,+ preservationOperationIds: [], freshAttemptRunId: null,+ };+}++export function reserveSystemRecoveryAttempt(state: SystemRecoveryState, now = Date.now()): SystemRecoveryState | null {+ if (state.state === "complete" || state.state === "exhausted" ||+ (state.nextAttemptAt !== null && state.nextAttemptAt > now)) return null;+ // A reclaimed physical owner first reconciles the same interrupted attempt.+ // Starting another call is not evidence that the prior call failed.+ if (state.state === "running" && state.attemptId) return { ...state, revision: state.revision + 1 };+ if ((state.deadlineAt !== null && now >= state.deadlineAt) ||+ (state.attempts > 0 && state.retriesUsed >= SYSTEM_RECOVERY_MAX_RETRIES)) return null;+ return { ...state, revision: state.revision + 1, state: "running", attemptId: randomUUID(),+ attempts: state.attempts + 1, retriesUsed: state.retriesUsed + (state.attempts > 0 ? 1 : 0), nextAttemptAt: null };+}++/** The caller persists this timestamp. A restart must not recalculate jitter. */+export function failSystemRecovery(+ state: SystemRecoveryState, failure: SystemRecoveryFailure,+ options: { now?: number; retryAfterAt?: number; evidenceFingerprint?: string } = {},+): SystemRecoveryState {+ const now = options.now ?? Date.now();+ const firstFailureAt = state.firstFailureAt ?? now;+ const deadlineAt = state.deadlineAt ?? firstFailureAt + SYSTEM_RECOVERY_WINDOW_MS;+ const retryNumber = state.retriesUsed + 1;+ const entropy = createHash("sha256").update(`${state.generationId}:${retryNumber}`).digest().readUInt32BE(0) / 0xffffffff;+ const delay = infrastructureRetryDelayMs(retryNumber, entropy);+ const nextAttemptAt = Math.max(now + delay, options.retryAfterAt ?? 0);+ const retryable = ["retry_transient", "recheck_evidence"].includes(failure.retryClass);+ const retry = retryable && retryNumber <= SYSTEM_RECOVERY_MAX_RETRIES && nextAttemptAt < deadlineAt;+ return { ...state, revision: state.revision + 1, firstFailureAt, deadlineAt,+ providerCooldownAt: options.retryAfterAt ?? null,+ state: retry ? failure.retryClass === "recheck_evidence" ? "awaiting_evidence" : "scheduled" : "exhausted",+ nextAttemptAt: retry ? nextAttemptAt : null,+ failure: { code: failure.code, retryClass: failure.retryClass,+ evidenceFingerprint: options.evidenceFingerprint ?? createHash("sha256").update(`${state.sourceRunId}:${failure.code}`).digest("hex") },+ };+}diff --git a/server/src/services/system-recovery.ts b/server/src/services/system-recovery.tsnew file mode 100644index 0000000000..75eea95666--- /dev/null+++ b/server/src/services/system-recovery.ts@@ -0,0 +1,70 @@+import { and, eq, sql } from "drizzle-orm";+import { issueComments, issueRecoveryActions, type Db } from "@paperclipai/db";+import { createSystemRecovery, readSystemRecovery, type SystemRecoveryState } from "./system-recovery-state.js";+import type { WorkspaceRecoverySourceIdentity } from "./workspace-recovery-source.js";++export async function adoptSystemRecovery(db: Db, source: WorkspaceRecoverySourceIdentity) {+ return db.transaction(async tx => {+ const state = createSystemRecovery(source.runId);+ // Atomic, once per source. An exhausted previous execution budget is history;+ // adoption grants only the explicitly versioned maintenance capability.+ const adopted = await tx.update(issueRecoveryActions).set({+ ownerType: "system", ownerAgentId: null, ownerUserId: null,+ evidence: sql`${issueRecoveryActions.evidence} || jsonb_build_object(+ 'previousWorkspaceRecovery', ${issueRecoveryActions.evidence}->'workspaceRecovery',+ 'systemRecovery', ${JSON.stringify(state)}::jsonb,+ 'workspaceRecovery', ${JSON.stringify({+ schema: "paperclip.workspace-recovery.v1", runId: source.runId, status: "queued",+ stage: "verifying_stop", attempt: 0, attemptLimit: 6, requestIds: [],+ })}::jsonb)`,+ updatedAt: new Date(),+ }).where(and(eq(issueRecoveryActions.companyId, source.companyId), eq(issueRecoveryActions.id, source.actionId),+ eq(issueRecoveryActions.sourceIssueId, source.issueId),+ sql`${issueRecoveryActions.evidence}->>'runId' = ${source.runId}`,+ sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`))+ .returning({ id: issueRecoveryActions.id });+ if (!adopted.length) return;+ // Classify only notices emitted by the historical recovery producer, bound+ // to this exact source/action. Their content remains available in diagnostics;+ // neither user prose nor unrelated user-action notices are suppressed.+ await tx.update(issueComments).set({+ metadata: sql`${issueComments.metadata} || '{"recoveryResponsibility":"system"}'::jsonb`,+ }).where(and(eq(issueComments.companyId, source.companyId), eq(issueComments.issueId, source.issueId),+ eq(issueComments.authorType, "system"),+ sql`${issueComments.presentation}->>'kind' = 'system_notice'`,+ sql`${issueComments.metadata}->>'recoveryResponsibility' is null`,+ sql`${issueComments.metadata} @> ${JSON.stringify({ version: 1, sourceRunId: source.runId,+ sections: [{ rows: [{ type: "key_value", label: "Recovery action", value: source.actionId }] }] })}::jsonb`));+ });+}++/** CAS protects a newer manual generation from an old worker's late write.+ * This is bookkeeping authority only; physical writes still require ownership. */+export async function updateSystemRecovery(db: Db, source: WorkspaceRecoverySourceIdentity,+ previous: SystemRecoveryState, next: SystemRecoveryState) {+ const status = next.state === "complete" ? "recovered" : next.state === "exhausted" ? "blocked"+ : next.state === "running" ? "recovering" : "queued";+ const compatibility = {+ schema: "paperclip.workspace-recovery.v1", runId: source.runId, status,+ stage: next.phase === "verify_execution" ? "verifying_stop" : next.phase === "preserve_files" ? "restoring_files" : "saving_receipts",+ attempt: next.attempts, attemptLimit: 6, retryable: true, retryAt: next.nextAttemptAt ?? undefined,+ };+ const [updated] = await db.update(issueRecoveryActions).set({+ ownerType: "system", ownerAgentId: null, ownerUserId: null,+ evidence: sql`${issueRecoveryActions.evidence} || jsonb_build_object('systemRecovery', ${JSON.stringify(next)}::jsonb,+ 'workspaceRecovery', ${JSON.stringify(compatibility)}::jsonb || jsonb_build_object('requestIds',+ coalesce(${issueRecoveryActions.evidence}#>'{workspaceRecovery,requestIds}', '[]'::jsonb)))`,+ updatedAt: new Date(),+ }).where(and(eq(issueRecoveryActions.companyId, source.companyId), eq(issueRecoveryActions.id, source.actionId),+ sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,generationId}' = ${previous.generationId}`,+ sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,revision}' = ${String(previous.revision)}`))+ .returning({ id: issueRecoveryActions.id });+ return Boolean(updated);+}++export async function loadSystemRecovery(db: Db, source: WorkspaceRecoverySourceIdentity) {+ const [row] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, source.companyId), eq(issueRecoveryActions.sourceIssueId, source.issueId),+ eq(issueRecoveryActions.id, source.actionId)));+ return readSystemRecovery(row?.evidence);+}diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.tsnew file mode 100644index 0000000000..249ff55d8e--- /dev/null+++ b/server/src/services/task-interruption-presentation.ts@@ -0,0 +1,108 @@+import { and, desc, eq, inArray, sql } from "drizzle-orm";+import { agents, agentWakeupRequests, approvals, companies, heartbeatRuns, issueApprovals, issueRecoveryActions,+ issues, issueTreeHoldMembers, issueTreeHolds, projects, type Db } from "@paperclipai/db";+import type { TaskInterruptionPresentation } from "@paperclipai/shared";+import { isAiAuthenticationBlocked } from "./ai-auth-failure.js";+import { readSystemRecovery } from "./system-recovery-state.js";++type ProjectionIssue = Pick<typeof issues.$inferSelect, "id" | "companyId" | "status" | "assigneeAgentId" | "projectId">;+type ProjectionRun = Pick<typeof heartbeatRuns.$inferSelect,+ "id" | "status" | "scheduledRetryAt" | "errorCode" | "livenessState" | "resultJson">;+type ProjectionState = {+ run?: ProjectionRun;+ action?: typeof issueRecoveryActions.$inferSelect;+ wait?: { id: string; requestedAt: Date };+ agent?: Pick<typeof agents.$inferSelect, "status" | "pauseReason">;+ project?: Pick<typeof projects.$inferSelect, "pausedAt" | "pauseReason">;+ company?: Pick<typeof companies.$inferSelect, "status" | "pauseReason">;+ paused: boolean;+ approval: boolean;+};++/** Presentation never grants authority. Dispatch repeats all gates under its+ * locks. The same projection is used in detail, lists and attention surfaces. */+export function projectTaskInterruption(issue: ProjectionIssue, input: ProjectionState, now = Date.now()): TaskInterruptionPresentation | null {+ const { run, wait, action, agent, project, company } = input;+ if (!run) return null;+ const system = readSystemRecovery(action?.evidence);+ const base: TaskInterruptionPresentation = { intentId: wait?.id ?? null, responsibility: "system",+ state: "resolved", nextRetryAt: null, canRetry: false, userAction: null,+ sourceRunIds: [run.id], observedRunId: run.id };+ if (["done", "cancelled"].includes(issue.status) || (run.status === "succeeded" && !wait)) return base;+ const userAction = !issue.assigneeAgentId ? "assign_agent" : input.approval || run.errorCode === "native_provider_approval_required" ? "approval"+ : isAiAuthenticationBlocked(run) ? "reconnect"+ : run.errorCode === "native_provider_model_rejected" ? "choose_model"+ : [agent?.pauseReason, project?.pauseReason, company?.pauseReason].some(reason => reason === "budget" || reason === "budget_exceeded")+ ? "budget" : input.paused || project?.pausedAt || agent?.status === "paused" || company?.status === "paused" ? "resume" : null;+ if (userAction) return { ...base, responsibility: "user", state: "waiting_for_user", userAction };+ if (["running", "queued"].includes(run.status)) return { ...base, state: "working" };+ const retryAt = system?.nextAttemptAt ?? run.scheduledRetryAt?.getTime();+ if (retryAt && retryAt > now) return { ...base, state: "retry_scheduled",+ nextRetryAt: new Date(retryAt).toISOString(), canRetry: true };+ const activeObservation = action?.evidence.systemRecoveryActiveAt;+ if (system?.state === "running" && typeof activeObservation === "number" &&+ activeObservation > now - 45_000) return { ...base, state: "working" };+ if (wait && wait.requestedAt.getTime() > now - 10_000 && system?.state !== "exhausted")+ return { ...base, state: "working" };+ return { ...base, state: "failed", canRetry: true };+}++/** Batch list reads rather than doing seven queries per row. Keep run logs and+ * large result bodies out of this projection; only authentication evidence is+ * needed for the typed reconnect action. */+export async function taskInterruptionPresentations(db: Db, companyId: string, input: ProjectionIssue[]) {+ const selected = input.filter(issue => issue.companyId === companyId);+ const result = new Map<string, TaskInterruptionPresentation | null>();+ if (!selected.length) return result;+ const ids = selected.map(issue => issue.id);+ const runIssue = sql<string>`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId')`;+ const wakeIssue = sql<string>`${agentWakeupRequests.payload}->>'issueId'`;+ const agentIds = selected.flatMap(issue => issue.assigneeAgentId ? [issue.assigneeAgentId] : []);+ const projectIds = selected.flatMap(issue => issue.projectId ? [issue.projectId] : []);+ const [runs, waits, agentRows, projectRows, pauseRows, approvalRows, companyRows] = await Promise.all([+ db.selectDistinctOn([runIssue], { issueId: runIssue, id: heartbeatRuns.id, status: heartbeatRuns.status,+ errorCode: heartbeatRuns.errorCode, livenessState: heartbeatRuns.livenessState, scheduledRetryAt: heartbeatRuns.scheduledRetryAt,+ resultJson: sql<Record<string, unknown>>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete')`,+ }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), inArray(runIssue, ids)))+ .orderBy(runIssue, desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)),+ db.selectDistinctOn([wakeIssue], { issueId: wakeIssue, id: agentWakeupRequests.id, requestedAt: agentWakeupRequests.requestedAt })+ .from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), inArray(wakeIssue, ids),+ eq(agentWakeupRequests.status, "deferred_issue_execution"), eq(agentWakeupRequests.requestedByActorType, "user")))+ .orderBy(wakeIssue, desc(agentWakeupRequests.requestedAt)),+ agentIds.length ? db.select({ id: agents.id, status: agents.status, pauseReason: agents.pauseReason }).from(agents)+ .where(and(eq(agents.companyId, companyId), inArray(agents.id, agentIds))) : [],+ projectIds.length ? db.select({ id: projects.id, pausedAt: projects.pausedAt, pauseReason: projects.pauseReason }).from(projects)+ .where(and(eq(projects.companyId, companyId), inArray(projects.id, projectIds))) : [],+ db.select({ issueId: issueTreeHoldMembers.issueId }).from(issueTreeHoldMembers).innerJoin(issueTreeHolds, and(+ eq(issueTreeHolds.companyId, issueTreeHoldMembers.companyId), eq(issueTreeHolds.id, issueTreeHoldMembers.holdId)))+ .where(and(eq(issueTreeHoldMembers.companyId, companyId), inArray(issueTreeHoldMembers.issueId, ids),+ eq(issueTreeHolds.status, "active"), eq(issueTreeHolds.mode, "pause"))),+ db.select({ issueId: issueApprovals.issueId }).from(issueApprovals).innerJoin(approvals, and(+ eq(approvals.companyId, issueApprovals.companyId), eq(approvals.id, issueApprovals.approvalId)))+ .where(and(eq(issueApprovals.companyId, companyId), inArray(issueApprovals.issueId, ids),+ inArray(approvals.status, ["pending", "revision_requested"]))),+ db.select({ status: companies.status, pauseReason: companies.pauseReason }).from(companies).where(eq(companies.id, companyId)),+ ]);+ const runIds = runs.map(run => run.id);+ const actions = runIds.length ? await db.selectDistinctOn([issueRecoveryActions.sourceIssueId]).from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids),+ inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds),+ sql`${issueRecoveryActions.evidence} ? 'systemRecovery'`,+ )).orderBy(issueRecoveryActions.sourceIssueId, desc(issueRecoveryActions.createdAt)) : [];+ const byIssue = <T extends { issueId: string }>(rows: T[]) => new Map(rows.map(row => [row.issueId, row]));+ const runMap = byIssue(runs), waitMap = byIssue(waits);+ const actionMap = new Map(actions.map(action => [action.sourceIssueId, action]));+ const agentMap = new Map(agentRows.map(agent => [agent.id, agent]));+ const projectMap = new Map(projectRows.map(project => [project.id, project]));+ const pauses = new Set(pauseRows.map(row => row.issueId)), approvalsSet = new Set(approvalRows.map(row => row.issueId));+ for (const issue of selected) result.set(issue.id, projectTaskInterruption(issue, {+ run: runMap.get(issue.id), action: actionMap.get(issue.id), wait: waitMap.get(issue.id),+ agent: agentMap.get(issue.assigneeAgentId ?? ""), project: projectMap.get(issue.projectId ?? ""),+ company: companyRows[0], paused: pauses.has(issue.id), approval: approvalsSet.has(issue.id),+ }));+ return result;+}++export async function taskInterruptionPresentation(db: Db, issue: ProjectionIssue) {+ return (await taskInterruptionPresentations(db, issue.companyId, [issue])).get(issue.id) ?? null;+}diff --git a/server/src/services/task-retry.test.ts b/server/src/services/task-retry.test.tsnew file mode 100644index 0000000000..693ee1a4e8--- /dev/null+++ b/server/src/services/task-retry.test.ts@@ -0,0 +1,311 @@+import { randomUUID } from "node:crypto";+import { and, eq, sql } from "drizzle-orm";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issues, issueRecoveryActions, toolApplications, toolConnections, toolInvocations, applyPendingMigrations } from "@paperclipai/db";+import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";+import { priorRecoveryApiReceipt, unresolvedRecoveryToolInvocation } from "./recovery-effect-receipts.js";+import { requestTaskRetry } from "./task-retry.js";+import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js";+import { settleUnrecoverableExecutions } from "./execution-recovery-resolution.js";+import { createSystemRecovery, failSystemRecovery, readSystemRecovery, SystemRecoveryFailure } from "./system-recovery-state.js";+import { instanceSettingsService } from "./instance-settings.js";+import { heartbeatService } from "./heartbeat.js";++describe("durable task Retry admission", () => {+ let postgres: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;+ let db: ReturnType<typeof createDb>;+ beforeAll(async () => {+ const externalUrl = process.env.PAPERCLIP_TASK_RETRY_TEST_DATABASE_URL;+ if (externalUrl) {+ await applyPendingMigrations(externalUrl);+ db = createDb(externalUrl);+ } else {+ postgres = await startEmbeddedPostgresTestDatabase("task-retry-");+ db = createDb(postgres.connectionString);+ }+ }, 30_000);+ afterAll(async () => { await db?.$client.end(); await postgres?.cleanup(); });+ async function seed() {+ const companyId = randomUUID(), issueId = randomUUID(), agentId = randomUUID(), runId = randomUUID();+ await db.insert(companies).values({ id: companyId, name: "Retry company", issuePrefix: `T${companyId.slice(0, 6)}` });+ await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "paperclip_runner", status: "idle" });+ await db.insert(issues).values({ id: issueId, companyId, title: "Continue saved work", status: "blocked", assigneeAgentId: agentId });+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, status: "failed",+ contextSnapshot: { issueId }, finishedAt: new Date() });+ return { db, companyId, issueId, actorId: "board", observedRunId: runId, idempotencyKey: randomUUID() };+ }+ it("serializes concurrent clicks and remembers each key after completion", async () => {+ const input = await seed();+ const second = { ...input, idempotencyKey: randomUUID() };+ const [one, two] = await Promise.all([requestTaskRetry(input), requestTaskRetry(second)]);+ expect(one.requestId).toBe(two.requestId);+ const rows = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId));+ expect(rows.filter(row => row.status === "deferred_issue_execution")).toHaveLength(1);+ expect(rows).toHaveLength(2);+ await db.update(agentWakeupRequests).set({ status: "failed" }).where(eq(agentWakeupRequests.id, one.requestId!));+ expect((await requestTaskRetry(input)).requestId).toBe(one.requestId);+ expect((await requestTaskRetry(second)).requestId).toBe(one.requestId);+ const next = await requestTaskRetry({ ...input, idempotencyKey: randomUUID() });+ expect(next.requestId).not.toBe(one.requestId);+ });+ it("does not resurrect completed tasks or retry an obsolete assignment", async () => {+ const input = await seed();+ await db.update(issues).set({ status: "done" }).where(eq(issues.id, input.issueId));+ expect(await requestTaskRetry(input)).toMatchObject({ accepted: false, stale: true });+ await db.update(issues).set({ status: "blocked", assigneeAgentId: null }).where(eq(issues.id, input.issueId));+ expect(await requestTaskRetry(input)).toMatchObject({ accepted: false, stale: true });+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(0);+ });+ it("requires current Agent Chat ownership and enablement even when replaying a retry receipt", async () => {+ const input = await seed();+ const settings = instanceSettingsService(db);+ await settings.updateExperimental({ enableAgentChat: true });+ await db.update(issues).set({ conversationAgentId: (await db.select().from(issues).where(eq(issues.id, input.issueId)))[0].assigneeAgentId,+ conversationUserId: input.actorId, conversationState: "waiting" }).where(eq(issues.id, input.issueId));+ try {+ await expect(requestTaskRetry({ ...input, actorId: "another-user" })).rejects.toMatchObject({ status: 403 });+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(0);+ const accepted = await requestTaskRetry(input);+ expect(accepted.accepted).toBe(true);+ await settings.updateExperimental({ enableAgentChat: false });+ await expect(requestTaskRetry(input)).rejects.toMatchObject({ status: 404 });+ await settings.updateExperimental({ enableAgentChat: true });+ await db.update(issues).set({ conversationUserId: "new-owner" }).where(eq(issues.id, input.issueId));+ await expect(requestTaskRetry(input)).rejects.toMatchObject({ status: 403 });+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId))).toHaveLength(1);+ const next = await requestTaskRetry({ ...input, actorId: "new-owner", idempotencyKey: randomUUID() });+ expect(next.requestId).not.toBe(accepted.requestId);+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, accepted.requestId!)))[0].status).toBe("failed");+ } finally { await settings.updateExperimental({ enableAgentChat: false }); }+ });+ it.each(["owner", "feature"] as const)("rechecks Agent Chat $0 at dispatch after waiting for the issue lock", async gate => {+ const input = { ...await seed(), actorId: "local-board", actorSource: "local_implicit" };+ const settings = instanceSettingsService(db);+ await settings.updateExperimental({ enableAgentChat: true, enableNativeRunner: true });+ const [issue] = await db.select().from(issues).where(eq(issues.id, input.issueId));+ await db.update(issues).set({ conversationAgentId: issue.assigneeAgentId, conversationUserId: input.actorId,+ conversationState: "waiting" }).where(eq(issues.id, input.issueId));+ // Keep admitted runs queued: this test asserts admission, not provider behavior.+ await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })+ .where(eq(agents.id, issue.assigneeAgentId!));+ await db.insert(heartbeatRuns).values({ companyId: input.companyId, agentId: issue.assigneeAgentId!, status: "running" });+ const receipt = await requestTaskRetry(input);+ let release!: () => void, ready!: () => void, holderPid = 0;+ const held = new Promise<void>(resolve => { ready = resolve; });+ const unlock = new Promise<void>(resolve => { release = resolve; });+ const holder = db.transaction(async tx => {+ holderPid = (await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`))[0].pid;+ await tx.select().from(issues).where(eq(issues.id, issue.id)).for("update");+ ready(); await unlock;+ if (gate === "owner") await tx.update(issues).set({ conversationUserId: "new-owner" }).where(eq(issues.id, issue.id));+ else await instanceSettingsService(tx as unknown as typeof db).updateExperimental({ enableAgentChat: false });+ });+ let dispatch: Promise<unknown> | undefined;+ try {+ await held;+ dispatch = heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!).catch(error => error);+ await expect.poll(async () => (await db.execute<{ waiting: boolean }>(sql`select exists(+ select 1 from pg_stat_activity where datname = current_database()+ and ${holderPid} = any(pg_blocking_pids(pid))) as waiting`))[0].waiting, { timeout: 5_000 }).toBe(true);+ release(); await holder;+ expect(await dispatch).toMatchObject({ status: gate === "owner" ? 403 : 404 });+ expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),+ eq(heartbeatRuns.status, "queued")))).toHaveLength(0);+ // Restore current authority; the same saved receipt can then admit one run.+ await settings.updateExperimental({ enableAgentChat: true });+ await db.update(issues).set({ conversationUserId: input.actorId }).where(eq(issues.id, issue.id));+ await heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!);+ expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),+ eq(heartbeatRuns.status, "queued")))).toHaveLength(1);+ } finally {+ release(); await Promise.allSettled([holder, dispatch]);+ await settings.updateExperimental({ enableAgentChat: false, enableNativeRunner: false });+ }+ }, 30_000);+ it("replaces an exhausted unadmitted generation only on a new deliberate click", async () => {+ const input = await seed();+ const first = await requestTaskRetry(input);+ const state = failSystemRecovery(createSystemRecovery(input.observedRunId, first.requestId!),+ new SystemRecoveryFailure("source_unavailable", "service_required"));+ const [action] = await db.insert(issueRecoveryActions).values({+ companyId: input.companyId, sourceIssueId: input.issueId, kind: "active_run_watchdog",+ ownerType: "system", cause: "legacy_execution_requires_reconciliation", fingerprint: randomUUID(),+ nextAction: "System recovery", evidence: { runId: input.observedRunId, systemRecovery: state },+ }).returning();+ expect((await requestTaskRetry(input)).requestId).toBe(first.requestId);+ const nextInput = { ...input, idempotencyKey: randomUUID() };+ const next = await requestTaskRetry(nextInput);+ expect(next.requestId).not.toBe(first.requestId);+ const [updated] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id));+ expect(readSystemRecovery(updated.evidence)).toMatchObject({ generationId: next.requestId, attempts: 0 });+ expect((await requestTaskRetry(nextInput)).requestId).toBe(next.requestId);+ const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, input.companyId));+ expect(wakes.find(row => row.id === first.requestId)?.status).toBe("failed");+ expect(wakes.filter(row => row.status === "deferred_issue_execution")).toHaveLength(1);+ });+ it("binds a key to its company, task and actor across all statuses", async () => {+ const input = await seed();+ const receipt = await requestTaskRetry(input);+ await db.update(agentWakeupRequests).set({ status: "completed" }).where(and(+ eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, receipt.requestId!)));+ await expect(requestTaskRetry({ ...input, actorId: "another-user" })).rejects.toThrow("different task or user");+ expect((await requestTaskRetry(input)).requestId).toBe(receipt.requestId);+ const other = await seed();+ expect((await requestTaskRetry({ ...other, idempotencyKey: input.idempotencyKey })).requestId).not.toBe(receipt.requestId);+ });+ it("keeps an adopted historical hold with its maintenance owner", async () => {+ const input = await seed();+ const system = createSystemRecovery(input.observedRunId);+ const [action] = await db.insert(issueRecoveryActions).values({+ companyId: input.companyId, sourceIssueId: input.issueId, kind: "active_run_watchdog",+ status: "active", ownerType: "system", returnOwnerAgentId: null,+ cause: "legacy_execution_requires_reconciliation", fingerprint: randomUUID(),+ nextAction: "System preservation", evidence: { runId: input.observedRunId, systemRecovery: system },+ }).returning();+ await settleUnrecoverableExecutions(db);+ const [current] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id));+ expect(current.status).toBe("active");+ expect(current.ownerType).toBe("system");+ expect(current.evidence.systemRecovery).toEqual(system);+ expect(current.evidence.automaticRecovery).toBeUndefined();+ });+ it.each(["evaluate", "continue"])("keeps an admitted %s retry isolated after a failure without a preserved workspace", async strategy => {+ const input = await seed();+ const receipt = await requestTaskRetry(input);+ const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.observedRunId));+ const [successor] = await db.insert(heartbeatRuns).values({ companyId: input.companyId,+ agentId: source.agentId, issueId: input.issueId, status: "queued",+ contextSnapshot: { issueId: input.issueId, taskRetryRequestId: receipt.requestId } }).returning();+ expect(await readFreshWorkspaceReadiness(db, successor)).toBeNull();+ const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!));+ await db.update(agentWakeupRequests).set({ runId: successor.id, status: "coalesced",+ payload: { ...wake.payload, taskRetry: { ...(wake.payload!.taskRetry as object), strategy } } })+ .where(eq(agentWakeupRequests.id, receipt.requestId!));+ const readiness = await readFreshWorkspaceReadiness(db, successor);+ expect(readiness).toMatchObject({ mode: "fresh_isolated_workspace", retryIntentId: receipt.requestId,+ sourceRunId: source.id });+ expect(await readFreshWorkspaceReadiness(db, successor)).toEqual(readiness);+ expect(await readFreshWorkspaceReadiness(db, { ...successor, id: randomUUID() })).toBeNull();+ });+ it("reuses completed API effects only from the retry ancestry while retaining unrelated uncertainty", async () => {+ const input = await seed();+ const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.observedRunId));+ const receipt = { operationId: "PATCH /api/issues/{id}", digest: "same-title", state: "completed",+ result: { ok: true, status: 200, data: { title: "Earlier title" } } };+ const [earlier] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, issueId: input.issueId,+ agentId: source.agentId, status: "succeeded", createdAt: new Date(1_000), resultJson: { apiToolReceipts: { receipt } } }).returning();+ const accepted = await requestTaskRetry(input);+ const [successor] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, issueId: input.issueId,+ agentId: source.agentId, status: "running", createdAt: new Date(Date.now() + 1_000) }).returning();+ await db.update(agentWakeupRequests).set({ status: "coalesced", runId: successor.id })+ .where(eq(agentWakeupRequests.id, accepted.requestId!));+ const call = { companyId: input.companyId, issueId: input.issueId, runId: successor.id,+ operationId: receipt.operationId, digest: receipt.digest };+ expect(await priorRecoveryApiReceipt(db, call)).toBeNull();+ // An actual predecessor edge makes the exact receipt relevant, even across multiple attempts.+ await db.update(heartbeatRuns).set({ retryOfRunId: earlier.id }).where(eq(heartbeatRuns.id, source.id));+ expect(await priorRecoveryApiReceipt(db, call)).toEqual(receipt);+ await db.update(heartbeatRuns).set({ retryOfRunId: null }).where(eq(heartbeatRuns.id, source.id));+ await db.update(heartbeatRuns).set({ resultJson: { apiToolReceipts: { receipt: { ...receipt,+ state: "pending", result: { ok: false, outcome: "unknown" } } } } }).where(eq(heartbeatRuns.id, earlier.id));+ expect(await priorRecoveryApiReceipt(db, call)).toMatchObject({ state: "pending", result: { outcome: "unknown" } });+ });++ async function automaticSuccessorOfTaskRetry() {+ const input = await seed();+ const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.observedRunId));+ const intent = await requestTaskRetry(input);+ const [retry] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, issueId: input.issueId,+ agentId: source.agentId, runtimeMode: "native", status: "failed", createdAt: new Date(Date.now() + 1_000) }).returning();+ await db.update(agentWakeupRequests).set({ status: "coalesced", runId: retry.id })+ .where(eq(agentWakeupRequests.id, intent.requestId!));+ const [automatic] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, issueId: input.issueId,+ agentId: source.agentId, runtimeMode: "native", status: "running", retryOfRunId: retry.id,+ createdAt: new Date(Date.now() + 2_000) }).returning();+ await db.insert(agentWakeupRequests).values({ companyId: input.companyId, agentId: source.agentId,+ runId: automatic.id, source: "automation", reason: "transient_failure", status: "coalesced",+ requestedByActorType: "system", payload: { issueId: input.issueId, retryOfRunId: retry.id } });+ return { input, retry, automatic };+ }++ it.each(["completed", "pending"] as const)("automatic successors inherit %s API receipts after task Retry", async state => {+ const { input, retry, automatic } = await automaticSuccessorOfTaskRetry();+ const receipt = { operationId: "POST /api/companies/{companyId}/projects", digest: "same-project", state,+ result: state === "completed" ? { ok: true, status: 201 } : { ok: false, outcome: "unknown" } };+ await db.update(heartbeatRuns).set({ resultJson: { apiToolReceipts: { receipt } } }).where(eq(heartbeatRuns.id, retry.id));+ const call = { companyId: input.companyId, issueId: input.issueId, runId: automatic.id,+ operationId: receipt.operationId, digest: receipt.digest };+ expect(await priorRecoveryApiReceipt(db, call)).toMatchObject({ state, result: receipt.result });+ // A transcript predecessor is insufficient; the persisted run edge owns lineage.+ await db.update(heartbeatRuns).set({ retryOfRunId: null, contextSnapshot: { previousRunId: retry.id } })+ .where(eq(heartbeatRuns.id, automatic.id));+ expect(await priorRecoveryApiReceipt(db, call)).toBeNull();+ });++ it("automatic successors retain uncertain upstream mutation fences after task Retry", async () => {+ const { input, retry, automatic } = await automaticSuccessorOfTaskRetry();+ const [application] = await db.insert(toolApplications).values({ companyId: input.companyId,+ name: "Test API", type: "rest_api" }).returning();+ const [connection] = await db.insert(toolConnections).values({ companyId: input.companyId, applicationId: application.id,+ name: "Test API", uid: randomUUID(), transport: "rest_api" }).returning();+ const [invocation] = await db.insert(toolInvocations).values({ companyId: input.companyId, issueId: input.issueId,+ runId: retry.id, connectionId: connection.id, toolName: "create_project", riskLevel: "write",+ status: "timed_out", startedAt: new Date() }).returning();+ const call = { companyId: input.companyId, issueId: input.issueId, runId: automatic.id,+ connectionId: connection.id, toolName: "create_project", risk: "write" };+ expect(await unresolvedRecoveryToolInvocation(db, call)).toBe(invocation.id);+ expect(await unresolvedRecoveryToolInvocation(db, { ...call, risk: "read" })).toBeNull();+ });++ it("retires a deferred Retry when newer work appears while dispatch waits for the issue lock", async () => {+ const input = { ...await seed(), actorId: "local-board", actorSource: "local_implicit" };+ await instanceSettingsService(db).updateExperimental({ enableNativeRunner: true });+ const [issue] = await db.select().from(issues).where(eq(issues.id, input.issueId));+ await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } })+ .where(eq(agents.id, issue.assigneeAgentId!));+ await db.insert(heartbeatRuns).values({ companyId: input.companyId, agentId: issue.assigneeAgentId!, status: "running" });+ const receipt = await requestTaskRetry(input);+ let release!: () => void, ready!: () => void, holderPid = 0;+ const held = new Promise<void>(resolve => { ready = resolve; });+ const unlock = new Promise<void>(resolve => { release = resolve; });+ const newerRunId = randomUUID();+ const holder = db.transaction(async tx => {+ holderPid = (await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`))[0].pid;+ await tx.select().from(issues).where(eq(issues.id, issue.id)).for("update");+ ready(); await unlock;+ await tx.insert(heartbeatRuns).values({ id: newerRunId, companyId: input.companyId, issueId: issue.id,+ agentId: issue.assigneeAgentId!, status: "succeeded", finishedAt: new Date(), createdAt: new Date(Date.now() + 1_000) });+ await tx.update(issues).set({ status: "in_progress", executionRunId: newerRunId }).where(eq(issues.id, issue.id));+ });+ let dispatch: Promise<unknown> | undefined;+ try {+ await held;+ dispatch = heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!);+ await expect.poll(async () => (await db.execute<{ waiting: boolean }>(sql`select exists(+ select 1 from pg_stat_activity where datname = current_database()+ and ${holderPid} = any(pg_blocking_pids(pid))) as waiting`))[0].waiting, { timeout: 5_000 }).toBe(true);+ release(); await holder; await dispatch;+ await heartbeatService(db).resumeTaskRetry(input.companyId, receipt.requestId!);+ expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),+ eq(heartbeatRuns.status, "queued")))).toHaveLength(0);+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)))[0])+ .toMatchObject({ status: "skipped", runId: null, error: "task_retry_superseded" });+ } finally {+ release(); await Promise.allSettled([holder, dispatch]);+ await instanceSettingsService(db).updateExperimental({ enableNativeRunner: false });+ }+ }, 30_000);++ it("does not attach a new deliberate Retry to an unadmitted request for an older run", async () => {+ const input = await seed();+ const old = await requestTaskRetry(input);+ const [issue] = await db.select().from(issues).where(eq(issues.id, input.issueId));+ const [newer] = await db.insert(heartbeatRuns).values({ companyId: input.companyId, issueId: input.issueId,+ agentId: issue.assigneeAgentId!, status: "failed", finishedAt: new Date(), createdAt: new Date(Date.now() + 1_000) }).returning();+ const next = await requestTaskRetry({ ...input, observedRunId: newer.id, idempotencyKey: randomUUID() });+ expect(next.requestId).not.toBe(old.requestId);+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, old.requestId!)))[0])+ .toMatchObject({ status: "skipped", error: "task_retry_superseded" });+ });++});diff --git a/server/src/services/task-retry.ts b/server/src/services/task-retry.tsnew file mode 100644index 0000000000..a443027f61--- /dev/null+++ b/server/src/services/task-retry.ts@@ -0,0 +1,192 @@+import { z } from "zod";+import { randomUUID } from "node:crypto";+import { and, desc, eq, inArray, or, sql } from "drizzle-orm";+import { agentWakeupRequests, chatActions, chatConversations, chatEndpoints, heartbeatRuns, issues, issueRecoveryActions, type Db } from "@paperclipai/db";+import { conflict, forbidden, notFound } from "../errors.js";+import { persistActivity } from "./activity-log.js";+import { createSystemRecovery, readSystemRecovery } from "./system-recovery-state.js";+import { updateSystemRecovery } from "./system-recovery.js";+import { instanceSettingsService } from "./instance-settings.js";++export async function assertTaskRetryConversationAllowed(+ db: Db,+ issue: { conversationAgentId?: string | null; conversationUserId?: string | null },+ actorId: string,+) {+ if (!issue.conversationAgentId) return;+ if (!(await instanceSettingsService(db).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled");+ if (issue.conversationUserId !== actorId) throw forbidden("Only the conversation owner can retry a chat run");+}++const taskRetryIntentSchema = z.object({+ schema: z.literal("paperclip.task-retry.v1"), generationId: z.string().uuid(), sourceRunId: z.string().uuid(),+ actorId: z.string().min(1), actorSource: z.enum(["local_implicit", "session", "board_key", "cloud_tenant"]).default("session"), strategy: z.enum(["evaluate", "continue", "fresh_isolated_workspace", "finalize_result"]),+ chatActionId: z.string().uuid().optional(), canonicalIntentId: z.string().uuid().optional(),+});+export type TaskRetryIntent = z.infer<typeof taskRetryIntentSchema>;+export function readTaskRetryIntent(payload: Record<string, unknown> | null | undefined): TaskRetryIntent | null {+ const result = taskRetryIntentSchema.safeParse(payload?.taskRetry);+ return result.success ? result.data : null;+}++/** Caller holds the issue dispatch lock. Newer work supersedes an unadmitted+ * Retry; retiring its authority does not acknowledge or discard saved input. */+export async function retireSupersededTaskRetry(db: Db, input: {+ companyId: string; issueId: string; requestId: string; sourceRunId: string;+}) {+ const [latest] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, input.companyId),+ or(eq(heartbeatRuns.issueId, input.issueId), eq(heartbeatRuns.nativeIssueId, input.issueId),+ sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}`),+ )).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);+ if (latest?.id === input.sourceRunId) return false;+ const retired = await db.update(agentWakeupRequests).set({ status: "skipped", error: "task_retry_superseded",+ finishedAt: new Date(), updatedAt: new Date() }).where(and(+ eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, input.requestId),+ eq(agentWakeupRequests.reason, "task_retry"), sql`${agentWakeupRequests.runId} is null`,+ sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,+ inArray(agentWakeupRequests.status, ["deferred_issue_execution", "queued", "claimed"]),+ )).returning({ id: agentWakeupRequests.id });+ return retired.length > 0;+}++/** Persist a deliberate click under dispatch's issue-first lock order. This+ * transaction never contacts a provider. The normal wake queue owns execution. */+export async function requestTaskRetry(input: {+ db: Db; companyId: string; issueId: string; actorId: string;+ idempotencyKey: string; observedRunId: string | null; actorSource?: string;+ prepareChatRetry?: (tx: Db, scope: { companyId: string; issueId: string; agentId: string;+ failedRunId: string; initiatedByUserId: string; retryIntentId?: string }) => Promise<{ actionId: string }>;+}) {+ return input.db.transaction(async tx => {+ const db = tx as unknown as Db;+ const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, input.companyId),+ eq(issues.id, input.issueId))).for("update");+ if (!issue) throw notFound("Task not found");+ await assertTaskRetryConversationAllowed(db, issue, input.actorId);+ const key = `task-retry:${input.idempotencyKey}`;+ const [sameRequest] = await tx.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.idempotencyKey, key)));+ if (sameRequest) {+ if (sameRequest.payload?.issueId !== issue.id || sameRequest.requestedByActorId !== input.actorId)+ throw conflict("This retry request belongs to a different task or user.");+ const intent = readTaskRetryIntent(sameRequest.payload);+ return { requestId: intent?.canonicalIntentId ?? sameRequest.id, accepted: true, stale: false,+ observedRunId: intent?.sourceRunId ?? null, chatActionId: intent?.chatActionId };+ }+ const [latest] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, issue.companyId),+ or(eq(heartbeatRuns.issueId, issue.id), eq(heartbeatRuns.nativeIssueId, issue.id),+ sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`)))+ .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);+ if (["done", "cancelled"].includes(issue.status) || !issue.assigneeAgentId || !latest ||+ latest.agentId !== issue.assigneeAgentId || input.observedRunId !== latest.id) {+ return { requestId: null, accepted: false, stale: true, observedRunId: latest?.id ?? null };+ }+ let active = (await tx.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, issue.companyId), eq(agentWakeupRequests.agentId, issue.assigneeAgentId),+ sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`,+ sql`${agentWakeupRequests.payload}->'taskRetry'->>'schema' = 'paperclip.task-retry.v1'`,+ inArray(agentWakeupRequests.status, ["deferred_issue_execution", "queued", "claimed"]),+ )).orderBy(desc(agentWakeupRequests.requestedAt)).limit(1)).at(0);+ const activeIntent = readTaskRetryIntent(active?.payload);+ if (active && !active.runId && activeIntent && await retireSupersededTaskRetry(db, {+ companyId: issue.companyId, issueId: issue.id, requestId: active.id, sourceRunId: activeIntent.sourceRunId,+ })) active = undefined;+ if (active && !active.runId && issue.conversationAgentId && active.requestedByActorId !== issue.conversationUserId) {+ // A former owner's unadmitted receipt cannot own the new owner's Retry.+ await tx.update(agentWakeupRequests).set({ status: "failed", finishedAt: new Date(), updatedAt: new Date() })+ .where(eq(agentWakeupRequests.id, active.id));+ active = undefined;+ }+ const busy = ["queued", "running", "scheduled_retry"].includes(latest.status);+ const records = await tx.select().from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, issue.companyId), eq(issueRecoveryActions.sourceIssueId, issue.id),+ sql`${issueRecoveryActions.evidence}->>'runId' = ${latest.id}`)).for("update");+ // An unadmitted request can outlive its exhausted repair. A new deliberate+ // click replaces that generation; a replay of the same key returned above.+ if (active && !busy && !active.runId && records.some(action =>+ readSystemRecovery(action.evidence)?.state === "exhausted")) {+ await tx.update(agentWakeupRequests).set({ status: "failed", finishedAt: new Date(), updatedAt: new Date() })+ .where(eq(agentWakeupRequests.id, active.id));+ active = undefined;+ }+ const id = randomUUID();+ const intent: TaskRetryIntent = { schema: "paperclip.task-retry.v1", generationId: active?.id ?? id,+ sourceRunId: latest.id, actorId: input.actorId,+ actorSource: taskRetryIntentSchema.shape.actorSource.parse(input.actorSource ?? "session"), strategy: "evaluate",+ ...(active ? { canonicalIntentId: active.id } : {}) };+ // Preserve external chat authority through its existing admission owner.+ // Generic board Retry must never manufacture a chat-inbound request.+ const [chat] = await tx.select({ id: chatConversations.id }).from(chatConversations)+ .innerJoin(chatEndpoints, eq(chatEndpoints.id, chatConversations.endpointId)).where(and(+ eq(chatConversations.companyId, issue.companyId), eq(chatConversations.issueId, issue.id),+ eq(chatEndpoints.externalExecutionPolicy, "restricted"))).limit(1);+ await tx.insert(agentWakeupRequests).values({ id, companyId: issue.companyId, agentId: issue.assigneeAgentId,+ source: "on_demand", triggerDetail: "manual", reason: "task_retry", idempotencyKey: key,+ requestedByActorType: "user", requestedByActorId: input.actorId,+ status: active || busy ? "coalesced" : "deferred_issue_execution",+ runId: active?.runId ?? (busy ? latest.id : null),+ payload: { issueId: issue.id, taskRetry: intent }, finishedAt: active || busy ? new Date() : null });+ if (chat && !active && !busy) {+ if (!input.prepareChatRetry) throw conflict("Retry is unavailable for this connected conversation.");+ intent.chatActionId = (await input.prepareChatRetry(db, { companyId: issue.companyId, issueId: issue.id,+ agentId: issue.assigneeAgentId, failedRunId: latest.id, initiatedByUserId: input.actorId, retryIntentId: id })).actionId;+ await tx.update(agentWakeupRequests).set({ payload: { issueId: issue.id, taskRetry: intent } })+ .where(eq(agentWakeupRequests.id, id));+ }+ if (!busy) {+ for (const action of records) {+ const previous = readSystemRecovery(action.evidence);+ if (!previous || previous.state === "complete") continue;+ // Active repair keeps its attempt and cooldown. An exhausted generation+ // gets a new budget only because this click is a new durable intent.+ const next = previous.state === "exhausted"+ ? { ...createSystemRecovery(latest.id, id), revision: previous.revision + 1,+ preservationOperationIds: previous.preservationOperationIds,+ providerCooldownAt: previous.providerCooldownAt, nextAttemptAt: previous.providerCooldownAt }+ : { ...previous, revision: previous.revision + 1, intentId: active?.id ?? id,+ // Retry may advance our backoff, never a provider's cooldown and+ // never an operation whose physical owner is still running.+ nextAttemptAt: previous.state === "running" ? previous.nextAttemptAt+ : Math.max(Date.now(), previous.providerCooldownAt ?? 0) };+ if (next.generationId !== previous.generationId) await persistActivity(db, {+ companyId: issue.companyId, actorType: "system", actorId: "task-retry", entityType: "issue", entityId: issue.id,+ action: "issue.recovery_generation_replaced", runId: latest.id,+ details: { recoveryActionId: action.id, previousGeneration: previous, nextGenerationId: next.generationId },+ });+ await updateSystemRecovery(db, { companyId: issue.companyId, issueId: issue.id, runId: latest.id,+ actionId: action.id }, previous, next);+ }+ }+ await persistActivity(db, { companyId: issue.companyId, actorType: "user", actorId: input.actorId,+ action: "issue.retry_requested", entityType: "issue", entityId: issue.id, runId: latest.id,+ details: { requestId: active?.id ?? id, sourceRunId: latest.id, attachedToExistingWork: Boolean(active || busy) } });+ return { requestId: active?.id ?? id, accepted: true, stale: false, observedRunId: latest.id,+ chatActionId: intent.chatActionId };+ });+}++/** Chat owns admission and authorization. The task receipt follows that+ * durable outcome; it never launches a parallel generic board execution. */+export async function reconcileTaskChatRetryReceipts(db: Db) {+ const pending = await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.reason, "task_retry"), eq(agentWakeupRequests.status, "deferred_issue_execution"),+ sql`${agentWakeupRequests.payload}#>>'{taskRetry,chatActionId}' is not null`,+ )).orderBy(agentWakeupRequests.updatedAt).limit(50);+ for (const wake of pending) {+ const intent = readTaskRetryIntent(wake.payload);+ if (!intent?.chatActionId) continue;+ const [chat] = await db.select().from(chatActions).where(and(eq(chatActions.companyId, wake.companyId),+ eq(chatActions.id, intent.chatActionId), eq(chatActions.kind, "failed_run_retry"),+ sql`${chatActions.payload}->>'issueId' = ${String(wake.payload?.issueId)}`));+ const [receipt] = chat ? await db.select().from(agentWakeupRequests).where(and(+ eq(agentWakeupRequests.companyId, wake.companyId), eq(agentWakeupRequests.id, chat.id),+ eq(agentWakeupRequests.agentId, wake.agentId))) : [];+ const failed = chat && ["failed", "cancelled"].includes(chat.status);+ await db.update(agentWakeupRequests).set({+ ...(receipt?.runId ? { status: "coalesced", runId: receipt.runId, finishedAt: new Date() }+ : failed ? { status: "failed", finishedAt: new Date() } : {}),+ updatedAt: new Date(),+ }).where(and(eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.status, "deferred_issue_execution")));+ }+}diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.tsindex 9a4c1fe4c6..73b9245366 100644--- a/server/src/services/tool-gateway.ts+++ b/server/src/services/tool-gateway.ts@@ -160,6 +160,7 @@ import {type ToolRuntimeSlotView,} from "./tool-runtime-supervisor.js";import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js";+import { unresolvedRecoveryToolInvocation } from "./recovery-effect-receipts.js";import { isRetiredComposioConnection, RETIRED_COMPOSIO_MESSAGE } from "@paperclipai/shared";import {createPaperclipCloudConnector,@@ -10274,6 +10275,19 @@ export function createToolGatewayService(let effectiveParameters: unknown = requestedParameters;let effectiveArgumentsSummary = argumentValidation.summary;+ if (session.runId && session.issueId && tool.connectionId && tool.risk !== "read" &&+ // This owner has an exact publication receipt/reconciliation protocol.+ !(tool.providerType === "paperclip_github_chat" &&+ ["comment", "update_comment", "submit_review"].includes(tool.upstreamToolName ?? ""))) {+ const unresolved = await unresolvedRecoveryToolInvocation(db, {+ companyId: session.companyId, issueId: session.issueId, runId: session.runId,+ connectionId: tool.connectionId, toolName: tool.name, risk: tool.risk,+ });+ if (unresolved) throw new ToolGatewayHttpError(409,+ "A previous operation has an unconfirmed outcome. Reconcile it before repeating this operation; reads and independent work remain available.",+ "recovery_effect_outcome_unresolved", { invocationId: unresolved });+ }+if (!input.approvedActionRequestId) {const replay = await replayMatchingAgentAction({session,diff --git a/server/src/services/workspace-recovery-backfill.ts b/server/src/services/workspace-recovery-backfill.tsnew file mode 100644index 0000000000..fa81317f18--- /dev/null+++ b/server/src/services/workspace-recovery-backfill.ts@@ -0,0 +1,108 @@+import { and, asc, eq, inArray, sql } from "drizzle-orm";+import { agentWakeupRequests, environmentLeases, heartbeatRuns, issues, issueRecoveryActions, type Db } from "@paperclipai/db";+import { adoptSystemRecovery } from "./system-recovery.js";+import { terminalWorkspaceRunStates, workspaceExportCauses } from "./workspace-recovery-source.js";++/** Progress lives on each source, so restarts and additional servers neither+ * restart a global scan nor grant a second policy-adoption budget. */+export async function adoptHistoricalWorkspaceRecoveries(db: Db) {+ const rows = await db.select().from(issueRecoveryActions).where(and(+ sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`,+ sql`${issueRecoveryActions.evidence}->>'runId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'`,+ sql`(${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ or ${inArray(issueRecoveryActions.cause, workspaceExportCauses)})`,+ )).orderBy(asc(issueRecoveryActions.id)).limit(50);+ for (const action of rows) await adoptSystemRecovery(db, {+ companyId: action.companyId, issueId: action.sourceIssueId, actionId: action.id, runId: String(action.evidence.runId),+ });+ const remaining = 50 - rows.length;+ if (remaining === 0) return rows.length;+ // Both branches use durable indexed candidate identities. The lease branch+ // covers old runs which predate the run-level restore descriptor. It never+ // searches for a replacement allocation or consults today's agent config.+ const candidates = sql`(+ select id from ${heartbeatRuns} where result_json->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ and not (coalesce(result_json, '{}'::jsonb) ? 'systemRecoveryAdoption')+ and status in ('failed', 'interrupted', 'timed_out', 'cancelled', 'succeeded')+ union+ select heartbeat_run_id from ${environmentLeases}+ where lease_policy = 'retain_on_failure' and heartbeat_run_id is not null+ and not (coalesce(metadata, '{}'::jsonb) ? 'systemRecoveryAdoption')+ )`;+ const missing = await db.select({ run: heartbeatRuns, issue: issues }).from(heartbeatRuns).innerJoin(issues, and(+ eq(issues.companyId, heartbeatRuns.companyId),+ sql`${issues.id}::text = coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId')`,+ )).where(and(inArray(heartbeatRuns.status, terminalWorkspaceRunStates),+ sql`${heartbeatRuns.id} in ${candidates}`,+ sql`not (coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ? 'systemRecoveryAdoption')`,+ )).orderBy(asc(heartbeatRuns.id)).limit(remaining);+ for (const { run, issue } of missing) await db.transaction(async tx => {+ await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, issue.id)).for("update");+ const [current] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, run.companyId),+ eq(heartbeatRuns.id, run.id))).for("update");+ if (!current || current.resultJson?.systemRecoveryAdoption) return;+ const [existing] = await tx.select().from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issue.id),+ sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`,+ sql`(${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ or ${inArray(issueRecoveryActions.cause, [...workspaceExportCauses,+ "legacy_execution_requires_reconciliation", "native_continuation_requires_reconciliation"])})`)).limit(1);+ const [active] = await tx.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and(+ eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issue.id),+ inArray(issueRecoveryActions.status, ["active", "escalated"]))).limit(1);+ const retained = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(+ eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),+ eq(environmentLeases.issueId, issue.id), eq(environmentLeases.leasePolicy, "retain_on_failure"),+ )).orderBy(asc(environmentLeases.id)).for("update");+ const historicalWorkspaceSource = { schema: "paperclip.historical-workspace-source.v1", runId: run.id,+ leaseIds: retained.map(lease => lease.id) };+ const action = existing ?? (await tx.insert(issueRecoveryActions).values({+ companyId: run.companyId, sourceIssueId: issue.id, kind: "active_run_watchdog", ownerType: "system",+ returnOwnerAgentId: run.agentId,+ cause: run.runtimeMode === "native" ? "native_continuation_requires_reconciliation" : "legacy_execution_requires_reconciliation",+ fingerprint: `retained-source:${run.id}`,+ // A maintenance record may retain a no-replay obligation without stealing+ // the current task's active approval/user-action owner.+ status: active || ["done", "cancelled"].includes(issue.status) ? "resolved" : "active",+ outcome: active ? "blocked" : null,+ nextAction: "Paperclip owns preservation of this historical source.",+ evidence: { runId: run.id, workspaceRestoreRecovery: current.resultJson?.workspaceRestoreRecovery,+ workspaceRestoreFailure: current.resultJson?.workspaceRestoreFailure, historicalWorkspaceSource,+ automaticRecovery: { replay: "blocked" } },+ }).returning())[0];+ if (existing && !existing.evidence.historicalWorkspaceSource) await tx.update(issueRecoveryActions).set({+ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify({ historicalWorkspaceSource })}::jsonb`,+ }).where(eq(issueRecoveryActions.id, action.id));+ await adoptSystemRecovery(tx as unknown as Db, { companyId: run.companyId, issueId: issue.id, runId: run.id, actionId: action.id });+ const adoption = { policyVersion: 1, actionId: action.id };+ await tx.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ||+ ${JSON.stringify({ systemRecoveryAdoption: adoption })}::jsonb` })+ .where(eq(heartbeatRuns.id, run.id));+ if (retained.length) await tx.update(environmentLeases).set({+ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ systemRecoveryAdoption: adoption })}::jsonb`,+ }).where(and(eq(environmentLeases.companyId, run.companyId), inArray(environmentLeases.id, retained.map(lease => lease.id))));+ });+ return rows.length + missing.length;+}++/** Protected diagnostics report actual outcomes, not just completion of a scan. */+export async function historicalRecoveryCounts(db: Db, companyId: string) {+ const rows = await db.select({+ classified: sql<number>`count(*)::int`,+ repaired: sql<number>`count(*) filter (where ${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' = 'complete')::int`,+ waitingInputDelivered: sql<number>`count(*) filter (where exists (+ select 1 from ${agentWakeupRequests} w where w.company_id = ${issueRecoveryActions.companyId}+ and w.run_id::text = ${issueRecoveryActions.evidence}#>>'{explicitUserContinuation,runId}'+ and w.status in ('coalesced', 'completed') and w.requested_by_actor_type = 'user'))::int`,+ awaitingRetry: sql<number>`count(*) filter (where ${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' = 'complete'+ and exists (select 1 from ${issues} i where i.id = ${issueRecoveryActions.sourceIssueId}+ and i.company_id = ${issueRecoveryActions.companyId} and i.status not in ('done', 'cancelled')+ and i.execution_run_id is null)+ and not exists (select 1 from ${agentWakeupRequests} w where w.company_id = ${issueRecoveryActions.companyId}+ and w.payload->>'issueId' = ${issueRecoveryActions.sourceIssueId}::text and w.status = 'deferred_issue_execution')+ and ${issueRecoveryActions.evidence}#>>'{explicitUserContinuation,runId}' is null)::int`,+ unresolvedSources: sql<number>`count(*) filter (where ${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' <> 'complete')::int`,+ }).from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId),+ sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,policyVersion}' = '1'`));+ return rows[0];+}diff --git a/server/src/services/workspace-recovery-receipt.ts b/server/src/services/workspace-recovery-receipt.tsindex 1f2fa6adc8..0552db209b 100644--- a/server/src/services/workspace-recovery-receipt.ts+++ b/server/src/services/workspace-recovery-receipt.ts@@ -36,12 +36,12 @@ export function workspaceRecoveryDisplay(evidence: Record<string, unknown>, runI/** Only the host writes workspace operations. Adapter output and a user-supplied* repair note cannot substitute for this exact copyback receipt. Stop/authority* are checked separately at every continuation admission. */-export async function hasVerifiedWorkspaceRepair(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,+export async function verifiedWorkspaceRepairReceipt(db: Db, run: Pick<typeof heartbeatRuns.$inferSelect,"id" | "companyId" | "nativeIssueId" | "issueId" | "contextSnapshot" | "runnerProfileJson">) {const issueId = run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId;const reference = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync);- if (typeof issueId !== "string" || !reference || reference.state !== "finalized" || !reference.finalHostSha256) return false;- const [receipt] = await db.select({ metadata: workspaceOperations.metadata }).from(workspaceOperations).where(and(+ if (typeof issueId !== "string" || !reference || reference.state !== "finalized" || !reference.finalHostSha256) return null;+ const [receipt] = await db.select({ id: workspaceOperations.id, metadata: workspaceOperations.metadata }).from(workspaceOperations).where(and(eq(workspaceOperations.companyId, run.companyId), eq(workspaceOperations.issueId, issueId),eq(workspaceOperations.heartbeatRunId, run.id), eq(workspaceOperations.phase, "workspace_recovery"),eq(workspaceOperations.status, "succeeded"),@@ -49,11 +49,15 @@ export async function hasVerifiedWorkspaceRepair(db: Db, run: Pick<typeof heartbconst proof = receipt?.metadata;if (!proof || proof.leaseId !== reference.leaseId || proof.providerLeaseId !== reference.providerLeaseId|| proof.descriptorSha256 !== reference.descriptorSha256 || proof.finalHostSha256 !== reference.finalHostSha256- || typeof proof.recoveryActionId !== "string") return false;+ || typeof proof.recoveryActionId !== "string") return null;const [action] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId),eq(issueRecoveryActions.id, proof.recoveryActionId),)).limit(1);const state = readWorkspaceRecovery(action?.evidence ?? null);- return state?.runId === run.id && state.status === "recovered";+ return state?.runId === run.id && state.status === "recovered" ? receipt.id : null;+}++export async function hasVerifiedWorkspaceRepair(...args: Parameters<typeof verifiedWorkspaceRepairReceipt>) {+ return (await verifiedWorkspaceRepairReceipt(...args)) !== null;}diff --git a/server/src/services/workspace-recovery-snapshot.ts b/server/src/services/workspace-recovery-snapshot.tsnew file mode 100644index 0000000000..62c3d0212b--- /dev/null+++ b/server/src/services/workspace-recovery-snapshot.ts@@ -0,0 +1,196 @@+import { z } from "zod";+import { createReadStream, createWriteStream } from "node:fs";+import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";+import { createHash } from "node:crypto";+import os from "node:os";+import path from "node:path";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";+import { and, desc, eq, sql } from "drizzle-orm";+import { workspaceOperations, type Db } from "@paperclipai/db";+import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";+import { createCommandManagedRuntimeClient } from "@paperclipai/adapter-utils/command-managed-runtime";+import { createTarballFromDirectory, exportSandboxWorkspaceSnapshot, restoreVerifiedSnapshotArchive } from "@paperclipai/adapter-utils/sandbox-managed-runtime";+import { captureDirectorySnapshotOffThread, disposeDirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge";+import { getStorageService, type StorageService } from "../storage/index.js";+import { SystemRecoveryFailure } from "./system-recovery-state.js";+import { recoveryRunAncestry } from "./recovery-run-ancestry.js";++const storedFileSchema = z.object({ objectKey: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/), byteSize: z.number().int().positive() });+type StoredFile = z.infer<typeof storedFileSchema>;+const snapshotSchema = z.object({+ schema: z.literal("paperclip.workspace-recovery-snapshot.v1"), recoveryActionId: z.string().uuid(),+ leaseId: z.string().uuid(), providerLeaseId: z.string().min(1), archive: storedFileSchema, manifest: storedFileSchema,+});+export type PreservedWorkspaceSnapshot = z.infer<typeof snapshotSchema>;+function readSnapshot(value: unknown, companyId: string, runId: string) {+ const parsed = snapshotSchema.safeParse(value);+ if (!parsed.success) throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ const s = parsed.data;+ const prefix = `${companyId}/workspace-recovery/${runId}/${s.leaseId}/`;+ if (s.archive.objectKey !== `${prefix}${s.archive.sha256}.tar` || s.manifest.objectKey !== `${prefix}${s.manifest.sha256}.jsonl`)+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ return s;+}++async function digest(stream: AsyncIterable<Buffer | string>, limit = Number.MAX_SAFE_INTEGER) {+ const hash = createHash("sha256");+ let byteSize = 0;+ for await (const chunk of stream) {+ byteSize += Buffer.byteLength(chunk);+ if (byteSize > limit) throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ hash.update(chunk);+ }+ return { sha256: hash.digest("hex"), byteSize };+}++export async function verifyStoredRecoveryFile(storage: StorageService, companyId: string, file: StoredFile) {+ const object = await storage.getObject(companyId, file.objectKey);+ try {+ const actual = await digest(object.stream, file.byteSize);+ if (actual.sha256 !== file.sha256 || actual.byteSize !== file.byteSize)+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ } finally { object.stream.destroy(); }+}++/** The durable operation is written before uploading. A lost upload reply or+ * DB commit is reconciled against that same object identity on the next pass. */+export async function preserveWorkspaceSnapshot(input: {+ db: Db; companyId: string; issueId: string; runId: string; actionId: string;+ leaseId: string; providerLeaseId: string; target: AdapterSandboxExecutionTarget;+ assertHeld(): Promise<void>;+}) {+ if (!input.target.runner) throw new SystemRecoveryFailure("source_unavailable", "service_required");+ const storage = getStorageService();+ const scope = and(eq(workspaceOperations.companyId, input.companyId),+ eq(workspaceOperations.heartbeatRunId, input.runId), eq(workspaceOperations.phase, "workspace_recovery_snapshot"),+ sql`${workspaceOperations.metadata}->>'leaseId' = ${input.leaseId}`,+ sql`${workspaceOperations.metadata}->>'providerLeaseId' = ${input.providerLeaseId}`,+ sql`${workspaceOperations.metadata}->>'recoveryActionId' = ${input.actionId}`);+ const [existing] = await input.db.select().from(workspaceOperations).where(scope)+ .orderBy(desc(workspaceOperations.createdAt)).limit(1);+ if (existing?.metadata?.schema === "paperclip.workspace-recovery-snapshot.v1") {+ const saved = readSnapshot(existing.metadata, input.companyId, input.runId);+ const heads = await Promise.all([storage.headObject(input.companyId, saved.archive.objectKey),+ storage.headObject(input.companyId, saved.manifest.objectKey)]);+ if (heads.every(head => head.exists)) {+ await verifyStoredRecoveryFile(storage, input.companyId, saved.archive);+ await verifyStoredRecoveryFile(storage, input.companyId, saved.manifest);+ await input.assertHeld();+ await input.db.update(workspaceOperations).set({ status: "succeeded", finishedAt: new Date(), updatedAt: new Date() })+ .where(eq(workspaceOperations.id, existing.id));+ return existing.id;+ }+ if (existing.status === "succeeded") throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ }+ const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-preserve-"));+ try {+ await input.assertHeld();+ const client = createCommandManagedRuntimeClient({ runner: input.target.runner,+ commandCwd: input.target.remoteCwd, timeoutMs: input.target.timeoutMs ?? 120_000 });+ const directory = path.join(root, "files");+ await exportSandboxWorkspaceSnapshot({ client, remoteDir: input.target.remoteCwd,+ stagingDir: directory, operationId: `preserve:${input.actionId}:${input.leaseId}` }).catch(error => {+ if (error?.code === "WORKSPACE_SNAPSHOT_EXPORT_UNSUPPORTED")+ throw new SystemRecoveryFailure("source_unavailable", "use_alternative_strategy");+ throw error;+ });+ await input.assertHeld();+ const manifestPath = path.join(root, "manifest.jsonl");+ const snapshot = await captureDirectorySnapshotOffThread(directory, { exclude: [], diskBacked: true });+ try {+ await pipeline(Readable.from((function* () {+ yield `${JSON.stringify({ schema: "paperclip.workspace-file-manifest.v1" })}\n`;+ for (const entry of snapshot.entries) yield `${JSON.stringify(entry)}\n`;+ })()), createWriteStream(manifestPath, { flags: "wx", mode: 0o600 }));+ } finally { await disposeDirectorySnapshot(snapshot); }+ const archivePath = path.join(root, "workspace.tar");+ await createTarballFromDirectory({ localDir: directory, archivePath });+ const files = await Promise.all([archivePath, manifestPath].map(async file => ({+ ...await digest(createReadStream(file)), file,+ })));+ const prefix = `${input.companyId}/workspace-recovery/${input.runId}/${input.leaseId}`;+ const stored = files.map((file, index) => ({ objectKey: `${prefix}/${file.sha256}.${index === 0 ? "tar" : "jsonl"}`,+ sha256: file.sha256, byteSize: file.byteSize }));+ const metadata: PreservedWorkspaceSnapshot = { schema: "paperclip.workspace-recovery-snapshot.v1",+ recoveryActionId: input.actionId, leaseId: input.leaseId, providerLeaseId: input.providerLeaseId,+ archive: stored[0], manifest: stored[1] };+ await input.assertHeld();+ const [operation] = existing+ ? await input.db.update(workspaceOperations).set({ metadata, status: "running", updatedAt: new Date() })+ .where(eq(workspaceOperations.id, existing.id)).returning()+ : await input.db.insert(workspaceOperations).values({ companyId: input.companyId, issueId: input.issueId,+ heartbeatRunId: input.runId, phase: "workspace_recovery_snapshot", status: "running", metadata }).returning();+ for (const [index, file] of files.entries()) {+ if (!(await storage.headObject(input.companyId, stored[index].objectKey)).exists) {+ if ((await stat(file.file)).size === 0) {+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ }+ await storage.putFile({ companyId: input.companyId, namespace: "workspace-recovery",+ originalFilename: path.basename(file.file), contentType: index === 0 ? "application/x-tar" : "application/x-ndjson",+ objectKey: stored[index].objectKey, body: createReadStream(file.file), sha256: file.sha256, byteSize: file.byteSize });+ }+ await verifyStoredRecoveryFile(storage, input.companyId, stored[index]);+ }+ await input.assertHeld();+ await input.db.update(workspaceOperations).set({ status: "succeeded", finishedAt: new Date(), updatedAt: new Date() })+ .where(eq(workspaceOperations.id, operation.id));+ return operation.id;+ } finally { await rm(root, { recursive: true, force: true }); }+}++/** Recovered files are an attachment to a fresh attempt, never an overlay.+ * Atomically publish each immutable snapshot directory after verification. */+export async function attachPreservedWorkspaceSnapshots(input: {+ db: Db; companyId: string; issueId: string; sourceRunIds: string[]; cwd: string;+}) {+ const storage = getStorageService();+ const results: Array<{ operationId: string; path: string; sourceRunId: string }> = [];+ const sources = await recoveryRunAncestry(input);+ for (const { id: sourceRunId } of sources) {+ const rows = await input.db.select().from(workspaceOperations).where(and(+ eq(workspaceOperations.companyId, input.companyId), eq(workspaceOperations.issueId, input.issueId),+ eq(workspaceOperations.heartbeatRunId, sourceRunId), eq(workspaceOperations.phase, "workspace_recovery_snapshot"),+ eq(workspaceOperations.status, "succeeded")));+ for (const operation of rows) {+ const saved = readSnapshot(operation.metadata, input.companyId, sourceRunId);+ const parent = path.join(await realpath(input.cwd), ".paperclip-recovered");+ await mkdir(parent, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => { if (error.code !== "EEXIST") throw error; });+ if ((await lstat(parent)).isSymbolicLink() || await realpath(parent) !== parent)+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ const destination = path.join(parent, operation.id);+ const provenance = { schema: saved.schema, operationId: operation.id, sourceRunId,+ leaseId: saved.leaseId, sha256: saved.archive.sha256 };+ const priorStat = await lstat(destination).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; return null; });+ if (priorStat && (!priorStat.isDirectory() || priorStat.isSymbolicLink() || await realpath(destination) !== destination))+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ const provenancePath = path.join(destination, "provenance.json");+ if (priorStat) {+ const proof = await lstat(provenancePath).catch(() => null);+ if (!proof?.isFile() || proof.isSymbolicLink())+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ }+ const prior = priorStat ? await readFile(provenancePath, "utf8").catch(() => null) : null;+ if (prior === JSON.stringify(provenance)) {+ results.push({ operationId: operation.id, path: destination, sourceRunId });+ continue;+ }+ if (priorStat) throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ await verifyStoredRecoveryFile(storage, input.companyId, saved.manifest);+ const staging = await mkdtemp(path.join(parent, ".preparing-"));+ try {+ const archivePath = path.join(staging, "snapshot.tar");+ const object = await storage.getObject(input.companyId, saved.archive.objectKey);+ try { await pipeline(object.stream, createWriteStream(archivePath, { flags: "wx", mode: 0o600 })); }+ finally { object.stream.destroy(); }+ await restoreVerifiedSnapshotArchive({ archivePath, localDir: path.join(staging, "files"), ...saved.archive });+ await rm(archivePath);+ await writeFile(path.join(staging, "provenance.json"), JSON.stringify(provenance), { flag: "wx", mode: 0o600 });+ // Never replace an earlier attachment or user edits on a restart.+ await rename(staging, destination);+ results.push({ operationId: operation.id, path: destination, sourceRunId });+ } finally { await rm(staging, { recursive: true, force: true }); }+ }+ }+ return results;+}diff --git a/server/src/services/workspace-recovery-source.ts b/server/src/services/workspace-recovery-source.tsnew file mode 100644index 0000000000..cd5e0b61f2--- /dev/null+++ b/server/src/services/workspace-recovery-source.ts@@ -0,0 +1,74 @@+import { and, eq, inArray, ne, or, sql } from "drizzle-orm";+import { environmentLeases, environments, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, type Db } from "@paperclipai/db";+import { adapterExecutionControls } from "./adapter-execution-control.js";+import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js";+import { SystemRecoveryFailure } from "./system-recovery-state.js";++export const workspaceExportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"];+export const terminalWorkspaceRunStates = ["failed", "interrupted", "timed_out", "cancelled", "succeeded"];+export type WorkspaceRecoverySourceIdentity = { companyId: string; issueId: string; runId: string; actionId: string };++/** Resolve only the immutable source recorded by the failed run. Never discover+ * a candidate by recency, mutable adapter configuration, or a provider search. */+export async function inspectWorkspaceRecoverySource(db: Db, input: WorkspaceRecoverySourceIdentity) {+ const invalid = () => new SystemRecoveryFailure("source_binding_invalid", "service_required");+ const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId)));+ const [action] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId),+ eq(issueRecoveryActions.sourceIssueId, input.issueId), eq(issueRecoveryActions.id, input.actionId)));+ if (!run || !action || action.evidence.runId !== run.id || !terminalWorkspaceRunStates.includes(run.status) ||+ (run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId) !== input.issueId) throw invalid();+ const rawReference = run.runnerProfileJson?.nativeWorkspaceSync;+ const reference = readNativeWorkspaceSyncReference(rawReference);+ if (rawReference != null && !reference) throw invalid();+ const recorded = run.resultJson?.workspaceRestoreRecovery as { schema?: unknown; leaseIds?: unknown } | undefined;+ if (recorded != null && recorded.schema !== "paperclip.workspace-restore-recovery.v1") throw invalid();+ const historical = action.evidence.historicalWorkspaceSource as { schema?: unknown; runId?: unknown; leaseIds?: unknown } | undefined;+ if (historical != null && (historical.schema !== "paperclip.historical-workspace-source.v1" || historical.runId !== run.id)) throw invalid();+ const leaseIds = recorded ? recorded.leaseIds+ : reference && workspaceExportCauses.includes(action.cause) ? [reference.leaseId]+ : historical?.leaseIds;+ if (!Array.isArray(leaseIds) || leaseIds.length === 0)+ throw new SystemRecoveryFailure("historical_source_missing", "use_alternative_strategy");+ if (leaseIds.some(id => typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) ||+ new Set(leaseIds).size !== leaseIds.length || (reference && !leaseIds.includes(reference.leaseId))) throw invalid();+ const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(+ eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, run.id)));+ if (coordinator?.leaseOwner || adapterExecutionControls.has(run.id) ||+ (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()))+ throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ const sources = [];+ for (const leaseId of leaseIds as string[]) {+ const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),+ eq(environmentLeases.id, leaseId), eq(environmentLeases.heartbeatRunId, run.id)));+ const descriptor = reference?.leaseId === leaseId ? reference : null;+ const remoteCwd = lease?.metadata?.remoteCwd;+ if (!lease || lease.issueId !== input.issueId || !lease.environmentId || !lease.providerLeaseId ||+ !lease.provider || lease.provider === "local" || !["retain_on_failure", "ephemeral"].includes(lease.leasePolicy) ||+ typeof remoteCwd !== "string" || !remoteCwd.startsWith("/") ||+ (descriptor && (lease.providerLeaseId !== descriptor.providerLeaseId || remoteCwd !== descriptor.remoteCwd ||+ (lease.executionWorkspaceId && lease.executionWorkspaceId !== descriptor.workspaceId)))) throw invalid();+ const [other] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(+ ne(environmentLeases.id, lease.id), eq(environmentLeases.provider, lease.provider),+ eq(environmentLeases.providerLeaseId, lease.providerLeaseId))).limit(1);+ if (other) throw new SystemRecoveryFailure("allocation_ownership_ambiguous", "service_required");+ // Snapshot export writes only a new staging directory. A native baseline+ // merge additionally needs exclusive ownership of its host destination.+ if (descriptor) {+ const [writer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, input.companyId), inArray(heartbeatRuns.status, ["queued", "running"]),+ sql`not exists (select 1 from ${issueRecoveryActions} a+ where a.company_id = ${input.companyId} and a.source_issue_id = ${input.issueId}+ and a.evidence->>'runId' = ${run.id}+ and a.evidence#>>'{explicitUserContinuation,runId}' = ${heartbeatRuns.id}::text+ and a.evidence#>>'{explicitUserContinuation,readiness,mode}' = 'fresh_isolated_workspace')`,+ or(eq(heartbeatRuns.nativeIssueId, input.issueId), eq(heartbeatRuns.issueId, input.issueId),+ sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}`,+ sql`${heartbeatRuns.contextSnapshot}->>'executionWorkspaceId' = ${descriptor.workspaceId}`))).limit(1);+ if (writer) throw new SystemRecoveryFailure("workspace_writer_active", "recheck_evidence");+ }+ const [environment] = await db.select().from(environments).where(eq(environments.id, lease.environmentId));+ if (!environment) throw new SystemRecoveryFailure("source_unavailable", "service_required");+ sources.push({ lease, environment, reference: descriptor, remoteCwd });+ }+ return { run, action, sources };+}diff --git a/server/src/services/workspace-recovery.test.ts b/server/src/services/workspace-recovery.test.tsindex 5df72d901c..2576dbe394 100644--- a/server/src/services/workspace-recovery.test.ts+++ b/server/src/services/workspace-recovery.test.ts@@ -1,11 +1,28 @@+import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js";+import { createHeartbeatWorkspaceResolver, resolveExecutionWorkspaceReuseRequestForIssue } from "./heartbeat/workspaces.js";+import { environmentService } from "./environments.js";+import { environmentRunOrchestrator } from "./environment-run-orchestrator.js";+import { executionWorkspaceService } from "./execution-workspaces.js";+import { workspaceOperationService } from "./workspace-operations.js";+import { instanceSettingsService } from "./instance-settings.js";+import { projectTaskInterruption } from "./task-interruption-presentation.js";+import { readSystemRecovery } from "./system-recovery-state.js";+import { adoptSystemRecovery } from "./system-recovery.js";+import { getStorageService } from "../storage/index.js";+import { attachPreservedWorkspaceSnapshots } from "./workspace-recovery-snapshot.js";+import { adoptHistoricalWorkspaceRecoveries, historicalRecoveryCounts } from "./workspace-recovery-backfill.js";+import { createSystemRecovery, failSystemRecovery, SystemRecoveryFailure } from "./system-recovery-state.js";+import { requestTaskRetry } from "./task-retry.js";+import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js";import { execFile } from "node:child_process";import { randomUUID } from "node:crypto";-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";import { and, eq, inArray, sql } from "drizzle-orm";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";-import { agents, approvals, budgetPolicies, costEvents, issueApprovals, issueTreeHolds, issueTreeHoldMembers, companies, createDb, environmentLeases, environments, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, agentWakeupRequests, workspaceOperations } from "@paperclipai/db";+import { agents, approvals, budgetPolicies, costEvents, completionContracts, issueApprovals, issueTreeHolds, issueTreeHoldMembers, companies, createDb, environmentLeases, environments, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, agentWakeupRequests, workspaceOperations } from "@paperclipai/db";+import { resumePreservedResultFinalization } from "./preserved-result-finalization.js";import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";import type { EnvironmentLease } from "@paperclipai/shared";import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";@@ -18,7 +35,11 @@ import { hasVerifiedWorkspaceRepair, readWorkspaceRecovery } from "./workspace-rimport { getExecutionBlocker } from "./execution-blocker.js";import * as workerProof from "./native-runtime/native-workspace-platform-proof.js";const targets = vi.hoisted(() => new Map<string, AdapterSandboxExecutionTarget>());-vi.mock("./environment-execution-target.js", () => ({ resolveEnvironmentExecutionTarget: async (input: { leaseId: string }) => targets.get(input.leaseId) }));+vi.mock("./environment-execution-target.js", async importOriginal => {+ const actual = await importOriginal<typeof import("./environment-execution-target.js")>();+ return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters<typeof actual.resolveEnvironmentExecutionTarget>[0]) =>+ (input.leaseId ? targets.get(input.leaseId) : undefined) ?? actual.resolveEnvironmentExecutionTarget(input) };+});describe("automatic retained workspace recovery", () => {let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;@@ -35,7 +56,7 @@ describe("automatic retained workspace recovery", () => {if (priorHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = priorHome;if (priorInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID; else process.env.PAPERCLIP_INSTANCE_ID = priorInstance;});- async function seed(mode = "native") {+ async function seed(mode = "native", nativeDescriptor = true) {const companyId = randomUUID(), issueId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), actionId = randomUUID();await db.insert(companies).values({ id: companyId, name: "Workspace recovery", defaultResponsibleUserId: "board", issuePrefix: `R${companyId.slice(0, 6)}` });await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "paperclip_runner", status: "idle", runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } });@@ -62,9 +83,22 @@ describe("automatic retained workspace recovery", () => {child.stdin?.end(input.stdin ?? "");}) } };targets.set(lease.id, target);- const prepared = await prepareNativeWorkspaceSync({ db, companyId, workspaceId: issueId, workspaceLocalDir: host,- runId, lease: lease as EnvironmentLease, target, resourceDisposition: "destroy" });- expect(prepared).not.toBeNull();+ if (nativeDescriptor) {+ const prepared = await prepareNativeWorkspaceSync({ db, companyId, workspaceId: issueId, workspaceLocalDir: host,+ runId, lease: lease as EnvironmentLease, target, resourceDisposition: "destroy" });+ expect(prepared).not.toBeNull();+ } else {+ // Provider boundary only: real temporary files, no native baseline. The+ // production provider's syncOut contract validates its archive itself.+ target.runner!.syncIn = async () => ({ filesTransferred: 0, bytesTransferred: 0, operations: [] });+ target.runner!.syncOut = async operations => {+ for (const operation of operations) for (const file of operation.files)+ await cp(file.sourcePath, file.targetPath, { recursive: true, dereference: false });+ return { filesTransferred: 2, bytesTransferred: 0, operations: [] };+ };+ await mkdir(remote, { recursive: true });+ await writeFile(path.join(remote, "existing.txt"), "base\n");+ }await writeFile(path.join(remote, "saved.txt"), "finished work\n");await writeFile(path.join(host, "newer.txt"), "newer local work\n");const recovery = { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] };@@ -83,6 +117,153 @@ describe("automatic retained workspace recovery", () => {const action = async (id: string) => (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, id)))[0]!;const run = async (id: string) => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0]!;+ it("adopts only the exact historical infrastructure notice, preserving prose and user-action notices", async () => {+ const f = await seed("legacy", false);+ const metadata = { version: 1 as const, sourceRunId: f.runId,+ sections: [{ rows: [{ type: "key_value" as const, label: "Recovery action", value: f.actionId }] }] };+ const base = { companyId: f.companyId, issueId: f.issueId, body: "Original technical history",+ authorType: "system" as const, presentation: { kind: "system_notice" as const, tone: "danger" as const,+ title: "Recovery needs attention", detailsDefaultOpen: false }, metadata };+ const comments = await db.insert(issueComments).values([+ base,+ { ...base, authorType: "user", authorUserId: "board" },+ { ...base, metadata: { ...metadata, sourceRunId: randomUUID() } },+ { ...base, metadata: { ...metadata, recoveryResponsibility: "user" as const } },+ ]).returning();+ await adoptSystemRecovery(db, f);+ await adoptSystemRecovery(db, f);+ const rows = await db.select().from(issueComments).where(eq(issueComments.companyId, f.companyId));+ expect(rows.find(row => row.id === comments[0].id)?.metadata?.recoveryResponsibility).toBe("system");+ for (const original of comments.slice(1)) {+ expect(rows.find(row => row.id === original.id)?.metadata).toEqual(original.metadata);+ }+ expect(rows.every(row => row.body === base.body)).toBe(true);+ });++ async function makeRetryDue(actionId: string) {+ const current = await action(actionId);+ const state = readSystemRecovery(current.evidence)!;+ await db.update(issueRecoveryActions).set({ evidence: { ...current.evidence,+ systemRecovery: { ...state, nextAttemptAt: 0 } } }).where(eq(issueRecoveryActions.id, actionId));+ }++ it("re-enters only the existing finalizer for an accepted result, once per intent, preserving failure history", async () => {+ const f = await seed();+ const contractId = randomUUID(), resultId = randomUUID();+ await db.insert(completionContracts).values({ id: contractId, companyId: f.companyId, issueId: f.issueId,+ revision: 1, schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard",+ completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",+ contractJson: {}, canonicalSha256: "contract", createdByActorType: "system", createdByActorId: "test" });+ await db.update(heartbeatRuns).set({ completionContractId: contractId }).where(eq(heartbeatRuns.id, f.runId));+ await db.insert(nativeRunResults).values({ id: resultId, companyId: f.companyId, issueId: f.issueId, runId: f.runId,+ completionContractId: contractId, schemaStatus: "accepted", serverFingerprint: "result", canonicalSha256: "result",+ resultJson: { terminal: { runTerminalState: "succeeded" } } });+ await db.update(nativeRunFinalizations).set({ resultId, attempt: 3, failureCode: "native_workspace_sync_out_retry_exhausted" })+ .where(eq(nativeRunFinalizations.runId, f.runId));+ expect(await resumePreservedResultFinalization(db, f.companyId, f.runId)).toBe(false);+ await recoverRetainedWorkspace(f.input);+ const attempts = await Promise.all([resumePreservedResultFinalization(db, f.companyId, f.runId),+ resumePreservedResultFinalization(db, f.companyId, f.runId)]);+ expect(attempts.filter(Boolean)).toHaveLength(1);+ const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId));+ expect(coordinator).toMatchObject({ phase: "workspace_finalizing", resultId, attempt: 3 });+ expect(coordinator.recoveryHistory).toEqual([expect.objectContaining({+ kind: "preserved_result_finalization", previousFailureCode: "native_workspace_sync_out_retry_exhausted",+ })]);+ expect(await run(f.runId)).toMatchObject({ status: "failed", errorCode: "execution_interrupted" });+ await db.update(nativeRunFinalizations).set({ phase: "terminal_failure" }).where(eq(nativeRunFinalizations.runId, f.runId));+ expect(await resumePreservedResultFinalization(db, f.companyId, f.runId)).toBe(false);+ const retry = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId: "board",+ idempotencyKey: randomUUID(), observedRunId: f.runId });+ expect(await resumePreservedResultFinalization(db, f.companyId, f.runId)).toBe(true);+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, retry.requestId!)))[0])+ .toMatchObject({ status: "coalesced", runId: f.runId, payload: { taskRetry: { strategy: "finalize_result" } } });+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);+ expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.companyId, f.companyId))).toHaveLength(1);+ }, 30_000);++ it("preserves a historical legacy source without manufacturing a native descriptor or overwriting current files", async () => {+ const f = await seed("legacy", false);+ await recoverRetainedWorkspace(f.input);+ const operations = await db.select().from(workspaceOperations).where(and(+ eq(workspaceOperations.heartbeatRunId, f.runId), eq(workspaceOperations.phase, "workspace_recovery_snapshot"),+ eq(workspaceOperations.status, "succeeded"),+ ));+ expect(operations).toHaveLength(1);+ expect(operations[0].metadata).toMatchObject({ leaseId: f.lease.id, providerLeaseId: f.providerLeaseId });+ const fresh = path.join(root, randomUUID()); await mkdir(fresh);+ const attached = await attachPreservedWorkspaceSnapshots({ db, companyId: f.companyId, issueId: f.issueId,+ sourceRunIds: [f.runId], cwd: fresh });+ expect(await readFile(path.join(attached[0].path, "files", "saved.txt"), "utf8")).toBe("finished work\n");+ expect(await readFile(path.join(attached[0].path, "provenance.json"), "utf8")).toContain(f.runId);+ expect(await readFile(path.join(f.host, "newer.txt"), "utf8")).toBe("newer local work\n");+ expect((await run(f.runId)).runnerProfileJson?.nativeWorkspaceSync).toBeUndefined();+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0);+ expect((await run(f.runId)).status).toBe("failed");+ }, 30_000);++ it("keeps earlier recovered snapshots readable across repeated fresh retries", async () => {+ const f = await seed("legacy", false);+ await recoverRetainedWorkspace(f.input);+ const source = await run(f.runId);+ const replacementId = randomUUID(), laterId = randomUUID(), intentId = randomUUID();+ await db.insert(heartbeatRuns).values([+ { id: replacementId, companyId: f.companyId, agentId: source.agentId,+ status: "failed", contextSnapshot: { issueId: f.issueId } },+ { id: laterId, companyId: f.companyId, agentId: source.agentId,+ status: "failed", retryOfRunId: replacementId, contextSnapshot: { issueId: f.issueId } },+ ]);+ await db.insert(agentWakeupRequests).values({+ id: intentId, companyId: f.companyId, agentId: source.agentId, runId: replacementId,+ source: "on_demand", triggerDetail: "manual", reason: "task_retry", status: "coalesced",+ requestedByActorType: "user", requestedByActorId: "owner-user",+ payload: { issueId: f.issueId, taskRetry: { schema: "paperclip.task-retry.v1",+ generationId: intentId, sourceRunId: f.runId, actorId: "owner-user", strategy: "fresh_isolated_workspace" } },+ });+ const first = path.join(root, randomUUID()), next = path.join(root, randomUUID());+ await mkdir(first); await mkdir(next);+ await attachPreservedWorkspaceSnapshots({ db, companyId: f.companyId, issueId: f.issueId,+ sourceRunIds: [f.runId], cwd: first });+ const attached = await attachPreservedWorkspaceSnapshots({ db, companyId: f.companyId, issueId: f.issueId,+ sourceRunIds: [laterId], cwd: next });+ expect(attached).toHaveLength(1);+ expect(attached[0].sourceRunId).toBe(f.runId);+ expect(await readFile(path.join(attached[0].path, "files", "saved.txt"), "utf8")).toBe("finished work\n");+ expect(await readFile(path.join(attached[0].path, "provenance.json"), "utf8")).toContain(f.runId);+ expect(await attachPreservedWorkspaceSnapshots({ db, companyId: f.companyId, issueId: randomUUID(),+ sourceRunIds: [laterId], cwd: next })).toEqual([]);+ }, 30_000);++ it("reconciles an uploaded snapshot after a lost upload acknowledgement without exporting again", async () => {+ const f = await seed("legacy", false);+ const target = targets.get(f.lease.id)!;+ const exportFiles = vi.spyOn(target.runner!, "syncOut");+ const storage = getStorageService(), put = storage.putFile.bind(storage);+ let uploads = 0;+ const lostReply = vi.spyOn(storage, "putFile").mockImplementation(async input => {+ const receipt = await put(input);+ if (++uploads === 2) throw new Error("Lost upload acknowledgement");+ return receipt;+ });+ try { await recoverRetainedWorkspace(f.input); } finally { lostReply.mockRestore(); }+ const [pending] = await db.select().from(workspaceOperations).where(and(+ eq(workspaceOperations.heartbeatRunId, f.runId), eq(workspaceOperations.phase, "workspace_recovery_snapshot")));+ expect(pending.status).toBe("running");+ expect(uploads).toBe(2);+ await makeRetryDue(f.actionId);+ const restarted = createDb(temporary.connectionString);+ try { await recoverRetainedWorkspace({ ...f.input, db: restarted }); }+ finally { await restarted.$client.end(); }+ const operations = await db.select().from(workspaceOperations).where(and(+ eq(workspaceOperations.heartbeatRunId, f.runId), eq(workspaceOperations.phase, "workspace_recovery_snapshot")));+ expect(operations).toHaveLength(1);+ expect(operations[0]).toMatchObject({ id: pending.id, status: "succeeded", metadata: pending.metadata });+ expect(exportFiles).toHaveBeenCalledTimes(1);+ expect(await readFile(path.join(f.remote, "saved.txt"), "utf8")).toBe("finished work\n");+ expect(await readFile(path.join(f.host, "newer.txt"), "utf8")).toBe("newer local work\n");+ exportFiles.mockRestore();+ }, 30_000);+it.each(["native", "legacy"])("recovers real files without an accepted result or another turn: %s", async mode => {const f = await seed(mode);await recoverRetainedWorkspace(f.input);@@ -102,6 +283,70 @@ describe("automatic retained workspace recovery", () => {expect(await db.select().from(workspaceOperations).where(and(eq(workspaceOperations.companyId, f.companyId), eq(workspaceOperations.phase, "workspace_recovery")))).toHaveLength(1);}, 30_000);+ it("keeps verified copyback files in the preserved workspace on ordinary Retry", async () => {+ const f = await seed();+ await recoverRetainedWorkspace(f.input);+ const source = await run(f.runId);+ await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: source.agentId, status: "running" });+ const request = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId: "local-board", actorSource: "local_implicit",+ observedRunId: source.id, idempotencyKey: randomUUID() });+ await heartbeatService(db).resumeTaskRetry(f.companyId, request.requestId!);+ const [successor] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")));+ expect(successor).toBeDefined();+ const [receipt] = await db.select().from(workspaceOperations).where(and(eq(workspaceOperations.heartbeatRunId, f.runId),+ eq(workspaceOperations.phase, "workspace_recovery"), eq(workspaceOperations.status, "succeeded")));+ const readiness = await readFreshWorkspaceReadiness(db, successor);+ expect(readiness).toEqual({ mode: "resume_preserved_workspace", preservationReceiptId: receipt.id });+ const [agent] = await db.select().from(agents).where(eq(agents.id, source.agentId));+ const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId));+ const localEnvironment = await environmentService(db).ensureLocalEnvironment(f.companyId);+ const prepared = await prepareHeartbeatWorkspace(db, {+ run: successor, agent,+ task: { issueRef: issue, issueId: f.issueId, context: { issueId: f.issueId }, responsibleUserId: "local-board",+ previousSessionParams: null, freshWorkspace: readiness },+ policy: { trustPreset: { kind: "standard", preset: "standard", boundary: null, sourcePresets: {} },+ isolatedWorkspacesEnabled: false, effectiveExecutionWorkspaceMode: "shared_workspace",+ requestedExecutionWorkspaceMode: "shared_workspace", useIsolatedTaskDirectory: false,+ nativeChatWorkspaceScope: null, projectExecutionWorkspacePolicy: null, issueExecutionWorkspaceSettings: null,+ environmentExecutionWorkspaceSettings: null, executionPolicy: { executionMode: "any" } },+ environment: { selectedEnvironmentId: localEnvironment.id, localEnvironment, selectedEnvironmentForConfig: localEnvironment,+ environmentResolution: { environmentId: localEnvironment.id, source: "default" },+ resolvedInstanceSettings: await instanceSettingsService(db).get() },+ config: { mergedConfig: { cwd: f.host }, configSnapshot: null, secretManifest: [] },+ reuse: { requestedShouldReuseExisting: false, existingExecutionWorkspace: null, reusableExistingExecutionWorkspace: null,+ workspaceReuseRequest: resolveExecutionWorkspaceReuseRequestForIssue({ issueExecutionWorkspaceId: null,+ issueExecutionWorkspacePreference: null, existingExecutionWorkspaceStatus: null }),+ nativeRecoveryExecutionWorkspaceId: null, persistedNativeExecutionInput: null, isDotRun: false, runOptions: {} },+ services: { envOrchestrator: environmentRunOrchestrator(db), executionWorkspacesSvc: executionWorkspaceService(db),+ workspaceOperationsSvc: workspaceOperationService(db), ...createHeartbeatWorkspaceResolver(db), appendRunEvent: vi.fn() },+ controllerLease: { assertOwned: vi.fn(async () => {}) }, nativeRunnerPreparationSpans: [],+ });+ expect(prepared.executionWorkspace.cwd).toBe(f.host);+ expect(await readFile(path.join(prepared.executionWorkspace.cwd, "saved.txt"), "utf8")).toBe("finished work\n");+ expect(await readFile(path.join(f.host, "newer.txt"), "utf8")).toBe("newer local work\n");+ const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, request.requestId!));+ expect(wake.payload?.taskRetry).toMatchObject({ strategy: "continue" });+ }, 30_000);++ it("projects active preservation without waiting input as working, and stale observations as failed", async () => {+ const f = await seed();+ const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId));+ const state = { ...createSystemRecovery(f.runId), state: "running" as const };+ const recovery = { ...await action(f.actionId), evidence: { systemRecovery: state, systemRecoveryActiveAt: Date.now() } };+ const input = { run: await run(f.runId), action: recovery, paused: false, approval: false };+ expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "working", intentId: null, canRetry: false });+ expect(projectTaskInterruption(issue, input, Date.now() + 60_000)).toMatchObject({ state: "failed", canRetry: true });+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0);+ });++ it.each([["native_provider_model_rejected", "choose_model"], ["native_provider_approval_required", "approval"]] as const)(+ "projects %s as the meaningful user action %s", async (errorCode, userAction) => {+ const f = await seed();+ const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId));+ expect(projectTaskInterruption(issue, { run: { ...await run(f.runId), errorCode }, paused: false, approval: false }))+ .toMatchObject({ state: "waiting_for_user", responsibility: "user", userAction, canRetry: false });+ });+it("serializes concurrent repairs through the physical workspace lock", async () => {const f = await seed(); let ready!: () => void, release!: () => void;const started = new Promise<void>(resolve => { ready = resolve; }), gate = new Promise<void>(resolve => { release = resolve; });@@ -113,15 +358,17 @@ describe("automatic retained workspace recovery", () => {expect(readWorkspaceRecovery((await action(f.actionId)).evidence)?.status).toBe("recovered");}, 30_000);- it.each(["missing_stop", "wrong_stop", "another_owner", "active_writer", "missing_descriptor"])("retains the source and starts no provider for %s", async kind => {+ it.each(["missing_stop", "wrong_stop", "another_owner", "active_writer", "invalid_descriptor"])("retains the source and starts no provider for %s", async kind => {const f = await seed();if (kind === "missing_stop" || kind === "wrong_stop") await db.update(environmentLeases).set({ metadata: { ...f.lease.metadata,...(kind === "wrong_stop" ? { remoteExecutionTermination: remoteTerminationReceipt({ ...f.lease, id: randomUUID() }, { providerLeaseId: f.providerLeaseId, state: "stopped" }) } : {}) } }).where(eq(environmentLeases.id, f.lease.id));+ if (kind === "missing_stop" || kind === "wrong_stop") f.runtime.retryPendingSandboxTeardown.mockResolvedValue({ providerLeaseId: randomUUID(), state: "unknown" });if (kind === "another_owner") await db.insert(environmentLeases).values({ companyId: f.companyId, heartbeatRunId: f.runId, provider: "daytona", providerLeaseId: f.providerLeaseId });if (kind === "active_writer") await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.lease.heartbeatRunId ? (await run(f.runId)).agentId : "", status: "running", nativeIssueId: f.issueId });- if (kind === "missing_descriptor") await db.update(heartbeatRuns).set({ runnerProfileJson: {} }).where(eq(heartbeatRuns.id, f.runId));+ if (kind === "invalid_descriptor") await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceSync: { schema: "corrupt" } } }).where(eq(heartbeatRuns.id, f.runId));await recoverRetainedWorkspace(f.input);- expect(readWorkspaceRecovery((await action(f.actionId)).evidence)).toMatchObject({ status: "blocked", retryable: false });+ expect(readSystemRecovery((await action(f.actionId)).evidence)).toMatchObject({ state:+ ["missing_stop", "wrong_stop", "active_writer"].includes(kind) ? "awaiting_evidence" : "exhausted" });expect(f.runtime.resumeRunLease).not.toHaveBeenCalled();expect(await hasVerifiedWorkspaceRepair(db, await run(f.runId))).toBe(false);expect(await readFile(path.join(f.remote, "saved.txt"), "utf8")).toBe("finished work\n");@@ -136,7 +383,7 @@ describe("automatic retained workspace recovery", () => {await writeFile(path.join(f.host, "saved.txt"), "later user edit\n");const pending = await action(f.actionId);await db.update(issueRecoveryActions).set({ evidence: { ...pending.evidence,- workspaceRecovery: { ...readWorkspaceRecovery(pending.evidence), retryAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));+ systemRecovery: { ...readSystemRecovery(pending.evidence), nextAttemptAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));const request = { ...f.input, idempotencyKey: randomUUID(), actorId: "user" };await requestWorkspaceRecovery(request); await requestWorkspaceRecovery(request);await recoverRetainedWorkspace(f.input);@@ -166,7 +413,7 @@ describe("automatic retained workspace recovery", () => {await writeFile(path.join(f.host, "later.txt"), "work saved during the interruption\n");const pending = await action(f.actionId);await db.update(issueRecoveryActions).set({ evidence: { ...pending.evidence,- workspaceRecovery: { ...readWorkspaceRecovery(pending.evidence), retryAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));+ systemRecovery: { ...readSystemRecovery(pending.evidence), nextAttemptAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));const restarted = createDb(temporary.connectionString);try {await recoverRetainedWorkspace({ ...f.input, db: restarted });@@ -183,8 +430,26 @@ describe("automatic retained workspace recovery", () => {expect(readWorkspaceRecovery((await action(f.actionId)).evidence)).toBeNull();});- it.each(["native", "legacy", "native_export"])("delivers only saved user input once through ordinary admission: %s", async mode => {- const f = await seed(mode === "legacy" ? "legacy" : "native"), commentId = randomUUID(), queueId = randomUUID();+ it.each([false, true])("adopts exact retained leases without a run descriptor (existing action: %s)", async existingAction => {+ const f = await seed("legacy", false);+ await db.update(heartbeatRuns).set({ resultJson: null }).where(eq(heartbeatRuns.id, f.runId));+ if (existingAction) await db.update(issueRecoveryActions).set({ evidence: { runId: f.runId } })+ .where(eq(issueRecoveryActions.id, f.actionId));+ else await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));+ await adoptHistoricalWorkspaceRecoveries(db);+ const [adopted] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.companyId, f.companyId));+ expect(adopted.evidence.historicalWorkspaceSource).toMatchObject({ runId: f.runId, leaseIds: [f.lease.id] });+ const generation = readSystemRecovery(adopted.evidence)!.generationId;+ expect(await recoverRetainedWorkspace({ ...f.input, actionId: adopted.id })).toBeUndefined();+ expect(readSystemRecovery((await action(adopted.id)).evidence)?.state).toBe("complete");+ await adoptHistoricalWorkspaceRecoveries(db);+ expect(readSystemRecovery((await action(adopted.id)).evidence)?.generationId).toBe(generation);+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0);+ expect(await readFile(path.join(f.host, "newer.txt"), "utf8")).toBe("newer local work\n");+ });++ it.each(["native", "legacy", "native_export", "legacy_snapshot"])("delivers only saved user input once through ordinary admission: %s", async mode => {+ const f = await seed(mode.startsWith("legacy") ? "legacy" : "native", mode !== "legacy_snapshot"), commentId = randomUUID(), queueId = randomUUID();if (mode === "native_export") {await db.update(issueRecoveryActions).set({ cause: "native_workspace_sync_out_retry_exhausted", evidence: { runId: f.runId } }).where(eq(issueRecoveryActions.id, f.actionId));await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, f.runId));@@ -206,6 +471,49 @@ describe("automatic retained workspace recovery", () => {expect(turns[0].contextSnapshot).toMatchObject({ forceFreshSession: true, previousRunId: f.runId, wakeCommentIds: [commentId] });expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, queueId)))[0]).toMatchObject({ status: "coalesced", runId: turns[0].id });expect((await run(f.runId)).status).toBe("failed");+ if (mode === "legacy_snapshot") expect(await readFreshWorkspaceReadiness(db, turns[0])).toMatchObject({+ mode: "fresh_isolated_workspace", retryIntentId: queueId, sourceRunId: f.runId, retainedSourceIds: [f.lease.id] });+ }, 30_000);++ it.each(["copyback_unknown", "source_unavailable", "executor_unknown"])("ordinary task Retry evaluates fresh isolation independently: %s", async failure => {+ const f = await seed("legacy", false);+ const source = await run(f.runId);+ await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: source.agentId, status: "running" });+ if (failure === "copyback_unknown") await db.update(heartbeatRuns).set({ runnerProfileJson: {+ ...source.runnerProfileJson, nativeWorkspaceFinalizationOwner: {+ token: randomUUID(), hostname: "previous-controller", pid: 123, processStartedAt: new Date().toISOString(),+ },+ } }).where(eq(heartbeatRuns.id, f.runId));+ else f.runtime.resumeRunLease.mockRejectedValue(new Error("Provider source unavailable"));+ await recoverRetainedWorkspace(f.input);+ if (failure === "executor_unknown") await db.update(environmentLeases).set({+ metadata: sql`${environmentLeases.metadata} - 'remoteExecutionTermination'`,+ }).where(eq(environmentLeases.id, f.lease.id));+ const commentId = randomUUID(), queueId = randomUUID();+ await db.insert(issueComments).values({ id: commentId, companyId: f.companyId, issueId: f.issueId,+ authorType: "user", authorUserId: "local-board", body: "Use the completed result. Do not publish it again." });+ await db.insert(agentWakeupRequests).values({ id: queueId, companyId: f.companyId, agentId: source.agentId,+ source: "on_demand", reason: "issue_commented", status: "deferred_issue_execution",+ requestedByActorType: "user", requestedByActorId: "local-board",+ payload: { issueId: f.issueId, commentId, _paperclipWakeContext: { issueId: f.issueId,+ wakeReason: "issue_commented", wakeCommentIds: [commentId], wakeCommentId: commentId } } });+ const request = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, actorId: "local-board",+ actorSource: "local_implicit", observedRunId: f.runId, idempotencyKey: randomUUID() });+ const heartbeat = heartbeatService(db);+ await Promise.all([heartbeat.resumeTaskRetry(f.companyId, request.requestId!), heartbeat.resumeTaskRetry(f.companyId, request.requestId!)]);+ const turns = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")));+ expect(turns).toHaveLength(failure === "executor_unknown" ? 0 : 1);+ if (turns[0]) {+ expect(turns[0].contextSnapshot?.wakeCommentIds).toEqual([commentId]);+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, queueId)))[0])+ .toMatchObject({ runId: turns[0].id, status: "coalesced" });+ expect(await readFreshWorkspaceReadiness(db, turns[0])).toMatchObject({ mode: "fresh_isolated_workspace", retryIntentId: request.requestId });+ // A restarted dispatch worker finds the same run and cannot create another.+ await heartbeatService(db).resumeTaskRetry(f.companyId, request.requestId!);+ expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "queued")))).toHaveLength(1);+ }+ expect(await hasVerifiedWorkspaceRepair(db, await run(f.runId))).toBe(false);+ expect(await readFile(path.join(f.remote, "saved.txt"), "utf8")).toBe("finished work\n");}, 30_000);it("queues cleanup only after verified persistence and keeps it separate from recovery", async () => {@@ -267,7 +575,7 @@ describe("automatic retained workspace recovery", () => {expect(f.runtime.resumeRunLease).not.toHaveBeenCalled();expect((await run(f.runId)).runnerProfileJson?.nativeWorkspaceFinalizationOwner).toEqual(prior);expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ workspaceRepairRequired: true,- workspaceRecovery: { status: "blocked", canRetry: false, message: expect.stringContaining("previous session stopped") } });+ workspaceRecovery: { status: "queued", canRetry: false } });}, 30_000);it("binds the first automatic repair to authoritative old-controller stop proof without an accepted result", async () => {@@ -297,30 +605,34 @@ describe("automatic retained workspace recovery", () => {const failCommit = vi.spyOn(activity, "persistActivity").mockRejectedValueOnce(new Error("Interrupted receipt transaction"));try { await recoverRetainedWorkspace(f.input); } finally { failCommit.mockRestore(); }expect(await hasVerifiedWorkspaceRepair(db, await run(f.runId))).toBe(false);- expect(await db.select().from(workspaceOperations).where(and(eq(workspaceOperations.companyId, f.companyId), eq(workspaceOperations.phase, "workspace_recovery")))).toHaveLength(0);+ expect(await db.select().from(workspaceOperations).where(and(eq(workspaceOperations.companyId, f.companyId), eq(workspaceOperations.phase, "workspace_recovery")))).toHaveLength(1);expect(await readFile(path.join(f.host, "saved.txt"), "utf8")).toBe("finished work\n");const pending = await action(f.actionId);- await db.update(issueRecoveryActions).set({ evidence: { ...pending.evidence, workspaceRecovery: { ...readWorkspaceRecovery(pending.evidence), retryAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));+ await db.update(issueRecoveryActions).set({ evidence: { ...pending.evidence, systemRecovery: { ...readSystemRecovery(pending.evidence), nextAttemptAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));await recoverRetainedWorkspace(f.input);expect(await hasVerifiedWorkspaceRepair(db, await run(f.runId))).toBe(true);}, 30_000);- it("keeps retry budgets durable and gives an idempotent user retry only one extra attempt", async () => {+ it("persists six automatic attempts and admits one new generation per deliberate retry", async () => {const f = await seed();f.runtime.resumeRunLease.mockRejectedValue(new Error("Temporary provider failure"));- for (let attempt = 1; attempt <= 3; attempt++) {+ for (let attempt = 1; attempt <= 6; attempt++) {await recoverRetainedWorkspace(f.input);- const current = await action(f.actionId);- expect(readWorkspaceRecovery(current.evidence)?.attempt).toBe(attempt);- await db.update(issueRecoveryActions).set({ evidence: { ...current.evidence, workspaceRecovery: { ...readWorkspaceRecovery(current.evidence), retryAt: 0 } } }).where(eq(issueRecoveryActions.id, f.actionId));+ expect(readSystemRecovery((await action(f.actionId)).evidence)?.attempts).toBe(attempt);+ if (attempt < 6) await makeRetryDue(f.actionId);}await recoverRetainedWorkspace(f.input);- expect(f.runtime.resumeRunLease).toHaveBeenCalledTimes(3);+ expect(f.runtime.resumeRunLease).toHaveBeenCalledTimes(6);+ expect(readSystemRecovery((await action(f.actionId)).evidence)?.state).toBe("exhausted");+ const before = readSystemRecovery((await action(f.actionId)).evidence)!;const request = { ...f.input, idempotencyKey: randomUUID(), actorId: "board" };await requestWorkspaceRecovery(request); await requestWorkspaceRecovery(request);await recoverRetainedWorkspace(f.input); await recoverRetainedWorkspace(f.input);- expect(f.runtime.resumeRunLease).toHaveBeenCalledTimes(4);- expect(readWorkspaceRecovery((await action(f.actionId)).evidence)).toMatchObject({ status: "blocked", attempt: 4, attemptLimit: 4 });+ const after = readSystemRecovery((await action(f.actionId)).evidence)!;+ expect(f.runtime.resumeRunLease).toHaveBeenCalledTimes(7);+ expect(after.generationId).not.toBe(before.generationId);+ expect(after.attempts).toBe(1);+ expect(after.revision).toBeGreaterThan(before.revision);}, 30_000);it("discovers historical sources in the periodic sweep without creating a user request", async () => {@@ -341,8 +653,9 @@ describe("automatic retained workspace recovery", () => {cause: "unrelated_history", fingerprint: `history-${i}`, nextAction: "", evidence: {},})));await db.execute(sql`analyze ${issueRecoveryActions}`);+ await adoptHistoricalWorkspaceRecoveries(db);const plan = await db.execute(sql`explain (analyze, format json) ${retainedWorkspaceCandidates(db)}`);- expect(JSON.stringify(plan)).toContain("issue_recovery_actions_retained_workspace_recovery_idx");+ expect(JSON.stringify(plan)).toContain("issue_recovery_actions_system_recovery_due_idx");expect((await retainedWorkspaceCandidates(db)).length).toBeLessThanOrEqual(5);}, 30_000);diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.tsindex bcaf268c9a..5b880d5b65 100644--- a/server/src/services/workspace-recovery.ts+++ b/server/src/services/workspace-recovery.ts@@ -1,13 +1,13 @@+import { resumePreservedResultFinalization } from "./preserved-result-finalization.js";import { and, asc, eq, gt, inArray, ne, or, sql } from "drizzle-orm";-import { agentWakeupRequests, environmentLeases, environments, heartbeatRuns, issues, issueRecoveryActions, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db";+import { agentWakeupRequests, environmentLeases, heartbeatRuns, issues, issueRecoveryActions, workspaceOperations, type Db } from "@paperclipai/db";import type { Environment, EnvironmentLease } from "@paperclipai/shared";import { conflict } from "../errors.js";import { logger } from "../middleware/logger.js";-import { adapterExecutionControls } from "./adapter-execution-control.js";import type { EnvironmentRuntimeService } from "./environment-runtime.js";import { resolveEnvironmentExecutionTarget } from "./environment-execution-target.js";import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";-import { prepareStoppedSandboxForRecovery, settleStopOnlyCleanup } from "./sandbox-stop-and-retain.js";+import { hasStopOnlyCleanup, prepareHistoricalSandboxStopVerification, prepareSandboxStopAndRetain, prepareStoppedSandboxForRecovery, settleStopOnlyCleanup } from "./sandbox-stop-and-retain.js";import { persistActivity, publishActivity } from "./activity-log.js";import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";import { hasVerifiedWorkspaceRepair, readWorkspaceRecovery, type WorkspaceRecovery } from "./workspace-recovery-receipt.js";@@ -15,13 +15,14 @@ import { withNativeWorkspaceFinalizationOwnership } from "./native-runtime/nativimport { readNativeWorkspaceSyncReference, readNativeWorkspaceSyncLocalCwd, resumeNativeWorkspaceSync } from "./native-runtime/native-workspace-sync.js";import { classifyNativeWorkspaceFailure } from "./native-runtime/native-workspace-failure.js";+import { adoptSystemRecovery, loadSystemRecovery, updateSystemRecovery } from "./system-recovery.js";+import { createSystemRecovery, failSystemRecovery, readSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure, type SystemRecoveryState } from "./system-recovery-state.js";+import { inspectWorkspaceRecoverySource } from "./workspace-recovery-source.js";+import { preserveWorkspaceSnapshot } from "./workspace-recovery-snapshot.js";+import { adoptHistoricalWorkspaceRecoveries } from "./workspace-recovery-backfill.js";+const exportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"];const terminal = ["failed", "interrupted", "timed_out", "cancelled", "succeeded"];-class RecoveryBlocked extends Error {- constructor(message: string, readonly code: "stop" | "source" | "writer" = "source") { super(message); }-}-const stopMessage = "Paperclip couldn’t verify that the previous session stopped. This task needs service attention.";-const sourceMessage = "Paperclip couldn’t verify the retained workspace. This task needs service attention.";type Source = { companyId: string; issueId: string; runId: string; actionId: string };/** Admission records intent only. No request handler runs physical recovery. */@@ -38,196 +39,229 @@ export async function requestWorkspaceRecovery(input: Source & { db: Db; idempot}const prior = readWorkspaceRecovery(action.evidence);if (prior?.requestIds.includes(input.idempotencyKey) || prior?.status === "recovered") return { actionId: action.id, status: prior.status };- if (prior?.status === "blocked" && !prior.retryable) throw conflict(prior.message ?? sourceMessage);const pending = prior && ["queued", "recovering"].includes(prior.status);const state: WorkspaceRecovery = pending ? { ...prior!, requestIds: [...prior!.requestIds, input.idempotencyKey] }: { schema: "paperclip.workspace-recovery.v1", runId: run.id, status: "queued", stage: "verifying_stop",attempt: prior?.attempt ?? 0, attemptLimit: (prior?.attempt ?? 0) + 1,requestIds: [...(prior?.requestIds ?? []), input.idempotencyKey] };- await tx.update(issueRecoveryActions).set({ evidence: { ...action.evidence, workspaceRecovery: state }, updatedAt: new Date() })+ const previous = readSystemRecovery(action.evidence);+ const active = previous && ["scheduled", "running", "awaiting_evidence"].includes(previous.state);+ const system = active ? { ...previous, revision: previous.revision + 1,+ nextAttemptAt: previous.state === "running" ? previous.nextAttemptAt : Math.max(Date.now(), previous.providerCooldownAt ?? 0) } : { ...createSystemRecovery(run.id),+ revision: (previous?.revision ?? -1) + 1,+ preservationOperationIds: previous?.preservationOperationIds ?? [],+ providerCooldownAt: previous?.providerCooldownAt ?? null,+ nextAttemptAt: previous?.providerCooldownAt ?? null };+ await tx.update(issueRecoveryActions).set({ ownerType: "system", ownerAgentId: null, ownerUserId: null,+ evidence: { ...action.evidence, workspaceRecovery: state, systemRecovery: system }, updatedAt: new Date() }).where(eq(issueRecoveryActions.id, action.id));await persistActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "user", actorId: input.actorId,action: "issue.workspace_recovery_requested", entityType: "issue", entityId: issue.id, runId: run.id,- details: { recoveryActionId: action.id, idempotencyKey: input.idempotencyKey } });+ details: { recoveryActionId: action.id, idempotencyKey: input.idempotencyKey,+ ...(previous && previous.generationId !== system.generationId ? { previousGeneration: previous } : {}) } });return { actionId: action.id, status: state.status };});}-/** One source, one physical exporter. This does not accept/commit an old agent- * result, infer external effects, or create a provider turn or wake request. */+/** Physical repair remains serialized by the existing source ownership lock.+ * Neither preservation nor cleanup creates an agent turn. */export async function recoverRetainedWorkspace(input: Source & { db: Db; environmentRuntime: EnvironmentRuntimeService }) {const { db } = input;- async function inspect() {- const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId)));- const [action] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId),- eq(issueRecoveryActions.sourceIssueId, input.issueId), eq(issueRecoveryActions.id, input.actionId)));- const reference = readNativeWorkspaceSyncReference(run?.runnerProfileJson?.nativeWorkspaceSync);- if (!run || !action || action.evidence.runId !== run.id || !terminal.includes(run.status)- || (run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId) !== input.issueId- || !reference || (!hasRequiredWorkspaceRecovery(run.resultJson) && !exportCauses.includes(action.cause))) throw new RecoveryBlocked(sourceMessage);- const recorded = run.resultJson?.workspaceRestoreRecovery as { leaseIds?: unknown } | undefined;- if (hasRequiredWorkspaceRecovery(run.resultJson) && (!Array.isArray(recorded?.leaseIds)- || recorded.leaseIds.length !== 1 || recorded.leaseIds[0] !== reference.leaseId)) throw new RecoveryBlocked(sourceMessage);- const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, run.id)));- if (coordinator?.leaseOwner || adapterExecutionControls.has(run.id)- || (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) throw new RecoveryBlocked(stopMessage, "stop");- const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),- eq(environmentLeases.id, reference.leaseId), eq(environmentLeases.heartbeatRunId, run.id)));- if (!lease || lease.issueId !== input.issueId || lease.providerLeaseId !== reference.providerLeaseId- || !lease.environmentId || lease.leasePolicy === "reuse_by_environment"- || (lease.executionWorkspaceId && lease.executionWorkspaceId !== reference.workspaceId)) throw new RecoveryBlocked(sourceMessage);- const [other] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(- ne(environmentLeases.id, lease.id), eq(environmentLeases.provider, lease.provider!), eq(environmentLeases.providerLeaseId, lease.providerLeaseId!),- )).limit(1);- const [writer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(- eq(heartbeatRuns.companyId, input.companyId), inArray(heartbeatRuns.status, ["queued", "running"]),- or(eq(heartbeatRuns.nativeIssueId, input.issueId), eq(heartbeatRuns.issueId, input.issueId),- sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}`,- sql`${heartbeatRuns.contextSnapshot}->>'executionWorkspaceId' = ${reference.workspaceId}`),- )).limit(1);- if (other || writer) throw new RecoveryBlocked("The workspace has another execution owner. Recovery will not overwrite its work.", "writer");- const [environment] = await db.select().from(environments).where(eq(environments.id, lease.environmentId));- if (!environment) throw new RecoveryBlocked(sourceMessage);- return { run, action, reference, lease, environment };- }- const saveState = async (state: WorkspaceRecovery) => {- await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, '{workspaceRecovery}',- ${JSON.stringify(state)}::jsonb || jsonb_build_object('requestIds', coalesce(${issueRecoveryActions.evidence}#>'{workspaceRecovery,requestIds}', '[]'::jsonb)))`, updatedAt: new Date() })- .where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId)));- };- // Persist discovery before requesting an old controller's stop proof. The- // takeover check must bind to this repair intent even on the first sweep.- await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, '{workspaceRecovery}',- ${JSON.stringify({ schema: "paperclip.workspace-recovery.v1", runId: input.runId, status: "queued", stage: "verifying_stop",- attempt: 0, attemptLimit: 3, requestIds: [] })}::jsonb)`, updatedAt: new Date() })- .where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, input.issueId),- eq(issueRecoveryActions.id, input.actionId), sql`${issueRecoveryActions.evidence}->>'runId' = ${input.runId}`,- sql`not (${issueRecoveryActions.evidence} ? 'workspaceRecovery')`));- const owned = await withNativeWorkspaceFinalizationOwnership({ db, companyId: input.companyId, runId: input.runId,- retainedRepairActionId: input.actionId }, async ownership => {- const [action] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId)));- let state = readWorkspaceRecovery(action?.evidence ?? null);- if (state?.status === "recovered" || (state?.retryAt && state.retryAt > Date.now())) return;- if (state?.status === "blocked") {- // Cleanup can produce a real stop receipt after the initial inspection.- // Reconsider that new fact; do not poll the provider for unchanged unknowns.- if (state.blockerCode !== "stop") return;- const source = await inspect();- if (!hasRemoteTerminationReceipt(source.lease)) return;- }- if (state && state.attempt >= (state.attemptLimit ?? 3)) {- await saveState({ ...state, status: "blocked", retryable: true, message: "Recovery couldn’t finish. Your message is saved." });+ await adoptSystemRecovery(db, input);+ const initial = await loadSystemRecovery(db, input);+ if (!initial || initial.state === "complete" || initial.state === "exhausted" ||+ (initial.nextAttemptAt !== null && initial.nextAttemptAt > Date.now())) return;+ const runAttempt = async (ownership: { token: string; assertHeld(): Promise<void> }) => {+ let current = await loadSystemRecovery(db, input);+ if (!current) return;+ const reserved = reserveSystemRecoveryAttempt(current);+ if (!reserved) {+ if (current.state !== "exhausted" && current.deadlineAt !== null && Date.now() >= current.deadlineAt)+ await updateSystemRecovery(db, input, current, { ...current, revision: current.revision + 1,+ state: "exhausted", nextAttemptAt: null });return;}- state = { schema: "paperclip.workspace-recovery.v1", runId: input.runId, status: "recovering", stage: "verifying_stop",- attempt: (state?.attempt ?? 0) + 1, attemptLimit: state?.attemptLimit ?? 3, requestIds: state?.requestIds ?? [] };- await saveState(state);- let resumed: Awaited<ReturnType<typeof inspect>> | undefined;- let cleanupLease: typeof environmentLeases.$inferSelect | undefined;- let keepalive: ReturnType<typeof setInterval> | undefined;- let renewal = Promise.resolve();- try {- const source = await inspect();- // Verify the immutable descriptor's company/workspace binding before any- // provider call. Its local path cannot be supplied by the caller.- await readNativeWorkspaceSyncLocalCwd({ runId: source.run.id, companyId: source.run.companyId,- workspaceId: source.reference.workspaceId, reference: source.reference });- if (!hasRemoteTerminationReceipt(source.lease)- || (source.lease.metadata?.remoteExecutionTermination as { state?: string })?.state !== "stopped") throw new RecoveryBlocked(stopMessage, "stop");- const target = await resolveEnvironmentExecutionTarget({ db, companyId: input.companyId, adapterType: "paperclip_runner",- environment: source.environment, leaseId: source.lease.id, leaseMetadata: source.lease.metadata,- lease: source.lease as EnvironmentLease, environmentRuntime: input.environmentRuntime });- if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runner- || target.remoteCwd !== source.reference.remoteCwd) throw new RecoveryBlocked(sourceMessage);+ if (!await updateSystemRecovery(db, input, current, reserved)) return;+ current = reserved;+ const progress = async (patch: Partial<SystemRecoveryState>) => {await ownership.assertHeld();- // Atomically fence stop-only cleanup BEFORE an ambiguous resume call.- cleanupLease = await db.transaction(async tx => {- const [current] = await tx.select().from(environmentLeases).where(eq(environmentLeases.id, source.lease.id)).for("update");- if (!current || !hasRemoteTerminationReceipt(current) || current.providerLeaseId !== source.reference.providerLeaseId) throw new RecoveryBlocked(stopMessage, "stop");- const pending = await prepareStoppedSandboxForRecovery(tx as unknown as Db, current);- if (!pending) throw new RecoveryBlocked(sourceMessage);- const [claimed] = await tx.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({- pendingCleanupAttemptId: ownership.token, pendingCleanupInFlight: true, pendingCleanupLeaseExpiresAtMs: Date.now() + 15 * 60_000,- })}::jsonb` }).where(eq(environmentLeases.id, current.id)).returning();- return claimed;- });- resumed = source;- keepalive = setInterval(() => { renewal = renewal.then(async () => {- await ownership.assertHeld();- await db.update(environmentLeases).set({ metadata: sql`jsonb_set(${environmentLeases.metadata}, '{pendingCleanupLeaseExpiresAtMs}', ${JSON.stringify(Date.now() + 15 * 60_000)}::jsonb)` })- .where(and(eq(environmentLeases.id, source.lease.id), sql`${environmentLeases.metadata}->>'pendingCleanupAttemptId' = ${ownership.token}`));- }).catch(() => undefined); }, 30_000);- const opened = await input.environmentRuntime.resumeRunLease({ environment: source.environment as unknown as Environment, lease: cleanupLease as EnvironmentLease });- if (opened?.providerLeaseId !== source.reference.providerLeaseId || opened.metadata?.remoteCwd !== source.reference.remoteCwd) throw new RecoveryBlocked(sourceMessage);- await ownership.assertHeld();- await inspect();- state = { ...state, stage: "restoring_files" }; await saveState(state);- const copied = await resumeNativeWorkspaceSync({ db, runId: input.runId, target, assertOwnership: ownership.assertHeld });- if (!copied) throw new RecoveryBlocked(sourceMessage);- const current = await inspect();- if (current.reference.state !== "finalized" || !current.reference.finalHostSha256) throw new RecoveryBlocked(sourceMessage);- state = { ...state, stage: "saving_receipts" }; await saveState(state);- clearInterval(keepalive); await renewal;+ const next = { ...current!, ...patch, revision: current!.revision + 1 };+ if (!await updateSystemRecovery(db, input, current!, next)) throw new Error("workspace_recovery_generation_changed");+ current = next;+ };+ const observeActive = async () => {await ownership.assertHeld();- const stopped = await input.environmentRuntime.retryPendingSandboxTeardown({ environment: current.environment as unknown as Environment, lease: cleanupLease as EnvironmentLease });- const settled = await settleStopOnlyCleanup(db, cleanupLease, { attemptId: ownership.token, receipt: stopped });- cleanupLease = undefined;- if (!settled || !hasRemoteTerminationReceipt(settled)) throw new RecoveryBlocked(stopMessage, "stop");+ await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence},+ '{systemRecoveryActiveAt}', ${JSON.stringify(Date.now())}::jsonb)` }).where(and(+ eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId),+ sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,attemptId}' = ${reserved.attemptId}`));+ };+ let observing = Promise.resolve();+ const observer = setInterval(() => { observing = observing.then(observeActive).catch(() => undefined); }, 15_000);+ try {+ await observeActive();+ const inspected = await inspectWorkspaceRecoverySource(db, input);+ for (const source of inspected.sources) {+ const { lease, environment, remoteCwd } = source;+ let reference = source.reference;+ if (reference) {+ try { await readNativeWorkspaceSyncLocalCwd({ runId: input.runId, companyId: input.companyId,+ workspaceId: reference.workspaceId, reference }); }+ catch (error) {+ // Missing local merge metadata permits a separate snapshot of the+ // exact bound allocation. Corrupt metadata never weakens binding.+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") reference = null;+ else throw new SystemRecoveryFailure("source_binding_invalid", "service_required");+ }+ }+ let stoppedLease = lease;+ if (!hasRemoteTerminationReceipt(stoppedLease)) {+ const pending = await db.transaction(async tx => {+ const [fresh] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),+ eq(environmentLeases.id, lease.id))).for("update");+ if (!fresh || fresh.metadata?.pendingCleanupInFlight === true) return null;+ const prepared = hasStopOnlyCleanup(fresh) ? fresh : fresh.status === "released"+ ? await prepareHistoricalSandboxStopVerification(tx as unknown as Db, fresh)+ : await prepareSandboxStopAndRetain(tx as unknown as Db, fresh);+ if (!prepared) return null;+ const [claimed] = await tx.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} ||+ ${JSON.stringify({ pendingCleanupAttemptId: ownership.token, pendingCleanupInFlight: true,+ pendingCleanupLeaseExpiresAtMs: Date.now() + 15 * 60_000 })}::jsonb` })+ .where(eq(environmentLeases.id, lease.id)).returning();+ return claimed;+ });+ if (!pending) throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ // The cleanup service owns exact-allocation termination. No process ID+ // or terminal run status is substituted for its provider receipt.+ const receipt = await input.environmentRuntime.retryPendingSandboxTeardown({+ environment: environment as unknown as Environment, lease: pending as EnvironmentLease }).catch(async () => {+ await settleStopOnlyCleanup(db, pending, { attemptId: ownership.token });+ throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ });+ const settled = await settleStopOnlyCleanup(db, pending, { attemptId: ownership.token, receipt });+ if (!settled || !hasRemoteTerminationReceipt(settled))+ throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ stoppedLease = settled;+ }+ const target = await resolveEnvironmentExecutionTarget({ db, companyId: input.companyId, adapterType: "paperclip_runner",+ environment, leaseId: lease.id, leaseMetadata: stoppedLease.metadata,+ lease: stoppedLease as EnvironmentLease, environmentRuntime: input.environmentRuntime });+ if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runner || target.remoteCwd !== remoteCwd)+ throw new SystemRecoveryFailure("source_binding_invalid", "service_required");+ await ownership.assertHeld();+ const cleanupLease = await db.transaction(async tx => {+ const [fresh] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),+ eq(environmentLeases.id, lease.id))).for("update");+ if (!fresh || !hasRemoteTerminationReceipt(fresh) || fresh.providerLeaseId !== lease.providerLeaseId)+ throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ const pending = await prepareStoppedSandboxForRecovery(tx as unknown as Db, fresh);+ if (!pending) throw new SystemRecoveryFailure("source_binding_invalid", "service_required");+ const [claimed] = await tx.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({+ pendingCleanupAttemptId: ownership.token, pendingCleanupInFlight: true, pendingCleanupLeaseExpiresAtMs: Date.now() + 15 * 60_000,+ })}::jsonb` }).where(eq(environmentLeases.id, fresh.id)).returning();+ return claimed;+ });+ let renewal = Promise.resolve();+ const keepalive = setInterval(() => { renewal = renewal.then(async () => {+ await ownership.assertHeld();+ await db.update(environmentLeases).set({ metadata: sql`jsonb_set(${environmentLeases.metadata}, '{pendingCleanupLeaseExpiresAtMs}', ${JSON.stringify(Date.now() + 15 * 60_000)}::jsonb)` })+ .where(and(eq(environmentLeases.id, lease.id), sql`${environmentLeases.metadata}->>'pendingCleanupAttemptId' = ${ownership.token}`));+ }).catch(() => undefined); }, 30_000);+ let stopSettled = false;+ try {+ const opened = await input.environmentRuntime.resumeRunLease({ environment: environment as unknown as Environment,+ lease: cleanupLease as EnvironmentLease });+ if (opened?.providerLeaseId !== lease.providerLeaseId || opened.metadata?.remoteCwd !== remoteCwd)+ throw new SystemRecoveryFailure("source_binding_invalid", "service_required");+ await inspectWorkspaceRecoverySource(db, input);+ await progress({ phase: "preserve_files" });+ let operationId: string;+ if (reference) {+ const copied = await resumeNativeWorkspaceSync({ db, runId: input.runId, target, assertOwnership: ownership.assertHeld });+ if (!copied) throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ const after = await inspectWorkspaceRecoverySource(db, input);+ const finalized = after.sources.find(item => item.lease.id === lease.id)?.reference;+ if (finalized?.state !== "finalized" || !finalized.finalHostSha256)+ throw new SystemRecoveryFailure("snapshot_verification_failed", "service_required");+ await ownership.assertHeld();+ const [existing] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(+ eq(workspaceOperations.companyId, input.companyId), eq(workspaceOperations.heartbeatRunId, input.runId),+ eq(workspaceOperations.phase, "workspace_recovery"), eq(workspaceOperations.status, "succeeded"),+ sql`${workspaceOperations.metadata}->>'leaseId' = ${lease.id}`)).limit(1);+ const copy = existing ?? (await db.insert(workspaceOperations).values({ companyId: input.companyId, issueId: input.issueId,+ heartbeatRunId: input.runId, executionWorkspaceId: lease.executionWorkspaceId, phase: "workspace_recovery",+ status: "succeeded", finishedAt: new Date(), metadata: { recoveryActionId: input.actionId, leaseId: lease.id,+ providerLeaseId: lease.providerLeaseId, descriptorSha256: finalized.descriptorSha256,+ finalHostSha256: finalized.finalHostSha256 } }).returning({ id: workspaceOperations.id }))[0];+ operationId = copy.id;+ } else {+ operationId = await preserveWorkspaceSnapshot({ ...input, leaseId: lease.id,+ providerLeaseId: lease.providerLeaseId!, target, assertHeld: ownership.assertHeld });+ }+ await progress({ preservationOperationIds: [...new Set([...current!.preservationOperationIds, operationId])] });+ clearInterval(keepalive); await renewal;+ await ownership.assertHeld();+ const receipt = await input.environmentRuntime.retryPendingSandboxTeardown({ environment: environment as unknown as Environment,+ lease: cleanupLease as EnvironmentLease });+ const settled = await settleStopOnlyCleanup(db, cleanupLease, { attemptId: ownership.token, receipt });+ stopSettled = Boolean(settled && hasRemoteTerminationReceipt(settled));+ if (!stopSettled) throw new SystemRecoveryFailure("agent_stop_unconfirmed", "recheck_evidence");+ } finally {+ clearInterval(keepalive); await renewal;+ if (!stopSettled) {+ // A lost resume/export reply retains the same stop-only obligation.+ // The maintenance worker must never turn it into destructive cleanup.+ try {+ await ownership.assertHeld();+ const receipt = await input.environmentRuntime.retryPendingSandboxTeardown({ environment: environment as unknown as Environment,+ lease: cleanupLease as EnvironmentLease });+ await settleStopOnlyCleanup(db, cleanupLease, { attemptId: ownership.token, receipt });+ } catch { /* The persisted stop-only obligation remains authoritative. */ }+ }+ }+ }await ownership.assertHeld();- await db.transaction(async tx => {- const [locked] = await tx.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))).for("update");- if (!locked || locked.evidence.runId !== input.runId) throw new RecoveryBlocked(sourceMessage);- const [copy] = await tx.insert(workspaceOperations).values({ companyId: input.companyId, issueId: input.issueId,- heartbeatRunId: input.runId, executionWorkspaceId: current.lease.executionWorkspaceId,- phase: "workspace_recovery", status: "succeeded", finishedAt: new Date(),- metadata: { recoveryActionId: input.actionId, leaseId: settled.id, providerLeaseId: settled.providerLeaseId,- descriptorSha256: current.reference.descriptorSha256, finalHostSha256: current.reference.finalHostSha256 } }).returning({ id: workspaceOperations.id });+ const next = { ...current!, revision: current!.revision + 1, phase: "reconcile_effects" as const,+ state: "complete" as const, nextAttemptAt: null };+ const activity = await db.transaction(async tx => {await tx.insert(workspaceOperations).values({ companyId: input.companyId, issueId: input.issueId,- heartbeatRunId: input.runId, executionWorkspaceId: current.lease.executionWorkspaceId,- phase: "workspace_finalize", status: "succeeded", finishedAt: new Date(),- metadata: { owningService: "workspace_recovery", recoveryReceiptId: copy.id } });- await tx.update(issueRecoveryActions).set({ evidence: { ...locked.evidence,- workspaceRecovery: { ...state, requestIds: readWorkspaceRecovery(locked.evidence)?.requestIds ?? [], status: "recovered" } }, updatedAt: new Date() })- .where(eq(issueRecoveryActions.id, locked.id));- const activity = await persistActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "system", actorId: "workspace-recovery",+ heartbeatRunId: input.runId, phase: "workspace_finalize", status: "succeeded", finishedAt: new Date(),+ metadata: { owningService: "workspace_recovery", preservationOperationIds: next.preservationOperationIds } });+ if (!await updateSystemRecovery(tx as unknown as Db, input, current!, next))+ throw new Error("workspace_recovery_generation_changed");+ return persistActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "system", actorId: "workspace-recovery",action: "issue.workspace_recovered", entityType: "issue", entityId: input.issueId, runId: input.runId,details: { recoveryActionId: input.actionId, summary: "Saved work recovered." } });- return activity;- }).then(activity => {- try { publishActivity(activity.publication); }- catch { logger.warn({ runId: input.runId }, "Recovered workspace activity delivery deferred"); }});+ current = next;+ try { publishActivity(activity.publication); } catch { logger.warn({ runId: input.runId }, "Recovery activity delivery deferred"); }} catch (error) {- clearInterval(keepalive); await renewal;- if (resumed && cleanupLease) {- // Lost replies leave the same durable stop-only intent for the ordinary- // cleanup worker; never destroy a source with uncertain copyback.- try {- await ownership.assertHeld();- const receipt = await input.environmentRuntime.retryPendingSandboxTeardown({ environment: resumed.environment as unknown as Environment, lease: cleanupLease as EnvironmentLease });- await settleStopOnlyCleanup(db, cleanupLease, { attemptId: ownership.token, receipt });- } catch { /* Stop-only intent remains pinned. */ }- }await ownership.assertHeld();- const retryable = !(error instanceof RecoveryBlocked) && !classifyNativeWorkspaceFailure(error).permanent;- const retry = retryable && state.attempt < (state.attemptLimit ?? 3);- await saveState({ ...state, status: retry ? "queued" : "blocked", retryable,- ...(error instanceof RecoveryBlocked ? { blockerCode: error.code } : {}),- ...(retry ? { retryAt: Date.now() + 30_000 } : {}),- message: error instanceof RecoveryBlocked ? error.message : retryable- ? "Recovery couldn’t finish. Your message is saved." : sourceMessage });- logger.warn({ runId: input.runId, retryable, stage: state.stage }, "Workspace recovery did not finish; source retained");- } finally { clearInterval(keepalive); await renewal; }- });+ if (current!.state === "complete") {+ logger.warn({ runId: input.runId }, "Preserved workspace activity delivery deferred");+ return;+ }+ const classification = classifyNativeWorkspaceFailure(error);+ const failure = error instanceof SystemRecoveryFailure ? error+ : classification.code === "workspace_sync_out_unsafe_archive"+ ? new SystemRecoveryFailure("archive_unsafe", "service_required")+ : classification.code === "workspace_sync_out_unrecoverable"+ ? new SystemRecoveryFailure("source_unavailable", "use_alternative_strategy")+ : new SystemRecoveryFailure(current!.phase === "verify_execution" ? "provider_unavailable" : "export_interrupted", "retry_transient");+ const retryAfterAt = (error as { retryAfterAt?: unknown })?.retryAfterAt;+ await updateSystemRecovery(db, input, current!, failSystemRecovery(current!, failure, {+ ...(typeof retryAfterAt === "number" && Number.isFinite(retryAfterAt) ? { retryAfterAt } : {}),+ }));+ logger.warn({ err: error, runId: input.runId, failureCode: failure.code, phase: current!.phase }, "Workspace preservation deferred; source retained");+ } finally { clearInterval(observer); await observing; }+ };+ const owned = await withNativeWorkspaceFinalizationOwnership({ db, companyId: input.companyId, runId: input.runId,+ retainedRepairActionId: input.actionId }, runAttempt);if (!owned.acquired && owned.reason === "owner_unverified") {- const [run] = await db.select({ profile: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId)));- if (run?.profile?.nativeWorkspaceFinalizationOwner) {- const [action] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId)));- const state = readWorkspaceRecovery(action?.evidence ?? null);- await saveState({ schema: "paperclip.workspace-recovery.v1", runId: input.runId,- stage: "verifying_stop", attempt: state?.attempt ?? 0, requestIds: state?.requestIds ?? [],- status: "blocked", retryable: false, blockerCode: "owner", message: stopMessage });- }+ const current = await loadSystemRecovery(db, input);+ const reserved = current && reserveSystemRecoveryAttempt(current);+ if (current && reserved) await updateSystemRecovery(db, input, current,+ failSystemRecovery(reserved, new SystemRecoveryFailure("copyback_stop_unconfirmed", "recheck_evidence")));}}@@ -263,15 +297,12 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string) {then (${issueRecoveryActions.evidence}->>'runId')::uuid end`))).where(and(inArray(heartbeatRuns.status, terminal),sql`(${issueRecoveryActions.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'+ or ${issueRecoveryActions.evidence}->'historicalWorkspaceSource'->>'schema' = 'paperclip.historical-workspace-source.v1'or ${issueRecoveryActions.cause} in ('native_workspace_sync_out_unrecoverable', 'native_workspace_sync_out_retry_exhausted'))`,- sql`(${issueRecoveryActions.evidence}->'executionReconciliation' is null- or ${issueRecoveryActions.evidence}#>>'{workspaceRecovery,status}' = 'recovered')`,- sql`(coalesce(${issueRecoveryActions.evidence}#>>'{workspaceRecovery,status}', '') <> 'blocked' or- (${issueRecoveryActions.evidence}#>>'{workspaceRecovery,blockerCode}' = 'stop' and exists (- select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${heartbeatRuns.companyId}- and ${environmentLeases.heartbeatRunId} = ${heartbeatRuns.id} and ${environmentLeases.status} = 'released'- and ${environmentLeases.id}::text = ${heartbeatRuns.runnerProfileJson}#>>'{nativeWorkspaceSync,leaseId}'- and ${environmentLeases.cleanupStatus} = 'success' and ${environmentLeases.metadata}->'remoteExecutionTermination'->>'state' = 'stopped')))`,+ sql`${issueRecoveryActions.evidence} ? 'systemRecovery'`,+ sql`(${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence', 'complete', 'exhausted')+ and (${issueRecoveryActions.evidence}#>'{systemRecovery,nextAttemptAt}' = 'null'::jsonb+ or ${issueRecoveryActions.evidence}#>'{systemRecovery,nextAttemptAt}' <= to_jsonb(${Date.now()}::bigint)))`,sql`(${issueRecoveryActions.evidence}#>>'{workspaceRecovery,status}' is distinct from 'recovered' or(${heartbeatRuns.runnerProfileJson}#>>'{nativeWorkspaceSync,resourceDisposition}' = 'destroy' and exists (select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${heartbeatRuns.companyId}@@ -290,6 +321,7 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string) {* still owes cleanup even without saved input or after task reconciliation. */export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRuntimeService,onRecovered: (run: typeof heartbeatRuns.$inferSelect) => Promise<void>) {+ await adoptHistoricalWorkspaceRecoveries(db);let pending = workInFlight.get(db);if (!pending) { pending = new Set(); workInFlight.set(db, pending); }if (pending.size >= 2) return;@@ -303,9 +335,20 @@ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRuvoid (async () => { try {await recoverRetainedWorkspace({ db, environmentRuntime: runtime, companyId: action.companyId, issueId: action.sourceIssueId, runId: run.id, actionId: action.id });const [updated] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id));- if (readWorkspaceRecovery(updated?.evidence ?? null)?.status === "recovered") {+ const recovered = readWorkspaceRecovery(updated?.evidence ?? null)?.status === "recovered";+ const exhausted = readSystemRecovery(updated?.evidence)?.state === "exhausted";+ if (recovered || exhausted) {const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));- if (current) { await scheduleRecoveredWorkspaceCleanup(db, current); await onRecovered(current); }+ if (current) {+ if (recovered) {+ await resumePreservedResultFinalization(db, current.companyId, current.id);+ await scheduleRecoveredWorkspaceCleanup(db, current);+ }+ // Only normal dispatch can consume existing authorized input. An+ // exhausted export permits evaluation of an isolated continuation,+ // never another export attempt or a replay of an old assignment.+ await onRecovered(current);+ }}} catch { logger.warn({ runId: run.id }, "Retained workspace remains pending"); }finally { pending.delete(run.id); } })();diff --git a/tests/e2e/chat-adapters-ui-messaging.spec.ts b/tests/e2e/chat-adapters-ui-messaging.spec.tsindex 8ce693a2b0..286f8f24f8 100644--- a/tests/e2e/chat-adapters-ui-messaging.spec.ts+++ b/tests/e2e/chat-adapters-ui-messaging.spec.ts@@ -1285,7 +1285,7 @@ test.describe("Board send delivery refresh", () => {}});-test.describe("Exact failed chat run retry", () => {+test.describe("Failed chat task and exact run retry", () => {let seed: Seed;let issue: { id: string; identifier: string; title: string };@@ -1405,7 +1405,10 @@ test.describe("Exact failed chat run retry", () => {});return;}- if (pathname === `/api/agents/${seed.agentId}/wakeup`) {+ const retryPath = surface === "Inbox"+ ? `/api/issues/${issue.id}/retry`+ : `/api/agents/${seed.agentId}/wakeup`;+ if (pathname === retryPath) {expect(route.request().method()).toBe("POST");requests.push({companyId: url.searchParams.get("companyId"),@@ -1424,7 +1427,24 @@ test.describe("Exact failed chat run retry", () => {// The durable action exists, but no run has been admitted yet.await fulfill(route,- { actionId, issueId: issue.id, runId: null, status: outcome },+ surface === "Inbox"+ ? {+ requestId: actionId,+ accepted: true,+ stale: false,+ observedRunId: failedRunId,+ presentation: {+ intentId: actionId,+ responsibility: "system",+ state: outcome === "queued" ? "working" : "retry_scheduled",+ nextRetryAt: null,+ canRetry: false,+ userAction: null,+ sourceRunIds: [failedRunId],+ observedRunId: failedRunId,+ },+ }+ : { actionId, issueId: issue.id, runId: null, status: outcome },202,);}@@ -1467,15 +1487,25 @@ test.describe("Exact failed chat run retry", () => {await expect(retry).toHaveCount(1);await retry.click();await expect.poll(() => requests.length).toBe(1);- expect(requests[0]).toEqual({- companyId: seed.companyId,- body: {- source: "on_demand",- triggerDetail: "manual",- reason: "retry_failed_run",- failedRunId,- },- });+ expect(requests[0]).toEqual(surface === "Inbox"+ ? {+ companyId: null,+ body: {+ idempotencyKey: expect.stringMatching(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,+ ),+ observedRunId: failedRunId,+ },+ }+ : {+ companyId: seed.companyId,+ body: {+ source: "on_demand",+ triggerDetail: "manual",+ reason: "retry_failed_run",+ failedRunId,+ },+ });if (outcome === "denied") {await expect(page.getByText(denial, { exact: true })).toBeVisible();if (surface !== "agent run") {diff --git a/tests/e2e/fixtures/in-feed-codex.mjs b/tests/e2e/fixtures/in-feed-codex.mjsindex 5f8900a030..e1bcaec8e4 100644--- a/tests/e2e/fixtures/in-feed-codex.mjs+++ b/tests/e2e/fixtures/in-feed-codex.mjs@@ -55,6 +55,14 @@ async function finish(text, evidenceRef) {evidence: [{ ref: evidenceRef }], verification: [{ commandOrCheck: 'Fixture outcome', status: 'passed' }], attentionRequests: [], artifacts: [] });}async function execute() {+ if (process.argv.includes('--task-retry-fixture')) {+ const text = 'The saved result is confirmed. No external publication was repeated.';+ await call('report_progress', { idempotencyKey: 'saved-result-confirmation', body: text });+ await finish(text, 'fixture:preserved-result');+ send({ method: 'item/completed', params: { threadId, turnId, item: { id: `answer-${turnId}`, type: 'agentMessage', phase: 'final_answer', text } } });+ send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });+ return;+ }if (process.argv.includes('--completion-stream-fixture')) {// Report completion before a deliberately slow final answer. The real// runner and control plane must keep listening after the tool succeeds.diff --git a/tests/e2e/fixtures/task-retry-bin/codex b/tests/e2e/fixtures/task-retry-bin/codexnew file mode 100755index 0000000000..2508d177f8--- /dev/null+++ b/tests/e2e/fixtures/task-retry-bin/codex@@ -0,0 +1,2 @@+#!/bin/sh+exec node "$(dirname "$0")/../in-feed-codex.mjs" "$@" --task-retry-fixturediff --git a/tests/e2e/legacy-failure-continuation.spec.ts b/tests/e2e/legacy-failure-continuation.spec.tsindex 216261cb87..4eaa73092f 100644--- a/tests/e2e/legacy-failure-continuation.spec.ts+++ b/tests/e2e/legacy-failure-continuation.spec.ts@@ -11,7 +11,7 @@ async function json(response: APIResponse) {return response.json();}-for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "queued_interrupt", "automatic_message"] as const) {+for (const action of ["task_retry", "retry_after_reload", "inbox_retry", "message", "queued_retry", "automatic_message"] as const) {test(`legacy startup hold: ${action} reaches a new agent response`, async ({ page, request }) => {test.setTimeout(120_000);const root = await mkdtemp(path.join(os.tmpdir(), "legacy-recovery-browser-"));@@ -41,7 +41,7 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "q// Seed the historical incident, then exercise all recovery through the UI.// No adapter.invoke or new dispatch identity exists on this pre-upgrade run.await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId: company.id, agentId: agent.id,- status: "failed", runtimeMode: "legacy", processPid: action === "queued_interrupt" ? process.pid : 999999999,+ status: "failed", runtimeMode: "legacy", processPid: action === "queued_retry" ? process.pid : 999999999,responsibleUserId: issue.responsibleUserId, errorCode: "process_lost", error: "Server restarted during startup",startedAt: new Date(Date.now() - 10_000), finishedAt: new Date(Date.now() - 5_000),contextSnapshot: { issueId: issue.id },@@ -52,18 +52,18 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "qevidence: { runId: sourceRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } },});await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issue.id));- if (action === "queued_interrupt") {+ if (action === "queued_retry") {await db.insert(authUsers).values({ id: "original-board", name: "Original author", email: "[email protected]",createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user",principalId: "original-board", membershipRole: "operator", status: "active" });}- if (action === "queued_interrupt" || action === "automatic_message") {+ if (action === "queued_retry" || action === "automatic_message") {const commentId = randomUUID();// Reproduce a real user comment saved while the failed run was active,// including queues originally created by a system wake.await db.insert(issueComments).values({ id: commentId, companyId: company.id, issueId: issue.id,- authorType: "user", authorUserId: action === "queued_interrupt" ? "original-board" : "local-board", body: "Approved",+ authorType: "user", authorUserId: action === "queued_retry" ? "original-board" : "local-board", body: "Approved",createdAt: new Date(Date.now() - 8_000),});await db.insert(agentWakeupRequests).values({ companyId: company.id, agentId: agent.id,@@ -75,25 +75,25 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "qconst taskUrl = `/${company.issuePrefix}/issues/${issue.identifier}`;await page.goto(action === "inbox_retry" ? `/${company.issuePrefix}/inbox/all` : taskUrl);if (action === "task_retry") {- const notice = page.getByRole("status", { name: "Task recovery" });- await expect(notice).toContainText("Server restarted during startup");- await expect(notice).toContainText("Automatic recovery stopped.");- await expect(notice.getByRole("link", { name: "Inspect run" }))- .toHaveAttribute("href", new RegExp(`/agents/${agent.id}/runs/${sourceRunId}$`));+ const notice = page.getByRole("status", { name: "Task status" });+ await expect(notice).toContainText("Couldn’t finish this attempt. Your message is saved.");+ await expect(page.getByText("Automatic recovery stopped.", { exact: true })).toHaveCount(0);+ await expect(notice.getByRole("link", { name: "Inspect run" })).toHaveCount(0);await expect(notice.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();- const presentation = await notice.evaluate(element => {- const style = getComputedStyle(element);- return { border: style.borderTopWidth, background: style.backgroundColor };- });- expect(parseFloat(presentation.border)).toBeGreaterThan(0);- expect(presentation.background).not.toBe("rgba(0, 0, 0, 0)");- await test.info().attach("recovery-notice", { body: await notice.screenshot(), contentType: "image/png" });+ await test.info().attach("task-retry", { body: await notice.screenshot(), contentType: "image/png" });+ }+ if (action === "retry_after_reload") {+ await page.reload();+ await expect(page.getByRole("button", { name: "Try again", exact: true })).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeEnabled();}- if (action === "queued_interrupt") {- const interrupt = page.getByRole("button", { name: "Interrupt", exact: true });- await expect(interrupt).toBeEnabled();+ if (action === "queued_retry") {+ await expect(page.getByRole("button", { name: "Interrupt", exact: true })).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Steer", exact: true })).toHaveCount(0);+ const retry = page.getByRole("button", { name: "Retry", exact: true });+ await expect(retry).toBeEnabled();await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, sourceRunId));- await interrupt.click();+ await retry.click();} else if (action === "automatic_message") {// No Retry, duplicate message, or status change: the saved input runs.} else if (action === "message") {@@ -105,15 +105,15 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "qpage.waitForResponse((response) => {const request = response.request();return request.method() === "POST"- && new URL(response.url()).pathname.endsWith(`/agents/${agent.id}/wakeup`)- && request.postDataJSON()?.failedRunId === sourceRunId;+ && new URL(response.url()).pathname.endsWith(`/issues/${issue.id}/retry`)+ && request.postDataJSON()?.observedRunId === sourceRunId;}),page.getByRole("button", { name: "Retry", exact: true }).click(),]);expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true);await page.goto(taskUrl);} else {- await page.getByRole("button", { name: action === "thread_retry" ? "Try again" : "Retry", exact: true }).click();+ await page.getByRole("button", { name: "Retry", exact: true }).click();}await expect(page.getByText("Answered the pending follow-up once.", { exact: false })).toBeVisible({ timeout: 45_000 });await expect(page.getByRole("status", { name: "Task recovery" })).toHaveCount(0);@@ -123,7 +123,7 @@ for (const action of ["task_retry", "thread_retry", "inbox_retry", "message", "qexpect(runs.filter(run => run.id !== sourceRunId)).toHaveLength(1);expect(runs.find(run => run.id === sourceRunId)).toMatchObject({ status: "failed", resultJson: null });const prompts = await readFile(path.join(root, "prompts"), "utf8");- if (action === "queued_interrupt" || action === "automatic_message") {+ if (action === "queued_retry" || action === "automatic_message") {expect(prompts).toContain("Approved");await expect(page.getByRole("button", { name: "Interrupt", exact: true })).toHaveCount(0);}diff --git a/ui/src/adapters/paperclip-runner/index.test.ts b/ui/src/adapters/paperclip-runner/index.test.tsindex df5fdfd9f5..fe165415de 100644--- a/ui/src/adapters/paperclip-runner/index.test.ts+++ b/ui/src/adapters/paperclip-runner/index.test.ts@@ -22,7 +22,7 @@ const piFailure = (overrides: Record<string, unknown> = {}, eventOverrides: Reco});describe("paperclip runner transcript projection", () => {- it("keeps both pinned Pi failure facts while rendering one consecutive diagnostic", async () => {+ it("keeps both pinned Pi failure facts in diagnostics without adding a task warning", async () => {const adapter = createPiProfileExtensionAdapter({ workspacePath: "/fixture", sessionId: "session-1", turnId: "turn-1" });const notice = { sessionId: "session-1", category: "runtime_failure", severity: "error",summary: "Pi process exited with code 4", details: { reason: "native_process_exited" } };@@ -36,9 +36,9 @@ describe("paperclip runner transcript projection", () => {runId: "run-1", normalizedSessionId: "session-1", turnId: "turn-1", ...event,} }), "2026-10-03T07:00:00.000Z"));expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({ family: "provider_notice", payload: { userActionable: false } });expect(transcriptToTaskChatItems(entries, { runId: "run-1", agentName: "Pi", running: false }))- .toEqual([expect.objectContaining({ kind: "protocol", family: "provider_notice",- details: expect.arrayContaining([{ label: "Severity", value: "error", mono: false }]) })]);+ .toEqual([]);expect(raw).toEqual(before);});diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.tsindex 6c71709a4f..fb1251e5bc 100644--- a/ui/src/api/issues.ts+++ b/ui/src/api/issues.ts@@ -300,6 +300,8 @@ export const issuesApi = {api.post<{ runId: string; resultId: string; status: "queued" }>(`/issues/${id}/recovery-actions/resume-workspace-finalization`, data),retryWorkspaceExport: (id: string, data: { actionId: string; runId: string; repairNote: string }) =>api.post<{ runId: string; resultId: string; leaseId: string; status: "queued" }>(`/issues/${id}/recovery-actions/retry-workspace-export`, data),+ retryTask: (issueId: string, body: { idempotencyKey: string; observedRunId: string | null }) =>+ api.post<{ requestId: string | null; accepted: boolean; stale: boolean; presentation: import("@paperclipai/shared").TaskInterruptionPresentation | null }>(`/issues/${issueId}/retry`, body),recoverWorkspace: (id: string, data: { actionId: string; runId: string; idempotencyKey: string }) =>api.post<{ actionId: string; status: string }>(`/issues/${id}/recovery-actions/recover-workspace`, data),reconstructWorkspace: (id: string, data: { actionId: string; runId: string; expectedStatusVersion: number; attachmentIds: string[];diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsxindex 206475f483..e79d926ebc 100644--- a/ui/src/components/ExecutionBlockerNotice.test.tsx+++ b/ui/src/components/ExecutionBlockerNotice.test.tsx@@ -1,355 +1,61 @@// @vitest-environment jsdom-import { act, type AnchorHTMLAttributes } from "react";+import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { TaskInterruptionPresentation } from "@paperclipai/shared";import { ExecutionBlockerNotice } from "./ExecutionBlockerNotice";-import { agentsApi } from "../api/agents";-import { activityApi } from "../api/activity";-import { issuesApi } from "../api/issues";-import { queryKeys } from "../lib/queryKeys";-vi.mock("../lib/router", () => ({- Link: ({ to, ...props }: AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => <a href={to} {...props} />,-}));-vi.mock("../api/agents", () => ({ agentsApi: { retryFailedRun: vi.fn() } }));-vi.mock("../api/activity", () => ({ activityApi: { runsForIssue: vi.fn() } }));-vi.mock("../api/issues", () => ({ issuesApi: { recoveryActions: vi.fn(), listAttachments: vi.fn(), reconstructWorkspace: vi.fn(), recoverWorkspace: vi.fn() } }));-describe("stopped task recovery notice", () => {+const failed: TaskInterruptionPresentation = {+ intentId: "intent", responsibility: "system", state: "failed", nextRetryAt: null,+ canRetry: true, userAction: null, sourceRunIds: ["source"], observedRunId: "source",+};+describe("ordinary task interruption", () => {let root: Root;let container: HTMLDivElement;- let client: QueryClient;- const onRetried = vi.fn();- beforeEach(async () => {- vi.clearAllMocks();- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [] });- vi.mocked(issuesApi.listAttachments).mockResolvedValue([]);- container = document.createElement("div"); document.body.append(container);+ const retry = vi.fn();+ beforeEach(() => {+ retry.mockReset(); container = document.createElement("div"); document.body.append(container);root = createRoot(container);- client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });- vi.mocked(activityApi.runsForIssue).mockResolvedValue([{ runId: "failed-run", agentId: "agent", status: "failed" }] as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "legacy_execution_requires_reconciliation",- nextAction: "Automatic recovery stopped. Recorded work is preserved; actions with unverified outcomes will not be repeated.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });});- afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });- it.each(["queued", "recovering", "blocked"] as const)("shows observed workspace recovery state: %s", async status => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" canRecover onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "native_continuation_requires_reconciliation",- nextAction: "Recover the retained source", workspaceRepairRequired: true, savedMessageCount: 1,- workspaceRecovery: { status, stage: "restoring_files", canRetry: status === "blocked",- message: "Recovery couldn’t finish. Your message is saved." },- }} />- </QueryClientProvider>));- expect(container.textContent).not.toContain("operator attention");- if (status === "blocked") {- expect(container.textContent).toContain("Recovery couldn’t finish");- vi.mocked(issuesApi.recoverWorkspace).mockResolvedValue({ actionId: "recovery", status: "queued" });- await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());- expect(issuesApi.recoverWorkspace).toHaveBeenCalledWith("task", expect.objectContaining({ actionId: "recovery", runId: "failed-run", idempotencyKey: expect.any(String) }));- expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();- } else {- expect(container.textContent).toContain("Recovering saved work…");- expect(container.textContent).toContain("Your message is saved and will continue after recovery.");- expect(container.querySelector("button")).toBeNull();- }- });- it("keeps the recovery guidance and an inspection link alongside Retry", () => {- const notice = container.querySelector('[role="status"][aria-label="Task recovery"]')!;- expect(notice.textContent).toContain("Recorded work is preserved");- expect(notice.textContent).toContain("Retry");- expect(notice.classList.contains("task-context-notice")).toBe(true);- expect(notice.querySelector("a")?.getAttribute("href")).toBe("/agents/agent/runs/failed-run");- });- it.each([false, true])("explains cancelled runs and saved input; continue eligibility %s", async canContinue => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",- cause: "legacy_execution_requires_reconciliation", runStatus: "cancelled",- runError: "Provider cancelled execution", savedMessageCount: 2, canContinue,- nextAction: canContinue ? "Verify provider shutdown before continuing."- : "Inspect the run before sending a new message to request continuation.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain("Provider cancelled execution");- expect(container.textContent).toContain("2 saved messages are waiting");- expect(container.querySelector("a")?.getAttribute("href")).toContain("cancelled-run");- expect(container.querySelector("button")?.textContent ?? null).toBe(canContinue ? "Continue" : null);- if (!canContinue) expect(container.textContent).toContain("sending a new message to request continuation");- if (canContinue) {- vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);- await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());- expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "cancelled-run", "company");- }- });- it("keeps removed-chat guidance without suggesting a message to an unavailable destination", async () => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",- cause: "legacy_execution_requires_reconciliation", runStatus: "cancelled", canContinue: false,- nextAction: "This chat connection was removed. Inspect the stopped run and create a new task to continue the work.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain("create a new task");- expect(container.textContent).not.toContain("sending a new message");- expect(container.querySelector("button")).toBeNull();- expect(container.querySelector("a")?.textContent).toBe("Inspect run");- });- it("keeps the required next action for other reconciliation causes", async () => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "action_outcome_unknown",- nextAction: "Verify the external action outcome before continuing.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain("Verify the external action outcome before continuing.");- expect(container.textContent).not.toContain("Automatic recovery of this task stopped.");- });- it.each(["native_continuation_requires_reconciliation", "native_session_cleanup_quarantined"])("links to the source run instead of offering a retry rejected by %s", async (cause) => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",- cause,- nextAction: "Inspect the original failure and reconcile the previous execution before continuing.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain("Work paused.");- expect(container.textContent).not.toContain("Retry");- const link = container.querySelector("a")!;- expect(link.textContent).toBe("Inspect run");- expect(link.getAttribute("href")).toBe("/agents/agent/runs/failed-run");- expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();- });- it("keeps workspace repair guidance and inspection without offering the legacy Retry fallback", async () => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{- recoveryActionId: "repair", runId: "failed-run", agentId: "agent", cause: "legacy_execution_requires_reconciliation",- workspaceRepairRequired: true, canRecordWorkspaceRepair: true, canRetry: false, canContinue: false,- nextAction: "The original sandbox is retained. Recover the missing files and record workspace repair evidence.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain("Paperclip must recover the saved workspace");- // The hold also covers unsafe archives and local runs, so the notice must not promise retries or a kept sandbox.- expect(container.textContent).not.toContain("retrying");- expect(container.textContent).not.toContain("no work is lost");- expect(container.textContent).not.toContain("record workspace repair evidence");- expect(container.querySelector("button")).toBeNull();- expect(container.querySelector("textarea, input")).toBeNull();- expect(container.querySelector("a")?.textContent).toBe("Inspect run");- expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();- });-- it.each([false, true])("preserves source reconstruction and its queued state: %s", async pending => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" canManage issueStatus="blocked" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause: "native_workspace_sync_out_unrecoverable",- workspaceRepairRequired: true, canReconstructWorkspace: !pending, workspaceReconstructionPending: pending,- workspaceRecoveryStatusVersion: 1, nextAction: pending ? "Continuation from saved sources is queued and waiting for execution checks." : "Inspect surviving source attachments.",- }} />- </QueryClientProvider>));- expect(container.textContent).toContain(pending ? "Continuation queued." : "Continue from saved sources");- expect(container.textContent).not.toContain(pending ? "Work paused." : "recovered workspace files");- expect(container.querySelector("summary")?.closest("details")?.open).toBe(false);- expect(issuesApi.reconstructWorkspace).not.toHaveBeenCalled();- if (pending) {- expect(container.querySelector("textarea")).toBeNull();- expect(issuesApi.listAttachments).not.toHaveBeenCalled();- }- });-- it.each(["running", "missed", "wrong-run", "replay-blocked", "delegated"])("uses observed recovery liveness, including for readers: %s", async state => {- const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent",- evidence: { runId: state === "wrong-run" ? "other-run" : "failed-run",- automaticRecovery: { replay: state === "replay-blocked" ? "blocked" : "held" } },- attemptCount: 1, maxAttempts: 3, outcome: state === "delegated" ? "delegated" : null,- wakePolicy: state === "delegated" ? null : { kind: "resume_native_run", runId: "failed-run", attempt: 1, maxAttempts: 3, notBefore: "2020-01-01T00:00:00Z" },- nativeRunActivity: state === "missed" ? null : { runId: "failed-run", status: "running" },- };- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: action, actions: [action] } as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="live-task" issueStatus="blocked" canManage={false} onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", workspaceRepairRequired: true,- cause: "native_continuation_requires_reconciliation", nextAction: "Operator inspection is required.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(Boolean(container.querySelector('[aria-label="Task recovery"]'))).toBe(state !== "running");- });-- it("retries the exact failed run and refreshes the task", async () => {- vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);+ afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); });+ const render = async (presentation = failed, options: { canRetry?: boolean; optimistic?: boolean; takingLonger?: boolean; error?: Error } = {}) => {+ await act(async () => root.render(<ExecutionBlockerNotice presentation={presentation} canRetry onRetry={retry} {...options} />));+ };+ it("offers one Retry without delegating infrastructure chores", async () => {+ await render();+ expect(container.textContent).toContain("Couldn’t finish this attempt. Your message is saved.");+ expect(container.querySelectorAll("button")).toHaveLength(1);await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "failed-run", "company");- expect(onRetried).toHaveBeenCalledOnce();- });-- it("reveals a missed retry when every recovery poll returns identical data", async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-10-18T00:00:00Z"));- try {- const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent", outcome: null,- evidence: { runId: "failed-run" }, attemptCount: 1, maxAttempts: 3,- wakePolicy: { kind: "resume_native_run", runId: "failed-run", attempt: 1, maxAttempts: 3,- notBefore: "2026-10-18T00:00:10Z" }, nativeRunActivity: null };- const response = { active: action, actions: [action] };- vi.mocked(issuesApi.recoveryActions).mockResolvedValue(response as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="expiry-task" issueStatus="blocked" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",- cause: "native_continuation_requires_reconciliation", nextAction: "Inspect the missed recovery.",- }} />- </QueryClientProvider>));- await act(async () => { await vi.advanceTimersByTimeAsync(1); });- expect(container.querySelector('[aria-label="Task recovery"]')).toBeNull();- const before = vi.mocked(issuesApi.recoveryActions).mock.calls.length;- await act(async () => { await vi.advanceTimersByTimeAsync(41_000); });- expect(vi.mocked(issuesApi.recoveryActions).mock.calls.length).toBeGreaterThan(before);- expect(container.querySelector('[aria-label="Task recovery"]')).not.toBeNull();- expect(container.textContent).toContain("Inspect the missed recovery.");- } finally { vi.useRealTimers(); }- });-- it("shows a recovery refresh error instead of trusting cached activity", async () => {- const action = { id: "recovery", kind: "active_run_watchdog", status: "active", ownerType: "agent", outcome: null,- evidence: { runId: "failed-run" }, attemptCount: 1, maxAttempts: 3,- wakePolicy: { kind: "resume_native_run", runId: "failed-run" },- nativeRunActivity: { runId: "failed-run", status: "running", workspaceOperationId: null } };- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: action, actions: [action] } as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="read-error-task" issueStatus="blocked" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent",- cause: "native_continuation_requires_reconciliation", nextAction: "Inspect the current run.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.querySelector('[aria-label="Task recovery"]')).toBeNull();- vi.mocked(issuesApi.recoveryActions).mockRejectedValue(new Error("Recovery service unavailable"));- await act(async () => { await client.refetchQueries({ queryKey: queryKeys.issues.recoveryActions("read-error-task", "recovery", "failed-run") }); });- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.querySelector('[role="alert"]')?.textContent).toContain("Recovery service unavailable");- expect(container.textContent).toContain("Inspect the current run.");- });-- it.each([- "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.",- "The selected model is not supported by the current ChatGPT connection. Choose a supported model or a compatible AI connection.",- ])("shows the model rejection and repair action without expanding run logs: %s", async (runError) => {- vi.mocked(activityApi.runsForIssue).mockResolvedValue([{ runId: "model-run", agentId: "agent",- status: "failed", errorCode: "native_provider_model_rejected" }] as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="model-task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "model-run", agentId: "agent",- cause: "native_continuation_requires_reconciliation", canRetry: true,- runError,- nextAction: "Inspect the original failure before continuing.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.textContent).toContain("Model unavailable.");- expect(container.textContent).toContain(runError);- expect(container.textContent).toContain("clear the task's model override, then retry");- expect(container.textContent).toContain("Inspect the original failure before continuing.");+ expect(retry).toHaveBeenCalledOnce();+ expect(container.querySelector("a, details, input, textarea")).toBeNull();+ expect(container.textContent).not.toMatch(/service attention|process|receipt|workspace/i);+ });+ it("shows persisted backoff with a usable Retry", async () => {+ vi.useFakeTimers(); vi.setSystemTime(new Date("2026-10-20T00:00:00Z"));+ await render({ ...failed, state: "retry_scheduled", nextRetryAt: "2026-10-20T00:00:30Z" });+ expect(container.textContent).toContain("Trying again in 30s");+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ expect(container.textContent).toContain("Trying again in 25s");expect(container.querySelector("button")?.textContent).toBe("Retry");});-- it.each(["native_continuation_requires_reconciliation", "uncertain_external_action"])("offers Retry for a server-admitted native failure: %s", async cause => {- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "failed-run", agentId: "agent", cause,- canRetry: true,- nextAction: "Automatic recovery stopped. Try again or send a new message to continue.",- }} />- </QueryClientProvider>));- const button = container.querySelector<HTMLButtonElement>("button");- expect(button?.textContent).toBe("Retry");- vi.mocked(agentsApi.retryFailedRun).mockResolvedValue({} as never);- await act(async () => button!.click());- expect(agentsApi.retryFailedRun).toHaveBeenCalledWith("agent", "failed-run", "company");- });- it("shows a failed Retry in the same container and allows another attempt", async () => {- vi.mocked(agentsApi.retryFailedRun).mockRejectedValue(new Error("Environment cleanup is still running."));- await act(async () => container.querySelector<HTMLButtonElement>("button")!.click());- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.querySelector('[role="alert"]')?.textContent).toBe("Environment cleanup is still running.");- expect(container.querySelector<HTMLButtonElement>("button")!.disabled).toBe(false);- expect(onRetried).not.toHaveBeenCalled();+ it.each(["working", "resolved"] as const)("does not duplicate the thread indicator for %s", async state => {+ await render({ ...failed, state }); expect(container.textContent).toBe("");});- it("shows a settled hold's decision even when there is no active recovery action", async () => {- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{- id: "recovery", status: "resolved", resolutionNote: "The last tool outcome could not be verified.",- evidence: { runId: "cancelled-run", automaticRecovery: { replay: "blocked" } },- }] as never });- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent", runStatus: "cancelled",- cause: "legacy_execution_requires_reconciliation", nextAction: "Send a new message after inspecting the run.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(issuesApi.recoveryActions).toHaveBeenCalledWith("task");- expect(container.querySelector("details")?.textContent).toContain("The last tool outcome could not be verified.");- expect(container.querySelector("details")?.textContent).toContain("stopped automatic retries");- expect(container.querySelector("button")).toBeNull();- expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();+ it("leaves genuine user decisions to their specific action surface", async () => {+ await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "approval", canRetry: false });+ expect(container.textContent).toBe("");});- it("does not show a different run's historical recovery decision", async () => {- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{- id: "recovery", status: "resolved", resolutionNote: "Old decision",- evidence: { runId: "another-run", automaticRecovery: { replay: "blocked" } },- }] as never });- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",- cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.querySelector("details")).toBeNull();- expect(container.textContent).not.toContain("Old decision");+ it("does not give read-only users a mutation", async () => {+ await render(failed, { canRetry: false }); expect(container.querySelector("button")).toBeNull();});- it("reports a recovery history read failure without hiding the current guidance", async () => {- vi.mocked(issuesApi.recoveryActions).mockRejectedValue(new Error("History unavailable"));- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",- cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",- }} />- </QueryClientProvider>));- await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });- expect(container.querySelector('[role="alert"]')?.textContent).toContain("History unavailable");- expect(container.textContent).toContain("Inspect the current run.");+ it("removes the stale failure immediately while admission is pending", async () => {+ await render(failed, { optimistic: true }); expect(container.textContent).toBe("");+ await render(failed, { optimistic: true, takingLonger: true });+ expect(container.textContent).toContain("Taking longer than usual…");});- it("refreshes a decision while the same stopped run remains open", async () => {- vi.mocked(issuesApi.recoveryActions).mockClear();- vi.useFakeTimers();- try {- const action = { id: "recovery", status: "active", resolutionNote: "Inspection pending", evidence: { runId: "cancelled-run" } };- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [action] } as never);- await act(async () => root.render(<QueryClientProvider client={client}>- <ExecutionBlockerNotice companyId="company" issueId="task" issueStatus="blocked" canManage onRetried={onRetried} blocker={{- recoveryActionId: "recovery", runId: "cancelled-run", agentId: "agent",- cause: "legacy_execution_requires_reconciliation", nextAction: "Inspect the current run.",- }} />- </QueryClientProvider>));- await act(async () => { await vi.advanceTimersByTimeAsync(1); });- expect(container.textContent).toContain("Inspection pending");- vi.mocked(issuesApi.recoveryActions).mockResolvedValue({ active: null, actions: [{ ...action,- status: "resolved", resolutionNote: "Preserved work; automatic replay stopped", evidence: {- runId: "cancelled-run", automaticRecovery: { replay: "blocked" },- },- }] } as never);- await act(async () => { await vi.advanceTimersByTimeAsync(5_001); });- expect(issuesApi.recoveryActions).toHaveBeenCalledTimes(2);- expect(container.textContent).toContain("Preserved work; automatic replay stopped");- expect(container.textContent).not.toContain("Inspection pending");- } finally {- vi.useRealTimers();- }+ it("shows a definitive admission rejection instead of silently dropping Retry", async () => {+ await render(failed, { error: new Error("Your task access changed. Refresh the task.") });+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("Your task access changed.");+ expect(container.querySelectorAll("button")).toHaveLength(1);});});diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsxindex 1418abe375..9c34d72748 100644--- a/ui/src/components/ExecutionBlockerNotice.tsx+++ b/ui/src/components/ExecutionBlockerNotice.tsx@@ -1,136 +1,30 @@-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { useEffect, useRef } from "react";-import type { ExecutionBlocker, Issue } from "@paperclipai/shared";-import { WorkspaceReconstructionRecovery } from "./WorkspaceReconstructionRecovery";-import { agentsApi } from "../api/agents";-import { activityApi } from "../api/activity";-import { issuesApi } from "../api/issues";-import { queryKeys } from "../lib/queryKeys";+import type { TaskInterruptionPresentation } from "@paperclipai/shared";import { Button } from "./ui/button";import { cn } from "../lib/utils";-import { Link } from "../lib/router";-import { deriveRecoveryDisplayState } from "../lib/recovery-display";-import { readRecoveryRetryLineage } from "../lib/recovery-lineage";import { useSecondTick } from "../hooks/useSecondTick";-export function ExecutionBlockerNotice({ companyId, issueId, issueStatus, canManage = false, canRecover = canManage, blocker, onRetried, className }: {+/** One ordinary interruption surface. Technical records remain in diagnostics. */+export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimistic, takingLonger, error, className }: {+ presentation: TaskInterruptionPresentation | null | undefined;+ canRetry: boolean;+ onRetry: () => void;+ optimistic?: boolean;+ takingLonger?: boolean;+ error?: Error | null;className?: string;- companyId: string;- issueId: string;- issueStatus?: Issue["status"];- canManage?: boolean;- canRecover?: boolean;- blocker: ExecutionBlocker;- onRetried: () => void;}) {- const queryClient = useQueryClient();- const recoveryRequestKey = useRef<string | null>(null);- const { data: recovery, error: recoveryError } = useQuery({- queryKey: queryKeys.issues.recoveryActions(issueId, blocker.recoveryActionId ?? null, blocker.runId ?? null),- queryFn: () => issuesApi.recoveryActions(issueId),- enabled: Boolean(blocker.recoveryActionId) && !["done", "cancelled"].includes(issueStatus ?? ""),- refetchInterval: 5_000,- });- const hold = recovery?.actions.find(action => action.id === blocker.recoveryActionId &&- (action.evidence.runId ?? action.evidence.sourceRunId) === blocker.runId);- const replayBlocked = (hold?.evidence.automaticRecovery as { replay?: unknown } | undefined)?.replay === "blocked";- const { data: runs, error: runsError } = useQuery({- queryKey: queryKeys.issues.runs(issueId),- queryFn: () => activityApi.runsForIssue(issueId),- });- const failedRun = runs?.find(run => run.runId === blocker.runId &&- ["failed", "timed_out"].includes(run.status));- const modelRejected = failedRun?.errorCode === "native_provider_model_rejected";- const requiresInspection = blocker.cause === "native_continuation_requires_reconciliation" ||- blocker.cause === "native_session_cleanup_quarantined";- const retry = useMutation({- mutationFn: () => agentsApi.retryFailedRun(blocker.agentId!, blocker.runId!, companyId),- onSuccess: () => {- onRetried();- for (const queryKey of [queryKeys.issues.detail(issueId), queryKeys.issues.runs(issueId),- queryKeys.issues.liveRuns(issueId), queryKeys.issues.activeRun(issueId)]) {- void queryClient.invalidateQueries({ queryKey });- }- },- });- const repair = useMutation({- mutationFn: () => {- recoveryRequestKey.current ??= crypto.randomUUID();- return issuesApi.recoverWorkspace(issueId, { actionId: blocker.recoveryActionId!, runId: blocker.runId!,- idempotencyKey: recoveryRequestKey.current });- },- onSuccess: () => {- recoveryRequestKey.current = null;- onRetried();- void queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId) });- void queryClient.invalidateQueries({ queryKey: queryKeys.issues.recoveryActions(issueId, blocker.recoveryActionId, blocker.runId) });- },- });- useEffect(() => {- if (recovery) void queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId) });- }, [recovery, queryClient, issueId]);- const workspaceRecovery = blocker.workspaceRecovery;- const repairing = workspaceRecovery?.status === "queued" || workspaceRecovery?.status === "recovering";- const now = Date.now();- const lineage = hold ? readRecoveryRetryLineage(hold, { now }) : null;- const recovering = Boolean(!recoveryError && !runsError && hold && !replayBlocked &&- deriveRecoveryDisplayState(hold, { now }) === "in_progress" && lineage?.hasDurablePath);- // Identical poll responses do not render again. Recheck a scheduled path's- // expiry with the shared clock, and stop ticking once it expires or starts.- useSecondTick(Boolean(recovering && lineage?.nextRetryAt && !lineage.liveRunId));- if (recovering && !workspaceRecovery) return null;- const hasDetails = Boolean(blocker.runError || (blocker.workspaceRepairRequired && blocker.nextAction) ||- (canManage && hold && (replayBlocked || hold.resolutionNote)));+ useSecondTick(presentation?.state === "retry_scheduled");+ if (error && !optimistic && !takingLonger) return <div role="alert" className={cn("flex items-center justify-between gap-2 text-sm text-destructive", className)}><span>{error.message}</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry}>Retry</Button>}</div>;+ if (takingLonger) return <div role="status" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}><span>Taking longer than usual…</span>{canRetry && <Button variant="outline" size="sm" onClick={onRetry}>Retry</Button>}</div>;+ if (optimistic || !presentation || presentation.responsibility !== "system" ||+ !["failed", "retry_scheduled"].includes(presentation.state)) return null;+ const seconds = Math.max(0, Math.ceil((Date.parse(presentation.nextRetryAt ?? "") - Date.now()) / 1000));return (- <div role="status" aria-label="Task recovery" className={cn("task-context-notice flex flex-wrap items-center justify-between gap-2", className)}>- <div className="min-w-0 flex-1 break-words">- <p className="font-medium">{repairing ? "Recovering saved work…" : workspaceRecovery?.status === "blocked" ? "Recovery needs attention." : blocker.workspaceReconstructionPending ? "Continuation queued." : modelRejected ? "Model unavailable." : "Work paused."}</p>- {modelRejected && <p>Choose a supported model or clear the task's model override, then retry.</p>}- {workspaceRecovery ? (- repairing ? Boolean(blocker.savedMessageCount) && <p>Your message is saved and will continue after recovery.</p>- : <p>{workspaceRecovery.message}</p>- ) : blocker.workspaceReconstructionPending ? <p>{blocker.nextAction}</p> : blocker.workspaceRepairRequired ? (- <p>Paperclip must recover the saved workspace before work can continue.</p>- ) : <p>{blocker.nextAction}</p>}- {!workspaceRecovery && Boolean(blocker.savedMessageCount) && (- <p>{blocker.savedMessageCount} saved {blocker.savedMessageCount === 1 ? "message is" : "messages are"} waiting for recovery.</p>- )}- {workspaceRecovery && !repairing && !workspaceRecovery.canRetry && Boolean(blocker.savedMessageCount) && (- <p>Your message is saved.</p>- )}- </div>- {blocker.agentId && blocker.runId && (- <Button variant="outline" size="sm" asChild>- <Link to={`/agents/${blocker.agentId}/runs/${blocker.runId}`}>Inspect run</Link>- </Button>- )}- {canRecover && workspaceRecovery?.canRetry && blocker.recoveryActionId && blocker.runId && (- <Button size="sm" disabled={repair.isPending} onClick={() => repair.mutate()}>- {repair.isPending ? "Queuing recovery…" : "Retry recovery"}- </Button>- )}- {repair.isError && <p role="alert" className="w-full text-destructive">{repair.error.message}</p>}- {!blocker.workspaceRepairRequired && (!requiresInspection || blocker.canRetry) && blocker.agentId && blocker.runId &&- ((blocker.cause === "legacy_execution_requires_reconciliation" && failedRun) || blocker.canContinue || blocker.canRetry) && (- <Button variant="outline" size="sm" disabled={retry.isPending} onClick={() => retry.mutate()}>- {retry.isPending ? "Starting…" : blocker.canContinue ? "Continue" : "Retry"}- </Button>- )}- {retry.isError && (- <p role="alert" className="w-full text-destructive">{retry.error.message}</p>- )}- {runsError && <p role="alert" className="w-full text-destructive">{runsError.message}</p>}- {hasDetails && <details className="w-full text-muted-foreground">- <summary className="cursor-pointer">Recovery details</summary>- {blocker.runError && <p className="break-words">{blocker.runError}</p>}- {!blocker.workspaceRepairRequired && <p>{blocker.nextAction}</p>}- {canManage && replayBlocked &&- <p>Paperclip stopped automatic retries to avoid repeating work with an unknown outcome. Inspect the run before requesting continuation.</p>}- {canManage && hold?.resolutionNote && <p>{hold.resolutionNote}</p>}- </details>}- {recoveryError && <p role="alert" className="w-full text-destructive">Unable to load recovery details: {recoveryError.message}</p>}- {blocker.canReconstructWorkspace && <WorkspaceReconstructionRecovery key={`reconstruct:${blocker.recoveryActionId}:${blocker.runId}`}- issueId={issueId} blocker={blocker} canManage={canManage} onRecorded={onRetried} />}+ <div role="status" aria-label="Task status" className={cn("flex items-center justify-between gap-2 text-sm text-muted-foreground", className)}>+ <span>{presentation.state === "retry_scheduled"+ ? `Trying again in ${seconds > 60 ? `${Math.ceil(seconds / 60)}m` : `${seconds}s`}…`+ : "Couldn’t finish this attempt. Your message is saved."}</span>+ {canRetry && presentation.canRetry && <Button variant="outline" size="sm" onClick={onRetry}>Retry</Button>}</div>);}diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsxindex 1d1699f6c4..a2000c86a1 100644--- a/ui/src/components/IssueChatThread.tsx+++ b/ui/src/components/IssueChatThread.tsx@@ -3,6 +3,7 @@ import { useCurrentWorkspaceRetry, useWorkspaceBaseRefRecovery, useWorkspaceRetrimport { WorkspaceBaseRefRecoveryNotice } from "./WorkspaceBaseRefRecoveryNotice";import { DispositionRecoveryNotice, useDispositionRecoverySnapshot } from "./DispositionRecoveryNotice";import { AgentAvatar } from "@/components/AgentAvatar";+import { TaskChatRunnerTurn } from "./task-chat/TaskChatRunnerTurn";import type { ComposerRunSettings } from "./task-chat/composer-run-settings";import { ComposerRunSettingsPicker } from "./task-chat/ComposerRunSettingsPicker";import { ComposerAddMenu, ComposerModeChip } from "./task-chat/ComposerAddMenu";@@ -542,6 +543,8 @@ interface IssueChatComposerProps {interface IssueChatThreadProps {executionBlocked?: boolean;+ interruption?: import("@paperclipai/shared").TaskInterruptionPresentation | null;+ retryPreparing?: boolean;/** Browser sessions are placed chronologically by the default task thread. */browsers?: import("@paperclipai/shared").TaskBrowser[];onOpenBrowser?: (browserId: string) => void;@@ -5771,6 +5774,8 @@ export function IssueChatThread({successfulRunHandoff = null,scheduledRetry = null,recoveryAction = null,+ interruption,+ retryPreparing = false,onResolveRecoveryAction,onReissueIsolatedRecoveryAction,reissueIsolatedRecoveryActionPending = false,@@ -6092,14 +6097,47 @@ export function IssueChatThread({return true;}+ const [submissionPending, setSubmissionPending] = useState(false);+ const [submissionTakingLonger, setSubmissionTakingLonger] = useState(false);+ const submissionRequestId = useRef<string | null>(null);+ useEffect(() => {+ const confirmed = submissionRequestId.current && comments.some(comment =>+ comment.clientRequestId === submissionRequestId.current && !("clientStatus" in comment && comment.clientStatus));+ // The previous intent's projection cannot acknowledge this submission.+ if (isRunning || confirmed) {+ setSubmissionPending(false);+ setSubmissionTakingLonger(false);+ }+ }, [isRunning, comments, submissionPending]);+ useEffect(() => {+ if (!submissionPending) return;+ const timer = window.setTimeout(() => {+ setSubmissionTakingLonger(true);+ void onRefreshLatestComments?.();+ }, 10_000);+ return () => window.clearTimeout(timer);+ }, [submissionPending, onRefreshLatestComments]);const sendComposerComment = useCallback<IssueChatThreadProps["onAdd"]>(- (body, reopen, reassignment, attachmentIds, clientRequestId, runSettings) => {+ async (body, reopen, reassignment, attachmentIds, clientRequestId, runSettings) => {pendingSubmitScrollRef.current = true;- return runSettings- ? onAdd(body, reopen, reassignment, attachmentIds, clientRequestId, runSettings)- : onAdd(body, reopen, reassignment, attachmentIds, clientRequestId);+ if (issueAssigneeAgentId) {+ submissionRequestId.current = clientRequestId ?? null;+ setSubmissionPending(true);+ setSubmissionTakingLonger(false);+ }+ try {+ await (runSettings+ ? onAdd(body, reopen, reassignment, attachmentIds, clientRequestId, runSettings)+ : onAdd(body, reopen, reassignment, attachmentIds, clientRequestId));+ setSubmissionPending(false);+ setSubmissionTakingLonger(false);+ } catch (error) {+ setSubmissionPending(error instanceof CommentSubmissionUnknownError);+ setSubmissionTakingLonger(error instanceof CommentSubmissionUnknownError);+ throw error;+ }},- [onAdd],+ [onAdd, issueAssigneeAgentId],);const runtime = usePaperclipIssueRuntime({messages,@@ -6628,6 +6666,12 @@ export function IssueChatThread({/>)))}+ {!isRunning && issueAssigneeAgentId && (submissionPending || retryPreparing || interruption?.state === "working") ? (+ <TaskChatRunnerTurn items={[]} status="queued" startedAtMs={null}+ agent={agentMap?.get(issueAssigneeAgentId)}+ agentName={agentMap?.get(issueAssigneeAgentId)?.name}+ preparationLabel={submissionTakingLonger ? "Taking longer than usual…" : undefined} />+ ) : null}{showComposer ? (<divdata-testid="issue-chat-thread-notices"diff --git a/ui/src/components/IssueRow.tsx b/ui/src/components/IssueRow.tsxindex 9bbf76d55a..9ec5b3dd64 100644--- a/ui/src/components/IssueRow.tsx+++ b/ui/src/components/IssueRow.tsx@@ -217,7 +217,12 @@ export function IssueRow({const recoveryAction = issue.activeRecoveryAction ?? null;// The row already carries the issue's own scheduled retry, so the chip can tell a retry the// scheduler is actually running from one whose due time simply passed.- const recoveryIndicator = recoveryAction && !requiresExecutionReconciliation(recoveryAction.cause)+ const recoveryIndicator = issue.interruption?.responsibility === "system" && issue.interruption.state !== "resolved"+ ? <span className="text-xs text-muted-foreground" data-testid="issue-row-interruption">+ {issue.interruption.state === "working" ? "Thinking"+ : issue.interruption.state === "retry_scheduled" ? "Trying again soon" : "Retry available"}+ </span>+ : recoveryAction && !requiresExecutionReconciliation(recoveryAction.cause)? renderRecoveryChip(recoveryAction, selected, { scheduledRetry: issue.scheduledRetry ?? null }): null;const parkedBlockerIndicator = hasAssignedBacklogBlocker(issue.blockedBy) ? (diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsxindex 9aa9471e79..c84e2edc5c 100644--- a/ui/src/components/TaskChatThread.test.tsx+++ b/ui/src/components/TaskChatThread.test.tsx@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ThemeProvider } from "@/context/ThemeContext";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { TaskChatThread } from "./TaskChatThread";+import { IssueChatThread } from "./IssueChatThread";import type {Agent,IssueDocument,@@ -84,6 +85,7 @@ vi.mock("@/hooks/useStreamlinedUiEnabled", () => ({}),}));vi.mock("@/lib/router", () => ({+ useLocation: () => ({ pathname: "/issues/issue", hash: "", search: "", key: "test", state: null }),Link: ({to,children,@@ -399,19 +401,57 @@ it.each([true, false])("keeps an upload attached when a conversation draft becomexpect(onAdd.mock.calls[0]?.[3]).toEqual([id]);});-it("does not claim the agent is working while a follow-up waits behind recovery", async () => {+it("shows Thinking during admission and clears it when the saved follow-up enters backoff", async () => {const pending = { id: "optimistic-recovery", companyId: "company", issueId: "issue", authorType: "user" as const,authorAgentId: null, authorUserId: "board", body: "Confirm the existing result.", presentation: null, metadata: null,createdAt: new Date(), updatedAt: new Date(), clientStatus: "pending" as const };- const show = (executionBlocked: boolean) => render(<TaskChatThread issueId="issue" issueStatus="blocked" executionBlocked={executionBlocked} comments={[pending]}+ const show = (accepted: boolean) => render(<TaskChatThread issueId="issue" issueStatus="blocked" executionBlocked+ comments={[{ ...pending, clientStatus: accepted ? "queued" : "pending" }]}+ interruption={accepted ? { intentId: "saved-input", responsibility: "system", state: "retry_scheduled",+ nextRetryAt: new Date(Date.now() + 30_000).toISOString(), canRetry: true, userAction: null,+ sourceRunIds: ["failed-run"], observedRunId: "failed-run" } : null}onAdd={async () => {}} issueAssigneeAgentId="agent"agentMap={new Map([["agent", { id: "agent", name: "Worker", adapterType: "paperclip_runner" } as Agent]])} />);- show(true);+ show(false);expect(container.textContent).toContain("Confirm the existing result.");+ expect(container.textContent).toContain("Thinking");+ show(true);expect(container.textContent).not.toContain("Thinking");expect(container.textContent).not.toContain("Working");- show(false);- expect(container.textContent).toContain("Working");+});++it.each((["task", "legacy"] as const).flatMap(surface =>+ ([null, "failed", "resolved"] as const).map(previousState => ({ surface, previousState })),+))("keeps $surface admission Thinking through an old $previousState projection until acknowledgement", async ({ surface, previousState }) => {+ let acknowledge!: () => void;+ const onAdd = vi.fn(() => new Promise<void>(resolve => { acknowledge = resolve; }));+ const refresh = vi.fn();+ const Component = surface === "task" ? TaskChatThread : IssueChatThread;+ render(<Component comments={[]} issueId="issue" issueAssigneeAgentId="agent"+ issueStatus="todo" onAdd={onAdd} onRefreshLatestComments={refresh}+ interruption={previousState ? { intentId: "previous-intent", responsibility: "system", state: previousState,+ nextRetryAt: null, canRetry: previousState === "failed", userAction: null,+ sourceRunIds: ["previous-run"], observedRunId: "previous-run" } : null}+ agentMap={new Map([["agent", { id: "agent", name: "Worker", adapterType: "paperclip_runner" } as Agent]])} />);+ await act(async () => { editorCallbacks.change("Save this note."); });+ const send = surface === "task"+ ? container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')+ : [...container.querySelectorAll("button")].find(button => button.textContent === "Send");+ expect(send).toBeDefined();+ vi.useFakeTimers();+ try {+ await act(async () => { send!.click(); });+ expect(onAdd).toHaveBeenCalledTimes(1);+ expect(container.textContent).toContain("Thinking");+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ expect(container.textContent).toContain("Taking longer than usual");+ expect(refresh).toHaveBeenCalledTimes(1);+ await act(async () => { acknowledge(); });+ expect(container.textContent).not.toContain("Thinking");+ expect(container.textContent).not.toContain("Taking longer than usual");+ } finally {+ vi.useRealTimers();+ }});it("prepares comment-link history and its composer before reveal", async () => {@@ -1988,6 +2028,8 @@ describe("TaskChatThread runtime transcript selection", () => {renderThread({comments: [],onAdd: async () => {},+ interruption: { intentId: null, responsibility: "user", state: "waiting_for_user", nextRetryAt: null,+ canRetry: false, userAction: "choose_model", sourceRunIds: ["model-rejected"], observedRunId: "model-rejected" },linkedRuns: [{runId: "model-rejected", runtimeMode: "native", status: "failed",errorCode: "native_provider_model_rejected",@@ -4073,7 +4115,7 @@ describe("TaskChatThread Paperclip Runner queue", () => {expect(occurrenceCount(queuedComment.body)).toBe(1);});- it.each(["run-1", null])("keeps legacy queued delivery available with target %s", (targetRunId) => {+ it.each(["run-1", null])("offers legacy interruption only with a live target (%s)", (targetRunId) => {const onInterruptQueued = vi.fn(async () => {});renderThread({comments: [@@ -4108,9 +4150,14 @@ describe("TaskChatThread Paperclip Runner queue", () => {const interrupt = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-queued-prp-1"]',);- expect(interrupt).not.toBeNull();- flushSync(() => interrupt!.click());- expect(onInterruptQueued).toHaveBeenCalledWith(targetRunId);+ if (targetRunId) {+ expect(interrupt).not.toBeNull();+ flushSync(() => interrupt!.click());+ expect(onInterruptQueued).toHaveBeenCalledWith(targetRunId);+ } else {+ expect(interrupt).toBeNull();+ expect(onInterruptQueued).not.toHaveBeenCalled();+ }});it("cancels an optimistic queued row locally before server acknowledgement", async () => {diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsxindex 81190c3312..e33b7194ea 100644--- a/ui/src/components/TaskChatThread.tsx+++ b/ui/src/components/TaskChatThread.tsx@@ -1,4 +1,5 @@import { TaskChatShimmerScope } from "@/components/task-chat/TaskChatShimmer";+import { CommentSubmissionUnknownError } from "../lib/comment-submit-result";import {ISSUE_DETAIL_CONTENT_PAINT_MARK,ISSUE_DETAIL_CONTENT_MEASURE,@@ -850,6 +851,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {const projectedComments = useMemo(() =>comments.flatMap((comment) => {+ if (comment.authorType === "system" && comment.metadata?.recoveryResponsibility === "system") return [];if (statusRelevance.isHistoricalNotice(comment)) return [];if (isRedundantAiRecoveryNotice(comment, interactions)) return [];if (comment.body !== LEGACY_WITHHELD_RUN_COMMENT || !comment.runId)@@ -1556,7 +1558,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {!lastCommentIdByRun.has(source.id);if (executionWait) {settledRunIds.add(source.id);- if (historical) continue;+ if (historical || props.interruption) continue;const wait = meta?.resultJson?.executionWait;const waitKey = wait && typeof wait === "object" && "recoveryActionId" in wait? String(wait.recoveryActionId)@@ -1700,7 +1702,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {: undefined;const finishedAt =meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt;- if (!historical) entriesWithFailures.push({+ if (!historical && (!props.interruption || credentialAccess ||+ (props.interruption.responsibility === "user" &&+ ["native_provider_model_rejected", "native_provider_approval_required"].includes(code)))) entriesWithFailures.push({ms: toMs(finishedAt),order: 3,id,@@ -1764,7 +1768,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {? `Workspace setup failed before the agent started. ${retryDetail}`: `The run failed (${code}). ${retryDetail}`;const id = `${source.id}:failure`;- if (!historical) entriesWithFailures.push({+ if (!historical && (!props.interruption || credentialAccess)) entriesWithFailures.push({ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),order: 3,id,@@ -1847,7 +1851,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {} else if (!sourceHasNativeStop && !sourceHasLegacyStop && !lastCommentIdByRun.has(source.id)) {settledRunIds.add(source.id);const id = `${source.id}:terminal-notice`;- if (!historical) entriesWithFailures.push({+ if (!historical && (!props.interruption || credentialAccess)) entriesWithFailures.push({ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),order: 3,id,@@ -1880,7 +1884,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {!sourceHasNativeResponse) {const id = `${source.id}:terminal-notice`;- if (!historical) entriesWithFailures.push({+ if (!historical && (!props.interruption || credentialAccess)) entriesWithFailures.push({ms: toMs(meta?.finishedAt ?? meta?.startedAt ?? meta?.createdAt),order: 3,id,@@ -2173,6 +2177,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {};}, [orderedEntries,+ props.interruption,statusRelevance,canRetryFailedRun,interactions,@@ -2612,44 +2617,58 @@ export function TaskChatThread(props: TaskChatThreadProps) {[handleRuntimeRequestDecision, onSkipInteraction],);const runtimeComposerDisabledReason = composerDisabledReason ?? undefined;- const assigneeUsesPaperclipRunner = Boolean(- issueAssigneeAgentId &&- agentMap?.get(issueAssigneeAgentId)?.adapterType === "paperclip_runner",- );+ const hasAgentAssignee = Boolean(issueAssigneeAgentId);const [runnerSubmissionPending, setRunnerSubmissionPending] = useState(false);+ const [submissionTakingLonger, setSubmissionTakingLonger] = useState(false);+ const submissionRequestId = useRef<string | null>(null);useEffect(() => {- if (tailRunId) setRunnerSubmissionPending(false);- }, [tailRunId]);+ const confirmed = submissionRequestId.current && comments.some(comment =>+ comment.clientRequestId === submissionRequestId.current && !("clientStatus" in comment && comment.clientStatus));+ // The previous intent's projection cannot acknowledge this submission.+ if (tailRunId || confirmed) {+ setRunnerSubmissionPending(false);+ setSubmissionTakingLonger(false);+ }+ }, [tailRunId, comments, runnerSubmissionPending]);useEffect(() => {if (!runnerSubmissionPending || tailRunId) return;const timeout = window.setTimeout(- () => setRunnerSubmissionPending(false),+ () => {+ setSubmissionTakingLonger(true);+ void props.onRefreshLatestComments?.();+ },10_000,);return () => window.clearTimeout(timeout);}, [runnerSubmissionPending, tailRunId]);const handleThreadAdd = useCallback(async (...args: Parameters<typeof onAdd>) => {- if (assigneeUsesPaperclipRunner) setRunnerSubmissionPending(true);+ if (hasAgentAssignee) {+ submissionRequestId.current = args[4] ?? null;+ setRunnerSubmissionPending(true);+ setSubmissionTakingLonger(false);+ }try {await onAdd(...args);+ setRunnerSubmissionPending(false);+ setSubmissionTakingLonger(false);if (selectedPendingInput?.kind === "durable" && selectedPendingInput.interaction.kind === "ask_user_questions") {dismissQuestion(selectedPendingInput.interaction.id);setSelectedPendingKey(null);setTakeoverMode("normal");}} catch (error) {- setRunnerSubmissionPending(false);+ setRunnerSubmissionPending(error instanceof CommentSubmissionUnknownError);+ setSubmissionTakingLonger(error instanceof CommentSubmissionUnknownError);throw error;}},- [assigneeUsesPaperclipRunner, onAdd, selectedPendingInput, dismissQuestion],+ [hasAgentAssignee, onAdd, selectedPendingInput, dismissQuestion],);const optimisticRunnerStartup =- assigneeUsesPaperclipRunner &&- !props.executionBlocked &&+ hasAgentAssignee &&!tailRunId &&- (runnerSubmissionPending ||+ (props.retryPreparing || props.interruption?.state === "working" || runnerSubmissionPending ||commentItems.some((item) =>item.kind === "message" &&@@ -3038,7 +3057,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {>{prepareInitialContent ? (<>- {items.length === 0 && !tailRunId ? (+ {items.length === 0 && !tailRunId && !optimisticRunnerStartup ? (<divclassName={isMobile ? undefined : "min-h-0 flex-1 overflow-y-auto"@@ -3117,6 +3136,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {agentIcon={visibleTailAgentIcon}agent={tailAgent ?? (tailAgentId ? { id: tailAgentId } : undefined)}items={tailItems}+ preparationLabel={optimisticRunnerStartup && submissionTakingLonger ? "Taking longer than usual…" : undefined}allowSummaryFallback={!paperclipRunnerTail ||terminalHydratedRunIds.has(tailRunId ?? "") ||tailEntries.some((entry) => entry.kind === "run_terminal")}diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsxindex f25f8b5ddb..736987aaa1 100644--- a/ui/src/components/issue-properties/IssueProperties.tsx+++ b/ui/src/components/issue-properties/IssueProperties.tsx@@ -606,7 +606,7 @@ export function IssueProperties({() => isMainIssueWorkspace({ issue, project: issueProject }),[issue, issueProject],);- const showWorkspaceDetailLink = Boolean(issue.executionWorkspaceId) && !issueUsesMainWorkspace+ const showWorkspaceDetailLink = Boolean(issue.executionWorkspaceId && issue.currentExecutionWorkspace?.id === issue.executionWorkspaceId) && !issueUsesMainWorkspace&& experimentalSettings?.enableIsolatedWorkspaces === true;const workspaceRuntimeConfig = issueUsesMainWorkspace? nulldiff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsxindex ab2828867c..97d9b6ac00 100644--- a/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx+++ b/ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx@@ -80,10 +80,10 @@ describe("TaskChatQueuedMessages", () => {return props;}- it("shows the saved message's wait reason and removes it when admission succeeds", () => {+ it("keeps saved input visible without duplicating the task status", () => {const message = "Waiting for the previous environment to stop. Your message will start automatically.";render({ queue: { ...queue, executionWait: { reason: "remote_cleanup", message } } });- expect(container.querySelector('[role="status"]')?.textContent).toContain(message);+ expect(container.textContent).not.toContain(message);expect(container.textContent).toContain("First queued message");render();expect(container.textContent).not.toContain(message);@@ -361,7 +361,8 @@ describe("TaskChatQueuedMessages", () => {).toBeNull();});- it.each(["run-1", null])("delivers legacy queued messages with target %s", async (targetRunId) => {+ it("delivers legacy queued messages to a live target", async () => {+ const targetRunId = "run-1";const onInterrupt = vi.fn().mockResolvedValue(undefined);render({queue: {@@ -393,4 +394,11 @@ describe("TaskChatQueuedMessages", () => {),).toBeNull();});+ it("hides Steer and Interrupt without a live target while leaving saved messages editable", () => {+ render({ queue: { ...queue, targetRunId: null, protocol: "legacy", steeringDisposition: "unsupported" } });+ expect(container.textContent).toContain("First queued message");+ expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')).toBeNull();+ expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull();+ });+});diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.tsxindex baf0bbf799..691b462220 100644--- a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx+++ b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx@@ -146,7 +146,7 @@ function SortableQueuedMessage({{label}</span>- {queue.protocol === "legacy" || entry.source?.requiresFreshSession ? (+ {queue.targetRunId && (queue.protocol === "legacy" || entry.source?.requiresFreshSession ? (<buttontype="button"onClick={onInterrupt}@@ -178,7 +178,7 @@ function SortableQueuedMessage({)}Steer</button>- )}+ ))}<buttontype="button"@@ -382,11 +382,6 @@ export function TaskChatQueuedMessages({data-testid="task-chat-queued-messages"aria-label="Queued messages">- {queue.executionWait && (- <div role="status" aria-live="polite" className="px-3 py-1.5 text-xs text-muted-foreground">- {queue.executionWait.message}- </div>- )}<DndContextsensors={sensors}collisionDetection={closestCenter}diff --git a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx b/ui/src/components/task-chat/TaskChatRunnerTurn.tsxindex 59d7b2e555..81cf7b089d 100644--- a/ui/src/components/task-chat/TaskChatRunnerTurn.tsx+++ b/ui/src/components/task-chat/TaskChatRunnerTurn.tsx@@ -122,6 +122,7 @@ export function TaskChatRunnerTurn({items,status,execution,+ preparationLabel,startedAtMs,finishedAtMs,activityUnavailable = false,@@ -138,6 +139,8 @@ export function TaskChatRunnerTurn({items: readonly TaskChatItem[];status: string;execution?: ExecutionProjection | null;+ /** Presentation only while Send/Retry admission has no run yet. */+ preparationLabel?: string;startedAtMs: number | null;finishedAtMs?: number | null;activityUnavailable?: boolean;@@ -152,7 +155,8 @@ export function TaskChatRunnerTurn({) => void | Promise<void>;}) {const terminal = isTerminalRunStatus(status);- const waitingLabel = !terminal && execution?.phase === "waiting_for_provider" ? execution.label : null;+ const waitingLabel = !terminal && execution?.phase === "waiting_for_provider" ? execution.label+ : !runId && !terminal ? preparationLabel ?? null : null;const yielded = items.some((item) =>item.kind === "protocol" &&diff --git a/ui/src/components/task-chat/transcript-adapter.test.ts b/ui/src/components/task-chat/transcript-adapter.test.tsindex eda571be8f..7dd3c9104b 100644--- a/ui/src/components/task-chat/transcript-adapter.test.ts+++ b/ui/src/components/task-chat/transcript-adapter.test.ts@@ -221,7 +221,7 @@ describe("completion tool feed visibility", () => {const [notice] = transcriptToTaskChatItems([{kind: "provider_activity", ts: TS, family: "provider_notice", eventType: "provider.notice.recorded",status: "informational", title: "Provider notice", summary,- payload: { noticeId: "long-notice", summary },+ payload: { noticeId: "long-notice", summary, userActionable: true },}], { runId: "notice", running: false });expect(notice.kind === "protocol" && notice.surface === "provider_activity" &¬ice.details.find((detail) => detail.label === "Summary")?.value).toBe(summary);@@ -240,7 +240,7 @@ describe("completion tool feed visibility", () => {})),{ kind: "provider_activity", ts: TS, family: "provider_notice", eventType: "provider.notice.recorded",status: "informational", title: "Provider notice", summary: "Repository is not trusted",- payload: { noticeId: "notice", summary: "Repository is not trusted" } },+ payload: { noticeId: "notice", summary: "Repository is not trusted", userActionable: true } },];const parsed = transcriptToTaskChatItems(entries, { runId: "finish-visibility", running });expect(parsed).toHaveLength(4);@@ -858,19 +858,7 @@ describe("transcriptToTaskChatItems protocol surfaces", () => {description: "Canonical event details",},]);- expect(- notice?.kind === "protocol" && notice.surface === "provider_activity"- ? notice.details- : [],- ).toEqual(- expect.arrayContaining([- { label: "Severity", value: "warning", mono: false },- { label: "Category", value: "config", mono: false },- { label: "Scope", value: "environment", mono: false },- { label: "Recoverable", value: "Yes", mono: false },- { label: "User Actionable", value: "No", mono: false },- ]),- );+ expect(notice).toBeUndefined();});it("retains every canonical provider family for live and settled rendering", () => {@@ -898,7 +886,7 @@ describe("transcriptToTaskChatItems protocol surfaces", () => {status: index % 2 === 0 ? "running" : "completed",title: family,summary: `Visible ${family}`,- payload: { [`${family}Id`]: `${family}-1` },+ payload: { [`${family}Id`]: `${family}-1`, ...(family === "provider_notice" ? { userActionable: true } : {}) },}));const items = transcriptToTaskChatItems(entries, {...opts,diff --git a/ui/src/components/task-chat/transcript-adapter.ts b/ui/src/components/task-chat/transcript-adapter.tsindex b36559ee19..cbdfa50196 100644--- a/ui/src/components/task-chat/transcript-adapter.ts+++ b/ui/src/components/task-chat/transcript-adapter.ts@@ -875,6 +875,12 @@ export function transcriptToTaskChatItems(break;}case "provider_activity": {+ // Use producer classification, including the legacy generic Codex+ // categories, never message-text matching. The run transcript still+ // retains these diagnostics.+ if (entry.family === "provider_notice" && (entry.payload.userActionable !== true ||+ ["error", "warning", "guardianWarning", "configWarning", "deprecationNotice", "windows_worldWritableWarning"]+ .includes(String(entry.payload.category)))) break;const key = `provider:${providerActivityKey(entry)}`;const item = providerActivityItem(entry, runId, i);const existingIndex = protocolIndexByKey.get(key);diff --git a/ui/src/hooks/useTaskRetry.test.tsx b/ui/src/hooks/useTaskRetry.test.tsxnew file mode 100644index 0000000000..1cbec6ee9f--- /dev/null+++ b/ui/src/hooks/useTaskRetry.test.tsx@@ -0,0 +1,52 @@+// @vitest-environment jsdom+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Issue } from "@paperclipai/shared";+import { useTaskRetry } from "./useTaskRetry";+import { issuesApi } from "../api/issues";+vi.mock("../api/issues", () => ({ issuesApi: { retryTask: vi.fn() } }));+const issue = { id: "task", interruption: { observedRunId: "failed-run" } } as Issue;+function View({ task = issue }: { task?: Issue }) {+ const retry = useTaskRetry(task);+ return <><button onClick={retry.retry}>Retry</button>{retry.optimistic && <span>Thinking</span>}{retry.takingLonger && <span>Taking longer than usual…</span>}</>;+}+describe("optimistic task Retry", () => {+ let container: HTMLDivElement, root: Root, client: QueryClient;+ beforeEach(() => {+ vi.clearAllMocks(); container = document.createElement("div"); document.body.append(container); root = createRoot(container);+ client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ });+ afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); vi.useRealTimers(); });+ async function render(task = issue) { await act(async () => root.render(<QueryClientProvider client={client}><View task={task} /></QueryClientProvider>)); }+ it("paints Thinking before admission resolves and shares the same request across double clicks", async () => {+ let settle!: (value: Awaited<ReturnType<typeof issuesApi.retryTask>>) => void;+ vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(resolve => { settle = resolve; }));+ await render();+ await act(async () => container.querySelector("button")!.click());+ expect(container.textContent).toContain("Thinking");+ const request = vi.mocked(issuesApi.retryTask).mock.calls[0][1];+ await act(async () => container.querySelector("button")!.click());+ expect(vi.mocked(issuesApi.retryTask).mock.calls[1][1]).toEqual(request);+ await act(async () => { settle({ requestId: "intent", accepted: true, stale: false, presentation: null }); });+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });+ expect(container.textContent).not.toContain("Thinking");+ });+ it("reconciles an unknown admission with the original idempotency key after ten seconds", async () => {+ vi.useFakeTimers(); vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(() => {}));+ await render(); await act(async () => container.querySelector("button")!.click());+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ expect(container.textContent).toContain("Taking longer than usual…");+ expect(issuesApi.retryTask).toHaveBeenCalledTimes(2);+ expect(vi.mocked(issuesApi.retryTask).mock.calls[1]).toEqual(vi.mocked(issuesApi.retryTask).mock.calls[0]);+ });+ it("does not let an old task response settle a newer task's optimistic request", async () => {+ const settlements: Array<(value: Awaited<ReturnType<typeof issuesApi.retryTask>>) => void> = [];+ vi.mocked(issuesApi.retryTask).mockImplementation(() => new Promise(resolve => settlements.push(resolve)));+ await render(); await act(async () => container.querySelector("button")!.click());+ await render({ ...issue, id: "other-task" }); await act(async () => container.querySelector("button")!.click());+ await act(async () => settlements[0]({ requestId: "old", accepted: true, stale: false, presentation: null }));+ expect(container.textContent).toContain("Thinking");+ });+});diff --git a/ui/src/hooks/useTaskRetry.ts b/ui/src/hooks/useTaskRetry.tsnew file mode 100644index 0000000000..71544b9b00--- /dev/null+++ b/ui/src/hooks/useTaskRetry.ts@@ -0,0 +1,64 @@+import { useEffect, useRef, useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import type { Issue } from "@paperclipai/shared";+import { ApiError } from "../api/client";+import { issuesApi } from "../api/issues";+import { queryKeys } from "../lib/queryKeys";++export function useTaskRetry(issue: Issue | undefined) {+ const queryClient = useQueryClient();+ const request = useRef<{ issueId: string; idempotencyKey: string; observedRunId: string | null } | null>(null);+ const [optimistic, setOptimistic] = useState(false);+ const [takingLonger, setTakingLonger] = useState(false);+ const mutation = useMutation({+ mutationFn: ({ issueId, ...body }: { issueId: string; idempotencyKey: string; observedRunId: string | null }) =>+ issuesApi.retryTask(issueId, body),+ onSuccess: async (result, variables) => {+ const isCurrent = request.current?.idempotencyKey === variables.idempotencyKey;+ if (isCurrent) request.current = null;+ {+ queryClient.setQueryData<Issue>(queryKeys.issues.detail(variables.issueId), current =>+ current ? { ...current, interruption: result.presentation } : current);+ await Promise.all([queryKeys.issues.detail(variables.issueId), queryKeys.issues.runs(variables.issueId),+ queryKeys.issues.liveRuns(variables.issueId), queryKeys.issues.activeRun(variables.issueId)].map(queryKey =>+ queryClient.invalidateQueries({ queryKey })));+ }+ if (isCurrent && !request.current) { setOptimistic(false); setTakingLonger(false); }+ },+ onError: (error, variables) => {+ if (request.current?.idempotencyKey !== variables.idempotencyKey) return;+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {+ request.current = null;+ setOptimistic(false);+ setTakingLonger(false);+ } else {+ setTakingLonger(true);+ }+ },+ });+ useEffect(() => {+ if (!optimistic) return;+ const timer = window.setTimeout(() => {+ setTakingLonger(true);+ // Reconcile the identical durable request after a lost response. This+ // creates neither a second generation nor a second optimistic tail.+ if (request.current) mutation.mutate(request.current);+ }, 10_000);+ return () => window.clearTimeout(timer);+ }, [optimistic]);+ useEffect(() => {+ request.current = null;+ setOptimistic(false);+ setTakingLonger(false);+ mutation.reset();+ }, [issue?.id]);+ return { retry: () => {+ if (!issue) return;+ mutation.reset();+ request.current ??= { issueId: issue.id, idempotencyKey: crypto.randomUUID(),+ observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null };+ setOptimistic(true);+ setTakingLonger(false);+ mutation.mutate(request.current);+ }, optimistic, takingLonger, error: mutation.error };+}diff --git a/ui/src/lib/recovery-display.ts b/ui/src/lib/recovery-display.tsindex a645e751f7..8c064391ac 100644--- a/ui/src/lib/recovery-display.ts+++ b/ui/src/lib/recovery-display.ts@@ -108,6 +108,9 @@ export function deriveActiveRecoveryDisplayState(action: RecoveryDisplayInput,context?: RecoveryLivenessContext,): ActiveRecoveryDisplayState | null {+ // System repair is represented by the task's interruption projection.+ // Diagnostics may still inspect the full recovery record.+ if (action.ownerType === "system") return null;if (action.cause === "native_workspace_sync_out_unsafe_archive") return null;const state = deriveRecoveryDisplayState(action, context);return state === "resolved" ? null : state;diff --git a/ui/src/pages/Inbox.test.tsx b/ui/src/pages/Inbox.test.tsxindex 6e6c41fe19..24fe25a584 100644--- a/ui/src/pages/Inbox.test.tsx+++ b/ui/src/pages/Inbox.test.tsx@@ -32,6 +32,7 @@ const apiMocks = vi.hoisted(() => ({issuesList: vi.fn(),issuesCount: vi.fn(),issueLabels: vi.fn(),+ retryTask: vi.fn(),archiveFromInbox: vi.fn(),unarchiveFromInbox: vi.fn(),agentsList: vi.fn(),@@ -74,6 +75,7 @@ vi.mock("../api/issues", () => ({listCompact: apiMocks.issuesList,count: apiMocks.issuesCount,listLabels: apiMocks.issueLabels,+ retryTask: apiMocks.retryTask,markRead: vi.fn(),markUnread: vi.fn(),archiveFromInbox: apiMocks.archiveFromInbox,@@ -148,8 +150,8 @@ import {} from "./Inbox";vi.mock("@/lib/router", () => ({- Link: ({ children, className, ...props }: ComponentProps<"a">) => (- <a className={className} {...props}>{children}</a>+ Link: ({ children, className, to, ...props }: ComponentProps<"a"> & { to?: string }) => (+ <a className={className} href={to} {...props}>{children}</a>),useLocation: () => routerMock.location,useNavigate: () => routerMock.navigate,@@ -357,6 +359,7 @@ function resetInboxApiMocks() {apiMocks.issuesList.mockResolvedValue([]);apiMocks.issuesCount.mockResolvedValue({ count: 0 });apiMocks.issueLabels.mockResolvedValue([]);+ apiMocks.retryTask.mockReset().mockResolvedValue({ accepted: true, requestId: "retry-intent", presentation: null });apiMocks.archiveFromInbox.mockResolvedValue({ id: "issue-1", archivedAt: new Date() });apiMocks.unarchiveFromInbox.mockResolvedValue({ id: "issue-1", archivedAt: new Date() });apiMocks.agentsList.mockResolvedValue([]);@@ -414,8 +417,8 @@ describe("Inbox toolbar", () => {await vi.waitFor(() => {expect(apiMocks.heartbeatRunsList).toHaveBeenCalled();expect(queryClient.isFetching()).toBe(0);- for (const id of visible) expect(container.querySelector(`a[to$="/runs/${id}"]`)).not.toBeNull();- for (const id of hidden) expect(container.querySelector(`a[to$="/runs/${id}"]`)).toBeNull();+ for (const id of visible) expect(container.querySelector(`a[href$="/runs/${id}"]`)).not.toBeNull();+ for (const id of hidden) expect(container.querySelector(`a[href$="/runs/${id}"]`)).toBeNull();});} finally {act(() => root.unmount());@@ -1396,6 +1399,20 @@ describe("FailedRunInboxRow", () => {container.remove();});+ it("uses task presentation instead of infrastructure errors and keeps Retry in the task", () => {+ const root = createRoot(container);+ const issue = createIssue({ interruption: { intentId: "saved-input", responsibility: "system", state: "failed",+ nextRetryAt: null, canRetry: true, userAction: null, sourceRunIds: ["run-1"], observedRunId: "run-1" } });+ act(() => root.render(<FailedRunInboxRow run={createFailedRun({ issueId: issue.id, error: "Internal process identity missing" })}+ issueById={new Map([[issue.id, issue]])} agentName="Worker" issueLinkState={null}+ onDismiss={() => {}} onRetry={() => {}} isRetrying={false} />));+ expect(container.textContent).toContain("Couldn’t finish this attempt. Your message is saved.");+ expect(container.textContent).not.toContain("Internal process identity missing");+ expect(container.querySelector("a")?.getAttribute("href")).toBe(`/issues/${issue.id}`);+ expect(container.textContent).toContain("Retry");+ act(() => root.unmount());+ });+it("suppresses accent hover styling when selected", () => {const root = createRoot(container);const run = createFailedRun();diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsxindex 972647bc8e..5913637d3f 100644--- a/ui/src/pages/Inbox.tsx+++ b/ui/src/pages/Inbox.tsx@@ -10,6 +10,7 @@ import { ApiError } from "../api/client";import { dashboardApi } from "../api/dashboard";import { executionWorkspacesApi } from "../api/execution-workspaces";import { issuesApi } from "../api/issues";+import { useSecondTick } from "../hooks/useSecondTick";import { agentsApi } from "../api/agents";import { heartbeatsApi } from "../api/heartbeats";import { instanceSettingsApi } from "../api/instanceSettings";@@ -298,6 +299,7 @@ function approvalStatusLabel(status: Approval["status"]): string {}function readIssueIdFromRun(run: HeartbeatRun): string | null {+ if (run.issueId) return run.issueId;const context = run.contextSnapshot;if (!context) return null;@@ -383,7 +385,17 @@ export function FailedRunInboxRow({}) {const issueId = readIssueIdFromRun(run);const issue = issueId ? issueById.get(issueId) ?? null : null;- const displayError = runFailureMessage(run);+ const interruption = issue?.interruption;+ useSecondTick(interruption?.state === "retry_scheduled");+ const retrySeconds = Math.max(0, Math.ceil((Date.parse(interruption?.nextRetryAt ?? "") - Date.now()) / 1000));+ const displayError = isRetrying || interruption?.state === "working" ? "Thinking"+ : interruption?.state === "retry_scheduled" ? `Trying again in ${retrySeconds}s…`+ : interruption?.state === "failed" ? "Couldn’t finish this attempt. Your message is saved."+ : interruption?.state === "waiting_for_user" ? ({+ approval: "Approval required", reconnect: "Reconnect account", assign_agent: "Assign an agent", choose_model: "Choose a supported model",+ resume: "Work is paused", budget: "Budget limit reached",+ }[interruption.userAction ?? "resume"]) : runFailureMessage(run);+ const retryAvailable = !interruption || interruption.canRetry;const showUnreadSlot = unreadState !== null;const showUnreadDot = unreadState === "visible" || unreadState === "fading";@@ -417,7 +429,7 @@ export function FailedRunInboxRow({</span>) : null}<Link- to={`/agents/${run.agentId}/runs/${run.id}`}+ to={issueId ? `/issues/${issueId}` : `/agents/${run.agentId}/runs/${run.id}`}className={cn("flex min-w-0 flex-1 items-start gap-2 no-underline text-inherit transition-colors",selected ? "hover:bg-transparent" : "hover:bg-accent/50",@@ -442,7 +454,7 @@ export function FailedRunInboxRow({)}</span><span className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">- <StatusBadge status={run.status} />+ {!interruption && <StatusBadge status={run.status} />}{linkedAgentName && issue ? <span>{linkedAgentName}</span> : null}<span className="truncate max-w-(--sz-300px)">{displayError}</span><span>{timeAgo(run.createdAt)}</span>@@ -453,7 +465,7 @@ export function FailedRunInboxRow({{onArchive ? (<InboxArchiveButton onArchive={onArchive} disabled={archiveDisabled} />) : null}- <Button+ {retryAvailable && <Buttontype="button"variant="outline"size="sm"@@ -462,8 +474,8 @@ export function FailedRunInboxRow({disabled={isRetrying}><RotateCcw className="mr-1.5 h-3.5 w-3.5" />- {isRetrying ? "Retrying…" : "Retry"}- </Button>+ {isRetrying ? "Thinking" : "Retry"}+ </Button>}{!showUnreadSlot && (<buttontype="button"@@ -477,7 +489,7 @@ export function FailedRunInboxRow({</div></div><div className="mt-3 flex gap-2 sm:hidden">- <Button+ {retryAvailable && <Buttontype="button"variant="outline"size="sm"@@ -486,8 +498,8 @@ export function FailedRunInboxRow({disabled={isRetrying}><RotateCcw className="mr-1.5 h-3.5 w-3.5" />- {isRetrying ? "Retrying…" : "Retry"}- </Button>+ {isRetrying ? "Thinking" : "Retry"}+ </Button>}{!showUnreadSlot && (<buttontype="button"@@ -1334,9 +1346,10 @@ function StreamlinedInbox({const failedRuns = useMemo(() =>getLatestFailedRunsByAgent(heartbeatRuns ?? []).filter(- (r) => !isInboxEntityDismissed(dismissedAtByKey, `run:${r.id}`, r.createdAt),+ (r) => !isInboxEntityDismissed(dismissedAtByKey, `run:${r.id}`, r.createdAt)+ && issueById.get(readIssueIdFromRun(r) ?? "")?.interruption?.state !== "resolved",),- [heartbeatRuns, dismissedAtByKey],+ [heartbeatRuns, dismissedAtByKey, issueById],);const approvalsToRender = useMemo(() => {let filtered = getApprovalsForTab(approvals ?? [], tab, allApprovalFilter, currentUserId);@@ -1819,9 +1832,26 @@ function StreamlinedInbox({});const [retryingRunIds, setRetryingRunIds] = useState<Set<string>>(new Set());+ const retryRequestKeys = useRef(new Map<string, string>());const retryRunMutation = useMutation({mutationFn: async (run: HeartbeatRun) => {+ const issueId = readIssueIdFromRun(run);+ if (issueId) {+ let idempotencyKey = retryRequestKeys.current.get(run.id);+ if (!idempotencyKey) {+ idempotencyKey = crypto.randomUUID();+ retryRequestKeys.current.set(run.id, idempotencyKey);+ }+ const result = await issuesApi.retryTask(issueId, { idempotencyKey, observedRunId: run.id }).catch(error => {+ if (error instanceof ApiError && error.status >= 400 && error.status < 500)+ retryRequestKeys.current.delete(run.id);+ throw error;+ });+ queryClient.setQueryData<Issue>(queryKeys.issues.detail(issueId), current =>+ current ? { ...current, interruption: result.presentation } : current);+ return { newRun: { runId: null, issueId }, originalRun: run };+ }const result = await agentsApi.retryFailedRun(run.agentId,run.id,@@ -1833,6 +1863,7 @@ function StreamlinedInbox({setRetryingRunIds((prev) => new Set(prev).add(run.id));},onSuccess: ({ newRun, originalRun }) => {+ retryRequestKeys.current.delete(originalRun.id);queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId) });queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(originalRun.companyId, originalRun.agentId) });if (newRun.runId)diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex 3d2bdb95ae..edb17b776b 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -1,3 +1,4 @@+import { useTaskRetry } from "../hooks/useTaskRetry";import { grokBotApi } from "@/api/grokBot";import { WorkspaceBaseRefRecoveryProvider } from "../components/WorkspaceBaseRefRecovery";import { WorkspaceRetryControl } from "../components/WorkspaceRetryButton";@@ -1199,6 +1200,8 @@ function InboxMobileToolbar({type IssueDetailChatTabProps = {executionBlocked?: boolean;+ interruption?: Issue["interruption"];+ retryPreparing?: boolean;queryIssueId?: string;browsers?: import("@paperclipai/shared").TaskBrowser[];onOpenBrowser?: (browserId: string) => void;@@ -1357,6 +1360,8 @@ const DesignSandboxTaskThread = lazy(() => import("../components/design-sandbox/const IssueDetailChatTab = memo(function IssueDetailChatTab({executionBlocked,+ interruption,+ retryPreparing,queryIssueId,browsers,onOpenBrowser,@@ -2510,6 +2515,8 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({<EmailThreadProvider companyId={companyId} issueId={issueId}><ThreadComponentexecutionBlocked={executionBlocked}+ interruption={interruption}+ retryPreparing={retryPreparing}key={conversationMode ? draftKey : issueId}{...(!classicTaskInterfaceEnabled ? { creationActivity: resolvedActivity } : {})}onOpenSkill={onOpenSkill}@@ -3232,6 +3239,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSif (issueId) void prefetchIssueThread(queryClient, issueId);}, [issueId, queryClient]);const issue = queriedIssue ?? conversation?.issue ?? draftIssue;+ const taskRetry = useTaskRetry(issue ?? undefined);const resolveWritableIssueId = async () => {if (!conversation) return issueId!;const resolved = await conversation.ensureIssue();@@ -3978,7 +3986,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSconst threadComments = useMemo(() =>- mergeIssueComments(comments ?? [], optimisticComments).map((comment) => {+ mergeIssueComments(comments ?? [], optimisticComments)+ .filter(comment => !(comment.authorType === "system" && comment.metadata?.recoveryResponsibility === "system"))+ .map((comment) => {if ("clientId" in comment && comment.clientId)commentRenderKeys.current.set(comment.id, comment.clientId);const clientId = commentRenderKeys.current.get(comment.id);@@ -7784,16 +7794,15 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSissueCacheRefs={issueCacheRefs}/>- {resolvedDetailTab === "chat" && !issue.executionBlocker?.workspaceRecovery && (+ {resolvedDetailTab === "chat" && !issue.interruption && !issue.executionBlocker?.workspaceRecovery && (<WorkspaceExportRecovery key={`workspace-export:${issue.activeRecoveryAction?.id ?? issue.id}`}className={shellSectionClass}action={issue.activeRecoveryAction ?? null} />)}- {resolvedDetailTab === "chat" && issue.executionBlocker && (- <ExecutionBlockerNotice className={shellSectionClass} companyId={issue.companyId} issueId={issue.id}- issueStatus={issue.status} canManage={canManageBoardRuntime && canResolveBoardRecoveryAction}- canRecover={canResolveBoardRecoveryAction}- blocker={issue.executionBlocker} onRetried={invalidateIssueDetail} />+ {resolvedDetailTab === "chat" && (+ <ExecutionBlockerNotice className={shellSectionClass} presentation={issue.interruption}+ canRetry={canResolveBoardRecoveryAction} onRetry={taskRetry.retry}+ optimistic={taskRetry.optimistic} takingLonger={taskRetry.takingLonger} error={taskRetry.error} />)}{issue.status === "in_review" && issue.externalConversationState === "waiting" && (@@ -8124,6 +8133,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS}}><IssueDetailChatTabexecutionBlocked={Boolean(issue.executionBlocker)}+ interruption={issue.interruption}+ retryPreparing={taskRetry.optimistic}queryIssueId={issueId ?? issue.id}onOpenSkill={handleOpenSkill}browsers={browserQuery.data}@@ -8177,7 +8188,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskSblockerAttention={issue.blockerAttention ?? null}successfulRunHandoff={issue.successfulRunHandoff ?? null}scheduledRetry={issue.scheduledRetry ?? null}- recoveryAction={issue.activeRecoveryAction?.cause === "native_workspace_finalization_owner_unverified" ? null : issue.activeRecoveryAction ?? null}+ recoveryAction={issue.interruption?.responsibility === "system" || issue.activeRecoveryAction?.cause === "native_workspace_finalization_owner_unverified" ? null : issue.activeRecoveryAction ?? null}onResolveRecoveryAction={handleResolveRecoveryAction}onReissueIsolatedRecoveryAction={handleReissueIsolatedRecoveryAction@@ -8362,7 +8373,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS}resumeAssigneePending={resumeAssigneeAgent.isPending}onTryAgainNoLiveExecutionPath={- issue.status === "blocked" && issue.activeRecoveryAction+ issue.status === "blocked" && !issue.interruption && issue.activeRecoveryAction? handleTryAgainNoLiveExecutionPath: undefined}diff --git a/ui/storybook/stories/recovery/execution-blocker-notice.stories.tsx b/ui/storybook/stories/recovery/execution-blocker-notice.stories.tsxindex e261083b12..36a79e9a7a 100644--- a/ui/storybook/stories/recovery/execution-blocker-notice.stories.tsx+++ b/ui/storybook/stories/recovery/execution-blocker-notice.stories.tsx@@ -1,151 +1,70 @@import type { Meta, StoryObj } from "@storybook/react-vite";+import type { TaskInterruptionPresentation } from "@paperclipai/shared";import { useState } from "react";import { expect, userEvent, within } from "storybook/test";-import { RecoveryNoticeFixture } from "../../support/workspace-file-recovery/fixture";import { ExecutionBlockerNotice } from "@/components/ExecutionBlockerNotice";import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble";import { TaskChatLiveRunPill } from "@/components/task-chat/TaskChatLiveRunPill";+const failed: TaskInterruptionPresentation = {+ intentId: "saved-request", responsibility: "system", state: "failed", nextRetryAt: null,+ canRetry: true, userAction: null, sourceRunIds: ["stopped-run"], observedRunId: "stopped-run",+};const meta = {id: "task-chat-recovery-notice",title: "Projects and execution/Recovery/Task chat/Recovery notice",component: ExecutionBlockerNotice,- parameters: { docs: { story: { inline: false } }, paperclip: {- capabilities: ["recovery/diagnosis"], implementation: "production", boundary: "fixtures",- notes: "Production task notice with source-bound recovery reads. Automatic recovery stays quiet; unresolved holds expose inspection without infrastructure certification. Fixture APIs do not prove live provider recovery.",+ parameters: { paperclip: {+ capabilities: ["recovery/diagnosis", "recovery/exhaustion"], implementation: "production", boundary: "fixtures",+ notes: "Production task status driven by the shared presentation contract. Former inspection and certification examples now exercise ordinary Retry, quiet preparation, and permission gating. Fixture transitions do not prove provider recovery or durable admission.",} },- decorators: [(Story, context) => <RecoveryNoticeFixture key={context.id} state={context.parameters.recoveryState ?? "blocked"}>- <div className="mx-auto flex w-full max-w-2xl flex-col gap-4"><Story /></div>- </RecoveryNoticeFixture>],- args: {- companyId: "storybook-company", issueId: "storybook-recovery", issueStatus: "blocked", canManage: true, onRetried: () => {},- blocker: {- recoveryActionId: "recovery", runId: "stopped-run", agentId: "agent",- cause: "native_continuation_requires_reconciliation",- nextAction: "The previous action's outcome needs inspection before work can continue.",- },- },+ decorators: [(Story) => <div className="mx-auto flex w-full max-w-2xl flex-col gap-4"><Story /></div>],+ args: { presentation: failed, canRetry: true, onRetry: () => {} },} satisfies Meta<typeof ExecutionBlockerNotice>;export default meta;type Story = StoryObj<typeof meta>;-export const Stopped: Story = {};--const fileHold = {- ...meta.args.blocker,- nextAction: "The original workspace is retained. An operator must verify that its previous execution stopped before recovering files.",- runError: "runner_remote_provider_artifact_incompatible: provider pack verification failed ()",- workspaceRepairRequired: true, canRecordWorkspaceRepair: true,-};-const noRepairForm: NonNullable<Story["play"]> = async ({ canvasElement }) => {+const ordinaryRetry: NonNullable<Story["play"]> = async ({ canvasElement }) => {const canvas = within(canvasElement);- await expect(canvas.getByText("Work paused.")).toBeVisible();- await expect(canvas.queryByRole("textbox")).not.toBeInTheDocument();+ await expect(canvas.getByRole("button", { name: /^Retry$/ })).toBeVisible();+ await expect(canvas.queryByRole("link", { name: "Inspect run" })).not.toBeInTheDocument();await expect(canvas.queryByRole("checkbox")).not.toBeInTheDocument();- await expect(canvas.getByRole("link", { name: "Inspect run" })).toBeVisible();};-export const FileRecovery: Story = { args: { blocker: fileHold }, play: noRepairForm };+export const Stopped: Story = { play: ordinaryRetry };+export const FileRecovery: Story = { play: ordinaryRetry };export const RecoveringSavedWork: Story = {- args: { blocker: { ...fileHold, savedMessageCount: 1, workspaceRecovery: {- status: "recovering", stage: "restoring_files", canRetry: false, message: "Recovering saved work…",- } } },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText("Recovering saved work…")).toBeVisible();- await expect(canvas.getByText("Your message is saved and will continue after recovery.")).toBeVisible();- await expect(canvas.queryByRole("button", { name: "Retry recovery" })).not.toBeInTheDocument();- await expect(canvas.queryByText("Working")).not.toBeInTheDocument();- },+ args: { presentation: { ...failed, state: "working" } },+ play: async ({ canvasElement }) => { await expect(within(canvasElement).queryByRole("status")).not.toBeInTheDocument(); },};export const RetrySavedWork: Story = {- args: { blocker: { ...fileHold, savedMessageCount: 1, workspaceRecovery: {- status: "blocked", stage: "restoring_files", canRetry: true, message: "Recovery couldn’t finish. Your message is saved.",- } } },render: function RetryJourney(args) {- const [queued, setQueued] = useState(false);+ const [pending, setPending] = useState(false);return <><TaskChatBubble item={{ id: "saved-request", kind: "message", author: "human", authorName: "Alex",text: "Confirm the existing review and finish the task. Do not publish another review." }} />- <ExecutionBlockerNotice {...args} blocker={queued ? { ...args.blocker, workspaceRecovery: {- status: "queued", stage: "verifying_stop", canRetry: false, message: "Recovering saved work…",- } } : args.blocker} onRetried={() => setQueued(true)} />+ {pending && <TaskChatLiveRunPill status="running" startedAtMs={null} toolSummary={null} />}+ <ExecutionBlockerNotice {...args} optimistic={pending} onRetry={() => setPending(true)} /></>;},play: async ({ canvasElement }) => {const canvas = within(canvasElement);- await userEvent.click(canvas.getByRole("button", { name: "Retry recovery" }));- await expect(canvas.getByText("Recovering saved work…")).toBeVisible();- await expect(canvas.getByText("Your message is saved and will continue after recovery.")).toBeVisible();- await expect(canvas.queryByRole("textbox")).not.toBeInTheDocument();- },-};-export const PreviousSessionUnverified: Story = {- args: { blocker: { ...fileHold, savedMessageCount: 1, workspaceRecovery: {- status: "blocked", stage: "verifying_stop", canRetry: false,- message: "Paperclip couldn’t verify that the previous session stopped. This task needs service attention.",- } } },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText(/couldn’t verify that the previous session stopped/)).toBeVisible();- await expect(canvas.queryByRole("button", { name: "Retry recovery" })).not.toBeInTheDocument();- await expect(canvas.queryByRole("checkbox")).not.toBeInTheDocument();- },-};-export const FileRecoveryReadOnly: Story = { args: { blocker: fileHold, canManage: false }, play: noRepairForm };-// Preserve existing story IDs for saved inspection links.-export const FileRecoveryRecorded: Story = { args: { blocker: fileHold }, parameters: { recoveryState: "recorded" }, play: noRepairForm };-export const FileRecoveryRejected: Story = {- args: { blocker: fileHold }, parameters: { recoveryState: "rejected" },- play: async context => {- await noRepairForm(context);- const canvas = within(context.canvasElement);- await userEvent.click(canvas.getByText("Recovery details"));- await expect(canvas.getByText(/previous execution could not be verified stopped/)).toBeVisible();- },-};-export const AutomaticRecovery: Story = {- args: { blocker: fileHold }, parameters: { recoveryState: "automatic" },- render: args => <>- <TaskChatBubble item={{ id: "request", kind: "message", author: "human", authorName: "Dotta", text: "Review the test suite and open a PR with the useful cleanup." }} />- <TaskChatLiveRunPill status="running" startedAtMs={null} toolSummary={null} />- <ExecutionBlockerNotice {...args} />- </>,- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: /^Retry$/ }));await expect(canvas.getByText("Working")).toBeVisible();- await expect(canvas.queryByRole("status", { name: "Task recovery" })).not.toBeInTheDocument();- await expect(canvas.queryByRole("textbox")).not.toBeInTheDocument();- },-};-export const MissedRecovery: Story = { args: { blocker: fileHold }, parameters: { recoveryState: "expired" }, play: noRepairForm };-export const RecoveryReadUnavailable: Story = {- args: { blocker: fileHold }, parameters: { recoveryState: "unavailable" },- play: async context => {- await expect(await within(context.canvasElement).findByRole("alert")).toHaveTextContent("Recovery service unavailable");- await noRepairForm(context);- },-};-export const Mobile: Story = { args: { blocker: fileHold }, globals: { viewport: { value: "mobile", isRotated: false } }, play: noRepairForm };-export const SourceReconstruction: Story = {- args: { blocker: { ...fileHold, canReconstructWorkspace: true, workspaceRecoveryStatusVersion: 1,- nextAction: "The original workspace was destroyed. Continue only from verified surviving source attachments." } },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText("Continue from saved sources")).toBeVisible();- for (const input of canvas.queryAllByRole("textbox")) {- await expect(input).not.toBeVisible();- }- await userEvent.click(canvas.getByText("Continue from saved sources"));- await expect(canvas.getByText("test-audit.patch (4096 bytes)")).toBeVisible();- await expect(canvas.getByRole("button", { name: "Rebuild and continue" })).toBeDisabled();- },-};-export const ReconstructionQueued: Story = {- args: { blocker: { ...fileHold, workspaceReconstructionPending: true,- nextAction: "Continuation from saved sources is queued and waiting for execution checks." } },- play: async ({ canvasElement }) => {- const canvas = within(canvasElement);- await expect(canvas.getByText("Continuation queued.")).toBeVisible();- await expect(canvas.queryByText("Work paused.")).not.toBeInTheDocument();- await expect(canvas.queryByRole("textbox")).not.toBeInTheDocument();+ await expect(canvas.queryByRole("status")).not.toBeInTheDocument();},};+// Stable IDs retained: each historical failure now shares the ordinary Retry contract.+export const PreviousSessionUnverified: Story = { play: ordinaryRetry };+export const FileRecoveryReadOnly: Story = { args: { canRetry: false }, play: async ({ canvasElement }) => {+ await expect(within(canvasElement).queryByRole("button")).not.toBeInTheDocument();+} };+export const FileRecoveryRecorded: Story = { play: ordinaryRetry };+export const FileRecoveryRejected: Story = { play: ordinaryRetry };+export const AutomaticRecovery: Story = { ...RecoveringSavedWork };+export const MissedRecovery: Story = { play: ordinaryRetry };+export const RecoveryReadUnavailable: Story = { args: { takingLonger: true }, play: async ({ canvasElement }) => {+ await expect(within(canvasElement).getByText("Taking longer than usual…")).toBeVisible();+} };+export const Mobile: Story = { globals: { viewport: { value: "mobile", isRotated: false } }, play: ordinaryRetry };+export const SourceReconstruction: Story = { play: ordinaryRetry };+export const ReconstructionQueued: Story = { ...RecoveringSavedWork };+export const RetryScheduled: Story = { args: { presentation: { ...failed, state: "retry_scheduled", nextRetryAt: new Date(Date.now() + 60_000).toISOString() } }, play: ordinaryRetry };diff --git a/ui/storybook/stories/tasks/task-context-notices.stories.tsx b/ui/storybook/stories/tasks/task-context-notices.stories.tsxindex f1703181ab..e956789906 100644--- a/ui/storybook/stories/tasks/task-context-notices.stories.tsx+++ b/ui/storybook/stories/tasks/task-context-notices.stories.tsx@@ -26,9 +26,9 @@ function TaskContextNotices() {<div className="w-full space-y-3"><h1 className={`${shellSectionClass} text-xl font-semibold`}>Chat connection and recovery</h1><ExternallyConnectedTaskBanner className={`${shellSectionClass} mt-3`} companyId="demo" issueId="context-notices" />- <ExecutionBlockerNotice className={shellSectionClass} companyId="demo" issueId="context-notices" onRetried={() => {}}- blocker={{ recoveryActionId: "demo-recovery", runId: null, agentId: null, cause: "action_outcome_unknown",- nextAction: "Inspect the run before continuing. Recorded work is preserved." }} />+ <ExecutionBlockerNotice className={shellSectionClass} canRetry onRetry={() => {}}+ presentation={{ intentId: "intent", responsibility: "system", state: "failed", nextRetryAt: null,+ canRetry: true, userAction: null, sourceRunIds: [], observedRunId: null }} /><div className={shellSectionClass}><EmailMessageCard contextNotice issueId="context-notices" message={{id: "email-demo", providerMessageId: "email-demo", direction: "inbound",@@ -55,7 +55,7 @@ const meta = {],"implementation": "production","boundary": "fixtures",- "notes": "The filter uses one lowercase label without helper text. All chat-channel tasks count as bot-created; the focused visibility stories cover human-initiated channel work."+ "notes": "Production external-connection and email notices alongside compact task Retry. Query fixtures isolate the connection boundary; they do not verify remote chat permissions."},},} satisfies Meta<typeof TaskContextNotices>;@@ -66,9 +66,10 @@ export const ConnectionAndRecovery: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);const connection = await canvas.findByRole("region", { name: "External conversation" });- const recovery = canvas.getByRole("status", { name: "Task recovery" });+ const recovery = canvas.getByRole("status", { name: "Task status" });const email = canvas.getByRole("article", { name: "Email received" });- for (const card of [recovery, email]) {+ await expect(recovery.getBoundingClientRect().width).toBe(connection.getBoundingClientRect().width);+ for (const card of [email]) {await expect(card.getBoundingClientRect().width).toBe(connection.getBoundingClientRect().width);await expect(getComputedStyle(card).backgroundColor).toBe(getComputedStyle(connection).backgroundColor);await expect(getComputedStyle(card).padding).toBe(getComputedStyle(connection).padding);