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: make accounting durable and synchronize cost reporting (#14997)
Devin Foley799e4d556f5c
diff --git a/cli/src/__tests__/worktree.test.ts b/cli/src/__tests__/worktree.test.tsindex 6d36e06035..0dfa6210f5 100644--- a/cli/src/__tests__/worktree.test.ts+++ b/cli/src/__tests__/worktree.test.ts@@ -157,12 +157,12 @@ async function seedValidWorktreeSource(userId,role: "instance_admin",});- await db.insert(companies).values({- id: companyId,- name: "Seed Source",- issuePrefix: "SEED",- requireBoardApprovalForNewAgents: false,- });+ // Seed only columns present in the historical source schema. The current+ // model includes accounting columns that the worktree migration adds later.+ await db.$client`+ insert into companies (id, name, issue_prefix, require_board_approval_for_new_agents)+ values (${companyId}, 'Seed Source', 'SEED', false)+ `;await db.insert(companyMemberships).values({companyId,principalType: "user",diff --git a/packages/db/src/migrations/0312_easy_eternity.sql b/packages/db/src/migrations/0312_easy_eternity.sqlnew file mode 100644index 0000000000..b02c9dae3a--- /dev/null+++ b/packages/db/src/migrations/0312_easy_eternity.sql@@ -0,0 +1,232 @@+-- Preserve values while upgrading exact accounting. Additions are replay-safe.+CREATE TABLE IF NOT EXISTS "accounting_runtime_baselines" (+ "agent_id" uuid PRIMARY KEY NOT NULL,+ "company_id" uuid NOT NULL,+ "cost_cents" numeric(24, 7) NOT NULL,+ "input_tokens" numeric(30, 0) NOT NULL,+ "cached_input_tokens" numeric(30, 0) NOT NULL,+ "output_tokens" numeric(30, 0) NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "billing_invoice_lines" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "company_id" uuid NOT NULL,+ "invoice_id" uuid NOT NULL,+ "external_id" text NOT NULL,+ "kind" text NOT NULL,+ "amount_cents" numeric(24, 7) NOT NULL,+ "occurred_at" timestamp with time zone NOT NULL,+ "cost_event_id" uuid,+ "run_id" uuid,+ "provider_request_id" text,+ "model" text,+ "pricing" jsonb DEFAULT '{}'::jsonb NOT NULL,+ CONSTRAINT "billing_invoice_lines_amount_check" CHECK ("billing_invoice_lines"."amount_cents" >= 0),+ CONSTRAINT "billing_invoice_lines_kind_check" CHECK ("billing_invoice_lines"."kind" in ('inference', 'fee', 'credit'))+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "billing_invoices" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "company_id" uuid NOT NULL,+ "biller" text NOT NULL,+ "external_id" text NOT NULL,+ "currency" text NOT NULL,+ "receipt_hash" text NOT NULL,+ "imported_by" text NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "budget_reservations" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "company_id" uuid NOT NULL,+ "run_id" uuid NOT NULL,+ "agent_id" uuid NOT NULL,+ "project_id" uuid,+ "amount_cents" numeric(24, 7) NOT NULL,+ "state" text DEFAULT 'held' NOT NULL,+ "provider_started_at" timestamp with time zone,+ "settled_at" timestamp with time zone,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "budget_reservations_state_check" CHECK ("budget_reservations"."state" in ('held', 'settled', 'released')),+ CONSTRAINT "budget_reservations_amount_check" CHECK ("budget_reservations"."amount_cents" >= 0)+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "cost_adjustments" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "company_id" uuid NOT NULL,+ "cost_event_id" uuid NOT NULL,+ "invoice_line_id" uuid,+ "idempotency_key" text NOT NULL,+ "receipt_hash" text NOT NULL,+ "previous_cents" numeric(24, 7) NOT NULL,+ "corrected_cents" numeric(24, 7) NOT NULL,+ "previous_status" text NOT NULL,+ "previous_pricing" jsonb DEFAULT '{}'::jsonb NOT NULL,+ "reason" text NOT NULL,+ "actor_id" text NOT NULL,+ "pricing" jsonb DEFAULT '{}'::jsonb NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "cost_adjustments_amount_check" CHECK ("cost_adjustments"."previous_cents" >= 0 and "cost_adjustments"."corrected_cents" >= 0)+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "provider_billing_snapshots" (+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,+ "company_id" uuid NOT NULL,+ "provider" text NOT NULL,+ "account_id" text NOT NULL,+ "scope_id" text NOT NULL,+ "day" text NOT NULL,+ "amount_cents" numeric(24, 7) NOT NULL,+ "revision" integer DEFAULT 1 NOT NULL,+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "provider_billing_snapshots_amount_check" CHECK ("provider_billing_snapshots"."amount_cents" >= 0)+);+--> statement-breakpoint+CREATE TABLE IF NOT EXISTS "run_usage_receipts" (+ "id" uuid PRIMARY KEY NOT NULL,+ "company_id" uuid NOT NULL,+ "run_id" uuid NOT NULL,+ "source_id" uuid NOT NULL,+ "sequence" integer NOT NULL,+ "receipt_hash" text NOT NULL,+ "receipt_json" jsonb NOT NULL,+ "complete" boolean NOT NULL,+ "received_at" timestamp with time zone NOT NULL,+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,+ CONSTRAINT "run_usage_receipts_positive_sequence" CHECK ("run_usage_receipts"."sequence" > 0)+);+--> statement-breakpoint+DROP INDEX IF EXISTS "budget_incidents_policy_window_threshold_idx";--> statement-breakpoint+ALTER TABLE "agent_runtime_state" ALTER COLUMN "total_cost_cents" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "agents" ALTER COLUMN "spent_monthly_cents" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "budget_incidents" ALTER COLUMN "amount_observed" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "companies" ALTER COLUMN "spent_monthly_cents" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "cost_events" ALTER COLUMN "cost_cents" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "finance_events" ALTER COLUMN "amount_cents" SET DATA TYPE numeric(24, 7);--> statement-breakpoint+ALTER TABLE "agents" ADD COLUMN IF NOT EXISTS "spend_month_utc" text;--> statement-breakpoint+ALTER TABLE "budget_policies" ADD COLUMN IF NOT EXISTS "reservation_cents" numeric(24, 7) DEFAULT '0' NOT NULL;--> statement-breakpoint+ALTER TABLE "budget_policies" ADD COLUMN IF NOT EXISTS "unpriced_usage_policy" text DEFAULT 'block' NOT NULL;--> statement-breakpoint+ALTER TABLE "budget_policies" ADD COLUMN IF NOT EXISTS "enforcement_version" integer DEFAULT 0 NOT NULL;--> statement-breakpoint+ALTER TABLE "budget_policies" ADD COLUMN IF NOT EXISTS "enforcement_delivered_version" integer DEFAULT 0 NOT NULL;--> statement-breakpoint+ALTER TABLE "companies" ADD COLUMN IF NOT EXISTS "spend_month_utc" text;--> statement-breakpoint+ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "idempotency_key" text;--> statement-breakpoint+ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "receipt_hash" text;--> statement-breakpoint+ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "provider_request_id" text;--> statement-breakpoint+ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "reported_cost_cents" numeric(24, 7);--> statement-breakpoint+ALTER TABLE "cost_events" ADD COLUMN IF NOT EXISTS "pricing_provenance" jsonb;--> statement-breakpoint+ALTER TABLE "finance_events" ADD COLUMN IF NOT EXISTS "idempotency_key" text;--> statement-breakpoint+ALTER TABLE "finance_events" ADD COLUMN IF NOT EXISTS "receipt_hash" text;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "cost_accounting_pending" boolean DEFAULT false NOT NULL;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "cost_accounted_at" timestamp with time zone;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "accounting_projection_version" text;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "accounting_last_attempt_at" timestamp with time zone;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "accounting_last_error" text;--> statement-breakpoint+ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "accounting_attempt_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'accounting_runtime_baselines_agent_id_agents_id_fk' AND conrelid = 'public.accounting_runtime_baselines'::regclass) THEN+ ALTER TABLE "accounting_runtime_baselines" ADD CONSTRAINT "accounting_runtime_baselines_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'accounting_runtime_baselines_company_id_companies_id_fk' AND conrelid = 'public.accounting_runtime_baselines'::regclass) THEN+ ALTER TABLE "accounting_runtime_baselines" ADD CONSTRAINT "accounting_runtime_baselines_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'billing_invoice_lines_company_id_companies_id_fk' AND conrelid = 'public.billing_invoice_lines'::regclass) THEN+ ALTER TABLE "billing_invoice_lines" ADD CONSTRAINT "billing_invoice_lines_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'billing_invoice_lines_invoice_id_billing_invoices_id_fk' AND conrelid = 'public.billing_invoice_lines'::regclass) THEN+ ALTER TABLE "billing_invoice_lines" ADD CONSTRAINT "billing_invoice_lines_invoice_id_billing_invoices_id_fk" FOREIGN KEY ("invoice_id") REFERENCES "public"."billing_invoices"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'billing_invoice_lines_cost_event_id_cost_events_id_fk' AND conrelid = 'public.billing_invoice_lines'::regclass) THEN+ ALTER TABLE "billing_invoice_lines" ADD CONSTRAINT "billing_invoice_lines_cost_event_id_cost_events_id_fk" FOREIGN KEY ("cost_event_id") REFERENCES "public"."cost_events"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'billing_invoices_company_id_companies_id_fk' AND conrelid = 'public.billing_invoices'::regclass) THEN+ ALTER TABLE "billing_invoices" ADD CONSTRAINT "billing_invoices_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'budget_reservations_company_id_companies_id_fk' AND conrelid = 'public.budget_reservations'::regclass) THEN+ ALTER TABLE "budget_reservations" ADD CONSTRAINT "budget_reservations_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'budget_reservations_run_id_heartbeat_runs_id_fk' AND conrelid = 'public.budget_reservations'::regclass) THEN+ ALTER TABLE "budget_reservations" ADD CONSTRAINT "budget_reservations_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'budget_reservations_agent_id_agents_id_fk' AND conrelid = 'public.budget_reservations'::regclass) THEN+ ALTER TABLE "budget_reservations" ADD CONSTRAINT "budget_reservations_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'cost_adjustments_company_id_companies_id_fk' AND conrelid = 'public.cost_adjustments'::regclass) THEN+ ALTER TABLE "cost_adjustments" ADD CONSTRAINT "cost_adjustments_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'cost_adjustments_cost_event_id_cost_events_id_fk' AND conrelid = 'public.cost_adjustments'::regclass) THEN+ ALTER TABLE "cost_adjustments" ADD CONSTRAINT "cost_adjustments_cost_event_id_cost_events_id_fk" FOREIGN KEY ("cost_event_id") REFERENCES "public"."cost_events"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'cost_adjustments_invoice_line_id_billing_invoice_lines_id_fk' AND conrelid = 'public.cost_adjustments'::regclass) THEN+ ALTER TABLE "cost_adjustments" ADD CONSTRAINT "cost_adjustments_invoice_line_id_billing_invoice_lines_id_fk" FOREIGN KEY ("invoice_line_id") REFERENCES "public"."billing_invoice_lines"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'provider_billing_snapshots_company_id_companies_id_fk' AND conrelid = 'public.provider_billing_snapshots'::regclass) THEN+ ALTER TABLE "provider_billing_snapshots" ADD CONSTRAINT "provider_billing_snapshots_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'run_usage_receipts_company_id_companies_id_fk' AND conrelid = 'public.run_usage_receipts'::regclass) THEN+ ALTER TABLE "run_usage_receipts" ADD CONSTRAINT "run_usage_receipts_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'run_usage_receipts_run_id_heartbeat_runs_id_fk' AND conrelid = 'public.run_usage_receipts'::regclass) THEN+ ALTER TABLE "run_usage_receipts" ADD CONSTRAINT "run_usage_receipts_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE cascade ON UPDATE no action;+ END IF;+END $$;--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "accounting_runtime_baselines_company_idx" ON "accounting_runtime_baselines" USING btree ("company_id");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "billing_invoice_lines_identity_idx" ON "billing_invoice_lines" USING btree ("invoice_id","external_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "billing_invoice_lines_company_idx" ON "billing_invoice_lines" USING btree ("company_id","invoice_id");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "billing_invoices_identity_idx" ON "billing_invoices" USING btree ("company_id","biller","external_id");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "budget_reservations_run_idx" ON "budget_reservations" USING btree ("company_id","run_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "budget_reservations_active_idx" ON "budget_reservations" USING btree ("company_id","agent_id","project_id") WHERE "budget_reservations"."state" = 'held';--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "cost_adjustments_receipt_idx" ON "cost_adjustments" USING btree ("company_id","idempotency_key");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "cost_adjustments_event_idx" ON "cost_adjustments" USING btree ("company_id","cost_event_id","created_at");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "cost_adjustments_invoice_line_idx" ON "cost_adjustments" USING btree ("company_id","invoice_line_id");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "provider_billing_snapshots_identity_idx" ON "provider_billing_snapshots" USING btree ("company_id","provider","account_id","scope_id","day");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "run_usage_receipts_source_sequence_idx" ON "run_usage_receipts" USING btree ("company_id","run_id","source_id","sequence");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "run_usage_receipts_run_latest_idx" ON "run_usage_receipts" USING btree ("company_id","run_id","received_at");--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "cost_events_company_receipt_idx" ON "cost_events" USING btree ("company_id","idempotency_key");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "cost_events_provider_request_idx" ON "cost_events" USING btree ("company_id","biller","provider_request_id");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "cost_events_company_project_occurred_idx" ON "cost_events" USING btree ("company_id","project_id","occurred_at");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "cost_events_unpriced_idx" ON "cost_events" USING btree ("company_id","occurred_at","id") WHERE "cost_events"."cost_status" = 'unpriced' and "cost_events"."billing_type" <> 'subscription_included';--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "finance_events_company_receipt_idx" ON "finance_events" USING btree ("company_id","idempotency_key");--> statement-breakpoint+CREATE INDEX IF NOT EXISTS "heartbeat_runs_cost_accounting_pending_idx" ON "heartbeat_runs" USING btree ("updated_at","id") WHERE "heartbeat_runs"."cost_accounting_pending" = true;--> statement-breakpoint+CREATE UNIQUE INDEX IF NOT EXISTS "budget_incidents_policy_window_threshold_idx" ON "budget_incidents" USING btree ("policy_id","window_start","threshold_type") WHERE "budget_incidents"."status" = 'open';--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'budget_policies_reservation_nonnegative' AND conrelid = 'public.budget_policies'::regclass) THEN+ ALTER TABLE "budget_policies" ADD CONSTRAINT "budget_policies_reservation_nonnegative" CHECK ("budget_policies"."reservation_cents" >= 0);+ END IF;+END $$;--> statement-breakpoint+DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'cost_events_nonnegative_amounts' AND conrelid = 'public.cost_events'::regclass) THEN+ ALTER TABLE "cost_events" ADD CONSTRAINT "cost_events_nonnegative_amounts" CHECK ("cost_events"."cost_cents" >= 0 and "cost_events"."input_tokens" >= 0 and "cost_events"."cached_input_tokens" >= 0 and "cost_events"."output_tokens" >= 0);+ END IF;+END $$;+--> statement-breakpoint+-- Preserve the ledger precision in status-card update snapshots. Reapplying this type widening is safe.+ALTER TABLE "status_card_updates" ALTER COLUMN "cost_cents" SET DATA TYPE numeric(24, 7);diff --git a/packages/db/src/migrations/meta/0312_snapshot.json b/packages/db/src/migrations/meta/0312_snapshot.jsonnew file mode 100644index 0000000000..d9bcd5c6a6--- /dev/null+++ b/packages/db/src/migrations/meta/0312_snapshot.json@@ -0,0 +1,54406 @@+{+ "id": "9134843c-7e84-421e-915b-beab3c30acb3",+ "prevId": "53940222-21d7-4ccc-8b24-d8db300f4ec3",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.accounting_runtime_baselines": {+ "name": "accounting_runtime_baselines",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "cost_cents": {+ "name": "cost_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "numeric(30, 0)",+ "primaryKey": false,+ "notNull": true+ },+ "cached_input_tokens": {+ "name": "cached_input_tokens",+ "type": "numeric(30, 0)",+ "primaryKey": false,+ "notNull": true+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "numeric(30, 0)",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "accounting_runtime_baselines_company_idx": {+ "name": "accounting_runtime_baselines_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.billing_invoice_lines": {+ "name": "billing_invoice_lines",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "invoice_id": {+ "name": "invoice_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "amount_cents": {+ "name": "amount_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "occurred_at": {+ "name": "occurred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "cost_event_id": {+ "name": "cost_event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_request_id": {+ "name": "provider_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pricing": {+ "name": "pricing",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ }+ },+ "indexes": {+ "billing_invoice_lines_identity_idx": {+ "name": "billing_invoice_lines_identity_idx",+ "columns": [+ {+ "expression": "invoice_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "billing_invoice_lines_company_idx": {+ "name": "billing_invoice_lines_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "invoice_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "billing_invoice_lines_amount_check": {+ "name": "billing_invoice_lines_amount_check",+ "value": "\"billing_invoice_lines\".\"amount_cents\" >= 0"+ },+ "billing_invoice_lines_kind_check": {+ "name": "billing_invoice_lines_kind_check",+ "value": "\"billing_invoice_lines\".\"kind\" in ('inference', 'fee', 'credit')"+ }+ },+ "isRLSEnabled": false+ },+ "public.billing_invoices": {+ "name": "billing_invoices",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "biller": {+ "name": "biller",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "currency": {+ "name": "currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "receipt_hash": {+ "name": "receipt_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "imported_by": {+ "name": "imported_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "billing_invoices_identity_idx": {+ "name": "billing_invoices_identity_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "biller",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.budget_reservations": {+ "name": "budget_reservations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "amount_cents": {+ "name": "amount_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'held'"+ },+ "provider_started_at": {+ "name": "provider_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "settled_at": {+ "name": "settled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "budget_reservations_run_idx": {+ "name": "budget_reservations_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "budget_reservations_active_idx": {+ "name": "budget_reservations_active_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"budget_reservations\".\"state\" = 'held'",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "budget_reservations_state_check": {+ "name": "budget_reservations_state_check",+ "value": "\"budget_reservations\".\"state\" in ('held', 'settled', 'released')"+ },+ "budget_reservations_amount_check": {+ "name": "budget_reservations_amount_check",+ "value": "\"budget_reservations\".\"amount_cents\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.cost_adjustments": {+ "name": "cost_adjustments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "cost_event_id": {+ "name": "cost_event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "invoice_line_id": {+ "name": "invoice_line_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "receipt_hash": {+ "name": "receipt_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "previous_cents": {+ "name": "previous_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "corrected_cents": {+ "name": "corrected_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "previous_status": {+ "name": "previous_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "previous_pricing": {+ "name": "previous_pricing",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "pricing": {+ "name": "pricing",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cost_adjustments_receipt_idx": {+ "name": "cost_adjustments_receipt_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_adjustments_event_idx": {+ "name": "cost_adjustments_event_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cost_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_adjustments_invoice_line_idx": {+ "name": "cost_adjustments_invoice_line_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "invoice_line_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cost_adjustments_amount_check": {+ "name": "cost_adjustments_amount_check",+ "value": "\"cost_adjustments\".\"previous_cents\" >= 0 and \"cost_adjustments\".\"corrected_cents\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.provider_billing_snapshots": {+ "name": "provider_billing_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "day": {+ "name": "day",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "amount_cents": {+ "name": "amount_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "provider_billing_snapshots_identity_idx": {+ "name": "provider_billing_snapshots_identity_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "day",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "provider_billing_snapshots_amount_check": {+ "name": "provider_billing_snapshots_amount_check",+ "value": "\"provider_billing_snapshots\".\"amount_cents\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.run_usage_receipts": {+ "name": "run_usage_receipts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "sequence": {+ "name": "sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "receipt_hash": {+ "name": "receipt_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "receipt_json": {+ "name": "receipt_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "complete": {+ "name": "complete",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "received_at": {+ "name": "received_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "run_usage_receipts_source_sequence_idx": {+ "name": "run_usage_receipts_source_sequence_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "sequence",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "run_usage_receipts_run_latest_idx": {+ "name": "run_usage_receipts_run_latest_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "received_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "run_usage_receipts_positive_sequence": {+ "name": "run_usage_receipts_positive_sequence",+ "value": "\"run_usage_receipts\".\"sequence\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.activity_log": {+ "name": "activity_log",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entity_type": {+ "name": "entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entity_id": {+ "name": "entity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "details": {+ "name": "details",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "activity_log_company_created_idx": {+ "name": "activity_log_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_log_company_agent_created_idx": {+ "name": "activity_log_company_agent_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_log_company_responsible_user_created_idx": {+ "name": "activity_log_company_responsible_user_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_log_run_id_idx": {+ "name": "activity_log_run_id_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "activity_log_entity_type_id_idx": {+ "name": "activity_log_entity_type_id_idx",+ "columns": [+ {+ "expression": "entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "activity_log_company_id_companies_id_fk": {+ "name": "activity_log_company_id_companies_id_fk",+ "tableFrom": "activity_log",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.adapter_auth_sessions": {+ "name": "adapter_auth_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "environment_id": {+ "name": "environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "ai_connection": {+ "name": "ai_connection",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_grant_id": {+ "name": "connection_grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_method": {+ "name": "connection_method",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "adapter_type": {+ "name": "adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "public_session_id": {+ "name": "public_session_id",+ "type": "varchar(128)",+ "primaryKey": false,+ "notNull": true+ },+ "provider_lease_id": {+ "name": "provider_lease_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'starting'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "promotion_expires_at": {+ "name": "promotion_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "bound_at": {+ "name": "bound_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result_claim": {+ "name": "result_claim",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "adapter_auth_sessions_company_status_idx": {+ "name": "adapter_auth_sessions_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "adapter_auth_sessions_company_owner_adapter_active_uq": {+ "name": "adapter_auth_sessions_company_owner_adapter_active_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "adapter_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"adapter_auth_sessions\".\"status\" IN ('starting', 'waiting_for_user', 'promoting', 'awaiting_code', 'submitting')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "adapter_auth_sessions_public_session_id_uq": {+ "name": "adapter_auth_sessions_public_session_id_uq",+ "columns": [+ {+ "expression": "public_session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "adapter_auth_sessions_environment_idx": {+ "name": "adapter_auth_sessions_environment_idx",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "adapter_auth_sessions_expires_idx": {+ "name": "adapter_auth_sessions_expires_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "adapter_auth_sessions_provider_lease_idx": {+ "name": "adapter_auth_sessions_provider_lease_idx",+ "columns": [+ {+ "expression": "provider_lease_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_api_keys": {+ "name": "agent_api_keys",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key_hash": {+ "name": "key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scope_config": {+ "name": "scope_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_api_keys_key_hash_idx": {+ "name": "agent_api_keys_key_hash_idx",+ "columns": [+ {+ "expression": "key_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_api_keys_company_agent_idx": {+ "name": "agent_api_keys_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_commentary": {+ "name": "agent_commentary",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload_hash": {+ "name": "payload_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_commentary_run_key_uq": {+ "name": "agent_commentary_run_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_commentary_company_kind_created_idx": {+ "name": "agent_commentary_company_kind_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_commentary_kind_check": {+ "name": "agent_commentary_kind_check",+ "value": "\"agent_commentary\".\"kind\" in ('complaint', 'suggestion')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_config_revisions": {+ "name": "agent_config_revisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'patch'"+ },+ "rolled_back_from_revision_id": {+ "name": "rolled_back_from_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "changed_keys": {+ "name": "changed_keys",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "before_config": {+ "name": "before_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "after_config": {+ "name": "after_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_config_revisions_company_agent_created_idx": {+ "name": "agent_config_revisions_company_agent_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_config_revisions_agent_created_idx": {+ "name": "agent_config_revisions_agent_created_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_identity_keys": {+ "name": "agent_identity_keys",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "algorithm": {+ "name": "algorithm",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key_id": {+ "name": "key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "public_key_pem": {+ "name": "public_key_pem",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "private_key_material": {+ "name": "private_key_material",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_identity_keys_owner_fk": {+ "name": "agent_identity_keys_owner_fk",+ "tableFrom": "agent_identity_keys",+ "tableTo": "agents",+ "columnsFrom": [+ "company_id",+ "agent_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_identity_keys_algorithm_check": {+ "name": "agent_identity_keys_algorithm_check",+ "value": "\"agent_identity_keys\".\"algorithm\" = 'Ed25519'"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_instruction_heads": {+ "name": "agent_instruction_heads",+ "schema": "",+ "columns": {+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "entry_file": {+ "name": "entry_file",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "revision_id": {+ "name": "revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "company_id",+ "agent_id",+ "entry_file",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_instruction_revisions": {+ "name": "agent_instruction_revisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "entry_file": {+ "name": "entry_file",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_base64": {+ "name": "content_base64",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_hash": {+ "name": "content_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "byte_length": {+ "name": "byte_length",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_revision_id": {+ "name": "parent_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "base_revision_id": {+ "name": "base_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "restored_from_revision_id": {+ "name": "restored_from_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "actor_agent_id": {+ "name": "actor_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_run_id": {+ "name": "source_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_instruction_revisions_history_idx": {+ "name": "agent_instruction_revisions_history_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entry_file",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_instruction_working_copies": {+ "name": "agent_instruction_working_copies",+ "schema": "",+ "columns": {+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "entry_file": {+ "name": "entry_file",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "base_revision_id": {+ "name": "base_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "base_hash": {+ "name": "base_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "local_root": {+ "name": "local_root",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "execution_root": {+ "name": "execution_root",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "location": {+ "name": "location",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'prepared'"+ },+ "candidate_base64": {+ "name": "candidate_base64",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "candidate_hash": {+ "name": "candidate_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "receipt": {+ "name": "receipt",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "process_stopped_at": {+ "name": "process_stopped_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_instruction_copies_pending_idx": {+ "name": "agent_instruction_copies_pending_idx",+ "columns": [+ {+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_instruction_copies_agent_idx": {+ "name": "agent_instruction_copies_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_memberships": {+ "name": "agent_memberships",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'joined'"+ },+ "starred_at": {+ "name": "starred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_memberships_company_user_idx": {+ "name": "agent_memberships_company_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_memberships_company_user_starred_idx": {+ "name": "agent_memberships_company_user_starred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "starred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_memberships_agent_idx": {+ "name": "agent_memberships_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_memberships_company_user_agent_uq": {+ "name": "agent_memberships_company_user_agent_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_runtime_state": {+ "name": "agent_runtime_state",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "adapter_type": {+ "name": "adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state_json": {+ "name": "state_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "last_run_id": {+ "name": "last_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_run_status": {+ "name": "last_run_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "total_input_tokens": {+ "name": "total_input_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "total_output_tokens": {+ "name": "total_output_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "total_cached_input_tokens": {+ "name": "total_cached_input_tokens",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "total_cost_cents": {+ "name": "total_cost_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_runtime_state_company_agent_idx": {+ "name": "agent_runtime_state_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_runtime_state_company_updated_idx": {+ "name": "agent_runtime_state_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_session_goal_actions": {+ "name": "agent_session_goal_actions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "request_id": {+ "name": "request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload_json": {+ "name": "payload_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "result_json": {+ "name": "result_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_session_goal_actions_session_request_uniq": {+ "name": "agent_session_goal_actions_session_request_uniq",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "request_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_session_goal_actions_company_status_created_idx": {+ "name": "agent_session_goal_actions_company_status_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_session_goal_actions_session_created_idx": {+ "name": "agent_session_goal_actions_session_created_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_task_sessions": {+ "name": "agent_task_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "adapter_type": {+ "name": "adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_key": {+ "name": "task_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "session_params_json": {+ "name": "session_params_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "session_display_id": {+ "name": "session_display_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_run_id": {+ "name": "last_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_capability_json": {+ "name": "goal_capability_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "goal_json": {+ "name": "goal_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "goal_status": {+ "name": "goal_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_desired_state": {+ "name": "goal_desired_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_source_id": {+ "name": "goal_source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_source_cursor": {+ "name": "goal_source_cursor",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "goal_revision": {+ "name": "goal_revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "goal_observed_at": {+ "name": "goal_observed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_task_sessions_company_agent_adapter_task_uniq": {+ "name": "agent_task_sessions_company_agent_adapter_task_uniq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "adapter_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "task_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_task_sessions_company_agent_updated_idx": {+ "name": "agent_task_sessions_company_agent_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_task_sessions_company_task_updated_idx": {+ "name": "agent_task_sessions_company_task_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "task_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_wakeup_requests": {+ "name": "agent_wakeup_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trigger_detail": {+ "name": "trigger_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "coalesced_count": {+ "name": "coalesced_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "requested_by_actor_type": {+ "name": "requested_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_actor_id": {+ "name": "requested_by_actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_at": {+ "name": "requested_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "claimed_at": {+ "name": "claimed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_wakeup_requests_company_agent_status_idx": {+ "name": "agent_wakeup_requests_company_agent_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_company_requested_idx": {+ "name": "agent_wakeup_requests_company_requested_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "requested_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_agent_requested_idx": {+ "name": "agent_wakeup_requests_agent_requested_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "requested_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_review_path_recovery_idempotency_uq": {+ "name": "agent_wakeup_requests_review_path_recovery_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 'issue_review_path_lost:%' AND \"agent_wakeup_requests\".\"status\" <> 'skipped'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_disposition_repair_idempotency_uq": {+ "name": "agent_wakeup_requests_disposition_repair_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 'issue_disposition_repair:%' AND \"agent_wakeup_requests\".\"status\" <> 'skipped'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_question_response_delivery_idempotency_uq": {+ "name": "agent_wakeup_requests_question_response_delivery_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 'question-response:%' OR \"agent_wakeup_requests\".\"idempotency_key\" LIKE 'interaction:%') AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_connection_intent_delivery_idempotency_uq": {+ "name": "agent_wakeup_requests_connection_intent_delivery_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 'connection-intent:%' AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_tool_action_delivery_uq": {+ "name": "agent_wakeup_requests_tool_action_delivery_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 'tool-action-response:%' AND \"agent_wakeup_requests\".\"status\" NOT IN ('skipped', 'failed', 'cancelled')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_chat_completion_uq": {+ "name": "agent_wakeup_requests_chat_completion_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 'chat-completion:%'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_wakeup_requests_company_payload_issue_idx": {+ "name": "agent_wakeup_requests_company_payload_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"payload\" ->> 'issueId')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agents": {+ "name": "agents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'general'"+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "appearance": {+ "name": "appearance",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'idle'"+ },+ "reports_to": {+ "name": "reports_to",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "adapter_type": {+ "name": "adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'process'"+ },+ "adapter_config": {+ "name": "adapter_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "runtime_config": {+ "name": "runtime_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "default_environment_id": {+ "name": "default_environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "budget_monthly_cents": {+ "name": "budget_monthly_cents",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "spend_month_utc": {+ "name": "spend_month_utc",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spent_monthly_cents": {+ "name": "spent_monthly_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "pause_reason": {+ "name": "pause_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paused_at": {+ "name": "paused_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "error_reason": {+ "name": "error_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "permissions": {+ "name": "permissions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "last_heartbeat_at": {+ "name": "last_heartbeat_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agents_company_status_idx": {+ "name": "agents_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agents_company_reports_to_idx": {+ "name": "agents_company_reports_to_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "reports_to",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agents_company_default_environment_idx": {+ "name": "agents_company_default_environment_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "default_environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agents_company_id_companies_id_fk": {+ "name": "agents_company_id_companies_id_fk",+ "tableFrom": "agents",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agents_company_id_uq": {+ "name": "agents_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_connection_defaults": {+ "name": "ai_connection_defaults",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "method": {+ "name": "method",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_connection_defaults_owner_method_uq": {+ "name": "ai_connection_defaults_owner_method_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "method",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "ai_connection_defaults_provider_check": {+ "name": "ai_connection_defaults_provider_check",+ "value": "\"ai_connection_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google')"+ },+ "ai_connection_defaults_method_check": {+ "name": "ai_connection_defaults_method_check",+ "value": "\"ai_connection_defaults\".\"method\" in ('subscription','api_key')"+ }+ },+ "isRLSEnabled": false+ },+ "public.ai_connection_pools": {+ "name": "ai_connection_pools",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_key": {+ "name": "plugin_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_connection_router_cursors": {+ "name": "ai_connection_router_cursors",+ "schema": "",+ "columns": {+ "pool_id": {+ "name": "pool_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "last_member_id": {+ "name": "last_member_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_connection_task_pins": {+ "name": "ai_connection_task_pins",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "pool_id": {+ "name": "pool_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "task_key": {+ "name": "task_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "selection": {+ "name": "selection",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "member": {+ "name": "member",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_connection_task_pins_affinity_uq": {+ "name": "ai_connection_task_pins_affinity_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "pool_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "task_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_provider_defaults": {+ "name": "ai_provider_defaults",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_provider_defaults_owner_provider_uq": {+ "name": "ai_provider_defaults_owner_provider_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "ai_provider_defaults_provider_check": {+ "name": "ai_provider_defaults_provider_check",+ "value": "\"ai_provider_defaults\".\"provider\" in ('anthropic','openai','openrouter','xai','google')"+ }+ },+ "isRLSEnabled": false+ },+ "public.announcement_dismissals": {+ "name": "announcement_dismissals",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "announcement_id": {+ "name": "announcement_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "dismissed_at": {+ "name": "dismissed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "announcement_dismissals_user_id_announcement_id_pk": {+ "name": "announcement_dismissals_user_id_announcement_id_pk",+ "columns": [+ "user_id",+ "announcement_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.announcement_publications": {+ "name": "announcement_publications",+ "schema": "",+ "columns": {+ "announcement_id": {+ "name": "announcement_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.approval_comments": {+ "name": "approval_comments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "approval_id": {+ "name": "approval_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "approval_comments_company_idx": {+ "name": "approval_comments_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "approval_comments_approval_idx": {+ "name": "approval_comments_approval_idx",+ "columns": [+ {+ "expression": "approval_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "approval_comments_approval_created_idx": {+ "name": "approval_comments_approval_created_idx",+ "columns": [+ {+ "expression": "approval_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.approvals": {+ "name": "approvals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requested_by_agent_id": {+ "name": "requested_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_user_id": {+ "name": "requested_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "decision_note": {+ "name": "decision_note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_by_user_id": {+ "name": "decided_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "approvals_company_status_type_idx": {+ "name": "approvals_company_status_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "approvals_company_id_companies_id_fk": {+ "name": "approvals_company_id_companies_id_fk",+ "tableFrom": "approvals",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.assets": {+ "name": "assets",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "byte_size": {+ "name": "byte_size",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "sha256": {+ "name": "sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "original_filename": {+ "name": "original_filename",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "assets_company_created_idx": {+ "name": "assets_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "assets_company_provider_idx": {+ "name": "assets_company_provider_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "assets_company_object_key_uq": {+ "name": "assets_company_object_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "assets_company_id_companies_id_fk": {+ "name": "assets_company_id_companies_id_fk",+ "tableFrom": "assets",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "issuer": {+ "name": "issuer",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_issuer_account_id_uq": {+ "name": "account_issuer_account_id_uq",+ "columns": [+ {+ "expression": "issuer",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.board_api_keys": {+ "name": "board_api_keys",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key_hash": {+ "name": "key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "board_api_keys_key_hash_idx": {+ "name": "board_api_keys_key_hash_idx",+ "columns": [+ {+ "expression": "key_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "board_api_keys_user_idx": {+ "name": "board_api_keys_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.browser_use_browsers": {+ "name": "browser_use_browsers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_browser_id": {+ "name": "provider_browser_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "browser_use_browsers_provider_uq": {+ "name": "browser_use_browsers_provider_uq",+ "columns": [+ {+ "expression": "provider_browser_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "browser_use_browsers_session_idx": {+ "name": "browser_use_browsers_session_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.browser_use_runs": {+ "name": "browser_use_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "invocation_id": {+ "name": "invocation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_run_id": {+ "name": "provider_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "recovery_cursor": {+ "name": "recovery_cursor",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'creating'"+ },+ "detached_until": {+ "name": "detached_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "event_cursor": {+ "name": "event_cursor",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "events_drained": {+ "name": "events_drained",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "accounted_cents": {+ "name": "accounted_cents",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "progress": {+ "name": "progress",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result": {+ "name": "result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "browser_use_runs_invocation_uq": {+ "name": "browser_use_runs_invocation_uq",+ "columns": [+ {+ "expression": "invocation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "browser_use_runs_provider_uq": {+ "name": "browser_use_runs_provider_uq",+ "columns": [+ {+ "expression": "provider_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "browser_use_runs_session_idx": {+ "name": "browser_use_runs_session_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.browser_use_sessions": {+ "name": "browser_use_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_session_id": {+ "name": "provider_session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'starting'"+ },+ "idle_deadline": {+ "name": "idle_deadline",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "stop_requested": {+ "name": "stop_requested",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "lease_token": {+ "name": "lease_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "lease_until": {+ "name": "lease_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_poll_at": {+ "name": "next_poll_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "browser_use_sessions_task_idx": {+ "name": "browser_use_sessions_task_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "browser_use_sessions_provider_uq": {+ "name": "browser_use_sessions_provider_uq",+ "columns": [+ {+ "expression": "provider_session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.browser_use_settings": {+ "name": "browser_use_settings",+ "schema": "",+ "columns": {+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "allowed_profile_ids": {+ "name": "allowed_profile_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "max_cost_usd": {+ "name": "max_cost_usd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.budget_incidents": {+ "name": "budget_incidents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "policy_id": {+ "name": "policy_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "scope_type": {+ "name": "scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "metric": {+ "name": "metric",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "window_kind": {+ "name": "window_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "window_start": {+ "name": "window_start",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "window_end": {+ "name": "window_end",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "threshold_type": {+ "name": "threshold_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "amount_limit": {+ "name": "amount_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "amount_observed": {+ "name": "amount_observed",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'open'"+ },+ "approval_id": {+ "name": "approval_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "budget_incidents_company_status_idx": {+ "name": "budget_incidents_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "budget_incidents_company_scope_idx": {+ "name": "budget_incidents_company_scope_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "budget_incidents_policy_window_threshold_idx": {+ "name": "budget_incidents_policy_window_threshold_idx",+ "columns": [+ {+ "expression": "policy_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_start",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "threshold_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"budget_incidents\".\"status\" = 'open'",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.budget_policies": {+ "name": "budget_policies",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "scope_type": {+ "name": "scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "metric": {+ "name": "metric",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'billed_cents'"+ },+ "window_kind": {+ "name": "window_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "amount": {+ "name": "amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "reservation_cents": {+ "name": "reservation_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true,+ "default": "'0'"+ },+ "warn_percent": {+ "name": "warn_percent",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 80+ },+ "hard_stop_enabled": {+ "name": "hard_stop_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "unpriced_usage_policy": {+ "name": "unpriced_usage_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'block'"+ },+ "notify_enabled": {+ "name": "notify_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "enforcement_version": {+ "name": "enforcement_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "enforcement_delivered_version": {+ "name": "enforcement_delivered_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "budget_policies_company_scope_active_idx": {+ "name": "budget_policies_company_scope_active_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "is_active",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "budget_policies_company_window_idx": {+ "name": "budget_policies_company_window_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "metric",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "budget_policies_company_scope_metric_unique_idx": {+ "name": "budget_policies_company_scope_metric_unique_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "metric",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "budget_policies_reservation_nonnegative": {+ "name": "budget_policies_reservation_nonnegative",+ "value": "\"budget_policies\".\"reservation_cents\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.built_in_managed_resources": {+ "name": "built_in_managed_resources",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "bundle_key": {+ "name": "bundle_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_kind": {+ "name": "resource_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_key": {+ "name": "resource_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_id": {+ "name": "resource_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "stock_version": {+ "name": "stock_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "stock_hash": {+ "name": "stock_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "defaults_json": {+ "name": "defaults_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "built_in_managed_resources_company_idx": {+ "name": "built_in_managed_resources_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "built_in_managed_resources_resource_idx": {+ "name": "built_in_managed_resources_resource_idx",+ "columns": [+ {+ "expression": "resource_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "built_in_managed_resources_company_bundle_resource_uq": {+ "name": "built_in_managed_resources_company_bundle_resource_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bundle_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.case_attachments": {+ "name": "case_attachments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "asset_id": {+ "name": "asset_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "case_attachments_company_case_idx": {+ "name": "case_attachments_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_attachments_asset_uq": {+ "name": "case_attachments_asset_uq",+ "columns": [+ {+ "expression": "asset_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.case_documents": {+ "name": "case_documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "case_documents_company_case_key_uq": {+ "name": "case_documents_company_case_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_documents_document_uq": {+ "name": "case_documents_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_documents_company_case_updated_idx": {+ "name": "case_documents_company_case_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.case_events": {+ "name": "case_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_agent_id": {+ "name": "actor_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "case_events_case_created_idx": {+ "name": "case_events_case_created_idx",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_events_company_case_idx": {+ "name": "case_events_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "case_events_kind_check": {+ "name": "case_events_kind_check",+ "value": "\"case_events\".\"kind\" in (\n 'created',\n 'updated',\n 'fields_changed',\n 'status_changed',\n 'issue_linked',\n 'issue_unlinked',\n 'document_revised',\n 'child_linked',\n 'attachment_added',\n 'label_added',\n 'label_removed'\n )"+ },+ "case_events_actor_type_check": {+ "name": "case_events_actor_type_check",+ "value": "\"case_events\".\"actor_type\" in ('user', 'agent', 'system')"+ }+ },+ "isRLSEnabled": false+ },+ "public.case_issue_links": {+ "name": "case_issue_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "case_issue_links_case_issue_uq": {+ "name": "case_issue_links_case_issue_uq",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_issue_links_company_case_idx": {+ "name": "case_issue_links_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_issue_links_issue_idx": {+ "name": "case_issue_links_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "case_issue_links_role_check": {+ "name": "case_issue_links_role_check",+ "value": "\"case_issue_links\".\"role\" in ('origin', 'work', 'reference')"+ }+ },+ "isRLSEnabled": false+ },+ "public.case_labels": {+ "name": "case_labels",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "case_labels_case_label_uq": {+ "name": "case_labels_case_label_uq",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "label_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_labels_company_case_idx": {+ "name": "case_labels_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "case_labels_label_idx": {+ "name": "case_labels_label_idx",+ "columns": [+ {+ "expression": "label_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cases": {+ "name": "cases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "case_number": {+ "name": "case_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "case_type": {+ "name": "case_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "fields": {+ "name": "fields",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "parent_case_id": {+ "name": "parent_case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cases_company_case_number_uq": {+ "name": "cases_company_case_number_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_identifier_uq": {+ "name": "cases_identifier_uq",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_company_type_key_uq": {+ "name": "cases_company_type_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_company_status_idx": {+ "name": "cases_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_company_type_idx": {+ "name": "cases_company_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_company_project_idx": {+ "name": "cases_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_parent_idx": {+ "name": "cases_parent_idx",+ "columns": [+ {+ "expression": "parent_case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cases_title_search_idx": {+ "name": "cases_title_search_idx",+ "columns": [+ {+ "expression": "title",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "cases_identifier_search_idx": {+ "name": "cases_identifier_search_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "cases_summary_search_idx": {+ "name": "cases_summary_search_idx",+ "columns": [+ {+ "expression": "summary",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ }+ },+ "foreignKeys": {+ "cases_company_id_companies_id_fk": {+ "name": "cases_company_id_companies_id_fk",+ "tableFrom": "cases",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cases_status_check": {+ "name": "cases_status_check",+ "value": "\"cases\".\"status\" in ('draft', 'in_progress', 'in_review', 'approved', 'done', 'cancelled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_actions": {+ "name": "chat_actions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "principal_id": {+ "name": "principal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_action_id": {+ "name": "provider_action_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'received'"+ },+ "result": {+ "name": "result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_actions_provider_action_uq": {+ "name": "chat_actions_provider_action_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_action_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_agent_routes": {+ "name": "chat_agent_routes",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_endpoint_id": {+ "name": "source_endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "destination_endpoint_id": {+ "name": "destination_endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "trigger_mode": {+ "name": "trigger_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'explicit_mention'"+ },+ "max_hops": {+ "name": "max_hops",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_agent_routes_pair_uq": {+ "name": "chat_agent_routes_pair_uq",+ "columns": [+ {+ "expression": "source_endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "destination_endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_agent_routes_hops_check": {+ "name": "chat_agent_routes_hops_check",+ "value": "\"chat_agent_routes\".\"max_hops\" between 1 and 8"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_conversations": {+ "name": "chat_conversations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "resource_id": {+ "name": "resource_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "external_conversation_id": {+ "name": "external_conversation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_thread_id": {+ "name": "external_thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "session_generation": {+ "name": "session_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "external_label": {+ "name": "external_label",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_url": {+ "name": "provider_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_direct_message": {+ "name": "is_direct_message",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "communication_guidance": {+ "name": "communication_guidance",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "last_activity_at": {+ "name": "last_activity_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_conversations_issue_idx": {+ "name": "chat_conversations_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_conversations_thread_uq": {+ "name": "chat_conversations_thread_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_conversation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "session_generation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_conversations_state_check": {+ "name": "chat_conversations_state_check",+ "value": "\"chat_conversations\".\"state\" in ('active', 'waiting', 'completed', 'unavailable', 'endpoint_removed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_deliveries": {+ "name": "chat_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "principal_id": {+ "name": "principal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_event_id": {+ "name": "provider_event_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "deduplication_key": {+ "name": "deduplication_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event_kind": {+ "name": "event_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "normalized_event": {+ "name": "normalized_event",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'received'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "redacted_error": {+ "name": "redacted_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "received_at": {+ "name": "received_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_deliveries_work_idx": {+ "name": "chat_deliveries_work_idx",+ "columns": [+ {+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_deliveries_event_uq": {+ "name": "chat_deliveries_event_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_deliveries_dedupe_uq": {+ "name": "chat_deliveries_dedupe_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "deduplication_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_deliveries_state_check": {+ "name": "chat_deliveries_state_check",+ "value": "\"chat_deliveries\".\"state\" in ('received', 'filtered', 'processing', 'processed', 'retry', 'failed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_endpoint_leases": {+ "name": "chat_endpoint_leases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "lease_key": {+ "name": "lease_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_endpoint_leases_active_uq": {+ "name": "chat_endpoint_leases_active_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lease_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoint_leases_expiry_idx": {+ "name": "chat_endpoint_leases_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_endpoint_resources": {+ "name": "chat_endpoint_resources",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_resource_id": {+ "name": "provider_resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "parent_provider_resource_id": {+ "name": "parent_provider_resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "detail": {+ "name": "detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_url": {+ "name": "provider_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "availability": {+ "name": "availability",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'available'"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_endpoint_resources_endpoint_idx": {+ "name": "chat_endpoint_resources_endpoint_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoint_resources_external_uq": {+ "name": "chat_endpoint_resources_external_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_endpoint_resources_availability_check": {+ "name": "chat_endpoint_resources_availability_check",+ "value": "\"chat_endpoint_resources\".\"availability\" in ('available', 'unavailable', 'removed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_endpoints": {+ "name": "chat_endpoints",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "publication_mode": {+ "name": "publication_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'automatic'"+ },+ "external_execution_policy": {+ "name": "external_execution_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'restricted'"+ },+ "assigned_agent_id": {+ "name": "assigned_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "sponsor_user_id": {+ "name": "sponsor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "deployment_mode": {+ "name": "deployment_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'direct'"+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_account_label": {+ "name": "provider_account_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "bot_external_id": {+ "name": "bot_external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "bot_username": {+ "name": "bot_username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "bot_display_name": {+ "name": "bot_display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "bot_avatar_url": {+ "name": "bot_avatar_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "communication_instructions": {+ "name": "communication_instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "allow_direct_messages": {+ "name": "allow_direct_messages",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "allow_group_chats": {+ "name": "allow_group_chats",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "allow_unlinked_people": {+ "name": "allow_unlinked_people",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "concurrency_policy": {+ "name": "concurrency_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queue'"+ },+ "capabilities": {+ "name": "capabilities",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"threads\":false,\"directMessages\":false,\"nativeStreaming\":false,\"messageEdits\":false,\"messageDeletes\":false,\"reactions\":false,\"files\":false,\"cards\":false,\"actions\":false,\"modals\":false,\"slashCommands\":false,\"ephemeralMessages\":false,\"proactiveDirectMessages\":false}'::jsonb"+ },+ "setup": {+ "name": "setup",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"step\":\"provider_setup\"}'::jsonb"+ },+ "health_message": {+ "name": "health_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_event_at": {+ "name": "last_event_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_publication_at": {+ "name": "last_publication_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activated_at": {+ "name": "activated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_endpoints_company_idx": {+ "name": "chat_endpoints_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_agent_idx": {+ "name": "chat_endpoints_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "assigned_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_status_idx": {+ "name": "chat_endpoints_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_public_id_uq": {+ "name": "chat_endpoints_public_id_uq",+ "columns": [+ {+ "expression": "public_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_agentmail_inbox_uq": {+ "name": "chat_endpoints_agentmail_inbox_uq",+ "columns": [+ {+ "expression": "bot_external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"chat_endpoints\".\"provider\" = 'agentmail' and \"chat_endpoints\".\"status\" != 'archived' and \"chat_endpoints\".\"bot_external_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_connection_uq": {+ "name": "chat_endpoints_connection_uq",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_live_bot_external_uq": {+ "name": "chat_endpoints_live_bot_external_uq",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bot_external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_photon_number_uq": {+ "name": "chat_endpoints_photon_number_uq",+ "columns": [+ {+ "expression": "bot_external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"chat_endpoints\".\"provider\" = 'imessage-photon' and \"chat_endpoints\".\"status\" <> 'archived' and \"chat_endpoints\".\"bot_external_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_live_discord_bot_external_uq": {+ "name": "chat_endpoints_live_discord_bot_external_uq",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bot_external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_live_global_app_bot_external_uq": {+ "name": "chat_endpoints_live_global_app_bot_external_uq",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bot_external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "chat_endpoints_live_bot_username_uq": {+ "name": "chat_endpoints_live_bot_username_uq",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bot_username",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_endpoints_company_id_uq": {+ "name": "chat_endpoints_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_endpoints_publication_mode_check": {+ "name": "chat_endpoints_publication_mode_check",+ "value": "\"chat_endpoints\".\"publication_mode\" in ('automatic', 'explicit')"+ },+ "chat_endpoints_execution_policy_check": {+ "name": "chat_endpoints_execution_policy_check",+ "value": "\"chat_endpoints\".\"external_execution_policy\" in ('restricted', 'agent')"+ },+ "chat_endpoints_email_policy_check": {+ "name": "chat_endpoints_email_policy_check",+ "value": "\"chat_endpoints\".\"provider\" <> 'agentmail' or (\"chat_endpoints\".\"publication_mode\" = 'explicit' and \"chat_endpoints\".\"external_execution_policy\" = 'agent')"+ },+ "chat_endpoints_provider_check": {+ "name": "chat_endpoints_provider_check",+ "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"+ },+ "chat_endpoints_status_check": {+ "name": "chat_endpoints_status_check",+ "value": "\"chat_endpoints\".\"status\" in ('draft', 'verifying', 'active', 'paused', 'attention', 'revoked', 'archived')"+ },+ "chat_endpoints_deployment_check": {+ "name": "chat_endpoints_deployment_check",+ "value": "\"chat_endpoints\".\"deployment_mode\" in ('direct', 'relay')"+ },+ "chat_endpoints_concurrency_check": {+ "name": "chat_endpoints_concurrency_check",+ "value": "\"chat_endpoints\".\"concurrency_policy\" in ('burst', 'queue', 'debounce', 'drop', 'concurrent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_external_principals": {+ "name": "chat_external_principals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_account_id": {+ "name": "provider_account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "handle": {+ "name": "handle",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "avatar_url": {+ "name": "avatar_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "is_bot": {+ "name": "is_bot",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_external_principals_company_idx": {+ "name": "chat_external_principals_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_external_principals_external_uq": {+ "name": "chat_external_principals_external_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_account_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_external_principals_provider_check": {+ "name": "chat_external_principals_provider_check",+ "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"+ },+ "chat_external_principals_kind_check": {+ "name": "chat_external_principals_kind_check",+ "value": "\"chat_external_principals\".\"kind\" in ('user', 'bot', 'app', 'system')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_identity_links": {+ "name": "chat_identity_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "principal_id": {+ "name": "principal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "paperclip_user_id": {+ "name": "paperclip_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "confirmation_token_hash": {+ "name": "confirmation_token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "confirmed_at": {+ "name": "confirmed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_identity_links_user_idx": {+ "name": "chat_identity_links_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "paperclip_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_identity_links_endpoint_principal_uq": {+ "name": "chat_identity_links_endpoint_principal_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_identity_links_status_check": {+ "name": "chat_identity_links_status_check",+ "value": "\"chat_identity_links\".\"status\" in ('pending', 'linked', 'revoked', 'expired')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_message_links": {+ "name": "chat_message_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "publication_id": {+ "name": "publication_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "comment_id": {+ "name": "comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_message_id": {+ "name": "provider_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "direction": {+ "name": "direction",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_message_links_provider_message_uq": {+ "name": "chat_message_links_provider_message_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "conversation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_message_links_direction_check": {+ "name": "chat_message_links_direction_check",+ "value": "\"chat_message_links\".\"direction\" in ('inbound', 'outbound')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_publications": {+ "name": "chat_publications",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "comment_id": {+ "name": "comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "provider_message_id": {+ "name": "provider_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_url": {+ "name": "provider_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "redacted_error": {+ "name": "redacted_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "published_at": {+ "name": "published_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_publications_company_id_uq": {+ "name": "chat_publications_company_id_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_publications_work_idx": {+ "name": "chat_publications_work_idx",+ "columns": [+ {+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_publications_idempotency_uq": {+ "name": "chat_publications_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_publications_state_check": {+ "name": "chat_publications_state_check",+ "value": "\"chat_publications\".\"state\" in ('pending', 'streaming', 'published', 'retry', 'delivery_unknown', 'failed', 'cancelled', 'awaiting_consent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_sdk_state": {+ "name": "chat_sdk_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "state_key": {+ "name": "state_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_sdk_state_key_uq": {+ "name": "chat_sdk_state_key_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "state_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_sdk_state_expiry_idx": {+ "name": "chat_sdk_state_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_completion_deliveries": {+ "name": "chat_completion_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status_version": {+ "name": "status_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "target_run_id": {+ "name": "target_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "response_comment_id": {+ "name": "response_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_completion_deliveries_transition_uq": {+ "name": "chat_completion_deliveries_transition_uq",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_completion_deliveries_pending_idx": {+ "name": "chat_completion_deliveries_pending_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "task_id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_task_handoffs": {+ "name": "chat_task_handoffs",+ "schema": "",+ "columns": {+ "task_id": {+ "name": "task_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_generation": {+ "name": "session_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_task_handoffs_source_idx": {+ "name": "chat_task_handoffs_source_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "conversation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_discord_command_owners": {+ "name": "chat_discord_command_owners",+ "schema": "",+ "columns": {+ "application_id": {+ "name": "application_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "action_id": {+ "name": "action_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_discord_command_owners_application_check": {+ "name": "chat_discord_command_owners_application_check",+ "value": "\"chat_discord_command_owners\".\"application_id\" ~ '^[1-9][0-9]{16,19}$'"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_github_configurations": {+ "name": "chat_github_configurations",+ "schema": "",+ "columns": {+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "configuration": {+ "name": "configuration",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_github_config_revision_check": {+ "name": "chat_github_config_revision_check",+ "value": "\"chat_github_configurations\".\"revision\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_github_registrations": {+ "name": "chat_github_registrations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state_hash": {+ "name": "state_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trusted_origin": {+ "name": "trusted_origin",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "consumed_at": {+ "name": "consumed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_github_registration_state_uq": {+ "name": "chat_github_registration_state_uq",+ "columns": [+ {+ "expression": "state_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_github_registration_endpoint_idx": {+ "name": "chat_github_registration_endpoint_idx",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_github_registration_status_check": {+ "name": "chat_github_registration_status_check",+ "value": "\"chat_github_registrations\".\"status\" in ('pending', 'exchanging', 'completed', 'failed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_github_reviews": {+ "name": "chat_github_reviews",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "repository_id": {+ "name": "repository_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository": {+ "name": "repository",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "pull_number": {+ "name": "pull_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "head_sha": {+ "name": "head_sha",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "configuration_revision": {+ "name": "configuration_revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "policy_snapshot": {+ "name": "policy_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "event": {+ "name": "event",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "assessment": {+ "name": "assessment",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "conclusion": {+ "name": "conclusion",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "check_id": {+ "name": "check_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "check_url": {+ "name": "check_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary_id": {+ "name": "summary_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary_url": {+ "name": "summary_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "publication_receipts": {+ "name": "publication_receipts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_github_reviews_delivery_uq": {+ "name": "chat_github_reviews_delivery_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "delivery_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_github_reviews_pull_idx": {+ "name": "chat_github_reviews_pull_idx",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "pull_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_github_reviews_task_idx": {+ "name": "chat_github_reviews_task_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_github_review_pull_number_check": {+ "name": "chat_github_review_pull_number_check",+ "value": "\"chat_github_reviews\".\"pull_number\" > 0"+ },+ "chat_github_review_state_check": {+ "name": "chat_github_review_state_check",+ "value": "\"chat_github_reviews\".\"state\" in ('queued', 'running', 'completed', 'incomplete', 'error', 'superseded', 'manual_required')"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_teams_file_transfers": {+ "name": "chat_teams_file_transfers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "publication_id": {+ "name": "publication_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "comment_id": {+ "name": "comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "principal_id": {+ "name": "principal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "authorized_user_id": {+ "name": "authorized_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_generation": {+ "name": "runtime_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "credential_fingerprint": {+ "name": "credential_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_generation": {+ "name": "conversation_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_digest": {+ "name": "source_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "authority_digest": {+ "name": "authority_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "bot_app_id": {+ "name": "bot_app_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "aad_object_id": {+ "name": "aad_object_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_conversation_id": {+ "name": "provider_conversation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_user_id": {+ "name": "provider_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "sha256": {+ "name": "sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "byte_size": {+ "name": "byte_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_sha256": {+ "name": "token_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'consent_pending'"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "attempt_id": {+ "name": "attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "attempt_expires_at": {+ "name": "attempt_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "consent_message_id": {+ "name": "consent_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "file_info_message_id": {+ "name": "file_info_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_activity_id": {+ "name": "response_activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_digest": {+ "name": "response_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "private_state": {+ "name": "private_state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_teams_file_transfers_publication_uq": {+ "name": "chat_teams_file_transfers_publication_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "publication_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_teams_file_transfers_token_uq": {+ "name": "chat_teams_file_transfers_token_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "token_sha256",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_teams_file_transfers_work_idx": {+ "name": "chat_teams_file_transfers_work_idx",+ "columns": [+ {+ "expression": "phase",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "attempt_expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_teams_file_transfers_phase_check": {+ "name": "chat_teams_file_transfers_phase_check",+ "value": "\"chat_teams_file_transfers\".\"phase\" in ('consent_pending','consent_sending','consent_unknown','awaiting_consent','upload_pending','uploading','upload_unknown','file_info_pending','file_info_sending','file_info_unknown','delivered','declined','expired','cancelled','conflict')"+ },+ "chat_teams_file_transfers_bounds_check": {+ "name": "chat_teams_file_transfers_bounds_check",+ "value": "\"chat_teams_file_transfers\".\"version\" > 0 and \"chat_teams_file_transfers\".\"runtime_generation\" >= 0 and \"chat_teams_file_transfers\".\"conversation_generation\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" < 62914560"+ },+ "chat_teams_file_transfers_hash_check": {+ "name": "chat_teams_file_transfers_hash_check",+ "value": "\"chat_teams_file_transfers\".\"source_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"authority_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"sha256\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"token_sha256\" ~ '^[a-f0-9]{64}$'"+ },+ "chat_teams_file_transfers_attempt_check": {+ "name": "chat_teams_file_transfers_attempt_check",+ "value": "(\"chat_teams_file_transfers\".\"attempt_id\" is null) = (\"chat_teams_file_transfers\".\"attempt_expires_at\" is null)"+ }+ },+ "isRLSEnabled": false+ },+ "public.cli_auth_challenges": {+ "name": "cli_auth_challenges",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "secret_hash": {+ "name": "secret_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "command": {+ "name": "command",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_name": {+ "name": "client_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "requested_access": {+ "name": "requested_access",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'board'"+ },+ "requested_company_id": {+ "name": "requested_company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "pending_key_hash": {+ "name": "pending_key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "pending_key_name": {+ "name": "pending_key_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "approved_by_user_id": {+ "name": "approved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "board_api_key_id": {+ "name": "board_api_key_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "approved_at": {+ "name": "approved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "cancelled_at": {+ "name": "cancelled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cli_auth_challenges_secret_hash_idx": {+ "name": "cli_auth_challenges_secret_hash_idx",+ "columns": [+ {+ "expression": "secret_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cli_auth_challenges_approved_by_idx": {+ "name": "cli_auth_challenges_approved_by_idx",+ "columns": [+ {+ "expression": "approved_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cli_auth_challenges_requested_company_idx": {+ "name": "cli_auth_challenges_requested_company_idx",+ "columns": [+ {+ "expression": "requested_company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.companies": {+ "name": "companies",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "pause_reason": {+ "name": "pause_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paused_at": {+ "name": "paused_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "issue_prefix": {+ "name": "issue_prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'PAP'"+ },+ "issue_counter": {+ "name": "issue_counter",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "budget_monthly_cents": {+ "name": "budget_monthly_cents",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "spend_month_utc": {+ "name": "spend_month_utc",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "spent_monthly_cents": {+ "name": "spent_monthly_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "default_responsible_user_id": {+ "name": "default_responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "require_board_approval_for_new_agents": {+ "name": "require_board_approval_for_new_agents",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "interaction_resolver_governance": {+ "name": "interaction_resolver_governance",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "feedback_data_sharing_enabled": {+ "name": "feedback_data_sharing_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "feedback_data_sharing_consent_at": {+ "name": "feedback_data_sharing_consent_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "feedback_data_sharing_consent_by_user_id": {+ "name": "feedback_data_sharing_consent_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "feedback_data_sharing_terms_version": {+ "name": "feedback_data_sharing_terms_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "companies_issue_prefix_idx": {+ "name": "companies_issue_prefix_idx",+ "columns": [+ {+ "expression": "issue_prefix",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_logos": {+ "name": "company_logos",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "asset_id": {+ "name": "asset_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_logos_company_uq": {+ "name": "company_logos_company_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_logos_asset_uq": {+ "name": "company_logos_asset_uq",+ "columns": [+ {+ "expression": "asset_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_memberships": {+ "name": "company_memberships",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "principal_type": {+ "name": "principal_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "principal_id": {+ "name": "principal_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "membership_role": {+ "name": "membership_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_memberships_company_principal_unique_idx": {+ "name": "company_memberships_company_principal_unique_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_memberships_principal_status_idx": {+ "name": "company_memberships_principal_status_idx",+ "columns": [+ {+ "expression": "principal_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_memberships_company_status_idx": {+ "name": "company_memberships_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "company_memberships_company_id_companies_id_fk": {+ "name": "company_memberships_company_id_companies_id_fk",+ "tableFrom": "company_memberships",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_onboarding_seeds": {+ "name": "company_onboarding_seeds",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mission": {+ "name": "mission",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_name": {+ "name": "agent_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_role": {+ "name": "agent_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_task_title": {+ "name": "first_task_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_task_details": {+ "name": "first_task_details",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "applied_at": {+ "name": "applied_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_onboarding_seeds_company_uq": {+ "name": "company_onboarding_seeds_company_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_secret_bindings": {+ "name": "company_secret_bindings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config_path": {+ "name": "config_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "version_selector": {+ "name": "version_selector",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'latest'"+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "projection_class": {+ "name": "projection_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unclassified'"+ },+ "projection_allowlist_key": {+ "name": "projection_allowlist_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_secret_bindings_company_idx": {+ "name": "company_secret_bindings_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_bindings_secret_idx": {+ "name": "company_secret_bindings_secret_idx",+ "columns": [+ {+ "expression": "secret_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_bindings_target_idx": {+ "name": "company_secret_bindings_target_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_bindings_target_path_uq": {+ "name": "company_secret_bindings_target_path_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "config_path",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_secret_proposals": {+ "name": "company_secret_proposals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "proposed_name": {+ "name": "proposed_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "proposed_key": {+ "name": "proposed_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "proposed_description": {+ "name": "proposed_description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "justification": {+ "name": "justification",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value_ciphertext": {+ "name": "value_ciphertext",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "value_fingerprint_sha256": {+ "name": "value_fingerprint_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "value_length": {+ "name": "value_length",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "secret_proposal_id": {+ "name": "secret_proposal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "target_id": {+ "name": "target_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "config_path": {+ "name": "config_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "projection_class": {+ "name": "projection_class",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unclassified'"+ },+ "binding_target_policy_snapshot": {+ "name": "binding_target_policy_snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "proposer_ancestor_ids_snapshot": {+ "name": "proposer_ancestor_ids_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "target_ancestor_ids_snapshot": {+ "name": "target_ancestor_ids_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "proposed_by_agent_id": {+ "name": "proposed_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_issue_id": {+ "name": "origin_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "origin_run_id": {+ "name": "origin_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_user_id": {+ "name": "resolved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "resolution_reason": {+ "name": "resolution_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_secret_id": {+ "name": "created_secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "applied_binding_config_path": {+ "name": "applied_binding_config_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ciphertext_scrubbed_at": {+ "name": "ciphertext_scrubbed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_secret_proposals_company_status_idx": {+ "name": "company_secret_proposals_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_proposals_proposer_status_idx": {+ "name": "company_secret_proposals_proposer_status_idx",+ "columns": [+ {+ "expression": "proposed_by_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_proposals_expiry_idx": {+ "name": "company_secret_proposals_expiry_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_proposals_secret_proposal_idx": {+ "name": "company_secret_proposals_secret_proposal_idx",+ "columns": [+ {+ "expression": "secret_proposal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_proposals_interaction_idx": {+ "name": "company_secret_proposals_interaction_idx",+ "columns": [+ {+ "expression": "interaction_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "company_secret_proposals_kind_check": {+ "name": "company_secret_proposals_kind_check",+ "value": "\"company_secret_proposals\".\"kind\" in ('secret', 'binding')"+ },+ "company_secret_proposals_status_check": {+ "name": "company_secret_proposals_status_check",+ "value": "\"company_secret_proposals\".\"status\" in ('pending', 'approved', 'rejected', 'withdrawn', 'expired')"+ },+ "company_secret_proposals_projection_check": {+ "name": "company_secret_proposals_projection_check",+ "value": "\"company_secret_proposals\".\"projection_class\" = 'unclassified'"+ },+ "company_secret_proposals_shape_check": {+ "name": "company_secret_proposals_shape_check",+ "value": "(\n \"company_secret_proposals\".\"kind\" = 'secret'\n and \"company_secret_proposals\".\"proposed_name\" is not null\n and \"company_secret_proposals\".\"proposed_key\" is not null\n and \"company_secret_proposals\".\"secret_id\" is null\n and \"company_secret_proposals\".\"secret_proposal_id\" is null\n and \"company_secret_proposals\".\"target_type\" is null\n and \"company_secret_proposals\".\"target_id\" is null\n and \"company_secret_proposals\".\"config_path\" is null\n ) or (\n \"company_secret_proposals\".\"kind\" = 'binding'\n and ((\"company_secret_proposals\".\"secret_id\" is not null)::int + (\"company_secret_proposals\".\"secret_proposal_id\" is not null)::int) = 1\n and \"company_secret_proposals\".\"target_type\" = 'agent'\n and \"company_secret_proposals\".\"target_id\" is not null\n and \"company_secret_proposals\".\"config_path\" is not null\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.company_secret_provider_configs": {+ "name": "company_secret_provider_configs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'ready'"+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "health_status": {+ "name": "health_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "health_checked_at": {+ "name": "health_checked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "health_message": {+ "name": "health_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "health_details": {+ "name": "health_details",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "disabled_at": {+ "name": "disabled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_secret_provider_configs_company_idx": {+ "name": "company_secret_provider_configs_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_provider_configs_company_provider_idx": {+ "name": "company_secret_provider_configs_company_provider_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_provider_configs_default_uq": {+ "name": "company_secret_provider_configs_default_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"company_secret_provider_configs\".\"is_default\" = true",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_secret_versions": {+ "name": "company_secret_versions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "material": {+ "name": "material",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "value_sha256": {+ "name": "value_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_version_ref": {+ "name": "provider_version_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'current'"+ },+ "fingerprint_sha256": {+ "name": "fingerprint_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rotation_job_id": {+ "name": "rotation_job_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "company_secret_versions_secret_idx": {+ "name": "company_secret_versions_secret_idx",+ "columns": [+ {+ "expression": "secret_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_versions_value_sha256_idx": {+ "name": "company_secret_versions_value_sha256_idx",+ "columns": [+ {+ "expression": "value_sha256",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_versions_fingerprint_idx": {+ "name": "company_secret_versions_fingerprint_idx",+ "columns": [+ {+ "expression": "fingerprint_sha256",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secret_versions_secret_version_uq": {+ "name": "company_secret_versions_secret_version_uq",+ "columns": [+ {+ "expression": "secret_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_secrets": {+ "name": "company_secrets",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'company'"+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_secret_definition_id": {+ "name": "user_secret_definition_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_encrypted'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "managed_mode": {+ "name": "managed_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip_managed'"+ },+ "external_ref": {+ "name": "external_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_config_id": {+ "name": "provider_config_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_metadata": {+ "name": "provider_metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "ai_session_epoch": {+ "name": "ai_session_epoch",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "latest_version": {+ "name": "latest_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_resolved_at": {+ "name": "last_resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_rotated_at": {+ "name": "last_rotated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_secrets_company_idx": {+ "name": "company_secrets_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_company_scope_idx": {+ "name": "company_secrets_company_scope_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_company_owner_idx": {+ "name": "company_secrets_company_owner_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_user_definition_owner_idx": {+ "name": "company_secrets_user_definition_owner_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_secret_definition_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_company_provider_idx": {+ "name": "company_secrets_company_provider_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_provider_config_idx": {+ "name": "company_secrets_provider_config_idx",+ "columns": [+ {+ "expression": "provider_config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_company_name_uq": {+ "name": "company_secrets_company_name_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"company_secrets\".\"scope\" = 'company' and \"company_secrets\".\"deleted_at\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_company_key_uq": {+ "name": "company_secrets_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"company_secrets\".\"scope\" = 'company' and \"company_secrets\".\"deleted_at\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_secrets_user_definition_owner_uq": {+ "name": "company_secrets_user_definition_owner_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_secret_definition_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"company_secrets\".\"scope\" = 'user' and \"company_secrets\".\"deleted_at\" is null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "company_secrets_scope_shape_check": {+ "name": "company_secrets_scope_shape_check",+ "value": "(\n \"company_secrets\".\"scope\" = 'company'\n and \"company_secrets\".\"owner_user_id\" is null\n and \"company_secrets\".\"user_secret_definition_id\" is null\n ) or (\n \"company_secrets\".\"scope\" = 'user'\n and \"company_secrets\".\"owner_user_id\" is not null\n and \"company_secrets\".\"user_secret_definition_id\" is not null\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.company_skill_policies": {+ "name": "company_skill_policies",+ "schema": "",+ "columns": {+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "schema_version": {+ "name": "schema_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "default_effect": {+ "name": "default_effect",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rules": {+ "name": "rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_source_entries": {+ "name": "company_skill_source_entries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "inspection": {+ "name": "inspection",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "skill_id": {+ "name": "skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "selection": {+ "name": "selection",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'new'"+ },+ "present": {+ "name": "present",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "company_skill_source_entries_source_path_idx": {+ "name": "company_skill_source_entries_source_path_idx",+ "columns": [+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "path",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_source_entries_company_skill_idx": {+ "name": "company_skill_source_entries_company_skill_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_sources": {+ "name": "company_skill_sources",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "repository_id": {+ "name": "repository_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "repository_url": {+ "name": "repository_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "full_name": {+ "name": "full_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tracking_ref": {+ "name": "tracking_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "excluded_folders": {+ "name": "excluded_folders",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_success_at": {+ "name": "last_success_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_scan_commit": {+ "name": "last_scan_commit",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "lease_token": {+ "name": "lease_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "lease_expires_at": {+ "name": "lease_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_sources_repository_ref_idx": {+ "name": "company_skill_sources_repository_ref_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository_url",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tracking_ref",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_sources_identity_ref_idx": {+ "name": "company_skill_sources_identity_ref_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tracking_ref",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "company_skill_sources_connection_id_tool_connections_id_fk": {+ "name": "company_skill_sources_connection_id_tool_connections_id_fk",+ "tableFrom": "company_skill_sources",+ "tableTo": "tool_connections",+ "columnsFrom": [+ "connection_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_comments": {+ "name": "company_skill_comments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_skill_id": {+ "name": "company_skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "parent_comment_id": {+ "name": "parent_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_comments_company_skill_created_idx": {+ "name": "company_skill_comments_company_skill_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_comments_parent_idx": {+ "name": "company_skill_comments_parent_idx",+ "columns": [+ {+ "expression": "parent_comment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_stars": {+ "name": "company_skill_stars",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_skill_id": {+ "name": "company_skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_stars_skill_agent_idx": {+ "name": "company_skill_stars_skill_agent_idx",+ "columns": [+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_stars_skill_user_idx": {+ "name": "company_skill_stars_skill_user_idx",+ "columns": [+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_stars_company_skill_created_idx": {+ "name": "company_skill_stars_company_skill_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_test_inputs": {+ "name": "company_skill_test_inputs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "skill_id": {+ "name": "skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_test_inputs_company_skill_name_idx": {+ "name": "company_skill_test_inputs_company_skill_name_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_test_inputs_company_skill_active_idx": {+ "name": "company_skill_test_inputs_company_skill_active_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "deleted_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_test_run_templates": {+ "name": "company_skill_test_run_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_test_run_templates_company_active_idx": {+ "name": "company_skill_test_run_templates_company_active_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "deleted_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_test_runs": {+ "name": "company_skill_test_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "skill_id": {+ "name": "skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "input_id": {+ "name": "input_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "input_snapshot": {+ "name": "input_snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "skill_version_id": {+ "name": "skill_version_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_config_snapshot": {+ "name": "agent_config_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "template_id": {+ "name": "template_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "template_name": {+ "name": "template_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "template_body": {+ "name": "template_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "rendered_template_body": {+ "name": "rendered_template_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "harness_issue_description": {+ "name": "harness_issue_description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "output_document_key": {+ "name": "output_document_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'output'"+ },+ "output_snapshot": {+ "name": "output_snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "superseded_at": {+ "name": "superseded_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "harness_issue_expires_at": {+ "name": "harness_issue_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "harness_issue_deleted_at": {+ "name": "harness_issue_deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_test_runs_company_skill_created_idx": {+ "name": "company_skill_test_runs_company_skill_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_test_runs_company_issue_idx": {+ "name": "company_skill_test_runs_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_test_runs_company_input_created_idx": {+ "name": "company_skill_test_runs_company_input_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "input_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_test_runs_company_status_idx": {+ "name": "company_skill_test_runs_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_test_runs_company_harness_expires_idx": {+ "name": "company_skill_test_runs_company_harness_expires_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "harness_issue_expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skill_versions": {+ "name": "company_skill_versions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_skill_id": {+ "name": "company_skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision_number": {+ "name": "revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "release_id": {+ "name": "release_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "release_name": {+ "name": "release_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "released_at": {+ "name": "released_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "file_inventory": {+ "name": "file_inventory",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skill_versions_skill_revision_idx": {+ "name": "company_skill_versions_skill_revision_idx",+ "columns": [+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revision_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_versions_skill_release_idx": {+ "name": "company_skill_versions_skill_release_idx",+ "columns": [+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "release_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"company_skill_versions\".\"release_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skill_versions_company_skill_created_idx": {+ "name": "company_skill_versions_company_skill_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "company_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_skills": {+ "name": "company_skills",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "folder_id": {+ "name": "folder_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "markdown": {+ "name": "markdown",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_type": {+ "name": "source_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_path'"+ },+ "source_locator": {+ "name": "source_locator",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_ref": {+ "name": "source_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trust_level": {+ "name": "trust_level",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'markdown_only'"+ },+ "compatibility": {+ "name": "compatibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'compatible'"+ },+ "file_inventory": {+ "name": "file_inventory",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "icon_url": {+ "name": "icon_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tagline": {+ "name": "tagline",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "author_name": {+ "name": "author_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "homepage_url": {+ "name": "homepage_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "categories": {+ "name": "categories",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'"+ },+ "sharing_scope": {+ "name": "sharing_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'company'"+ },+ "public_share_token": {+ "name": "public_share_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "forked_from_skill_id": {+ "name": "forked_from_skill_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "forked_from_company_id": {+ "name": "forked_from_company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "star_count": {+ "name": "star_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "install_count": {+ "name": "install_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "fork_count": {+ "name": "fork_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "current_version_id": {+ "name": "current_version_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_skills_company_key_idx": {+ "name": "company_skills_company_key_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skills_company_name_idx": {+ "name": "company_skills_company_name_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skills_company_folder_idx": {+ "name": "company_skills_company_folder_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skills_company_categories_idx": {+ "name": "company_skills_company_categories_idx",+ "columns": [+ {+ "expression": "categories",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "company_skills_company_sharing_scope_idx": {+ "name": "company_skills_company_sharing_scope_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "sharing_scope",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skills_company_current_version_idx": {+ "name": "company_skills_company_current_version_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "current_version_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_skills_company_forked_from_idx": {+ "name": "company_skills_company_forked_from_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "forked_from_skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_transfer_runs": {+ "name": "company_transfer_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "direction": {+ "name": "direction",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "actor_key": {+ "name": "actor_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "container_ref": {+ "name": "container_ref",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "manifest_sha256": {+ "name": "manifest_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "manifest": {+ "name": "manifest",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "chunk_count": {+ "name": "chunk_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "blob_count": {+ "name": "blob_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "completed_parts": {+ "name": "completed_parts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_transfer_runs_company_idx": {+ "name": "company_transfer_runs_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_transfer_runs_idempotency_direction_idx": {+ "name": "company_transfer_runs_idempotency_direction_idx",+ "columns": [+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "direction",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_transfer_runs_actor_status_idx": {+ "name": "company_transfer_runs_actor_status_idx",+ "columns": [+ {+ "expression": "actor_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.company_user_sidebar_preferences": {+ "name": "company_user_sidebar_preferences",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_order": {+ "name": "project_order",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "company_user_sidebar_preferences_company_idx": {+ "name": "company_user_sidebar_preferences_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_user_sidebar_preferences_user_idx": {+ "name": "company_user_sidebar_preferences_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "company_user_sidebar_preferences_company_user_uq": {+ "name": "company_user_sidebar_preferences_company_user_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.completion_contracts": {+ "name": "completion_contracts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "schema_version": {+ "name": "schema_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "policy_version": {+ "name": "policy_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "risk": {+ "name": "risk",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "completion_authority": {+ "name": "completion_authority",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "incomplete_criteria_policy": {+ "name": "incomplete_criteria_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "contract_json": {+ "name": "contract_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "canonical_sha256": {+ "name": "canonical_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_actor_type": {+ "name": "created_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_actor_id": {+ "name": "created_by_actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "supersedes_contract_id": {+ "name": "supersedes_contract_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "completion_contracts_issue_revision_uq": {+ "name": "completion_contracts_issue_revision_uq",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revision",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "completion_contracts_issue_hash_uq": {+ "name": "completion_contracts_issue_hash_uq",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "canonical_sha256",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.connection_event_deliveries": {+ "name": "connection_event_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_delivery_id": {+ "name": "provider_delivery_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "event": {+ "name": "event",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "installation_id": {+ "name": "installation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "repository_id": {+ "name": "repository_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "normalized_payload": {+ "name": "normalized_payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'received'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_created_at": {+ "name": "provider_created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "processed_at": {+ "name": "processed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_event_deliveries_company_provider_id_uq": {+ "name": "connection_event_deliveries_company_provider_id_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_delivery_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_event_deliveries_company_status_idx": {+ "name": "connection_event_deliveries_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.connection_intent_deliveries": {+ "name": "connection_intent_deliveries",+ "schema": "",+ "columns": {+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_intent_deliveries_pending_idx": {+ "name": "connection_intent_deliveries_pending_idx",+ "columns": [+ {+ "expression": "delivered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cost_events": {+ "name": "cost_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "billing_code": {+ "name": "billing_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "receipt_hash": {+ "name": "receipt_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_request_id": {+ "name": "provider_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reported_cost_cents": {+ "name": "reported_cost_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": false+ },+ "pricing_provenance": {+ "name": "pricing_provenance",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "biller": {+ "name": "biller",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "billing_type": {+ "name": "billing_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "cost_status": {+ "name": "cost_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'reported'"+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "cached_input_tokens": {+ "name": "cached_input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "cost_cents": {+ "name": "cost_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "occurred_at": {+ "name": "occurred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cost_events_company_receipt_idx": {+ "name": "cost_events_company_receipt_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_provider_request_idx": {+ "name": "cost_events_provider_request_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "biller",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_request_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_project_occurred_idx": {+ "name": "cost_events_company_project_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_unpriced_idx": {+ "name": "cost_events_unpriced_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"cost_events\".\"cost_status\" = 'unpriced' and \"cost_events\".\"billing_type\" <> 'subscription_included'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_occurred_idx": {+ "name": "cost_events_company_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_agent_occurred_idx": {+ "name": "cost_events_company_agent_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_provider_occurred_idx": {+ "name": "cost_events_company_provider_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_biller_occurred_idx": {+ "name": "cost_events_company_biller_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "biller",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "cost_events_company_heartbeat_run_idx": {+ "name": "cost_events_company_heartbeat_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cost_events_nonnegative_amounts": {+ "name": "cost_events_nonnegative_amounts",+ "value": "\"cost_events\".\"cost_cents\" >= 0 and \"cost_events\".\"input_tokens\" >= 0 and \"cost_events\".\"cached_input_tokens\" >= 0 and \"cost_events\".\"output_tokens\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_archive_notification_outbox": {+ "name": "decision_archive_notification_outbox",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "archive_version": {+ "name": "archive_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "origin_agent_id": {+ "name": "origin_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_issue_id": {+ "name": "origin_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_archive_notification_outbox_uq": {+ "name": "decision_archive_notification_outbox_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "archive_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_archive_notification_outbox_pending_idx": {+ "name": "decision_archive_notification_outbox_pending_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "decision_archive_notification_outbox_status_check": {+ "name": "decision_archive_notification_outbox_status_check",+ "value": "\"decision_archive_notification_outbox\".\"status\" IN ('pending', 'delivering', 'delivered')"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_queue_items": {+ "name": "decision_queue_items",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "queue_id": {+ "name": "queue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "added_by_type": {+ "name": "added_by_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "added_by_agent_id": {+ "name": "added_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "added_by_user_id": {+ "name": "added_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "added_by_run_id": {+ "name": "added_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "added_by_agent_api_key_id": {+ "name": "added_by_agent_api_key_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_queue_items_queue_source_uq": {+ "name": "decision_queue_items_queue_source_uq",+ "columns": [+ {+ "expression": "queue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_queue_items_company_source_idx": {+ "name": "decision_queue_items_company_source_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id",+ "company_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "decision_queue_items_actor_check": {+ "name": "decision_queue_items_actor_check",+ "value": "(\n (\"decision_queue_items\".\"added_by_type\" = 'agent' AND \"decision_queue_items\".\"added_by_agent_id\" IS NOT NULL AND \"decision_queue_items\".\"added_by_user_id\" IS NULL)\n OR (\"decision_queue_items\".\"added_by_type\" = 'user' AND \"decision_queue_items\".\"added_by_agent_id\" IS NULL AND \"decision_queue_items\".\"added_by_user_id\" IS NOT NULL)\n OR (\"decision_queue_items\".\"added_by_type\" = 'system' AND \"decision_queue_items\".\"added_by_agent_id\" IS NULL AND \"decision_queue_items\".\"added_by_user_id\" IS NULL)\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_queues": {+ "name": "decision_queues",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_type": {+ "name": "created_by_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_api_key_id": {+ "name": "created_by_agent_api_key_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "retention_days": {+ "name": "retention_days",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seed_rules": {+ "name": "seed_rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "seed_rules_enabled": {+ "name": "seed_rules_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_queues_company_key_uq": {+ "name": "decision_queues_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_queues_company_updated_idx": {+ "name": "decision_queues_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "decision_queues_creator_check": {+ "name": "decision_queues_creator_check",+ "value": "(\n (\"decision_queues\".\"created_by_type\" = 'agent' AND \"decision_queues\".\"created_by_agent_id\" IS NOT NULL AND \"decision_queues\".\"created_by_user_id\" IS NULL)\n OR (\"decision_queues\".\"created_by_type\" = 'user' AND \"decision_queues\".\"created_by_agent_id\" IS NULL AND \"decision_queues\".\"created_by_user_id\" IS NOT NULL)\n OR (\"decision_queues\".\"created_by_type\" = 'system' AND \"decision_queues\".\"created_by_agent_id\" IS NULL AND \"decision_queues\".\"created_by_user_id\" IS NULL)\n )"+ },+ "decision_queues_retention_days_check": {+ "name": "decision_queues_retention_days_check",+ "value": "\"decision_queues\".\"retention_days\" IS NULL OR (\"decision_queues\".\"retention_days\" >= 1 AND \"decision_queues\".\"retention_days\" <= 3650)"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_retention": {+ "name": "decision_retention",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_activity_at": {+ "name": "source_activity_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "keep": {+ "name": "keep",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_reason": {+ "name": "archived_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_type": {+ "name": "archived_by_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_agent_id": {+ "name": "archived_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_user_id": {+ "name": "archived_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_run_id": {+ "name": "archived_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "archive_version": {+ "name": "archive_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_retention_company_source_uq": {+ "name": "decision_retention_company_source_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_retention_company_archived_idx": {+ "name": "decision_retention_company_archived_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "archived_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "decision_retention_archive_actor_check": {+ "name": "decision_retention_archive_actor_check",+ "value": "(\n (\"decision_retention\".\"archived_at\" IS NULL AND \"decision_retention\".\"archived_by_type\" IS NULL AND \"decision_retention\".\"archived_by_agent_id\" IS NULL AND \"decision_retention\".\"archived_by_user_id\" IS NULL)\n OR (\"decision_retention\".\"archived_at\" IS NOT NULL AND \"decision_retention\".\"archived_by_type\" = 'system' AND \"decision_retention\".\"archived_by_agent_id\" IS NULL AND \"decision_retention\".\"archived_by_user_id\" IS NULL)\n OR (\"decision_retention\".\"archived_at\" IS NOT NULL AND \"decision_retention\".\"archived_by_type\" = 'agent' AND \"decision_retention\".\"archived_by_agent_id\" IS NOT NULL AND \"decision_retention\".\"archived_by_user_id\" IS NULL)\n OR (\"decision_retention\".\"archived_at\" IS NOT NULL AND \"decision_retention\".\"archived_by_type\" = 'user' AND \"decision_retention\".\"archived_by_agent_id\" IS NULL AND \"decision_retention\".\"archived_by_user_id\" IS NOT NULL)\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_triage": {+ "name": "decision_triage",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "decide_by": {+ "name": "decide_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decide_by_date": {+ "name": "decide_by_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "set_by_type": {+ "name": "set_by_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "set_by_agent_id": {+ "name": "set_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "set_by_user_id": {+ "name": "set_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "set_by_run_id": {+ "name": "set_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "set_by_agent_api_key_id": {+ "name": "set_by_agent_api_key_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_triage_company_source_uq": {+ "name": "decision_triage_company_source_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_triage_company_decide_by_idx": {+ "name": "decision_triage_company_decide_by_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "decide_by",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "decision_triage_actor_check": {+ "name": "decision_triage_actor_check",+ "value": "(\n (\"decision_triage\".\"set_by_type\" = 'agent' AND \"decision_triage\".\"set_by_agent_id\" IS NOT NULL AND \"decision_triage\".\"set_by_user_id\" IS NULL)\n OR (\"decision_triage\".\"set_by_type\" = 'user' AND \"decision_triage\".\"set_by_agent_id\" IS NULL AND \"decision_triage\".\"set_by_user_id\" IS NOT NULL)\n )"+ },+ "decision_triage_decide_by_check": {+ "name": "decision_triage_decide_by_check",+ "value": "(\n (\"decision_triage\".\"decide_by\" IS NULL AND \"decision_triage\".\"decide_by_date\" IS NULL)\n OR (\"decision_triage\".\"decide_by\" IN ('today', 'this_week', 'whenever') AND \"decision_triage\".\"decide_by_date\" IS NULL)\n OR (\"decision_triage\".\"decide_by\" = 'date' AND \"decision_triage\".\"decide_by_date\" IS NOT NULL)\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_triage_events": {+ "name": "decision_triage_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "queue_id": {+ "name": "queue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_agent_id": {+ "name": "actor_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_run_id": {+ "name": "actor_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "agent_api_key_id": {+ "name": "agent_api_key_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "details": {+ "name": "details",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_triage_events_company_source_created_idx": {+ "name": "decision_triage_events_company_source_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_triage_events_queue_created_idx": {+ "name": "decision_triage_events_queue_created_idx",+ "columns": [+ {+ "expression": "queue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "decision_triage_events_actor_check": {+ "name": "decision_triage_events_actor_check",+ "value": "(\n (\"decision_triage_events\".\"actor_type\" = 'agent' AND \"decision_triage_events\".\"actor_agent_id\" IS NOT NULL AND \"decision_triage_events\".\"actor_user_id\" IS NULL)\n OR (\"decision_triage_events\".\"actor_type\" = 'user' AND \"decision_triage_events\".\"actor_agent_id\" IS NULL AND \"decision_triage_events\".\"actor_user_id\" IS NOT NULL)\n OR (\"decision_triage_events\".\"actor_type\" = 'system' AND \"decision_triage_events\".\"actor_agent_id\" IS NULL AND \"decision_triage_events\".\"actor_user_id\" IS NULL)\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.decision_training_examples": {+ "name": "decision_training_examples",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "cutoff_at": {+ "name": "cutoff_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "notes": {+ "name": "notes",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "notes_history": {+ "name": "notes_history",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "decision_outcome": {+ "name": "decision_outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "retention_policy": {+ "name": "retention_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'scrub_deleted_comments_v1'"+ },+ "snapshot": {+ "name": "snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_training_examples_company_created_at_idx": {+ "name": "decision_training_examples_company_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_training_examples_issue_idx": {+ "name": "decision_training_examples_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_training_examples_source_author_uq": {+ "name": "decision_training_examples_source_author_uq",+ "columns": [+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_by_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.decision_bundles": {+ "name": "decision_bundles",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "origin_agent_id": {+ "name": "origin_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_issue_id": {+ "name": "origin_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_run_id": {+ "name": "origin_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decision_bundles_company_created_at_idx": {+ "name": "decision_bundles_company_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.decision_effect_executions": {+ "name": "decision_effect_executions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "decision_id": {+ "name": "decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "effect_index": {+ "name": "effect_index",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "effect_type": {+ "name": "effect_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_issue_id": {+ "name": "target_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'claimed'"+ },+ "result": {+ "name": "result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activity_log_id": {+ "name": "activity_log_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "executed_at": {+ "name": "executed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "decision_effect_executions_decision_effect_uq": {+ "name": "decision_effect_executions_decision_effect_uq",+ "columns": [+ {+ "expression": "decision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "effect_index",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_effect_executions_target_issue_idx": {+ "name": "decision_effect_executions_target_issue_idx",+ "columns": [+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.decision_target_issues": {+ "name": "decision_target_issues",+ "schema": "",+ "columns": {+ "decision_id": {+ "name": "decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "decision_target_issues_decision_idx": {+ "name": "decision_target_issues_decision_idx",+ "columns": [+ {+ "expression": "decision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decision_target_issues_issue_idx": {+ "name": "decision_target_issues_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "decision_target_issues_decision_id_issue_id_pk": {+ "name": "decision_target_issues_decision_id_issue_id_pk",+ "columns": [+ "decision_id",+ "issue_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.decisions": {+ "name": "decisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "bundle_id": {+ "name": "bundle_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "origin_agent_id": {+ "name": "origin_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_issue_id": {+ "name": "origin_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "origin_run_id": {+ "name": "origin_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "rule_key": {+ "name": "rule_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "inputs": {+ "name": "inputs",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'open'"+ },+ "execution_status": {+ "name": "execution_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "chosen_option_id": {+ "name": "chosen_option_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "input_values": {+ "name": "input_values",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "decided_by_user_id": {+ "name": "decided_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "signed_spec": {+ "name": "signed_spec",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_snapshots": {+ "name": "target_snapshots",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "continuation_policy": {+ "name": "continuation_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "decisions_company_status_expires_at_idx": {+ "name": "decisions_company_status_expires_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decisions_bundle_idx": {+ "name": "decisions_bundle_idx",+ "columns": [+ {+ "expression": "bundle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decisions_origin_issue_idx": {+ "name": "decisions_origin_issue_idx",+ "columns": [+ {+ "expression": "origin_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "decisions_company_idempotency_uq": {+ "name": "decisions_company_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"decisions\".\"idempotency_key\" IS NOT NULL",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_annotation_anchor_snapshots": {+ "name": "document_annotation_anchor_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "from_revision_id": {+ "name": "from_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "from_revision_number": {+ "name": "from_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "to_revision_id": {+ "name": "to_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "to_revision_number": {+ "name": "to_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "previous_anchor": {+ "name": "previous_anchor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "next_anchor": {+ "name": "next_anchor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "anchor_state": {+ "name": "anchor_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "anchor_confidence": {+ "name": "anchor_confidence",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_annotation_anchor_snapshots_company_thread_created_at_idx": {+ "name": "document_annotation_anchor_snapshots_company_thread_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_anchor_snapshots_company_document_revision_idx": {+ "name": "document_annotation_anchor_snapshots_company_document_revision_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "to_revision_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_annotation_comments": {+ "name": "document_annotation_comments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "author_type": {+ "name": "author_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_comment_id": {+ "name": "issue_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_trust": {+ "name": "source_trust",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_annotation_comments_company_thread_created_at_idx": {+ "name": "document_annotation_comments_company_thread_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_company_issue_created_at_idx": {+ "name": "document_annotation_comments_company_issue_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_company_routine_created_at_idx": {+ "name": "document_annotation_comments_company_routine_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_company_case_created_at_idx": {+ "name": "document_annotation_comments_company_case_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_company_document_created_at_idx": {+ "name": "document_annotation_comments_company_document_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_issue_comment_idx": {+ "name": "document_annotation_comments_issue_comment_idx",+ "columns": [+ {+ "expression": "issue_comment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_comments_body_search_idx": {+ "name": "document_annotation_comments_body_search_idx",+ "columns": [+ {+ "expression": "body",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "document_annotation_comments_exactly_one_owner_chk": {+ "name": "document_annotation_comments_exactly_one_owner_chk",+ "value": "num_nonnulls(\"document_annotation_comments\".\"issue_id\", \"document_annotation_comments\".\"routine_id\", \"document_annotation_comments\".\"case_id\") = 1"+ }+ },+ "isRLSEnabled": false+ },+ "public.document_annotation_threads": {+ "name": "document_annotation_threads",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_key": {+ "name": "document_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'open'"+ },+ "anchor_state": {+ "name": "anchor_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "original_revision_id": {+ "name": "original_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "original_revision_number": {+ "name": "original_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "current_revision_id": {+ "name": "current_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "current_revision_number": {+ "name": "current_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "selected_text": {+ "name": "selected_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix_text": {+ "name": "prefix_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "suffix_text": {+ "name": "suffix_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "normalized_start": {+ "name": "normalized_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "normalized_end": {+ "name": "normalized_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "markdown_start": {+ "name": "markdown_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "markdown_end": {+ "name": "markdown_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "anchor_confidence": {+ "name": "anchor_confidence",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'exact'"+ },+ "anchor_selector": {+ "name": "anchor_selector",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_agent_id": {+ "name": "resolved_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_user_id": {+ "name": "resolved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_annotation_threads_company_document_status_idx": {+ "name": "document_annotation_threads_company_document_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_threads_company_issue_status_idx": {+ "name": "document_annotation_threads_company_issue_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_threads_company_routine_status_idx": {+ "name": "document_annotation_threads_company_routine_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_threads_company_case_status_idx": {+ "name": "document_annotation_threads_company_case_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_threads_company_current_revision_open_idx": {+ "name": "document_annotation_threads_company_current_revision_open_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "current_revision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_annotation_threads_company_anchor_state_idx": {+ "name": "document_annotation_threads_company_anchor_state_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "anchor_state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "document_annotation_threads_exactly_one_owner_chk": {+ "name": "document_annotation_threads_exactly_one_owner_chk",+ "value": "num_nonnulls(\"document_annotation_threads\".\"issue_id\", \"document_annotation_threads\".\"routine_id\", \"document_annotation_threads\".\"case_id\") = 1"+ }+ },+ "isRLSEnabled": false+ },+ "public.document_memberships": {+ "name": "document_memberships",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "starred_at": {+ "name": "starred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_memberships_company_user_starred_idx": {+ "name": "document_memberships_company_user_starred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "starred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_memberships_company_user_document_uq": {+ "name": "document_memberships_company_user_document_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_revisions": {+ "name": "document_revisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision_number": {+ "name": "revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "format": {+ "name": "format",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'markdown'"+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "change_summary": {+ "name": "change_summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_revisions_document_revision_uq": {+ "name": "document_revisions_document_revision_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revision_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "document_revisions_company_document_created_idx": {+ "name": "document_revisions_company_document_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.documents": {+ "name": "documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "format": {+ "name": "format",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'markdown'"+ },+ "latest_body": {+ "name": "latest_body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "latest_revision_id": {+ "name": "latest_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "latest_revision_number": {+ "name": "latest_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "locked_at": {+ "name": "locked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "locked_by_agent_id": {+ "name": "locked_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "locked_by_user_id": {+ "name": "locked_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_trust": {+ "name": "source_trust",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "documents_company_updated_idx": {+ "name": "documents_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "documents_company_created_idx": {+ "name": "documents_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "documents_title_search_idx": {+ "name": "documents_title_search_idx",+ "columns": [+ {+ "expression": "title",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "documents_latest_body_search_idx": {+ "name": "documents_latest_body_search_idx",+ "columns": [+ {+ "expression": "latest_body",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ }+ },+ "foreignKeys": {+ "documents_company_id_companies_id_fk": {+ "name": "documents_company_id_companies_id_fk",+ "tableFrom": "documents",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.email_endpoints": {+ "name": "email_endpoints",+ "schema": "",+ "columns": {+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "receive_mode": {+ "name": "receive_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "owned_api_key_id": {+ "name": "owned_api_key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "activation_at": {+ "name": "activation_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "sync_checkpoint": {+ "name": "sync_checkpoint",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_sync_at": {+ "name": "last_sync_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "email_endpoints_receive_mode_check": {+ "name": "email_endpoints_receive_mode_check",+ "value": "\"email_endpoints\".\"receive_mode\" in ('websocket', 'webhook')"+ }+ },+ "isRLSEnabled": false+ },+ "public.email_messages": {+ "name": "email_messages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_message_id": {+ "name": "provider_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "envelope": {+ "name": "envelope",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "text": {+ "name": "text",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "full_text": {+ "name": "full_text",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "direction": {+ "name": "direction",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "automatic": {+ "name": "automatic",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "attachment_ids": {+ "name": "attachment_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "timestamp": {+ "name": "timestamp",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "email_messages_provider_uq": {+ "name": "email_messages_provider_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "email_messages_conversation_idx": {+ "name": "email_messages_conversation_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "conversation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "timestamp",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "email_messages_direction_check": {+ "name": "email_messages_direction_check",+ "value": "\"email_messages\".\"direction\" in ('inbound', 'outbound')"+ }+ },+ "isRLSEnabled": false+ },+ "public.email_sends": {+ "name": "email_sends",+ "schema": "",+ "columns": {+ "publication_id": {+ "name": "publication_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "request": {+ "name": "request",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "actor": {+ "name": "actor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "digest": {+ "name": "digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "first_attempt_at": {+ "name": "first_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "email_sends_pending_idx": {+ "name": "email_sends_pending_idx",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "outcome",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"email_sends\".\"outcome\" in ('queued', 'uncertain')",+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "email_sends_outcome_check": {+ "name": "email_sends_outcome_check",+ "value": "\"email_sends\".\"outcome\" in ('queued', 'sent', 'delivered', 'failed', 'uncertain')"+ }+ },+ "isRLSEnabled": false+ },+ "public.environment_custom_image_setup_sessions": {+ "name": "environment_custom_image_setup_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "environment_id": {+ "name": "environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "template_id": {+ "name": "template_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "promoted_template_id": {+ "name": "promoted_template_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_lease_id": {+ "name": "provider_lease_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "environment_lease_id": {+ "name": "environment_lease_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'starting'"+ },+ "started_by_user_id": {+ "name": "started_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_by_agent_id": {+ "name": "started_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "base_template_ref": {+ "name": "base_template_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "connection_summary": {+ "name": "connection_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "connection_secret_ref": {+ "name": "connection_secret_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "environment_custom_image_setup_sessions_environment_status_idx": {+ "name": "environment_custom_image_setup_sessions_environment_status_idx",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_setup_sessions_environment_active_uq": {+ "name": "environment_custom_image_setup_sessions_environment_active_uq",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"environment_custom_image_setup_sessions\".\"status\" IN ('starting', 'waiting_for_user', 'capturing')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_setup_sessions_template_idx": {+ "name": "environment_custom_image_setup_sessions_template_idx",+ "columns": [+ {+ "expression": "template_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_setup_sessions_promoted_template_idx": {+ "name": "environment_custom_image_setup_sessions_promoted_template_idx",+ "columns": [+ {+ "expression": "promoted_template_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_setup_sessions_expires_idx": {+ "name": "environment_custom_image_setup_sessions_expires_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_setup_sessions_provider_lease_idx": {+ "name": "environment_custom_image_setup_sessions_provider_lease_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_lease_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.environment_custom_image_templates": {+ "name": "environment_custom_image_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "environment_id": {+ "name": "environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "template_kind": {+ "name": "template_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "template_ref": {+ "name": "template_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_template_ref": {+ "name": "source_template_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_environment_config_fingerprint": {+ "name": "source_environment_config_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "captured_at": {+ "name": "captured_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "superseded_by_template_id": {+ "name": "superseded_by_template_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "environment_custom_image_templates_environment_status_idx": {+ "name": "environment_custom_image_templates_environment_status_idx",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_templates_environment_provider_status_idx": {+ "name": "environment_custom_image_templates_environment_provider_status_idx",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_templates_environment_active_uq": {+ "name": "environment_custom_image_templates_environment_active_uq",+ "columns": [+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"environment_custom_image_templates\".\"status\" = 'active'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_templates_superseded_by_idx": {+ "name": "environment_custom_image_templates_superseded_by_idx",+ "columns": [+ {+ "expression": "superseded_by_template_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_custom_image_templates_last_used_idx": {+ "name": "environment_custom_image_templates_last_used_idx",+ "columns": [+ {+ "expression": "last_used_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.environment_leases": {+ "name": "environment_leases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "environment_id": {+ "name": "environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "lease_policy": {+ "name": "lease_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'ephemeral'"+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_lease_id": {+ "name": "provider_lease_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "acquired_at": {+ "name": "acquired_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "released_at": {+ "name": "released_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cleanup_status": {+ "name": "cleanup_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "environment_leases_company_environment_status_idx": {+ "name": "environment_leases_company_environment_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_leases_company_execution_workspace_idx": {+ "name": "environment_leases_company_execution_workspace_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_leases_company_issue_idx": {+ "name": "environment_leases_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_leases_heartbeat_run_idx": {+ "name": "environment_leases_heartbeat_run_idx",+ "columns": [+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_leases_company_last_used_idx": {+ "name": "environment_leases_company_last_used_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "last_used_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environment_leases_provider_lease_idx": {+ "name": "environment_leases_provider_lease_idx",+ "columns": [+ {+ "expression": "provider_lease_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.environments": {+ "name": "environments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "driver": {+ "name": "driver",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "env_vars": {+ "name": "env_vars",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "environments_status_idx": {+ "name": "environments_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environments_local_driver_idx": {+ "name": "environments_local_driver_idx",+ "columns": [+ {+ "expression": "driver",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"environments\".\"driver\" = 'local'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environments_managed_sandbox_idx": {+ "name": "environments_managed_sandbox_idx",+ "columns": [+ {+ "expression": "driver",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"environments\".\"driver\" = 'sandbox' AND (\"environments\".\"metadata\" ->> 'managedByPaperclip')::boolean = true",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "environments_name_idx": {+ "name": "environments_name_idx",+ "columns": [+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.execution_workspace_runtime_leases": {+ "name": "execution_workspace_runtime_leases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "owner_key": {+ "name": "owner_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "owner_issue_id": {+ "name": "owner_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_run_id": {+ "name": "owner_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_action": {+ "name": "last_action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "claimed_at": {+ "name": "claimed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "renewed_at": {+ "name": "renewed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "execution_workspace_runtime_leases_company_workspace_idx": {+ "name": "execution_workspace_runtime_leases_company_workspace_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspace_runtime_leases_company_owner_idx": {+ "name": "execution_workspace_runtime_leases_company_owner_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspace_runtime_leases_expires_at_idx": {+ "name": "execution_workspace_runtime_leases_expires_at_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.execution_workspaces": {+ "name": "execution_workspaces",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_workspace_id": {+ "name": "project_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "mode": {+ "name": "mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "strategy_type": {+ "name": "strategy_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "cwd": {+ "name": "cwd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "repo_url": {+ "name": "repo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "base_ref": {+ "name": "base_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "branch_name": {+ "name": "branch_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_type": {+ "name": "provider_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_fs'"+ },+ "provider_ref": {+ "name": "provider_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "derived_from_execution_workspace_id": {+ "name": "derived_from_execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "opened_at": {+ "name": "opened_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "closed_at": {+ "name": "closed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "cleanup_eligible_at": {+ "name": "cleanup_eligible_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "cleanup_reason": {+ "name": "cleanup_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "execution_workspaces_company_project_status_idx": {+ "name": "execution_workspaces_company_project_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspaces_company_project_workspace_status_idx": {+ "name": "execution_workspaces_company_project_workspace_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspaces_company_source_issue_idx": {+ "name": "execution_workspaces_company_source_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspaces_company_last_used_idx": {+ "name": "execution_workspaces_company_last_used_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "last_used_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "execution_workspaces_company_branch_idx": {+ "name": "execution_workspaces_company_branch_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "branch_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_object_mentions": {+ "name": "external_object_mentions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_record_id": {+ "name": "source_record_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "document_key": {+ "name": "document_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "property_key": {+ "name": "property_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "matched_text_redacted": {+ "name": "matched_text_redacted",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "sanitized_display_url": {+ "name": "sanitized_display_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_identity_hash": {+ "name": "canonical_identity_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_identity": {+ "name": "canonical_identity",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "object_id": {+ "name": "object_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_key": {+ "name": "provider_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "detector_key": {+ "name": "detector_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "object_type": {+ "name": "object_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "confidence": {+ "name": "confidence",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'exact'"+ },+ "created_by_plugin_id": {+ "name": "created_by_plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_object_mentions_company_source_issue_idx": {+ "name": "external_object_mentions_company_source_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_object_mentions_company_object_idx": {+ "name": "external_object_mentions_company_object_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_object_mentions_company_provider_idx": {+ "name": "external_object_mentions_company_provider_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_object_mentions_company_source_record_uq": {+ "name": "external_object_mentions_company_source_record_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_record_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "property_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "canonical_identity_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"external_object_mentions\".\"source_record_id\" is not null and \"external_object_mentions\".\"canonical_identity_hash\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_object_mentions_company_source_null_record_uq": {+ "name": "external_object_mentions_company_source_null_record_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "property_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "canonical_identity_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"external_object_mentions\".\"source_record_id\" is null and \"external_object_mentions\".\"canonical_identity_hash\" is not null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_objects": {+ "name": "external_objects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_key": {+ "name": "provider_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "object_type": {+ "name": "object_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "sanitized_canonical_url": {+ "name": "sanitized_canonical_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "canonical_identity_hash": {+ "name": "canonical_identity_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "display_key": {+ "name": "display_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "icon_key": {+ "name": "icon_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "display_title": {+ "name": "display_title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status_key": {+ "name": "status_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status_label": {+ "name": "status_label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status_icon_key": {+ "name": "status_icon_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status_category": {+ "name": "status_category",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "status_tone": {+ "name": "status_tone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'neutral'"+ },+ "liveness": {+ "name": "liveness",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "is_terminal": {+ "name": "is_terminal",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "data": {+ "name": "data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "remote_version": {+ "name": "remote_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "etag": {+ "name": "etag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_resolved_at": {+ "name": "last_resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_changed_at": {+ "name": "last_changed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_at": {+ "name": "last_error_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_refresh_at": {+ "name": "next_refresh_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_started_at": {+ "name": "refresh_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_message": {+ "name": "last_error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_objects_company_provider_object_idx": {+ "name": "external_objects_company_provider_object_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_objects_company_provider_status_idx": {+ "name": "external_objects_company_provider_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status_category",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_objects_company_refresh_idx": {+ "name": "external_objects_company_refresh_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_refresh_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_objects_company_external_id_uq": {+ "name": "external_objects_company_external_id_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_objects_company_identity_uq": {+ "name": "external_objects_company_identity_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "object_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "canonical_identity_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.feedback_exports": {+ "name": "feedback_exports",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "feedback_vote_id": {+ "name": "feedback_vote_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "vote": {+ "name": "vote",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_only'"+ },+ "destination": {+ "name": "destination",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "export_id": {+ "name": "export_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "consent_version": {+ "name": "consent_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "schema_version": {+ "name": "schema_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip-feedback-envelope-v2'"+ },+ "bundle_version": {+ "name": "bundle_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip-feedback-bundle-v2'"+ },+ "payload_version": {+ "name": "payload_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip-feedback-v1'"+ },+ "payload_digest": {+ "name": "payload_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload_snapshot": {+ "name": "payload_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "target_summary": {+ "name": "target_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "redaction_summary": {+ "name": "redaction_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_attempted_at": {+ "name": "last_attempted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "exported_at": {+ "name": "exported_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feedback_exports_feedback_vote_idx": {+ "name": "feedback_exports_feedback_vote_idx",+ "columns": [+ {+ "expression": "feedback_vote_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_exports_company_created_idx": {+ "name": "feedback_exports_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_exports_company_status_idx": {+ "name": "feedback_exports_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_exports_company_issue_idx": {+ "name": "feedback_exports_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_exports_company_project_idx": {+ "name": "feedback_exports_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_exports_company_author_idx": {+ "name": "feedback_exports_company_author_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "author_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.feedback_votes": {+ "name": "feedback_votes",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "vote": {+ "name": "vote",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "shared_with_labs": {+ "name": "shared_with_labs",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "shared_at": {+ "name": "shared_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "consent_version": {+ "name": "consent_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redaction_summary": {+ "name": "redaction_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "feedback_votes_company_issue_idx": {+ "name": "feedback_votes_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_votes_issue_target_idx": {+ "name": "feedback_votes_issue_target_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_votes_author_idx": {+ "name": "feedback_votes_author_idx",+ "columns": [+ {+ "expression": "author_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "feedback_votes_company_target_author_idx": {+ "name": "feedback_votes_company_target_author_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "author_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.finance_events": {+ "name": "finance_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "cost_event_id": {+ "name": "cost_event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "receipt_hash": {+ "name": "receipt_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "billing_code": {+ "name": "billing_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "event_kind": {+ "name": "event_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "direction": {+ "name": "direction",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'debit'"+ },+ "biller": {+ "name": "biller",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "execution_adapter_type": {+ "name": "execution_adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pricing_tier": {+ "name": "pricing_tier",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "quantity": {+ "name": "quantity",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "unit": {+ "name": "unit",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "amount_cents": {+ "name": "amount_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true+ },+ "currency": {+ "name": "currency",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'USD'"+ },+ "estimated": {+ "name": "estimated",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "external_invoice_id": {+ "name": "external_invoice_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata_json": {+ "name": "metadata_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "occurred_at": {+ "name": "occurred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "finance_events_company_receipt_idx": {+ "name": "finance_events_company_receipt_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_occurred_idx": {+ "name": "finance_events_company_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_biller_occurred_idx": {+ "name": "finance_events_company_biller_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "biller",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_kind_occurred_idx": {+ "name": "finance_events_company_kind_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "event_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_direction_occurred_idx": {+ "name": "finance_events_company_direction_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "direction",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_heartbeat_run_idx": {+ "name": "finance_events_company_heartbeat_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "finance_events_company_cost_event_idx": {+ "name": "finance_events_company_cost_event_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cost_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.folders": {+ "name": "folders",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "system_key": {+ "name": "system_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "folders_company_kind_position_idx": {+ "name": "folders_company_kind_position_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_company_kind_root_slug_uq": {+ "name": "folders_company_kind_root_slug_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"folders\".\"parent_id\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_company_kind_parent_slug_uq": {+ "name": "folders_company_kind_parent_slug_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"folders\".\"parent_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_company_kind_system_key_uq": {+ "name": "folders_company_kind_system_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "system_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"folders\".\"system_key\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "folders_company_kind_parent_position_idx": {+ "name": "folders_company_kind_parent_position_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "folders_company_id_companies_id_fk": {+ "name": "folders_company_id_companies_id_fk",+ "tableFrom": "folders",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.goals": {+ "name": "goals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "level": {+ "name": "level",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'task'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'planned'"+ },+ "parent_id": {+ "name": "parent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "goals_company_idx": {+ "name": "goals_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "goals_company_id_companies_id_fk": {+ "name": "goals_company_id_companies_id_fk",+ "tableFrom": "goals",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.heartbeat_run_events": {+ "name": "heartbeat_run_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigserial",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "seq": {+ "name": "seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "stream": {+ "name": "stream",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "level": {+ "name": "level",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "source_instance_id": {+ "name": "source_instance_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_event_id": {+ "name": "source_event_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "source_seq": {+ "name": "source_seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "source_payload_sha256": {+ "name": "source_payload_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "protocol_schema_version": {+ "name": "protocol_schema_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "heartbeat_run_events_run_seq_uq": {+ "name": "heartbeat_run_events_run_seq_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "seq",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_run_events_run_source_event_uq": {+ "name": "heartbeat_run_events_run_source_event_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"heartbeat_run_events\".\"source_event_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_run_events_run_source_seq_uq": {+ "name": "heartbeat_run_events_run_source_seq_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_instance_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_seq",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"heartbeat_run_events\".\"source_instance_id\" is not null and \"heartbeat_run_events\".\"source_seq\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_run_events_company_run_idx": {+ "name": "heartbeat_run_events_company_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_run_events_company_created_idx": {+ "name": "heartbeat_run_events_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.heartbeat_run_watchdog_decisions": {+ "name": "heartbeat_run_watchdog_decisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "evaluation_issue_id": {+ "name": "evaluation_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "decision": {+ "name": "decision",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "heartbeat_run_watchdog_decisions_company_run_created_idx": {+ "name": "heartbeat_run_watchdog_decisions_company_run_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_run_watchdog_decisions_company_run_snooze_idx": {+ "name": "heartbeat_run_watchdog_decisions_company_run_snooze_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "snoozed_until",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.heartbeat_runs": {+ "name": "heartbeat_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "invocation_source": {+ "name": "invocation_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'on_demand'"+ },+ "trigger_detail": {+ "name": "trigger_detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'queued'"+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_identity_context_id": {+ "name": "active_identity_context_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "execution_control_deadline_at": {+ "name": "execution_control_deadline_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "execution_status_delivery_id": {+ "name": "execution_status_delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "wakeup_request_id": {+ "name": "wakeup_request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "exit_code": {+ "name": "exit_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "signal": {+ "name": "signal",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cost_accounting_pending": {+ "name": "cost_accounting_pending",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "cost_accounted_at": {+ "name": "cost_accounted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "accounting_projection_version": {+ "name": "accounting_projection_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accounting_last_attempt_at": {+ "name": "accounting_last_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "accounting_last_error": {+ "name": "accounting_last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accounting_attempt_count": {+ "name": "accounting_attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "usage_json": {+ "name": "usage_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "result_json": {+ "name": "result_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_mode": {+ "name": "runtime_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'legacy'"+ },+ "runtime_mode_resolver_version": {+ "name": "runtime_mode_resolver_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_mode_reason": {+ "name": "runtime_mode_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_mode_resolved_at": {+ "name": "runtime_mode_resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "runner_profile_json": {+ "name": "runner_profile_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "runner_instance_id": {+ "name": "runner_instance_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "native_session_id": {+ "name": "native_session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "native_issue_id": {+ "name": "native_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "driver_kind": {+ "name": "driver_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "driver_version": {+ "name": "driver_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completion_contract_id": {+ "name": "completion_contract_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "completion_contract_sha256": {+ "name": "completion_contract_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_event_seq": {+ "name": "next_event_seq",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "native_phase": {+ "name": "native_phase",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "native_phase_updated_at": {+ "name": "native_phase_updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "session_id_before": {+ "name": "session_id_before",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "session_id_after": {+ "name": "session_id_after",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_store": {+ "name": "log_store",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_ref": {+ "name": "log_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_bytes": {+ "name": "log_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "log_sha256": {+ "name": "log_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_compressed": {+ "name": "log_compressed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "stdout_excerpt": {+ "name": "stdout_excerpt",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "stderr_excerpt": {+ "name": "stderr_excerpt",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_run_id": {+ "name": "external_run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "controller_boot_id": {+ "name": "controller_boot_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "controller_lease_expires_at": {+ "name": "controller_lease_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "execution_stage": {+ "name": "execution_stage",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "process_pid": {+ "name": "process_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "process_group_id": {+ "name": "process_group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "process_started_at": {+ "name": "process_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_output_at": {+ "name": "last_output_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_output_seq": {+ "name": "last_output_seq",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_output_stream": {+ "name": "last_output_stream",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_output_bytes": {+ "name": "last_output_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "retry_of_run_id": {+ "name": "retry_of_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "process_loss_retry_count": {+ "name": "process_loss_retry_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "scheduled_retry_at": {+ "name": "scheduled_retry_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scheduled_retry_attempt": {+ "name": "scheduled_retry_attempt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "scheduled_retry_reason": {+ "name": "scheduled_retry_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "issue_comment_status": {+ "name": "issue_comment_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'not_applicable'"+ },+ "issue_comment_satisfied_by_comment_id": {+ "name": "issue_comment_satisfied_by_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_comment_retry_queued_at": {+ "name": "issue_comment_retry_queued_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "liveness_state": {+ "name": "liveness_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "liveness_reason": {+ "name": "liveness_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "continuation_attempt": {+ "name": "continuation_attempt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_useful_action_at": {+ "name": "last_useful_action_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_action": {+ "name": "next_action",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "context_snapshot": {+ "name": "context_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "heartbeat_runs_cost_accounting_pending_idx": {+ "name": "heartbeat_runs_cost_accounting_pending_idx",+ "columns": [+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"heartbeat_runs\".\"cost_accounting_pending\" = true",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_execution_status_delivery_idx": {+ "name": "heartbeat_runs_execution_status_delivery_idx",+ "columns": [+ {+ "expression": "execution_status_delivery_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"heartbeat_runs\".\"execution_status_delivery_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_execution_control_deadline_idx": {+ "name": "heartbeat_runs_execution_control_deadline_idx",+ "columns": [+ {+ "expression": "execution_control_deadline_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"heartbeat_runs\".\"execution_control_deadline_at\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_native_replacement_predecessor_uq": {+ "name": "heartbeat_runs_native_replacement_predecessor_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "retry_of_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"heartbeat_runs\".\"scheduled_retry_reason\" = 'native_safe_replacement'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_agent_started_idx": {+ "name": "heartbeat_runs_company_agent_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_responsible_user_idx": {+ "name": "heartbeat_runs_company_responsible_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_liveness_idx": {+ "name": "heartbeat_runs_company_liveness_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "liveness_state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_status_last_output_idx": {+ "name": "heartbeat_runs_company_status_last_output_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "last_output_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_status_process_started_idx": {+ "name": "heartbeat_runs_company_status_process_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "process_started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_created_at_desc_idx": {+ "name": "heartbeat_runs_company_created_at_desc_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_ctx_issue_created_idx": {+ "name": "heartbeat_runs_company_ctx_issue_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"context_snapshot\" ->> 'issueId')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_ctx_task_created_idx": {+ "name": "heartbeat_runs_company_ctx_task_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"context_snapshot\" ->> 'taskId')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "heartbeat_runs_company_ctx_taskkey_created_idx": {+ "name": "heartbeat_runs_company_ctx_taskkey_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "(\"context_snapshot\" ->> 'taskKey')",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ },+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.inbox_dismissals": {+ "name": "inbox_dismissals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "item_key": {+ "name": "item_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'dismiss'"+ },+ "dismissed_at": {+ "name": "dismissed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "inbox_dismissals_company_user_idx": {+ "name": "inbox_dismissals_company_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "inbox_dismissals_company_item_idx": {+ "name": "inbox_dismissals_company_item_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "item_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "inbox_dismissals_company_user_item_idx": {+ "name": "inbox_dismissals_company_user_item_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "item_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.connection_grant_delegations": {+ "name": "connection_grant_delegations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_grant_delegations_company_agent_idx": {+ "name": "connection_grant_delegations_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grant_delegations_grant_agent_uq": {+ "name": "connection_grant_delegations_grant_agent_uq",+ "columns": [+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.connection_grant_members": {+ "name": "connection_grant_members",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "subject_type": {+ "name": "subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subject_id": {+ "name": "subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_grant_members_company_subject_idx": {+ "name": "connection_grant_members_company_subject_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grant_members_grant_subject_uq": {+ "name": "connection_grant_members_grant_subject_uq",+ "columns": [+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "connection_grant_members_subject_type_check": {+ "name": "connection_grant_members_subject_type_check",+ "value": "\"connection_grant_members\".\"subject_type\" in ('user')"+ }+ },+ "isRLSEnabled": false+ },+ "public.connection_grants": {+ "name": "connection_grants",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subject_user_id": {+ "name": "subject_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "subject_agent_id": {+ "name": "subject_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_tenant": {+ "name": "provider_tenant",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "credential_secret_refs": {+ "name": "credential_secret_refs",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "external_credential": {+ "name": "external_credential",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_by_agent_id": {+ "name": "revoked_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_by_user_id": {+ "name": "revoked_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_grants_company_connection_idx": {+ "name": "connection_grants_company_connection_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grants_subject_user_idx": {+ "name": "connection_grants_subject_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grants_subject_agent_idx": {+ "name": "connection_grants_subject_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grants_user_uq": {+ "name": "connection_grants_user_uq",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grants_agent_uq": {+ "name": "connection_grants_agent_uq",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_grants_default_uq": {+ "name": "connection_grants_default_uq",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"connection_grants\".\"is_default\" = true and \"connection_grants\".\"kind\" = 'organization'",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "connection_grants_company_id_uq": {+ "name": "connection_grants_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "connection_grants_kind_check": {+ "name": "connection_grants_kind_check",+ "value": "\"connection_grants\".\"kind\" in ('organization', 'user', 'agent')"+ },+ "connection_grants_status_check": {+ "name": "connection_grants_status_check",+ "value": "\"connection_grants\".\"status\" in ('active', 'revoked', 'expired', 'needs_reauthorization')"+ },+ "connection_grants_credential_source_one_of_check": {+ "name": "connection_grants_credential_source_one_of_check",+ "value": "\"connection_grants\".\"external_credential\" is null or jsonb_array_length(\"connection_grants\".\"credential_secret_refs\") = 0"+ },+ "connection_grants_subject_check": {+ "name": "connection_grants_subject_check",+ "value": "(\"connection_grants\".\"kind\" = 'user' and \"connection_grants\".\"subject_user_id\" is not null and \"connection_grants\".\"subject_agent_id\" is null) or (\"connection_grants\".\"kind\" = 'agent' and \"connection_grants\".\"subject_agent_id\" is not null and \"connection_grants\".\"subject_user_id\" is null) or (\"connection_grants\".\"kind\" = 'organization' and \"connection_grants\".\"subject_user_id\" is null and \"connection_grants\".\"subject_agent_id\" is null)"+ },+ "connection_grants_default_check": {+ "name": "connection_grants_default_check",+ "value": "\"connection_grants\".\"is_default\" = false or \"connection_grants\".\"kind\" = 'organization'"+ }+ },+ "isRLSEnabled": false+ },+ "public.connection_token_issuances": {+ "name": "connection_token_issuances",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requested_scope": {+ "name": "requested_scope",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "issued_scope": {+ "name": "issued_scope",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "ttl_seconds": {+ "name": "ttl_seconds",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "connection_token_issuances_company_created_idx": {+ "name": "connection_token_issuances_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_token_issuances_connection_created_idx": {+ "name": "connection_token_issuances_connection_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_token_issuances_agent_connection_idx": {+ "name": "connection_token_issuances_agent_connection_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "connection_token_issuances_run_idx": {+ "name": "connection_token_issuances_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.instance_settings": {+ "name": "instance_settings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "singleton_key": {+ "name": "singleton_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "default_environment_id": {+ "name": "default_environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "general": {+ "name": "general",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "experimental": {+ "name": "experimental",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "instance_settings_singleton_key_idx": {+ "name": "instance_settings_singleton_key_idx",+ "columns": [+ {+ "expression": "singleton_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.instance_user_roles": {+ "name": "instance_user_roles",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'instance_admin'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "instance_user_roles_user_role_unique_idx": {+ "name": "instance_user_roles_user_role_unique_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "instance_user_roles_role_idx": {+ "name": "instance_user_roles_role_idx",+ "columns": [+ {+ "expression": "role",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invites": {+ "name": "invites",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "invite_type": {+ "name": "invite_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'company_join'"+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "allowed_join_types": {+ "name": "allowed_join_types",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'both'"+ },+ "defaults_payload": {+ "name": "defaults_payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "invited_by_user_id": {+ "name": "invited_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "invites_token_hash_unique_idx": {+ "name": "invites_token_hash_unique_idx",+ "columns": [+ {+ "expression": "token_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invites_company_invite_state_idx": {+ "name": "invites_company_invite_state_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "invite_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revoked_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invites_company_id_companies_id_fk": {+ "name": "invites_company_id_companies_id_fk",+ "tableFrom": "invites",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_approvals": {+ "name": "issue_approvals",+ "schema": "",+ "columns": {+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "approval_id": {+ "name": "approval_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "linked_by_agent_id": {+ "name": "linked_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "linked_by_user_id": {+ "name": "linked_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_approvals_issue_idx": {+ "name": "issue_approvals_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_approvals_approval_idx": {+ "name": "issue_approvals_approval_idx",+ "columns": [+ {+ "expression": "approval_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_approvals_company_idx": {+ "name": "issue_approvals_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_approvals_pk": {+ "name": "issue_approvals_pk",+ "columns": [+ "issue_id",+ "approval_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_attachments": {+ "name": "issue_attachments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "asset_id": {+ "name": "asset_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_comment_id": {+ "name": "issue_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "originating_run_id": {+ "name": "originating_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_attachments_company_issue_idx": {+ "name": "issue_attachments_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_attachments_issue_comment_idx": {+ "name": "issue_attachments_issue_comment_idx",+ "columns": [+ {+ "expression": "issue_comment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_attachments_originating_run_idx": {+ "name": "issue_attachments_originating_run_idx",+ "columns": [+ {+ "expression": "originating_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_attachments_asset_uq": {+ "name": "issue_attachments_asset_uq",+ "columns": [+ {+ "expression": "asset_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_comments": {+ "name": "issue_comments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "on_behalf_of_user_id": {+ "name": "on_behalf_of_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "author_type": {+ "name": "author_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "derived_author_agent_id": {+ "name": "derived_author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "derived_created_by_run_id": {+ "name": "derived_created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "derived_author_source": {+ "name": "derived_author_source",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_request_id": {+ "name": "client_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_session_generation": {+ "name": "conversation_session_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "presentation": {+ "name": "presentation",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_by_type": {+ "name": "deleted_by_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_by_agent_id": {+ "name": "deleted_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_by_user_id": {+ "name": "deleted_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_by_run_id": {+ "name": "deleted_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_trust": {+ "name": "source_trust",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_comments_issue_idx": {+ "name": "issue_comments_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_comments_company_idx": {+ "name": "issue_comments_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_comments_company_issue_created_at_idx": {+ "name": "issue_comments_company_issue_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_comments_company_author_issue_created_at_idx": {+ "name": "issue_comments_company_author_issue_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "author_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_comments_body_search_idx": {+ "name": "issue_comments_body_search_idx",+ "columns": [+ {+ "expression": "body",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ },+ "issue_comments_company_id_uq": {+ "name": "issue_comments_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_create_idempotency_keys": {+ "name": "issue_create_idempotency_keys",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_create_idempotency_keys_company_key_uq": {+ "name": "issue_create_idempotency_keys_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_create_idempotency_keys_issue_idx": {+ "name": "issue_create_idempotency_keys_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_create_idempotency_keys_company_created_at_idx": {+ "name": "issue_create_idempotency_keys_company_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_documents": {+ "name": "issue_documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_documents_company_issue_key_uq": {+ "name": "issue_documents_company_issue_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_documents_document_uq": {+ "name": "issue_documents_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_documents_company_issue_updated_idx": {+ "name": "issue_documents_company_issue_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_execution_decisions": {+ "name": "issue_execution_decisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "stage_id": {+ "name": "stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "stage_type": {+ "name": "stage_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_agent_id": {+ "name": "actor_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_execution_decisions_company_issue_idx": {+ "name": "issue_execution_decisions_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_execution_decisions_stage_idx": {+ "name": "issue_execution_decisions_stage_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_inbox_archives": {+ "name": "issue_inbox_archives",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "archived_by_actor_type": {+ "name": "archived_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'user'"+ },+ "archived_by_agent_id": {+ "name": "archived_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_run_id": {+ "name": "archived_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_inbox_archives_company_issue_idx": {+ "name": "issue_inbox_archives_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_inbox_archives_company_user_idx": {+ "name": "issue_inbox_archives_company_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_inbox_archives_company_issue_user_idx": {+ "name": "issue_inbox_archives_company_issue_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_inbox_archives_archived_by_actor_type_check": {+ "name": "issue_inbox_archives_archived_by_actor_type_check",+ "value": "\"issue_inbox_archives\".\"archived_by_actor_type\" in ('user', 'agent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_labels": {+ "name": "issue_labels",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_labels_issue_idx": {+ "name": "issue_labels_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_labels_label_idx": {+ "name": "issue_labels_label_idx",+ "columns": [+ {+ "expression": "label_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_labels_company_idx": {+ "name": "issue_labels_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_labels_pk": {+ "name": "issue_labels_pk",+ "columns": [+ "issue_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_plan_decompositions": {+ "name": "issue_plan_decompositions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "accepted_plan_revision_id": {+ "name": "accepted_plan_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "accepted_interaction_id": {+ "name": "accepted_interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'in_flight'"+ },+ "request_fingerprint": {+ "name": "request_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requested_child_count": {+ "name": "requested_child_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "requested_children": {+ "name": "requested_children",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "child_issue_ids": {+ "name": "child_issue_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "owner_run_id": {+ "name": "owner_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_plan_decompositions_company_source_status_idx": {+ "name": "issue_plan_decompositions_company_source_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_plan_decompositions_active_owner_idx": {+ "name": "issue_plan_decompositions_active_owner_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue_plan_decompositions\".\"status\" = 'in_flight'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_plan_decompositions_source_revision_uq": {+ "name": "issue_plan_decompositions_source_revision_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "accepted_plan_revision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_question_response_deliveries": {+ "name": "issue_question_response_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_run_id": {+ "name": "source_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "target_run_id": {+ "name": "target_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "target_turn_id": {+ "name": "target_turn_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload_sha256": {+ "name": "payload_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "delivery_mode": {+ "name": "delivery_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "error_count": {+ "name": "error_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_code": {+ "name": "last_error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_question_response_deliveries_interaction_uq": {+ "name": "issue_question_response_deliveries_interaction_uq",+ "columns": [+ {+ "expression": "interaction_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_question_response_deliveries_correlation_uq": {+ "name": "issue_question_response_deliveries_correlation_uq",+ "columns": [+ {+ "expression": "correlation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_question_response_deliveries_pending_idx": {+ "name": "issue_question_response_deliveries_pending_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_question_response_deliveries_company_issue_idx": {+ "name": "issue_question_response_deliveries_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_question_response_deliveries_status_check": {+ "name": "issue_question_response_deliveries_status_check",+ "value": "\"issue_question_response_deliveries\".\"status\" IN ('pending', 'delivering', 'delivered', 'fallback_queued', 'failed')"+ },+ "issue_question_response_deliveries_mode_check": {+ "name": "issue_question_response_deliveries_mode_check",+ "value": "\"issue_question_response_deliveries\".\"delivery_mode\" IS NULL OR \"issue_question_response_deliveries\".\"delivery_mode\" IN ('steered', 'coalesced', 'wake_fallback')"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_read_states": {+ "name": "issue_read_states",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "last_read_at": {+ "name": "last_read_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_read_states_company_issue_idx": {+ "name": "issue_read_states_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_read_states_company_user_idx": {+ "name": "issue_read_states_company_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_read_states_company_issue_user_idx": {+ "name": "issue_read_states_company_issue_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_recovery_actions": {+ "name": "issue_recovery_actions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "recovery_issue_id": {+ "name": "recovery_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "owner_type": {+ "name": "owner_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'agent'"+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "previous_owner_agent_id": {+ "name": "previous_owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "return_owner_agent_id": {+ "name": "return_owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "cause": {+ "name": "cause",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "evidence": {+ "name": "evidence",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "next_action": {+ "name": "next_action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "wake_policy": {+ "name": "wake_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_policy": {+ "name": "monitor_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "max_attempts": {+ "name": "max_attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "timeout_at": {+ "name": "timeout_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_attempt_at": {+ "name": "last_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolution_note": {+ "name": "resolution_note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_recovery_actions_company_source_status_idx": {+ "name": "issue_recovery_actions_company_source_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_company_owner_status_idx": {+ "name": "issue_recovery_actions_company_owner_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "owner_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_company_recovery_issue_idx": {+ "name": "issue_recovery_actions_company_recovery_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "recovery_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_active_source_uq": {+ "name": "issue_recovery_actions_active_source_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_recovery_actions\".\"status\" in ('active', 'escalated')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_recovery_actions_active_fingerprint_uq": {+ "name": "issue_recovery_actions_active_fingerprint_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cause",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "fingerprint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_recovery_actions\".\"status\" in ('active', 'escalated')",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_reference_mentions": {+ "name": "issue_reference_mentions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_issue_id": {+ "name": "target_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_kind": {+ "name": "source_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_record_id": {+ "name": "source_record_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "document_key": {+ "name": "document_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "matched_text": {+ "name": "matched_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_reference_mentions_company_source_issue_idx": {+ "name": "issue_reference_mentions_company_source_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_reference_mentions_company_target_issue_idx": {+ "name": "issue_reference_mentions_company_target_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_reference_mentions_company_issue_pair_idx": {+ "name": "issue_reference_mentions_company_issue_pair_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_reference_mentions_company_source_mention_record_uq": {+ "name": "issue_reference_mentions_company_source_mention_record_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_record_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_reference_mentions\".\"source_record_id\" is not null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_reference_mentions_company_source_mention_null_record_uq": {+ "name": "issue_reference_mentions_company_source_mention_null_record_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_reference_mentions\".\"source_record_id\" is null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_relations": {+ "name": "issue_relations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "related_issue_id": {+ "name": "related_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_relations_company_issue_idx": {+ "name": "issue_relations_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_relations_company_related_issue_idx": {+ "name": "issue_relations_company_related_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "related_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_relations_company_type_idx": {+ "name": "issue_relations_company_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_relations_company_edge_uq": {+ "name": "issue_relations_company_edge_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "related_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_thread_interactions": {+ "name": "issue_thread_interactions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "continuation_policy": {+ "name": "continuation_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'wake_assignee'"+ },+ "requested_resolver_policy": {+ "name": "requested_resolver_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'anyone'"+ },+ "effective_resolver_policy": {+ "name": "effective_resolver_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'anyone'"+ },+ "resolver_policy_provenance": {+ "name": "resolver_policy_provenance",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'inherited'"+ },+ "effective_resolver_policy_source": {+ "name": "effective_resolver_policy_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'requested'"+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "origin_comment_ids": {+ "name": "origin_comment_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "source_comment_id": {+ "name": "source_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_identity_context_id": {+ "name": "source_identity_context_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_run_id": {+ "name": "source_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "addressee_agent_id": {+ "name": "addressee_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "addressee_user_id": {+ "name": "addressee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_agent_id": {+ "name": "resolved_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_run_id": {+ "name": "resolved_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_user_id": {+ "name": "resolved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "result": {+ "name": "result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_thread_interactions_issue_idx": {+ "name": "issue_thread_interactions_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_company_issue_created_at_idx": {+ "name": "issue_thread_interactions_company_issue_created_at_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_company_issue_status_idx": {+ "name": "issue_thread_interactions_company_issue_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_company_issue_idempotency_uq": {+ "name": "issue_thread_interactions_company_issue_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_thread_interactions\".\"idempotency_key\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_source_comment_idx": {+ "name": "issue_thread_interactions_source_comment_idx",+ "columns": [+ {+ "expression": "source_comment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_addressee_agent_idx": {+ "name": "issue_thread_interactions_addressee_agent_idx",+ "columns": [+ {+ "expression": "addressee_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_thread_interactions_addressee_user_idx": {+ "name": "issue_thread_interactions_addressee_user_idx",+ "columns": [+ {+ "expression": "addressee_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_tree_hold_members": {+ "name": "issue_tree_hold_members",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "hold_id": {+ "name": "hold_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "parent_issue_id": {+ "name": "parent_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "depth": {+ "name": "depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "issue_identifier": {+ "name": "issue_identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "issue_title": {+ "name": "issue_title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "issue_status": {+ "name": "issue_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "assignee_agent_id": {+ "name": "assignee_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_run_id": {+ "name": "active_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "active_run_status": {+ "name": "active_run_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "skipped": {+ "name": "skipped",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "skip_reason": {+ "name": "skip_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_tree_hold_members_hold_issue_uq": {+ "name": "issue_tree_hold_members_hold_issue_uq",+ "columns": [+ {+ "expression": "hold_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_tree_hold_members_company_issue_idx": {+ "name": "issue_tree_hold_members_company_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_tree_hold_members_hold_depth_idx": {+ "name": "issue_tree_hold_members_hold_depth_idx",+ "columns": [+ {+ "expression": "hold_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "depth",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_tree_holds": {+ "name": "issue_tree_holds",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "root_issue_id": {+ "name": "root_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "mode": {+ "name": "mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "release_policy": {+ "name": "release_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_actor_type": {+ "name": "created_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "released_at": {+ "name": "released_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "released_by_actor_type": {+ "name": "released_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "released_by_agent_id": {+ "name": "released_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "released_by_user_id": {+ "name": "released_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "released_by_run_id": {+ "name": "released_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "release_reason": {+ "name": "release_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "release_metadata": {+ "name": "release_metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_tree_holds_company_root_status_idx": {+ "name": "issue_tree_holds_company_root_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "root_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_tree_holds_company_status_mode_idx": {+ "name": "issue_tree_holds_company_status_mode_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "mode",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_watchdogs": {+ "name": "issue_watchdogs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "watchdog_agent_id": {+ "name": "watchdog_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "watchdog_issue_id": {+ "name": "watchdog_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_observed_fingerprint": {+ "name": "last_observed_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_reviewed_fingerprint": {+ "name": "last_reviewed_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_observed_stop_snapshot": {+ "name": "last_observed_stop_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_reviewed_stop_snapshot": {+ "name": "last_reviewed_stop_snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_triggered_at": {+ "name": "last_triggered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_completed_at": {+ "name": "last_completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_count": {+ "name": "trigger_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_run_id": {+ "name": "updated_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_watchdogs_company_issue_uq": {+ "name": "issue_watchdogs_company_issue_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_watchdogs_company_status_idx": {+ "name": "issue_watchdogs_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_watchdogs_company_agent_idx": {+ "name": "issue_watchdogs_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "watchdog_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_watchdogs_company_watchdog_issue_uq": {+ "name": "issue_watchdogs_company_watchdog_issue_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "watchdog_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_watchdogs\".\"watchdog_issue_id\" is not null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_work_products": {+ "name": "issue_work_products",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_service_id": {+ "name": "runtime_service_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "review_state": {+ "name": "review_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "is_primary": {+ "name": "is_primary",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "health_status": {+ "name": "health_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "source_trust": {+ "name": "source_trust",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_work_products_company_issue_type_idx": {+ "name": "issue_work_products_company_issue_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_work_products_company_execution_workspace_type_idx": {+ "name": "issue_work_products_company_execution_workspace_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_work_products_company_provider_external_id_idx": {+ "name": "issue_work_products_company_provider_external_id_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_work_products_company_updated_idx": {+ "name": "issue_work_products_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issues": {+ "name": "issues",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_agent_id": {+ "name": "conversation_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_user_id": {+ "name": "conversation_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_state": {+ "name": "conversation_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_session_generation": {+ "name": "conversation_session_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "conversation_boundary_comment_id": {+ "name": "conversation_boundary_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_workspace_id": {+ "name": "project_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "parent_id": {+ "name": "parent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title_needs_generation": {+ "name": "title_needs_generation",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'backlog'"+ },+ "status_version": {+ "name": "status_version",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_status_decision_id": {+ "name": "last_status_decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "work_mode": {+ "name": "work_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'standard'"+ },+ "harness_kind": {+ "name": "harness_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'medium'"+ },+ "review_policy": {+ "name": "review_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_agent_id": {+ "name": "assignee_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "checkout_run_id": {+ "name": "checkout_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_run_id": {+ "name": "execution_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_agent_name_key": {+ "name": "execution_agent_name_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "execution_locked_at": {+ "name": "execution_locked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "issue_number": {+ "name": "issue_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "origin_kind": {+ "name": "origin_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'manual'"+ },+ "origin_id": {+ "name": "origin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "origin_run_id": {+ "name": "origin_run_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "origin_identity_context_id": {+ "name": "origin_identity_context_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "continuation_identity_context_id": {+ "name": "continuation_identity_context_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "origin_fingerprint": {+ "name": "origin_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "request_depth": {+ "name": "request_depth",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "billing_code": {+ "name": "billing_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_adapter_overrides": {+ "name": "assignee_adapter_overrides",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "execution_policy": {+ "name": "execution_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "execution_state": {+ "name": "execution_state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_next_check_at": {+ "name": "monitor_next_check_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_wake_requested_at": {+ "name": "monitor_wake_requested_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_last_triggered_at": {+ "name": "monitor_last_triggered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_attempt_count": {+ "name": "monitor_attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "monitor_notes": {+ "name": "monitor_notes",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_scheduled_by": {+ "name": "monitor_scheduled_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_preference": {+ "name": "execution_workspace_preference",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_settings": {+ "name": "execution_workspace_settings",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "source_trust": {+ "name": "source_trust",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "unblock_descriptor": {+ "name": "unblock_descriptor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "blocked_transition_at": {+ "name": "blocked_transition_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "blocked_owner_notified_at": {+ "name": "blocked_owner_notified_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "cancelled_at": {+ "name": "cancelled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "hidden_at": {+ "name": "hidden_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issues_conversation_identity_idx": {+ "name": "issues_conversation_identity_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "conversation_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "conversation_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_status_idx": {+ "name": "issues_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_harness_kind_idx": {+ "name": "issues_company_harness_kind_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "harness_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_assignee_status_idx": {+ "name": "issues_company_assignee_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "assignee_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_assignee_user_status_idx": {+ "name": "issues_company_assignee_user_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "assignee_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_responsible_user_idx": {+ "name": "issues_company_responsible_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_parent_idx": {+ "name": "issues_company_parent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_project_idx": {+ "name": "issues_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_origin_idx": {+ "name": "issues_company_origin_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_project_workspace_idx": {+ "name": "issues_company_project_workspace_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_execution_workspace_idx": {+ "name": "issues_company_execution_workspace_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_monitor_due_idx": {+ "name": "issues_company_monitor_due_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "monitor_next_check_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_updated_idx": {+ "name": "issues_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_created_idx": {+ "name": "issues_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_open_normalized_title_created_idx": {+ "name": "issues_open_normalized_title_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(regexp_replace(btrim(\"title\"), '\\s+', ' ', 'g'))",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issues\".\"hidden_at\" is null and \"issues\".\"status\" not in ('done', 'cancelled')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_company_priority_idx": {+ "name": "issues_company_priority_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "priority",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_identifier_idx": {+ "name": "issues_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issues_title_search_idx": {+ "name": "issues_title_search_idx",+ "columns": [+ {+ "expression": "title",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "issues_identifier_search_idx": {+ "name": "issues_identifier_search_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "issues_description_search_idx": {+ "name": "issues_description_search_idx",+ "columns": [+ {+ "expression": "description",+ "isExpression": false,+ "asc": true,+ "nulls": "last",+ "opclass": "gin_trgm_ops"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "with": {}+ },+ "issues_open_routine_execution_uq": {+ "name": "issues_open_routine_execution_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_fingerprint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_liveness_recovery_incident_uq": {+ "name": "issues_active_liveness_recovery_incident_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_liveness_recovery_leaf_uq": {+ "name": "issues_active_liveness_recovery_leaf_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_fingerprint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_stale_run_evaluation_uq": {+ "name": "issues_active_stale_run_evaluation_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_task_watchdog_uq": {+ "name": "issues_active_task_watchdog_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_productivity_review_uq": {+ "name": "issues_active_productivity_review_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_active_stranded_issue_recovery_uq": {+ "name": "issues_active_stranded_issue_recovery_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "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,+ "method": "btree",+ "with": {}+ },+ "issues_onboarding_first_task_uq": {+ "name": "issues_onboarding_first_task_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issues\".\"origin_kind\" = 'onboarding_first_task'",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issues_company_id_uq": {+ "name": "issues_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "issues_conversation_identity_check": {+ "name": "issues_conversation_identity_check",+ "value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )"+ }+ },+ "isRLSEnabled": false+ },+ "public.join_requests": {+ "name": "join_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "invite_id": {+ "name": "invite_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "request_type": {+ "name": "request_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending_approval'"+ },+ "request_ip": {+ "name": "request_ip",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requesting_user_id": {+ "name": "requesting_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "request_email_snapshot": {+ "name": "request_email_snapshot",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_name": {+ "name": "agent_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "adapter_type": {+ "name": "adapter_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "capabilities": {+ "name": "capabilities",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_defaults_payload": {+ "name": "agent_defaults_payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "claim_secret_hash": {+ "name": "claim_secret_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "claim_secret_expires_at": {+ "name": "claim_secret_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "claim_secret_consumed_at": {+ "name": "claim_secret_consumed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_agent_id": {+ "name": "created_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "approved_by_user_id": {+ "name": "approved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "approved_at": {+ "name": "approved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "rejected_by_user_id": {+ "name": "rejected_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "rejected_at": {+ "name": "rejected_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "join_requests_invite_unique_idx": {+ "name": "join_requests_invite_unique_idx",+ "columns": [+ {+ "expression": "invite_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "join_requests_company_status_type_created_idx": {+ "name": "join_requests_company_status_type_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "request_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "join_requests_pending_human_user_uq": {+ "name": "join_requests_pending_human_user_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "requesting_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"requesting_user_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "join_requests_pending_human_email_uq": {+ "name": "join_requests_pending_human_email_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(\"request_email_snapshot\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"join_requests\".\"request_type\" = 'human' AND \"join_requests\".\"status\" = 'pending_approval' AND \"join_requests\".\"request_email_snapshot\" IS NOT NULL",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.labels": {+ "name": "labels",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "labels_company_idx": {+ "name": "labels_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "labels_company_name_idx": {+ "name": "labels_company_name_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "labels_company_id_companies_id_fk": {+ "name": "labels_company_id_companies_id_fk",+ "tableFrom": "labels",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.managed_agent_profiles": {+ "name": "managed_agent_profiles",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "profile_key": {+ "name": "profile_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "service": {+ "name": "service",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'anthropic_managed_agents'"+ },+ "anthropic_agent_id": {+ "name": "anthropic_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_version": {+ "name": "agent_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "environment_id": {+ "name": "environment_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "beta_version": {+ "name": "beta_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'managed-agents-2026-04-01'"+ },+ "default_model": {+ "name": "default_model",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'claude-sonnet-5'"+ },+ "default_max_list_cost_cents": {+ "name": "default_max_list_cost_cents",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "api_key_secret_id": {+ "name": "api_key_secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "retention_acknowledged": {+ "name": "retention_acknowledged",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "qualification": {+ "name": "qualification",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "qualified_at": {+ "name": "qualified_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "qualified_revision": {+ "name": "qualified_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "managed_agent_profiles_company_idx": {+ "name": "managed_agent_profiles_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "managed_agent_profiles_company_key_uq": {+ "name": "managed_agent_profiles_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "managed_agent_profiles_company_resource_uq": {+ "name": "managed_agent_profiles_company_resource_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "anthropic_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "environment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "managed_agent_profiles_service_check": {+ "name": "managed_agent_profiles_service_check",+ "value": "\"managed_agent_profiles\".\"service\" = 'anthropic_managed_agents'"+ },+ "managed_agent_profiles_beta_check": {+ "name": "managed_agent_profiles_beta_check",+ "value": "\"managed_agent_profiles\".\"beta_version\" = 'managed-agents-2026-04-01'"+ },+ "managed_agent_profiles_positive_budget_check": {+ "name": "managed_agent_profiles_positive_budget_check",+ "value": "\"managed_agent_profiles\".\"default_max_list_cost_cents\" > 0"+ },+ "managed_agent_profiles_qualified_revision_check": {+ "name": "managed_agent_profiles_qualified_revision_check",+ "value": "(\"managed_agent_profiles\".\"qualified_at\" IS NULL AND \"managed_agent_profiles\".\"qualified_revision\" IS NULL) OR (\"managed_agent_profiles\".\"qualified_at\" IS NOT NULL AND \"managed_agent_profiles\".\"qualification\" <> '{}'::jsonb AND \"managed_agent_profiles\".\"qualified_revision\" ~ '^sha256:[0-9a-f]{64}$')"+ }+ },+ "isRLSEnabled": false+ },+ "public.native_run_finalizations": {+ "name": "native_run_finalizations",+ "schema": "",+ "columns": {+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "attempt": {+ "name": "attempt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "lease_owner": {+ "name": "lease_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "lease_expires_at": {+ "name": "lease_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "controller_boot_id": {+ "name": "controller_boot_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "controller_pid": {+ "name": "controller_pid",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "controller_process_started_at": {+ "name": "controller_process_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "controller_generation": {+ "name": "controller_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "recovery_state": {+ "name": "recovery_state",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "recovery_request_id": {+ "name": "recovery_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "recovery_history": {+ "name": "recovery_history",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "result_id": {+ "name": "result_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "assessment_id": {+ "name": "assessment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "decision_id": {+ "name": "decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "failure_code": {+ "name": "failure_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failure_detail": {+ "name": "failure_detail",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "control_deadline_at": {+ "name": "control_deadline_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "native_run_finalizations_control_deadline_idx": {+ "name": "native_run_finalizations_control_deadline_idx",+ "columns": [+ {+ "expression": "control_deadline_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"native_run_finalizations\".\"control_deadline_at\" is not null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "native_issue_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "id"+ ],+ "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",+ "run_id",+ "assessment_id",+ "decision_id"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "assessment_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "native_run_finalizations_assessment_requires_result_check": {+ "name": "native_run_finalizations_assessment_requires_result_check",+ "value": "\"native_run_finalizations\".\"assessment_id\" is null or \"native_run_finalizations\".\"result_id\" is not null"+ },+ "native_run_finalizations_decision_requires_assessment_check": {+ "name": "native_run_finalizations_decision_requires_assessment_check",+ "value": "\"native_run_finalizations\".\"decision_id\" is null or \"native_run_finalizations\".\"assessment_id\" is not null"+ }+ },+ "isRLSEnabled": false+ },+ "public.native_run_results": {+ "name": "native_run_results",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "turn_id": {+ "name": "turn_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completion_contract_id": {+ "name": "completion_contract_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "caller_result_id": {+ "name": "caller_result_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "caller_dedupe_key": {+ "name": "caller_dedupe_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "server_fingerprint": {+ "name": "server_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "schema_status": {+ "name": "schema_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "rejection_code": {+ "name": "rejection_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result_json": {+ "name": "result_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "canonical_sha256": {+ "name": "canonical_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "native_run_results_run_fingerprint_uq": {+ "name": "native_run_results_run_fingerprint_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "server_fingerprint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "native_run_results_run_caller_result_uq": {+ "name": "native_run_results_run_caller_result_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "caller_result_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "native_run_results_run_caller_dedupe_uq": {+ "name": "native_run_results_run_caller_dedupe_uq",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "caller_dedupe_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "native_issue_id",+ "id",+ "completion_contract_id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.pipeline_automation_executions": {+ "name": "pipeline_automation_executions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "automation_id": {+ "name": "automation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "triggering_event_id": {+ "name": "triggering_event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "execution_issue_id": {+ "name": "execution_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "retry_of_execution_id": {+ "name": "retry_of_execution_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "generation": {+ "name": "generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_automation_executions_idempotency_uq": {+ "name": "pipeline_automation_executions_idempotency_uq",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "automation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "triggering_event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_automation_executions_company_case_idx": {+ "name": "pipeline_automation_executions_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_automation_executions_routine_idx": {+ "name": "pipeline_automation_executions_routine_idx",+ "columns": [+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_automation_executions_execution_issue_idx": {+ "name": "pipeline_automation_executions_execution_issue_idx",+ "columns": [+ {+ "expression": "execution_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_automation_executions_retry_of_execution_idx": {+ "name": "pipeline_automation_executions_retry_of_execution_idx",+ "columns": [+ {+ "expression": "retry_of_execution_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_automation_executions_status_check": {+ "name": "pipeline_automation_executions_status_check",+ "value": "\"pipeline_automation_executions\".\"status\" in ('succeeded', 'failed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_case_blockers": {+ "name": "pipeline_case_blockers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "blocked_by_case_id": {+ "name": "blocked_by_case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_case_blockers_case_blocked_by_uq": {+ "name": "pipeline_case_blockers_case_blocked_by_uq",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "blocked_by_case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_blockers_blocked_by_idx": {+ "name": "pipeline_case_blockers_blocked_by_idx",+ "columns": [+ {+ "expression": "blocked_by_case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_blockers_company_case_idx": {+ "name": "pipeline_case_blockers_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_case_blockers_no_self_block_check": {+ "name": "pipeline_case_blockers_no_self_block_check",+ "value": "\"pipeline_case_blockers\".\"case_id\" <> \"pipeline_case_blockers\".\"blocked_by_case_id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_case_documents": {+ "name": "pipeline_case_documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_case_documents_company_case_key_uq": {+ "name": "pipeline_case_documents_company_case_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_documents_document_uq": {+ "name": "pipeline_case_documents_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_documents_company_case_updated_idx": {+ "name": "pipeline_case_documents_company_case_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.pipeline_case_events": {+ "name": "pipeline_case_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_agent_id": {+ "name": "actor_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "from_stage_id": {+ "name": "from_stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "to_stage_id": {+ "name": "to_stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_case_events_case_created_idx": {+ "name": "pipeline_case_events_case_created_idx",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_events_company_case_idx": {+ "name": "pipeline_case_events_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_case_events_type_check": {+ "name": "pipeline_case_events_type_check",+ "value": "\"pipeline_case_events\".\"type\" in (\n 'ingested',\n 'updated',\n 'claimed',\n 'lease_released',\n 'lease_expired',\n 'transitioned',\n 'transition_forced',\n 'transition_suggested',\n 'suggestion_resolved',\n 'review_decided',\n 'conversation_opened',\n 'issue_linked',\n 'issue_unlinked',\n 'automation_executed',\n 'automation_failed',\n 'automation_retry_requested',\n 'automation_effects_retired',\n 'automation_retry_dispatched',\n 'blockers_set',\n 'blockers_resolved',\n 'children_terminal',\n 'upstream_drift',\n 'drift_acknowledged'\n )"+ },+ "pipeline_case_events_actor_type_check": {+ "name": "pipeline_case_events_actor_type_check",+ "value": "\"pipeline_case_events\".\"actor_type\" in ('user', 'agent', 'system')"+ },+ "pipeline_case_events_agent_run_check": {+ "name": "pipeline_case_events_agent_run_check",+ "value": "\"pipeline_case_events\".\"actor_type\" <> 'agent' or \"pipeline_case_events\".\"run_id\" is not null"+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_case_issue_links": {+ "name": "pipeline_case_issue_links",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_id": {+ "name": "case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "automation_attempt_id": {+ "name": "automation_attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "retired_at": {+ "name": "retired_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "retired_by_attempt_id": {+ "name": "retired_by_attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "retired_reason": {+ "name": "retired_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_case_issue_links_case_issue_uq": {+ "name": "pipeline_case_issue_links_case_issue_uq",+ "columns": [+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_issue_links_issue_idx": {+ "name": "pipeline_case_issue_links_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_issue_links_company_case_idx": {+ "name": "pipeline_case_issue_links_company_case_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_case_issue_links_automation_attempt_idx": {+ "name": "pipeline_case_issue_links_automation_attempt_idx",+ "columns": [+ {+ "expression": "automation_attempt_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_case_issue_links_role_check": {+ "name": "pipeline_case_issue_links_role_check",+ "value": "\"pipeline_case_issue_links\".\"role\" in ('origin', 'conversation', 'work', 'automation')"+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_cases": {+ "name": "pipeline_cases",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "pipeline_id": {+ "name": "pipeline_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "stage_id": {+ "name": "stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "case_key": {+ "name": "case_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "summary": {+ "name": "summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "fields": {+ "name": "fields",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "workspace_ref": {+ "name": "workspace_ref",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "parent_case_id": {+ "name": "parent_case_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "parent_case_version": {+ "name": "parent_case_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "request_key": {+ "name": "request_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "automation_attempt_id": {+ "name": "automation_attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "pending_suggestion": {+ "name": "pending_suggestion",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "lease_owner_type": {+ "name": "lease_owner_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "lease_agent_id": {+ "name": "lease_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "lease_user_id": {+ "name": "lease_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "lease_token": {+ "name": "lease_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "lease_expires_at": {+ "name": "lease_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "terminal_kind": {+ "name": "terminal_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "terminal_at": {+ "name": "terminal_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "retired_at": {+ "name": "retired_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "retired_by_attempt_id": {+ "name": "retired_by_attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "retired_reason": {+ "name": "retired_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "hidden_from_board_at": {+ "name": "hidden_from_board_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "child_count": {+ "name": "child_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "terminal_child_count": {+ "name": "terminal_child_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "origin_run_id": {+ "name": "origin_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_cases_pipeline_case_key_uq": {+ "name": "pipeline_cases_pipeline_case_key_uq",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "case_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_parent_request_key_uq": {+ "name": "pipeline_cases_parent_request_key_uq",+ "columns": [+ {+ "expression": "parent_case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "request_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"pipeline_cases\".\"request_key\" is not null and \"pipeline_cases\".\"retired_at\" is null",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_company_idx": {+ "name": "pipeline_cases_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_pipeline_stage_idx": {+ "name": "pipeline_cases_pipeline_stage_idx",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_parent_idx": {+ "name": "pipeline_cases_parent_idx",+ "columns": [+ {+ "expression": "parent_case_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_automation_attempt_idx": {+ "name": "pipeline_cases_automation_attempt_idx",+ "columns": [+ {+ "expression": "automation_attempt_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_retired_idx": {+ "name": "pipeline_cases_retired_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "retired_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_cases_lease_expires_idx": {+ "name": "pipeline_cases_lease_expires_idx",+ "columns": [+ {+ "expression": "lease_expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"pipeline_cases\".\"lease_expires_at\" is not null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_cases_terminal_kind_check": {+ "name": "pipeline_cases_terminal_kind_check",+ "value": "\"pipeline_cases\".\"terminal_kind\" is null or \"pipeline_cases\".\"terminal_kind\" in ('done', 'cancelled')"+ },+ "pipeline_cases_lease_owner_type_check": {+ "name": "pipeline_cases_lease_owner_type_check",+ "value": "\"pipeline_cases\".\"lease_owner_type\" is null or \"pipeline_cases\".\"lease_owner_type\" in ('user', 'agent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_documents": {+ "name": "pipeline_documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "pipeline_id": {+ "name": "pipeline_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_documents_company_pipeline_key_uq": {+ "name": "pipeline_documents_company_pipeline_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_documents_document_uq": {+ "name": "pipeline_documents_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_documents_company_pipeline_updated_idx": {+ "name": "pipeline_documents_company_pipeline_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.pipeline_stages": {+ "name": "pipeline_stages",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "pipeline_id": {+ "name": "pipeline_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_stages_pipeline_key_uq": {+ "name": "pipeline_stages_pipeline_key_uq",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_stages_pipeline_position_idx": {+ "name": "pipeline_stages_pipeline_position_idx",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "pipeline_stages_kind_check": {+ "name": "pipeline_stages_kind_check",+ "value": "\"pipeline_stages\".\"kind\" in ('working', 'review', 'done', 'cancelled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.pipeline_transitions": {+ "name": "pipeline_transitions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "pipeline_id": {+ "name": "pipeline_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "from_stage_id": {+ "name": "from_stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "to_stage_id": {+ "name": "to_stage_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipeline_transitions_pipeline_edge_uq": {+ "name": "pipeline_transitions_pipeline_edge_uq",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "from_stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "to_stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_transitions_pipeline_from_idx": {+ "name": "pipeline_transitions_pipeline_from_idx",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "from_stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipeline_transitions_pipeline_to_idx": {+ "name": "pipeline_transitions_pipeline_to_idx",+ "columns": [+ {+ "expression": "pipeline_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "to_stage_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.pipelines": {+ "name": "pipelines",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enforce_transitions": {+ "name": "enforce_transitions",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "pipelines_company_key_uq": {+ "name": "pipelines_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipelines_company_idx": {+ "name": "pipelines_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "pipelines_company_project_idx": {+ "name": "pipelines_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "pipelines_company_id_companies_id_fk": {+ "name": "pipelines_company_id_companies_id_fk",+ "tableFrom": "pipelines",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_company_settings": {+ "name": "plugin_company_settings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "settings_json": {+ "name": "settings_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_company_settings_company_idx": {+ "name": "plugin_company_settings_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_company_settings_plugin_idx": {+ "name": "plugin_company_settings_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_company_settings_company_plugin_uq": {+ "name": "plugin_company_settings_company_plugin_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_config": {+ "name": "plugin_config",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "config_json": {+ "name": "config_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_config_plugin_company_idx": {+ "name": "plugin_config_plugin_company_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_database_namespaces": {+ "name": "plugin_database_namespaces",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_key": {+ "name": "plugin_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "namespace_name": {+ "name": "namespace_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "namespace_mode": {+ "name": "namespace_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'schema'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_database_namespaces_plugin_idx": {+ "name": "plugin_database_namespaces_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_database_namespaces_namespace_idx": {+ "name": "plugin_database_namespaces_namespace_idx",+ "columns": [+ {+ "expression": "namespace_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_database_namespaces_status_idx": {+ "name": "plugin_database_namespaces_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_entities": {+ "name": "plugin_entities",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "entity_type": {+ "name": "entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_kind": {+ "name": "scope_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "data": {+ "name": "data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_entities_plugin_idx": {+ "name": "plugin_entities_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_entities_company_idx": {+ "name": "plugin_entities_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_entities_type_idx": {+ "name": "plugin_entities_type_idx",+ "columns": [+ {+ "expression": "entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_entities_scope_idx": {+ "name": "plugin_entities_scope_idx",+ "columns": [+ {+ "expression": "scope_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_job_runs": {+ "name": "plugin_job_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "job_id": {+ "name": "job_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "logs": {+ "name": "logs",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_job_runs_job_idx": {+ "name": "plugin_job_runs_job_idx",+ "columns": [+ {+ "expression": "job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_job_runs_plugin_idx": {+ "name": "plugin_job_runs_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_job_runs_company_idx": {+ "name": "plugin_job_runs_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_job_runs_status_idx": {+ "name": "plugin_job_runs_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_jobs": {+ "name": "plugin_jobs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "job_key": {+ "name": "job_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "schedule": {+ "name": "schedule",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "last_run_at": {+ "name": "last_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_run_at": {+ "name": "next_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_jobs_plugin_idx": {+ "name": "plugin_jobs_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_jobs_next_run_idx": {+ "name": "plugin_jobs_next_run_idx",+ "columns": [+ {+ "expression": "next_run_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_jobs_unique_idx": {+ "name": "plugin_jobs_unique_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "job_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_lifecycle_acknowledgments": {+ "name": "plugin_lifecycle_acknowledgments",+ "schema": "",+ "columns": {+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event_id": {+ "name": "event_id",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_lifecycle_acknowledgments_event_idx": {+ "name": "plugin_lifecycle_acknowledgments_event_idx",+ "columns": [+ {+ "expression": "event_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "plugin_lifecycle_acknowledgments_plugin_id_event_id_pk": {+ "name": "plugin_lifecycle_acknowledgments_plugin_id_event_id_pk",+ "columns": [+ "plugin_id",+ "event_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_logs": {+ "name": "plugin_logs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "level": {+ "name": "level",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "message": {+ "name": "message",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "meta": {+ "name": "meta",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_logs_plugin_time_idx": {+ "name": "plugin_logs_plugin_time_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_logs_company_idx": {+ "name": "plugin_logs_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_logs_level_idx": {+ "name": "plugin_logs_level_idx",+ "columns": [+ {+ "expression": "level",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_managed_resources": {+ "name": "plugin_managed_resources",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_key": {+ "name": "plugin_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_kind": {+ "name": "resource_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_key": {+ "name": "resource_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_id": {+ "name": "resource_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "defaults_json": {+ "name": "defaults_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_managed_resources_company_idx": {+ "name": "plugin_managed_resources_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_managed_resources_plugin_idx": {+ "name": "plugin_managed_resources_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_managed_resources_resource_idx": {+ "name": "plugin_managed_resources_resource_idx",+ "columns": [+ {+ "expression": "resource_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_managed_resources_company_plugin_resource_uq": {+ "name": "plugin_managed_resources_company_plugin_resource_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_migrations": {+ "name": "plugin_migrations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_key": {+ "name": "plugin_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "namespace_name": {+ "name": "namespace_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "migration_key": {+ "name": "migration_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "checksum": {+ "name": "checksum",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "plugin_version": {+ "name": "plugin_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "applied_at": {+ "name": "applied_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "plugin_migrations_plugin_key_idx": {+ "name": "plugin_migrations_plugin_key_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "migration_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_migrations_plugin_idx": {+ "name": "plugin_migrations_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_migrations_status_idx": {+ "name": "plugin_migrations_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_state": {+ "name": "plugin_state",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "scope_kind": {+ "name": "scope_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "namespace": {+ "name": "namespace",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "state_key": {+ "name": "state_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value_json": {+ "name": "value_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_state_plugin_scope_idx": {+ "name": "plugin_state_plugin_scope_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugin_webhook_deliveries": {+ "name": "plugin_webhook_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "webhook_key": {+ "name": "webhook_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "headers": {+ "name": "headers",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugin_webhook_deliveries_plugin_idx": {+ "name": "plugin_webhook_deliveries_plugin_idx",+ "columns": [+ {+ "expression": "plugin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_webhook_deliveries_company_idx": {+ "name": "plugin_webhook_deliveries_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_webhook_deliveries_status_idx": {+ "name": "plugin_webhook_deliveries_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugin_webhook_deliveries_key_idx": {+ "name": "plugin_webhook_deliveries_key_idx",+ "columns": [+ {+ "expression": "webhook_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.plugins": {+ "name": "plugins",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "plugin_key": {+ "name": "plugin_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "package_name": {+ "name": "package_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "api_version": {+ "name": "api_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "categories": {+ "name": "categories",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "manifest_json": {+ "name": "manifest_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'installed'"+ },+ "install_order": {+ "name": "install_order",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "package_path": {+ "name": "package_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "installed_at": {+ "name": "installed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "plugins_plugin_key_idx": {+ "name": "plugins_plugin_key_idx",+ "columns": [+ {+ "expression": "plugin_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "plugins_status_idx": {+ "name": "plugins_status_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.principal_permission_grants": {+ "name": "principal_permission_grants",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "principal_type": {+ "name": "principal_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "principal_id": {+ "name": "principal_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "permission_key": {+ "name": "permission_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope": {+ "name": "scope",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "granted_by_user_id": {+ "name": "granted_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "principal_permission_grants_unique_idx": {+ "name": "principal_permission_grants_unique_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "principal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "permission_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "principal_permission_grants_company_permission_idx": {+ "name": "principal_permission_grants_company_permission_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "permission_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_goals": {+ "name": "project_goals",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_goals_project_idx": {+ "name": "project_goals_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_goals_goal_idx": {+ "name": "project_goals_goal_idx",+ "columns": [+ {+ "expression": "goal_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_goals_company_idx": {+ "name": "project_goals_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_goals_project_id_goal_id_pk": {+ "name": "project_goals_project_id_goal_id_pk",+ "columns": [+ "project_id",+ "goal_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_memberships": {+ "name": "project_memberships",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'joined'"+ },+ "starred_at": {+ "name": "starred_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_memberships_company_user_idx": {+ "name": "project_memberships_company_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_memberships_company_user_starred_idx": {+ "name": "project_memberships_company_user_starred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "starred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_memberships_project_idx": {+ "name": "project_memberships_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_memberships_company_user_project_uq": {+ "name": "project_memberships_company_user_project_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_workspaces": {+ "name": "project_workspaces",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_type": {+ "name": "source_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_path'"+ },+ "cwd": {+ "name": "cwd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "repo_url": {+ "name": "repo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "repo_ref": {+ "name": "repo_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "default_ref": {+ "name": "default_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "visibility": {+ "name": "visibility",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "setup_command": {+ "name": "setup_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cleanup_command": {+ "name": "cleanup_command",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "remote_provider": {+ "name": "remote_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "remote_workspace_ref": {+ "name": "remote_workspace_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "shared_workspace_key": {+ "name": "shared_workspace_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "is_primary": {+ "name": "is_primary",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_workspaces_company_project_idx": {+ "name": "project_workspaces_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaces_project_primary_idx": {+ "name": "project_workspaces_project_primary_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "is_primary",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaces_project_source_type_idx": {+ "name": "project_workspaces_project_source_type_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaces_company_shared_key_idx": {+ "name": "project_workspaces_company_shared_key_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "shared_workspace_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_workspaces_project_remote_ref_idx": {+ "name": "project_workspaces_project_remote_ref_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "remote_provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "remote_workspace_ref",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.projects": {+ "name": "projects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'backlog'"+ },+ "lead_agent_id": {+ "name": "lead_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "target_date": {+ "name": "target_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "env": {+ "name": "env",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "pause_reason": {+ "name": "pause_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "paused_at": {+ "name": "paused_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_policy": {+ "name": "execution_workspace_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "projects_company_idx": {+ "name": "projects_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": 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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.provider_trace_records": {+ "name": "provider_trace_records",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'capturing'"+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trace_ref": {+ "name": "trace_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "frame_count": {+ "name": "frame_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "byte_count": {+ "name": "byte_count",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "digest": {+ "name": "digest",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by": {+ "name": "requested_by",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "provider_trace_records_run_unique": {+ "name": "provider_trace_records_run_unique",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "provider_trace_records_expiry_idx": {+ "name": "provider_trace_records_expiry_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "provider_trace_records_company_created_idx": {+ "name": "provider_trace_records_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.remote_agent_profiles": {+ "name": "remote_agent_profiles",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "profile_key": {+ "name": "profile_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "service": {+ "name": "service",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "configuration": {+ "name": "configuration",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "retention_acknowledged": {+ "name": "retention_acknowledged",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "qualification": {+ "name": "qualification",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "qualified_at": {+ "name": "qualified_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "qualified_revision": {+ "name": "qualified_revision",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "remote_agent_profiles_company_idx": {+ "name": "remote_agent_profiles_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "remote_agent_profiles_company_key_uq": {+ "name": "remote_agent_profiles_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "remote_agent_profiles_service_check": {+ "name": "remote_agent_profiles_service_check",+ "value": "\"remote_agent_profiles\".\"service\" = 'aws_bedrock_agentcore_harness'"+ },+ "remote_agent_profiles_qualified_revision_check": {+ "name": "remote_agent_profiles_qualified_revision_check",+ "value": "(\"remote_agent_profiles\".\"qualified_at\" IS NULL AND \"remote_agent_profiles\".\"qualified_revision\" IS NULL) OR (\"remote_agent_profiles\".\"qualified_at\" IS NOT NULL AND \"remote_agent_profiles\".\"qualification\" <> '{}'::jsonb AND \"remote_agent_profiles\".\"qualified_revision\" ~ '^sha256:[0-9a-f]{64}$')"+ }+ },+ "isRLSEnabled": false+ },+ "public.resource_lifecycle_events": {+ "name": "resource_lifecycle_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigint",+ "primaryKey": true,+ "notNull": true,+ "identity": {+ "type": "always",+ "name": "resource_lifecycle_events_id_seq",+ "schema": "public",+ "increment": "1",+ "startWith": "1",+ "minValue": "1",+ "maxValue": "9223372036854775807",+ "cache": "1",+ "cycle": false+ }+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_id": {+ "name": "resource_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "resource_lifecycle_events_creation_idx": {+ "name": "resource_lifecycle_events_creation_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"resource_lifecycle_events\".\"action\" = 'create'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "resource_lifecycle_events_company_idx": {+ "name": "resource_lifecycle_events_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "resource_lifecycle_events_resource_order_idx": {+ "name": "resource_lifecycle_events_resource_order_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "resource_lifecycle_events_resource_type_check": {+ "name": "resource_lifecycle_events_resource_type_check",+ "value": "\"resource_lifecycle_events\".\"resource_type\" IN ('agent', 'project')"+ },+ "resource_lifecycle_events_action_check": {+ "name": "resource_lifecycle_events_action_check",+ "value": "\"resource_lifecycle_events\".\"action\" = 'create' OR (\"resource_lifecycle_events\".\"resource_type\" = 'project' AND \"resource_lifecycle_events\".\"action\" IN ('update', 'archive')) OR (\"resource_lifecycle_events\".\"resource_type\" = 'agent' AND \"resource_lifecycle_events\".\"action\" IN ('pause', 'resume', 'terminate'))"+ }+ },+ "isRLSEnabled": false+ },+ "public.routine_documents": {+ "name": "routine_documents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routine_documents_company_routine_key_uq": {+ "name": "routine_documents_company_routine_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_documents_document_uq": {+ "name": "routine_documents_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_documents_company_routine_updated_idx": {+ "name": "routine_documents_company_routine_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routine_revisions": {+ "name": "routine_revisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision_number": {+ "name": "revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "snapshot": {+ "name": "snapshot",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "change_summary": {+ "name": "change_summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "restored_from_revision_id": {+ "name": "restored_from_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_run_id": {+ "name": "created_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routine_revisions_routine_revision_uq": {+ "name": "routine_revisions_routine_revision_uq",+ "columns": [+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revision_number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_revisions_company_routine_created_idx": {+ "name": "routine_revisions_company_routine_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_revisions_company_responsible_user_idx": {+ "name": "routine_revisions_company_responsible_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routine_runs": {+ "name": "routine_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "trigger_id": {+ "name": "trigger_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'received'"+ },+ "triggered_at": {+ "name": "triggered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "routine_revision_id": {+ "name": "routine_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_payload": {+ "name": "trigger_payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "dispatch_fingerprint": {+ "name": "dispatch_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "linked_issue_id": {+ "name": "linked_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "coalesced_into_run_id": {+ "name": "coalesced_into_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routine_runs_company_routine_idx": {+ "name": "routine_runs_company_routine_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_revision_idx": {+ "name": "routine_runs_revision_idx",+ "columns": [+ {+ "expression": "routine_revision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_company_responsible_user_idx": {+ "name": "routine_runs_company_responsible_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_trigger_idx": {+ "name": "routine_runs_trigger_idx",+ "columns": [+ {+ "expression": "trigger_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_dispatch_fingerprint_idx": {+ "name": "routine_runs_dispatch_fingerprint_idx",+ "columns": [+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "dispatch_fingerprint",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_linked_issue_idx": {+ "name": "routine_runs_linked_issue_idx",+ "columns": [+ {+ "expression": "linked_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_runs_trigger_idempotency_idx": {+ "name": "routine_runs_trigger_idempotency_idx",+ "columns": [+ {+ "expression": "trigger_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routine_triggers": {+ "name": "routine_triggers",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "routine_id": {+ "name": "routine_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "setup_pending": {+ "name": "setup_pending",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived": {+ "name": "archived",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "last_webhook_delivery": {+ "name": "last_webhook_delivery",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "cron_expression": {+ "name": "cron_expression",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_run_at": {+ "name": "next_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_fired_at": {+ "name": "last_fired_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "public_id": {+ "name": "public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "signing_mode": {+ "name": "signing_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "replay_window_sec": {+ "name": "replay_window_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_rotated_at": {+ "name": "last_rotated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_result": {+ "name": "last_result",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routine_triggers_company_routine_idx": {+ "name": "routine_triggers_company_routine_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "routine_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_triggers_company_kind_idx": {+ "name": "routine_triggers_company_kind_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_triggers_next_run_idx": {+ "name": "routine_triggers_next_run_idx",+ "columns": [+ {+ "expression": "next_run_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_triggers_public_id_idx": {+ "name": "routine_triggers_public_id_idx",+ "columns": [+ {+ "expression": "public_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routine_triggers_public_id_uq": {+ "name": "routine_triggers_public_id_uq",+ "columns": [+ {+ "expression": "public_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routine_webhook_test_receipts": {+ "name": "routine_webhook_test_receipts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "trigger_id": {+ "name": "trigger_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_key_hash": {+ "name": "delivery_key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "received_at": {+ "name": "received_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routine_webhook_test_receipts_delivery_uq": {+ "name": "routine_webhook_test_receipts_delivery_uq",+ "columns": [+ {+ "expression": "trigger_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "delivery_key_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.routines": {+ "name": "routines",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "folder_id": {+ "name": "folder_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "goal_id": {+ "name": "goal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "parent_issue_id": {+ "name": "parent_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_agent_id": {+ "name": "assignee_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'medium'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "concurrency_policy": {+ "name": "concurrency_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'coalesce_if_active'"+ },+ "catch_up_policy": {+ "name": "catch_up_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'skip_missed'"+ },+ "activity_gate_policy": {+ "name": "activity_gate_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'always'"+ },+ "activity_gate_scope": {+ "name": "activity_gate_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'company'"+ },+ "origin_kind": {+ "name": "origin_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'manual'"+ },+ "origin_id": {+ "name": "origin_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "variables": {+ "name": "variables",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "env": {+ "name": "env",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "latest_revision_id": {+ "name": "latest_revision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "latest_revision_number": {+ "name": "latest_revision_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_triggered_at": {+ "name": "last_triggered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_enqueued_at": {+ "name": "last_enqueued_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "routines_company_status_idx": {+ "name": "routines_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routines_company_assignee_idx": {+ "name": "routines_company_assignee_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "assignee_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routines_company_project_idx": {+ "name": "routines_company_project_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routines_company_folder_idx": {+ "name": "routines_company_folder_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "folder_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routines_company_responsible_user_idx": {+ "name": "routines_company_responsible_user_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "responsible_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "routines_company_origin_idx": {+ "name": "routines_company_origin_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "origin_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "routines_company_id_companies_id_fk": {+ "name": "routines_company_id_companies_id_fk",+ "tableFrom": "routines",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.run_identity_contexts": {+ "name": "run_identity_contexts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "message_id": {+ "name": "message_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "parent_context_id": {+ "name": "parent_context_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "cause": {+ "name": "cause",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'accepted'"+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "github": {+ "name": "github",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "run_identity_contexts_run_revision_idx": {+ "name": "run_identity_contexts_run_revision_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "revision",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "run_identity_contexts_run_correlation_idx": {+ "name": "run_identity_contexts_run_correlation_idx",+ "columns": [+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "correlation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "run_identity_contexts_company_run_idx": {+ "name": "run_identity_contexts_company_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.runner_api_response_reservations": {+ "name": "runner_api_response_reservations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "asset_id": {+ "name": "asset_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "reserved_bytes": {+ "name": "reserved_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "runner_api_response_reservations_company_idx": {+ "name": "runner_api_response_reservations_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.secret_access_events": {+ "name": "secret_access_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "secret_id": {+ "name": "secret_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "user_secret_definition_id": {+ "name": "user_secret_definition_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "secret_scope": {+ "name": "secret_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'company'"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_owner_user_id": {+ "name": "credential_owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_subject_type": {+ "name": "credential_subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_subject_id": {+ "name": "credential_subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "consumer_type": {+ "name": "consumer_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "consumer_id": {+ "name": "consumer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config_path": {+ "name": "config_path",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "secret_access_events_company_created_idx": {+ "name": "secret_access_events_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "secret_access_events_secret_created_idx": {+ "name": "secret_access_events_secret_created_idx",+ "columns": [+ {+ "expression": "secret_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "secret_access_events_user_definition_created_idx": {+ "name": "secret_access_events_user_definition_created_idx",+ "columns": [+ {+ "expression": "user_secret_definition_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "secret_access_events_company_credential_owner_idx": {+ "name": "secret_access_events_company_credential_owner_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "credential_owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "secret_access_events_consumer_idx": {+ "name": "secret_access_events_consumer_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "consumer_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "consumer_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "secret_access_events_run_idx": {+ "name": "secret_access_events_run_idx",+ "columns": [+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.smoke_run_steps": {+ "name": "smoke_run_steps",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "path": {+ "name": "path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scenario_step": {+ "name": "scenario_step",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "detail": {+ "name": "detail",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "screenshot_artifact_ref": {+ "name": "screenshot_artifact_ref",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "smoke_run_steps_company_run_idx": {+ "name": "smoke_run_steps_company_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "smoke_run_steps_company_path_idx": {+ "name": "smoke_run_steps_company_path_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "path",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.smoke_runs": {+ "name": "smoke_runs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "summary": {+ "name": "summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "smoke_runs_company_started_idx": {+ "name": "smoke_runs_company_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "smoke_runs_company_status_idx": {+ "name": "smoke_runs_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "smoke_runs_company_id_companies_id_fk": {+ "name": "smoke_runs_company_id_companies_id_fk",+ "tableFrom": "smoke_runs",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.status_card_updates": {+ "name": "status_card_updates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "card_id": {+ "name": "card_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "generation_issue_id": {+ "name": "generation_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "changes": {+ "name": "changes",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "cost_cents": {+ "name": "cost_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "query_version": {+ "name": "query_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "change_summary": {+ "name": "change_summary",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "error": {+ "name": "error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "status_card_updates_card_started_idx": {+ "name": "status_card_updates_card_started_idx",+ "columns": [+ {+ "expression": "card_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "status_card_updates_generation_issue_idx": {+ "name": "status_card_updates_generation_issue_idx",+ "columns": [+ {+ "expression": "generation_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.status_cards": {+ "name": "status_cards",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title_pinned": {+ "name": "title_pinned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "interest_prompt": {+ "name": "interest_prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "queries": {+ "name": "queries",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "query_version": {+ "name": "query_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "query_compiled_at": {+ "name": "query_compiled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "query_compiled_by_agent_id": {+ "name": "query_compiled_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_policy": {+ "name": "refresh_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'compiling'"+ },+ "pending_change_count": {+ "name": "pending_change_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "pending_change_hash": {+ "name": "pending_change_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_change_at": {+ "name": "last_change_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "fingerprint_at": {+ "name": "fingerprint_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "mentioned_issue_ids": {+ "name": "mentioned_issue_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_update_run_kind": {+ "name": "last_update_run_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_generated_at": {+ "name": "last_generated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_model": {+ "name": "last_model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "generating_issue_id": {+ "name": "generating_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "next_eval_at": {+ "name": "next_eval_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_user_id": {+ "name": "archived_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_agent_id": {+ "name": "archived_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "status_cards_company_archived_idx": {+ "name": "status_cards_company_archived_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "archived_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "status_cards_company_next_eval_idx": {+ "name": "status_cards_company_next_eval_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_eval_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.status_decision_effects": {+ "name": "status_decision_effects",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "decision_id": {+ "name": "decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "ordinal": {+ "name": "ordinal",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "effect_kind": {+ "name": "effect_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_state": {+ "name": "delivery_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempt_count": {+ "name": "attempt_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "status_decision_effects_decision_ordinal_uq": {+ "name": "status_decision_effects_decision_ordinal_uq",+ "columns": [+ {+ "expression": "decision_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "ordinal",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "status_decision_effects_company_idempotency_uq": {+ "name": "status_decision_effects_company_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.status_decisions": {+ "name": "status_decisions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "assessment_id": {+ "name": "assessment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "decision_version": {+ "name": "decision_version",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "policy_version": {+ "name": "policy_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "from_status": {+ "name": "from_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "to_status": {+ "name": "to_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason_code": {+ "name": "reason_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "decision_json": {+ "name": "decision_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "decision_digest": {+ "name": "decision_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "application_state": {+ "name": "application_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'proposed'"+ },+ "supersedes_decision_id": {+ "name": "supersedes_decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "applied_at": {+ "name": "applied_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "status_decisions_company_issue_version_uq": {+ "name": "status_decisions_company_issue_version_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "decision_version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "status_decisions_company_assessment_uq": {+ "name": "status_decisions_company_assessment_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "assessment_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "status_decisions_company_issue_digest_uq": {+ "name": "status_decisions_company_issue_digest_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "decision_digest",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "id"+ ],+ "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"+ ]+ },+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.summary_slots": {+ "name": "summary_slots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "scope_kind": {+ "name": "scope_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "slot_key": {+ "name": "slot_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'idle'"+ },+ "failure_reason": {+ "name": "failure_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "generating_issue_id": {+ "name": "generating_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_generated_at": {+ "name": "last_generated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_generated_by_agent_id": {+ "name": "last_generated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_model": {+ "name": "last_model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "summary_slots_document_uq": {+ "name": "summary_slots_document_uq",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "summary_slots_company_scope_idx": {+ "name": "summary_slots_company_scope_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scope_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "summary_slots_company_generating_issue_idx": {+ "name": "summary_slots_company_generating_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "generating_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "summary_slots_company_updated_idx": {+ "name": "summary_slots_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_access_audit_events": {+ "name": "tool_access_audit_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "gateway_id": {+ "name": "gateway_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_token_id": {+ "name": "gateway_token_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_public_id": {+ "name": "gateway_public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_name": {+ "name": "client_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_entry_id": {+ "name": "catalog_entry_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reason_code": {+ "name": "reason_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "details": {+ "name": "details",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_access_audit_company_created_idx": {+ "name": "tool_access_audit_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_access_audit_connection_idx": {+ "name": "tool_access_audit_connection_idx",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_access_audit_gateway_idx": {+ "name": "tool_access_audit_gateway_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "gateway_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_action_deliveries": {+ "name": "tool_action_deliveries",+ "schema": "",+ "columns": {+ "action_request_id": {+ "name": "action_request_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_action_deliveries_pending_idx": {+ "name": "tool_action_deliveries_pending_idx",+ "columns": [+ {+ "expression": "delivered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_action_requests": {+ "name": "tool_action_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "invocation_id": {+ "name": "invocation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "approval_id": {+ "name": "approval_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "canonical_arguments_hash": {+ "name": "canonical_arguments_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "canonical_arguments_summary": {+ "name": "canonical_arguments_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "signed_arguments": {+ "name": "signed_arguments",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "preview_markdown": {+ "name": "preview_markdown",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_agent_id": {+ "name": "requested_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_user_id": {+ "name": "requested_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_agent_id": {+ "name": "resolved_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by_user_id": {+ "name": "resolved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_by_agent_id": {+ "name": "decided_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "decided_by_user_id": {+ "name": "decided_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_action_requests_company_status_idx": {+ "name": "tool_action_requests_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_action_requests_invocation_idx": {+ "name": "tool_action_requests_invocation_idx",+ "columns": [+ {+ "expression": "invocation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_action_requests_issue_idx": {+ "name": "tool_action_requests_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_applications": {+ "name": "tool_applications",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "application_key": {+ "name": "application_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "plugin_id": {+ "name": "plugin_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_applications_company_idx": {+ "name": "tool_applications_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_applications_company_status_idx": {+ "name": "tool_applications_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_applications_company_name_uq": {+ "name": "tool_applications_company_name_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_applications_company_key_uq": {+ "name": "tool_applications_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "application_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_call_events": {+ "name": "tool_call_events",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_id": {+ "name": "gateway_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_token_id": {+ "name": "gateway_token_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_public_id": {+ "name": "gateway_public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_type": {+ "name": "client_subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_id": {+ "name": "client_subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_name": {+ "name": "client_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_session_id": {+ "name": "mcp_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_entry_id": {+ "name": "catalog_entry_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "invocation_id": {+ "name": "invocation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "action_request_id": {+ "name": "action_request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_slot_id": {+ "name": "runtime_slot_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decision": {+ "name": "decision",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "matched_policy_ids": {+ "name": "matched_policy_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "reason_code": {+ "name": "reason_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "policy_explanation": {+ "name": "policy_explanation",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "credential_scope_summary": {+ "name": "credential_scope_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "header_policy_summary": {+ "name": "header_policy_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "latency_ms": {+ "name": "latency_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "arguments_summary": {+ "name": "arguments_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "request_hash": {+ "name": "request_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "request_summary": {+ "name": "request_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "result_hash": {+ "name": "result_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result_summary": {+ "name": "result_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "result_size_bytes": {+ "name": "result_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "redaction_plan": {+ "name": "redaction_plan",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "rate_limit_state": {+ "name": "rate_limit_state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_call_events_company_created_idx": {+ "name": "tool_call_events_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_call_events_run_idx": {+ "name": "tool_call_events_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_call_events_issue_idx": {+ "name": "tool_call_events_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_call_events_invocation_idx": {+ "name": "tool_call_events_invocation_idx",+ "columns": [+ {+ "expression": "invocation_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_call_events_gateway_idx": {+ "name": "tool_call_events_gateway_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "gateway_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_catalog_entries": {+ "name": "tool_catalog_entries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "entry_kind": {+ "name": "entry_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'tool'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "input_schema": {+ "name": "input_schema",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "output_schema": {+ "name": "output_schema",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "annotations": {+ "name": "annotations",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "risk_level": {+ "name": "risk_level",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'read'"+ },+ "is_read_only": {+ "name": "is_read_only",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "is_write": {+ "name": "is_write",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_destructive": {+ "name": "is_destructive",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "version": {+ "name": "version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "version_hash": {+ "name": "version_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "schema_hash": {+ "name": "schema_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_seen_at": {+ "name": "first_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "reviewed_at": {+ "name": "reviewed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "reviewed_by_agent_id": {+ "name": "reviewed_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "reviewed_by_user_id": {+ "name": "reviewed_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "quarantined_at": {+ "name": "quarantined_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "quarantine_reason": {+ "name": "quarantine_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_catalog_entries_company_idx": {+ "name": "tool_catalog_entries_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_catalog_entries_application_idx": {+ "name": "tool_catalog_entries_application_idx",+ "columns": [+ {+ "expression": "application_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_catalog_entries_connection_idx": {+ "name": "tool_catalog_entries_connection_idx",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_catalog_entries_company_status_idx": {+ "name": "tool_catalog_entries_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_catalog_entries_connection_name_uq": {+ "name": "tool_catalog_entries_connection_name_uq",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_connection_app_snapshots": {+ "name": "tool_connection_app_snapshots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_key": {+ "name": "credential_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "toolkit": {+ "name": "toolkit",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "accounts": {+ "name": "accounts",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "checked_at": {+ "name": "checked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "error_at": {+ "name": "error_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "tool_connection_app_snapshots_owner_toolkit_uq": {+ "name": "tool_connection_app_snapshots_owner_toolkit_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "toolkit",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_connection_app_syncs": {+ "name": "tool_connection_app_syncs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_key": {+ "name": "credential_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "lease_id": {+ "name": "lease_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "checked": {+ "name": "checked",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "total": {+ "name": "total",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "failed": {+ "name": "failed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "last_completed_at": {+ "name": "last_completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_connection_app_syncs_owner_key_uq": {+ "name": "tool_connection_app_syncs_owner_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "credential_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_connection_installs": {+ "name": "tool_connection_installs",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_connection_installs_company_target_idx": {+ "name": "tool_connection_installs_company_target_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_connection_installs_connection_idx": {+ "name": "tool_connection_installs_connection_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_connection_installs_target_uq": {+ "name": "tool_connection_installs_target_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "tool_connection_installs_target_type_check": {+ "name": "tool_connection_installs_target_type_check",+ "value": "\"tool_connection_installs\".\"target_type\" in ('company', 'agent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.tool_connections": {+ "name": "tool_connections",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "uid": {+ "name": "uid",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "connection_kind": {+ "name": "connection_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'managed'"+ },+ "connection_purpose": {+ "name": "connection_purpose",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'tool'"+ },+ "ownership": {+ "name": "ownership",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'customer'"+ },+ "transport": {+ "name": "transport",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_kind": {+ "name": "auth_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "credential_source": {+ "name": "credential_source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip_vault'"+ },+ "external_credential": {+ "name": "external_credential",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "credential_policy": {+ "name": "credential_policy",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'shared'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'draft'"+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "agent_instructions": {+ "name": "agent_instructions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "transport_config": {+ "name": "transport_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "credential_refs": {+ "name": "credential_refs",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "credential_secret_refs": {+ "name": "credential_secret_refs",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "health_status": {+ "name": "health_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unchecked'"+ },+ "health_message": {+ "name": "health_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "health_checked_at": {+ "name": "health_checked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_health_at": {+ "name": "last_health_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_catalog_refresh_at": {+ "name": "last_catalog_refresh_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_connections_company_idx": {+ "name": "tool_connections_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_connections_application_idx": {+ "name": "tool_connections_application_idx",+ "columns": [+ {+ "expression": "application_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_connections_company_enabled_idx": {+ "name": "tool_connections_company_enabled_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "enabled",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_connections_company_uid_uq": {+ "name": "tool_connections_company_uid_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "uid",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "tool_connections_ownership_check": {+ "name": "tool_connections_ownership_check",+ "value": "\"tool_connections\".\"ownership\" in ('platform_shared', 'platform_provisioned', 'customer', 'dcr')"+ },+ "tool_connections_transport_check": {+ "name": "tool_connections_transport_check",+ "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'runtime_auth')"+ },+ "tool_connections_purpose_check": {+ "name": "tool_connections_purpose_check",+ "value": "\"tool_connections\".\"connection_purpose\" in ('tool', 'channel', 'ai')"+ },+ "tool_connections_channel_transport_check": {+ "name": "tool_connections_channel_transport_check",+ "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" = 'chat_sdk' or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )"+ },+ "tool_connections_auth_kind_check": {+ "name": "tool_connections_auth_kind_check",+ "value": "\"tool_connections\".\"auth_kind\" in ('oauth', 'api_key', 'none')"+ },+ "tool_connections_credential_source_check": {+ "name": "tool_connections_credential_source_check",+ "value": "\"tool_connections\".\"credential_source\" in ('paperclip_vault', 'vercel_connect')"+ },+ "tool_connections_credential_source_one_of_check": {+ "name": "tool_connections_credential_source_one_of_check",+ "value": "(\n (\"tool_connections\".\"credential_source\" = 'paperclip_vault' and \"tool_connections\".\"external_credential\" is null)\n or\n (\"tool_connections\".\"credential_source\" = 'vercel_connect' and \"tool_connections\".\"external_credential\" is not null and jsonb_array_length(\"tool_connections\".\"credential_refs\") = 0 and jsonb_array_length(\"tool_connections\".\"credential_secret_refs\") = 0)\n )"+ },+ "tool_connections_credential_policy_check": {+ "name": "tool_connections_credential_policy_check",+ "value": "\"tool_connections\".\"credential_policy\" in ('shared', 'per_user', 'per_user_with_fallback', 'per_agent')"+ }+ },+ "isRLSEnabled": false+ },+ "public.tool_gateway_rate_limit_counters": {+ "name": "tool_gateway_rate_limit_counters",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "counter_key": {+ "name": "counter_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "window_start_at": {+ "name": "window_start_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "window_ms": {+ "name": "window_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "limit": {+ "name": "limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "count": {+ "name": "count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "reset_at": {+ "name": "reset_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_gateway_rate_limit_counters_company_idx": {+ "name": "tool_gateway_rate_limit_counters_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_rate_limit_counters_window_uq": {+ "name": "tool_gateway_rate_limit_counters_window_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "counter_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_start_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_gateway_sessions": {+ "name": "tool_gateway_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_id": {+ "name": "gateway_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_token_id": {+ "name": "gateway_token_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_public_id": {+ "name": "gateway_public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_type": {+ "name": "client_subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_id": {+ "name": "client_subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_name": {+ "name": "client_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_session_id": {+ "name": "mcp_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_gateway_sessions_token_hash_uq": {+ "name": "tool_gateway_sessions_token_hash_uq",+ "columns": [+ {+ "expression": "token_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_sessions_company_agent_idx": {+ "name": "tool_gateway_sessions_company_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_sessions_company_expires_idx": {+ "name": "tool_gateway_sessions_company_expires_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_sessions_run_idx": {+ "name": "tool_gateway_sessions_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_sessions_issue_idx": {+ "name": "tool_gateway_sessions_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_gateway_sessions_gateway_idx": {+ "name": "tool_gateway_sessions_gateway_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "gateway_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_invocations": {+ "name": "tool_invocations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "idempotency_key": {+ "name": "idempotency_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_type": {+ "name": "actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "actor_id": {+ "name": "actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_id": {+ "name": "gateway_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_token_id": {+ "name": "gateway_token_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "gateway_public_id": {+ "name": "gateway_public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_type": {+ "name": "client_subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_subject_id": {+ "name": "client_subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_name": {+ "name": "client_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_session_id": {+ "name": "mcp_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "correlation_id": {+ "name": "correlation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_entry_id": {+ "name": "catalog_entry_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_version_hash": {+ "name": "catalog_version_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_schema_hash": {+ "name": "catalog_schema_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_type": {+ "name": "provider_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "application_key": {+ "name": "application_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "upstream_tool_name": {+ "name": "upstream_tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "risk_level": {+ "name": "risk_level",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "arguments_hash": {+ "name": "arguments_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "arguments_summary": {+ "name": "arguments_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "policy_decision": {+ "name": "policy_decision",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "matched_policy_ids": {+ "name": "matched_policy_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "policy_explanation": {+ "name": "policy_explanation",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "credential_scope_summary": {+ "name": "credential_scope_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "header_policy_summary": {+ "name": "header_policy_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "approval_state": {+ "name": "approval_state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'not_required'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "upstream_request_id": {+ "name": "upstream_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result_hash": {+ "name": "result_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "result_summary": {+ "name": "result_summary",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "result_size_bytes": {+ "name": "result_size_bytes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "result_artifact_id": {+ "name": "result_artifact_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "error_message": {+ "name": "error_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_invocations_company_created_idx": {+ "name": "tool_invocations_company_created_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_invocations_run_idx": {+ "name": "tool_invocations_run_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_invocations_issue_idx": {+ "name": "tool_invocations_issue_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_invocations_gateway_idx": {+ "name": "tool_invocations_gateway_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "gateway_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_invocations_company_idempotency_uq": {+ "name": "tool_invocations_company_idempotency_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_mcp_gateway_tokens": {+ "name": "tool_mcp_gateway_tokens",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "gateway_id": {+ "name": "gateway_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_prefix": {+ "name": "token_prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "subject_type": {+ "name": "subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'gateway_client'"+ },+ "subject_id": {+ "name": "subject_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_label": {+ "name": "client_label",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "owner_note": {+ "name": "owner_note",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "allowed_actions": {+ "name": "allowed_actions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[\"tools/list\",\"tools/call\"]'::jsonb"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expiry_override_reason": {+ "name": "expiry_override_reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expiry_override_by_user_id": {+ "name": "expiry_override_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expiry_override_by_agent_id": {+ "name": "expiry_override_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "expiry_override_at": {+ "name": "expiry_override_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_mcp_gateway_tokens_token_hash_uq": {+ "name": "tool_mcp_gateway_tokens_token_hash_uq",+ "columns": [+ {+ "expression": "token_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateway_tokens_expiry_idx": {+ "name": "tool_mcp_gateway_tokens_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateway_tokens_gateway_idx": {+ "name": "tool_mcp_gateway_tokens_gateway_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "gateway_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateway_tokens_subject_idx": {+ "name": "tool_mcp_gateway_tokens_subject_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateway_tokens_company_expires_idx": {+ "name": "tool_mcp_gateway_tokens_company_expires_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_mcp_gateways": {+ "name": "tool_mcp_gateways",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "gateway_public_id": {+ "name": "gateway_public_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'gw_' || replace(gen_random_uuid()::text, '-', '')"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "display_slug": {+ "name": "display_slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "profile_id": {+ "name": "profile_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "default_profile_mode": {+ "name": "default_profile_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'gateway_only'"+ },+ "context_scope_type": {+ "name": "context_scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'none'"+ },+ "context_scope_id": {+ "name": "context_scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "approval_issue_id": {+ "name": "approval_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "auth_config": {+ "name": "auth_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"version\":1,\"bearer\":{\"enabled\":true,\"tokenPrefix\":\"pcgw\",\"defaultTtlSeconds\":7776000,\"requireFiniteExpiry\":true,\"longLivedTokenRequiresOverride\":true},\"oauth\":{\"enabled\":false,\"reservedFor\":\"v1_5\",\"dynamicClientRegistration\":false,\"authorizationCodePkce\":false}}'::jsonb"+ },+ "header_policy": {+ "name": "header_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"version\":1,\"callerPassthrough\":{\"enabled\":false,\"allowedHeaders\":[]},\"staticHeaders\":[],\"generatedMetadata\":{\"enabled\":false,\"allowedHeaders\":[]},\"responseHeaders\":{\"forwardMcpRequiredHeaders\":true,\"forwardSafeCacheHeaders\":true}}'::jsonb"+ },+ "metadata_policy": {+ "name": "metadata_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"version\":1,\"forwardCompanyId\":false,\"forwardGatewayId\":false,\"forwardProjectId\":false,\"forwardIssueId\":false,\"forwardAgentId\":false,\"forwardRunId\":false,\"forwardCorrelationId\":true}'::jsonb"+ },+ "on_demand_tools_config": {+ "name": "on_demand_tools_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{\"enabled\":false,\"searchToolName\":\"search_tools\",\"runToolName\":\"run_tool\"}'::jsonb"+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_mcp_gateways_company_idx": {+ "name": "tool_mcp_gateways_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateways_company_status_idx": {+ "name": "tool_mcp_gateways_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateways_profile_idx": {+ "name": "tool_mcp_gateways_profile_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateways_public_id_uq": {+ "name": "tool_mcp_gateways_public_id_uq",+ "columns": [+ {+ "expression": "gateway_public_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateways_company_slug_uq": {+ "name": "tool_mcp_gateways_company_slug_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "slug",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_mcp_gateways_company_name_uq": {+ "name": "tool_mcp_gateways_company_name_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_oauth_states": {+ "name": "tool_oauth_states",+ "schema": "",+ "columns": {+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "code_verifier": {+ "name": "code_verifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_actor_type": {+ "name": "created_by_actor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_actor_id": {+ "name": "created_by_actor_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_session_id": {+ "name": "created_by_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "subject_user_id": {+ "name": "subject_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "subject_agent_id": {+ "name": "subject_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_scopes": {+ "name": "requested_scopes",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "return_to": {+ "name": "return_to",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "interaction_id": {+ "name": "interaction_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_oauth_states_company_idx": {+ "name": "tool_oauth_states_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_oauth_states_connection_idx": {+ "name": "tool_oauth_states_connection_idx",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_oauth_states_actor_idx": {+ "name": "tool_oauth_states_actor_idx",+ "columns": [+ {+ "expression": "created_by_actor_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_by_actor_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_oauth_states_subject_agent_idx": {+ "name": "tool_oauth_states_subject_agent_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subject_agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_oauth_states_expires_at_idx": {+ "name": "tool_oauth_states_expires_at_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_policies": {+ "name": "tool_policies",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "policy_type": {+ "name": "policy_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "priority": {+ "name": "priority",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "selectors": {+ "name": "selectors",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "conditions": {+ "name": "conditions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_policies_company_enabled_idx": {+ "name": "tool_policies_company_enabled_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "enabled",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_policies_company_type_idx": {+ "name": "tool_policies_company_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "policy_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_policies_company_name_uq": {+ "name": "tool_policies_company_name_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_profile_bindings": {+ "name": "tool_profile_bindings",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "profile_id": {+ "name": "profile_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "priority": {+ "name": "priority",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 100+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_profile_bindings_company_target_idx": {+ "name": "tool_profile_bindings_company_target_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profile_bindings_target_profile_uq": {+ "name": "tool_profile_bindings_target_profile_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_profile_entries": {+ "name": "tool_profile_entries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "profile_id": {+ "name": "profile_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "selector_type": {+ "name": "selector_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "effect": {+ "name": "effect",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'include'"+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "catalog_entry_id": {+ "name": "catalog_entry_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "tool_name": {+ "name": "tool_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "risk_level": {+ "name": "risk_level",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "conditions": {+ "name": "conditions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_profile_entries_company_profile_idx": {+ "name": "tool_profile_entries_company_profile_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profile_entries_application_idx": {+ "name": "tool_profile_entries_application_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "application_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profile_entries_connection_idx": {+ "name": "tool_profile_entries_connection_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profile_entries_catalog_entry_idx": {+ "name": "tool_profile_entries_catalog_entry_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "catalog_entry_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_profiles": {+ "name": "tool_profiles",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "profile_key": {+ "name": "profile_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "default_action": {+ "name": "default_action",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'deny'"+ },+ "new_tools_reviewed_at": {+ "name": "new_tools_reviewed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_profiles_company_status_idx": {+ "name": "tool_profiles_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profiles_company_key_uq": {+ "name": "tool_profiles_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "profile_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_profiles_company_name_uq": {+ "name": "tool_profiles_company_name_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_rate_limit_counters": {+ "name": "tool_rate_limit_counters",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "policy_id": {+ "name": "policy_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "counter_key": {+ "name": "counter_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_type": {+ "name": "scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "window_kind": {+ "name": "window_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "window_start_at": {+ "name": "window_start_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "limit": {+ "name": "limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "reset_at": {+ "name": "reset_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_rate_limit_counters_company_idx": {+ "name": "tool_rate_limit_counters_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_rate_limit_counters_window_uq": {+ "name": "tool_rate_limit_counters_window_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "policy_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "counter_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "window_start_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_runtime_metric_counters": {+ "name": "tool_runtime_metric_counters",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "metric": {+ "name": "metric",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "bucket_start_at": {+ "name": "bucket_start_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "count": {+ "name": "count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_runtime_metric_counters_company_metric_idx": {+ "name": "tool_runtime_metric_counters_company_metric_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "metric",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bucket_start_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_runtime_metric_counters_bucket_uq": {+ "name": "tool_runtime_metric_counters_bucket_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "metric",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "bucket_start_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_runtime_slots": {+ "name": "tool_runtime_slots",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "application_id": {+ "name": "application_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_workspace_id": {+ "name": "project_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "owner_scope_type": {+ "name": "owner_scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'connection'"+ },+ "owner_scope_id": {+ "name": "owner_scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_kind": {+ "name": "runtime_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_stdio'"+ },+ "slot_key": {+ "name": "slot_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'stopped'"+ },+ "reuse_key": {+ "name": "reuse_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_scope": {+ "name": "workspace_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_scope_hash": {+ "name": "credential_scope_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_ref": {+ "name": "provider_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "process_id": {+ "name": "process_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "command_template_key": {+ "name": "command_template_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "health_status": {+ "name": "health_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unchecked'"+ },+ "health_message": {+ "name": "health_message",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_health_check_at": {+ "name": "last_health_check_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_started_at": {+ "name": "last_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "stopped_at": {+ "name": "stopped_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "idle_expires_at": {+ "name": "idle_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "idle_deadline_at": {+ "name": "idle_deadline_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_runtime_slots_company_idx": {+ "name": "tool_runtime_slots_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_runtime_slots_connection_idx": {+ "name": "tool_runtime_slots_connection_idx",+ "columns": [+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_runtime_slots_execution_workspace_idx": {+ "name": "tool_runtime_slots_execution_workspace_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_runtime_slots_slot_key_uq": {+ "name": "tool_runtime_slots_slot_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "slot_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.tool_stdio_command_templates": {+ "name": "tool_stdio_command_templates",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "template_key": {+ "name": "template_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "command": {+ "name": "command",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "args": {+ "name": "args",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "env_keys": {+ "name": "env_keys",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "tools": {+ "name": "tools",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "disabled_at": {+ "name": "disabled_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "tool_stdio_command_templates_company_idx": {+ "name": "tool_stdio_command_templates_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_stdio_command_templates_company_status_idx": {+ "name": "tool_stdio_command_templates_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "tool_stdio_command_templates_company_key_uq": {+ "name": "tool_stdio_command_templates_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "template_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_inbox_agent_policies": {+ "name": "user_inbox_agent_policies",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "mode": {+ "name": "mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'open'"+ },+ "allowed_agent_ids": {+ "name": "allowed_agent_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_inbox_agent_policies_company_user_uq": {+ "name": "user_inbox_agent_policies_company_user_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_inbox_agent_policies_allowed_agent_ids_idx": {+ "name": "user_inbox_agent_policies_allowed_agent_ids_idx",+ "columns": [+ {+ "expression": "allowed_agent_ids",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "gin",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "user_inbox_agent_policies_mode_check": {+ "name": "user_inbox_agent_policies_mode_check",+ "value": "\"user_inbox_agent_policies\".\"mode\" in ('open', 'allowlist', 'disabled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.user_secret_declarations": {+ "name": "user_secret_declarations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_secret_definition_id": {+ "name": "user_secret_definition_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "target_type": {+ "name": "target_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "target_id": {+ "name": "target_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config_path": {+ "name": "config_path",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "env_key": {+ "name": "env_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "version_selector": {+ "name": "version_selector",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'latest'"+ },+ "required": {+ "name": "required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "allow_missing_override": {+ "name": "allow_missing_override",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_secret_declarations_company_idx": {+ "name": "user_secret_declarations_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_declarations_definition_idx": {+ "name": "user_secret_declarations_definition_idx",+ "columns": [+ {+ "expression": "user_secret_definition_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_declarations_target_idx": {+ "name": "user_secret_declarations_target_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_declarations_company_required_idx": {+ "name": "user_secret_declarations_company_required_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "required",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_declarations_target_path_uq": {+ "name": "user_secret_declarations_target_path_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "target_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "config_path",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_declarations_required_override_idx": {+ "name": "user_secret_declarations_required_override_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "allow_missing_override",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"user_secret_declarations\".\"allow_missing_override\" = true",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_secret_definitions": {+ "name": "user_secret_definitions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'local_encrypted'"+ },+ "managed_mode": {+ "name": "managed_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'paperclip_managed'"+ },+ "provider_config_id": {+ "name": "provider_config_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider_metadata": {+ "name": "provider_metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "usage_guidance": {+ "name": "usage_guidance",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_agent_id": {+ "name": "created_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_agent_id": {+ "name": "updated_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_secret_definitions_company_status_idx": {+ "name": "user_secret_definitions_company_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_definitions_company_provider_idx": {+ "name": "user_secret_definitions_company_provider_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_definitions_provider_config_idx": {+ "name": "user_secret_definitions_provider_config_idx",+ "columns": [+ {+ "expression": "provider_config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_secret_definitions_company_key_uq": {+ "name": "user_secret_definitions_company_key_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_secret_definitions\".\"deleted_at\" is null",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_sidebar_preferences": {+ "name": "user_sidebar_preferences",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "company_order": {+ "name": "company_order",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_sidebar_preferences_user_uq": {+ "name": "user_sidebar_preferences_user_uq",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.work_assessments": {+ "name": "work_assessments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "run_id": {+ "name": "run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "turn_id": {+ "name": "turn_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "contract_id": {+ "name": "contract_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "result_id": {+ "name": "result_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "trigger_kind": {+ "name": "trigger_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "trigger_ref": {+ "name": "trigger_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_capability": {+ "name": "trigger_capability",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_actor_company_id": {+ "name": "trigger_actor_company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "prior_issue_status": {+ "name": "prior_issue_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prior_status_version": {+ "name": "prior_status_version",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "prior_decision_id": {+ "name": "prior_decision_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "policy_version": {+ "name": "policy_version",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "assessment_json": {+ "name": "assessment_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "input_digest": {+ "name": "input_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "supersedes_assessment_id": {+ "name": "supersedes_assessment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "work_assessments_company_issue_input_uq": {+ "name": "work_assessments_company_issue_input_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "input_digest",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "native_issue_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "company_id",+ "issue_id",+ "run_id",+ "id"+ ],+ "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"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "work_assessments_trigger_actor_company_check": {+ "name": "work_assessments_trigger_actor_company_check",+ "value": "\"work_assessments\".\"trigger_actor_company_id\" = \"work_assessments\".\"company_id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.workspace_operations": {+ "name": "workspace_operations",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "heartbeat_run_id": {+ "name": "heartbeat_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "command": {+ "name": "command",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cwd": {+ "name": "cwd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'running'"+ },+ "exit_code": {+ "name": "exit_code",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "log_store": {+ "name": "log_store",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_ref": {+ "name": "log_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_bytes": {+ "name": "log_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": false+ },+ "log_sha256": {+ "name": "log_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "log_compressed": {+ "name": "log_compressed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "stdout_excerpt": {+ "name": "stdout_excerpt",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "stderr_excerpt": {+ "name": "stderr_excerpt",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_operations_company_run_started_idx": {+ "name": "workspace_operations_company_run_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "heartbeat_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_operations_company_workspace_started_idx": {+ "name": "workspace_operations_company_workspace_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_operations_company_workspace_issue_started_idx": {+ "name": "workspace_operations_company_workspace_issue_started_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "started_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_runtime_services": {+ "name": "workspace_runtime_services",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_workspace_id": {+ "name": "project_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "execution_workspace_id": {+ "name": "execution_workspace_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "scope_type": {+ "name": "scope_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scope_id": {+ "name": "scope_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "service_name": {+ "name": "service_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "lifecycle": {+ "name": "lifecycle",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reuse_key": {+ "name": "reuse_key",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "command": {+ "name": "command",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cwd": {+ "name": "cwd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "port": {+ "name": "port",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_ref": {+ "name": "provider_ref",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "owner_agent_id": {+ "name": "owner_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "started_by_run_id": {+ "name": "started_by_run_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "stopped_at": {+ "name": "stopped_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "stop_policy": {+ "name": "stop_policy",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "exposure": {+ "name": "exposure",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "exposure_handle": {+ "name": "exposure_handle",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "backend_url": {+ "name": "backend_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "health_status": {+ "name": "health_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unknown'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_runtime_services_company_workspace_status_idx": {+ "name": "workspace_runtime_services_company_workspace_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_runtime_services_company_execution_workspace_status_idx": {+ "name": "workspace_runtime_services_company_execution_workspace_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "execution_workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_runtime_services_company_project_status_idx": {+ "name": "workspace_runtime_services_company_project_status_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_runtime_services_run_idx": {+ "name": "workspace_runtime_services_run_idx",+ "columns": [+ {+ "expression": "started_by_run_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_runtime_services_company_updated_idx": {+ "name": "workspace_runtime_services_company_updated_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_attachment_uploads": {+ "name": "mcp_attachment_uploads",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "request_id": {+ "name": "request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "arguments_hash": {+ "name": "arguments_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "original_filename": {+ "name": "original_filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "byte_size": {+ "name": "byte_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sha256": {+ "name": "sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "object_key": {+ "name": "object_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "storage_provider": {+ "name": "storage_provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "cleaned_at": {+ "name": "cleaned_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_attachment_upload_request_uq": {+ "name": "mcp_attachment_upload_request_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "request_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_attachment_upload_expiry_idx": {+ "name": "mcp_attachment_upload_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_event_admissions": {+ "name": "mcp_event_admissions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "reserves_subscription": {+ "name": "reserves_subscription",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_event_admissions_expiry_idx": {+ "name": "mcp_event_admissions_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_event_admissions_grant_idx": {+ "name": "mcp_event_admissions_grant_idx",+ "columns": [+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_event_admissions_company_idx": {+ "name": "mcp_event_admissions_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_event_deliveries": {+ "name": "mcp_event_deliveries",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "subscription_id": {+ "name": "subscription_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "activity_id": {+ "name": "activity_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event": {+ "name": "event",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "outcome": {+ "name": "outcome",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "mcp_event_deliveries_activity_uq": {+ "name": "mcp_event_deliveries_activity_uq",+ "columns": [+ {+ "expression": "subscription_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "activity_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_event_deliveries_due_idx": {+ "name": "mcp_event_deliveries_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_event_subscriptions": {+ "name": "mcp_event_subscriptions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "arguments": {+ "name": "arguments",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_material": {+ "name": "delivery_material",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "verified_at": {+ "name": "verified_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "starts_at": {+ "name": "starts_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "stopped_at": {+ "name": "stopped_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "scanned_at": {+ "name": "scanned_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_event_subscriptions_expiry_idx": {+ "name": "mcp_event_subscriptions_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_event_subscriptions_company_idx": {+ "name": "mcp_event_subscriptions_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_file_tickets": {+ "name": "mcp_file_tickets",+ "schema": "",+ "columns": {+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "upload_id": {+ "name": "upload_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_file_ticket_expiry_idx": {+ "name": "mcp_file_ticket_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_file_ticket_grant_idx": {+ "name": "mcp_file_ticket_grant_idx",+ "columns": [+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_mutation_receipts": {+ "name": "mcp_mutation_receipts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "operation": {+ "name": "operation",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "request_id": {+ "name": "request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "arguments_hash": {+ "name": "arguments_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'reserved'"+ },+ "result": {+ "name": "result",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_mutation_receipts_request_uq": {+ "name": "mcp_mutation_receipts_request_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "operation",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "request_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_mutation_receipts_company_idx": {+ "name": "mcp_mutation_receipts_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_clients": {+ "name": "mcp_oauth_clients",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "registration_source_hash": {+ "name": "registration_source_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_uris": {+ "name": "redirect_uris",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "grant_types": {+ "name": "grant_types",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[\"authorization_code\",\"refresh_token\"]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_device_requests": {+ "name": "mcp_oauth_device_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "device_code_hash": {+ "name": "device_code_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_code_hash": {+ "name": "user_code_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource": {+ "name": "resource",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "requested_company_id": {+ "name": "requested_company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "source_hash": {+ "name": "source_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "interval_seconds": {+ "name": "interval_seconds",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 5+ },+ "next_poll_at": {+ "name": "next_poll_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_device_code_uq": {+ "name": "mcp_oauth_device_code_uq",+ "columns": [+ {+ "expression": "device_code_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_user_code_uq": {+ "name": "mcp_oauth_user_code_uq",+ "columns": [+ {+ "expression": "user_code_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_device_expiry_idx": {+ "name": "mcp_oauth_device_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_grants": {+ "name": "mcp_oauth_grants",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource": {+ "name": "resource",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "revoked_at": {+ "name": "revoked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_grants_user_company_idx": {+ "name": "mcp_oauth_grants_user_company_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_metadata_admissions": {+ "name": "mcp_oauth_metadata_admissions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "source_hash": {+ "name": "source_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "mcp_oauth_metadata_admissions_expiry_idx": {+ "name": "mcp_oauth_metadata_admissions_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_requests": {+ "name": "mcp_oauth_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redirect_uri": {+ "name": "redirect_uri",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource": {+ "name": "resource",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "challenge": {+ "name": "challenge",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requested_company_id": {+ "name": "requested_company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "code_hash": {+ "name": "code_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "consumed_at": {+ "name": "consumed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_requests_code_uq": {+ "name": "mcp_oauth_requests_code_uq",+ "columns": [+ {+ "expression": "code_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_requests_expiry_idx": {+ "name": "mcp_oauth_requests_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.mcp_oauth_tokens": {+ "name": "mcp_oauth_tokens",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "token_hash": {+ "name": "token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "used_at": {+ "name": "used_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "mcp_oauth_tokens_hash_uq": {+ "name": "mcp_oauth_tokens_hash_uq",+ "columns": [+ {+ "expression": "token_hash",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_tokens_grant_idx": {+ "name": "mcp_oauth_tokens_grant_idx",+ "columns": [+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "mcp_oauth_tokens_expiry_idx": {+ "name": "mcp_oauth_tokens_expiry_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "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"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {+ "public.chat_telegram_draft_ids": {+ "name": "chat_telegram_draft_ids",+ "schema": "public",+ "increment": "1",+ "startWith": "1",+ "minValue": "1",+ "maxValue": "2147483647",+ "cache": "1",+ "cycle": false+ }+ },+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex 07d73d0a9c..deecdaa16d 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -2171,6 +2171,13 @@"when": 1791321362665,"tag": "0311_mcp_file_transfers","breakpoints": true+ },+ {+ "idx": 312,+ "version": "7",+ "when": 1791336871975,+ "tag": "0312_easy_eternity",+ "breakpoints": true}]-}+}\ No newline at end of filediff --git a/packages/db/src/schema/accounting.ts b/packages/db/src/schema/accounting.tsnew file mode 100644index 0000000000..94869a8481--- /dev/null+++ b/packages/db/src/schema/accounting.ts@@ -0,0 +1,121 @@+import { sql } from "drizzle-orm";+import { boolean, check, index, integer, jsonb, numeric, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";+import { companies } from "./companies.js";+import { agents } from "./agents.js";+import { heartbeatRuns } from "./heartbeat_runs.js";++export const providerBillingSnapshots = pgTable("provider_billing_snapshots", {+ id: uuid("id").primaryKey().defaultRandom(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ provider: text("provider").notNull(),+ accountId: text("account_id").notNull(),+ scopeId: text("scope_id").notNull(),+ day: text("day").notNull(),+ amountCents: numeric("amount_cents", { precision: 24, scale: 7 }).notNull(),+ revision: integer("revision").notNull().default(1),+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({+ identity: uniqueIndex("provider_billing_snapshots_identity_idx").on(table.companyId, table.provider, table.accountId, table.scopeId, table.day),+ amount: check("provider_billing_snapshots_amount_check", sql`${table.amountCents} >= 0`),+}));+import { costEvents } from "./cost_events.js";++export const runUsageReceipts = pgTable("run_usage_receipts", {+ id: uuid("id").primaryKey(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ runId: uuid("run_id").notNull().references(() => heartbeatRuns.id, { onDelete: "cascade" }),+ sourceId: uuid("source_id").notNull(),+ sequence: integer("sequence").notNull(),+ receiptHash: text("receipt_hash").notNull(),+ receiptJson: jsonb("receipt_json").$type<Record<string, unknown>>().notNull(),+ complete: boolean("complete").notNull(),+ receivedAt: timestamp("received_at", { withTimezone: true }).notNull(),+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({+ sourceSequence: uniqueIndex("run_usage_receipts_source_sequence_idx").on(table.companyId, table.runId, table.sourceId, table.sequence),+ runLatest: index("run_usage_receipts_run_latest_idx").on(table.companyId, table.runId, table.receivedAt),+ positiveSequence: check("run_usage_receipts_positive_sequence", sql`${table.sequence} > 0`),+}));++export const accountingRuntimeBaselines = pgTable("accounting_runtime_baselines", {+ agentId: uuid("agent_id").primaryKey().references(() => agents.id, { onDelete: "cascade" }),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ // Historical totals are preserved explicitly. Only v2 acknowledgements add+ // to this baseline, including receipts whose occurrence date is backdated.+ costCents: numeric("cost_cents", { precision: 24, scale: 7 }).notNull(),+ inputTokens: numeric("input_tokens", { precision: 30, scale: 0 }).notNull(),+ cachedInputTokens: numeric("cached_input_tokens", { precision: 30, scale: 0 }).notNull(),+ outputTokens: numeric("output_tokens", { precision: 30, scale: 0 }).notNull(),+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({ company: index("accounting_runtime_baselines_company_idx").on(table.companyId) }));++export const budgetReservations = pgTable("budget_reservations", {+ id: uuid("id").primaryKey().defaultRandom(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ runId: uuid("run_id").notNull().references(() => heartbeatRuns.id, { onDelete: "cascade" }),+ agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }),+ projectId: uuid("project_id"),+ amountCents: numeric("amount_cents", { precision: 24, scale: 7 }).notNull(),+ state: text("state").notNull().default("held"),+ providerStartedAt: timestamp("provider_started_at", { withTimezone: true }),+ settledAt: timestamp("settled_at", { withTimezone: true }),+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({+ run: uniqueIndex("budget_reservations_run_idx").on(table.companyId, table.runId),+ active: index("budget_reservations_active_idx").on(table.companyId, table.agentId, table.projectId).where(sql`${table.state} = 'held'`),+ stateCheck: check("budget_reservations_state_check", sql`${table.state} in ('held', 'settled', 'released')`),+ amountCheck: check("budget_reservations_amount_check", sql`${table.amountCents} >= 0`),+}));++export const billingInvoices = pgTable("billing_invoices", {+ id: uuid("id").primaryKey().defaultRandom(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ biller: text("biller").notNull(),+ externalId: text("external_id").notNull(),+ currency: text("currency").notNull(),+ receiptHash: text("receipt_hash").notNull(),+ importedBy: text("imported_by").notNull(),+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({ identity: uniqueIndex("billing_invoices_identity_idx").on(table.companyId, table.biller, table.externalId) }));++export const billingInvoiceLines = pgTable("billing_invoice_lines", {+ id: uuid("id").primaryKey().defaultRandom(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ invoiceId: uuid("invoice_id").notNull().references(() => billingInvoices.id, { onDelete: "cascade" }),+ externalId: text("external_id").notNull(),+ kind: text("kind").notNull(),+ amountCents: numeric("amount_cents", { precision: 24, scale: 7 }).notNull(),+ occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),+ costEventId: uuid("cost_event_id").references(() => costEvents.id, { onDelete: "cascade" }),+ runId: uuid("run_id"),+ providerRequestId: text("provider_request_id"),+ model: text("model"),+ pricing: jsonb("pricing").$type<Record<string, unknown>>().notNull().default({}),+}, table => ({+ identity: uniqueIndex("billing_invoice_lines_identity_idx").on(table.invoiceId, table.externalId),+ company: index("billing_invoice_lines_company_idx").on(table.companyId, table.invoiceId),+ amount: check("billing_invoice_lines_amount_check", sql`${table.amountCents} >= 0`),+ kindCheck: check("billing_invoice_lines_kind_check", sql`${table.kind} in ('inference', 'fee', 'credit')`),+}));++export const costAdjustments = pgTable("cost_adjustments", {+ id: uuid("id").primaryKey().defaultRandom(),+ companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),+ costEventId: uuid("cost_event_id").notNull().references(() => costEvents.id, { onDelete: "cascade" }),+ invoiceLineId: uuid("invoice_line_id").references(() => billingInvoiceLines.id, { onDelete: "cascade" }),+ idempotencyKey: text("idempotency_key").notNull(),+ receiptHash: text("receipt_hash").notNull(),+ previousCents: numeric("previous_cents", { precision: 24, scale: 7 }).notNull(),+ correctedCents: numeric("corrected_cents", { precision: 24, scale: 7 }).notNull(),+ previousStatus: text("previous_status").notNull(),+ previousPricing: jsonb("previous_pricing").$type<Record<string, unknown>>().notNull().default({}),+ reason: text("reason").notNull(),+ actorId: text("actor_id").notNull(),+ pricing: jsonb("pricing").$type<Record<string, unknown>>().notNull().default({}),+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),+}, table => ({+ identity: uniqueIndex("cost_adjustments_receipt_idx").on(table.companyId, table.idempotencyKey),+ event: index("cost_adjustments_event_idx").on(table.companyId, table.costEventId, table.createdAt),+ invoiceLine: uniqueIndex("cost_adjustments_invoice_line_idx").on(table.companyId, table.invoiceLineId),+ amount: check("cost_adjustments_amount_check", sql`${table.previousCents} >= 0 and ${table.correctedCents} >= 0`),+}));diff --git a/packages/db/src/schema/agent_runtime_state.ts b/packages/db/src/schema/agent_runtime_state.tsindex b0095bb29b..9da64882e6 100644--- a/packages/db/src/schema/agent_runtime_state.ts+++ b/packages/db/src/schema/agent_runtime_state.ts@@ -1,4 +1,4 @@-import { pgTable, uuid, text, timestamp, jsonb, bigint, index } from "drizzle-orm/pg-core";+import { numeric, pgTable, uuid, text, timestamp, jsonb, bigint, index } from "drizzle-orm/pg-core";import { agents } from "./agents.js";import { companies } from "./companies.js";@@ -15,7 +15,7 @@ export const agentRuntimeState = pgTable(totalInputTokens: bigint("total_input_tokens", { mode: "number" }).notNull().default(0),totalOutputTokens: bigint("total_output_tokens", { mode: "number" }).notNull().default(0),totalCachedInputTokens: bigint("total_cached_input_tokens", { mode: "number" }).notNull().default(0),- totalCostCents: bigint("total_cost_cents", { mode: "number" }).notNull().default(0),+ totalCostCents: numeric("total_cost_cents", { precision: 24, scale: 7, mode: "number" }).notNull().default(0),lastError: text("last_error"),createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),diff --git a/packages/db/src/schema/agents.ts b/packages/db/src/schema/agents.tsindex 248c8c8d0b..88d0f50dc9 100644--- a/packages/db/src/schema/agents.ts+++ b/packages/db/src/schema/agents.ts@@ -2,6 +2,7 @@ import type { AgentAppearance } from "@paperclipai/shared";import {type AnyPgColumn,pgTable,+ numeric,uuid,text,integer,@@ -31,7 +32,8 @@ export const agents = pgTable(runtimeConfig: jsonb("runtime_config").$type<Record<string, unknown>>().notNull().default({}),defaultEnvironmentId: uuid("default_environment_id").references(() => environments.id, { onDelete: "set null" }),budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0),- spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0),+ spendMonthUtc: text("spend_month_utc"),+ spentMonthlyCents: numeric("spent_monthly_cents", { precision: 24, scale: 7, mode: "number" }).notNull().default(0),pauseReason: text("pause_reason"),pausedAt: timestamp("paused_at", { withTimezone: true }),errorReason: text("error_reason"),diff --git a/packages/db/src/schema/budget_incidents.ts b/packages/db/src/schema/budget_incidents.tsindex 57b9b3b012..e06de58334 100644--- a/packages/db/src/schema/budget_incidents.ts+++ b/packages/db/src/schema/budget_incidents.ts@@ -1,5 +1,5 @@import { sql } from "drizzle-orm";-import { index, integer, pgTable, text, timestamp, uuid, uniqueIndex } from "drizzle-orm/pg-core";+import { numeric, index, integer, pgTable, text, timestamp, uuid, uniqueIndex } from "drizzle-orm/pg-core";import { approvals } from "./approvals.js";import { budgetPolicies } from "./budget_policies.js";import { companies } from "./companies.js";@@ -18,7 +18,7 @@ export const budgetIncidents = pgTable(windowEnd: timestamp("window_end", { withTimezone: true }).notNull(),thresholdType: text("threshold_type").notNull(),amountLimit: integer("amount_limit").notNull(),- amountObserved: integer("amount_observed").notNull(),+ amountObserved: numeric("amount_observed", { precision: 24, scale: 7, mode: "number" }).notNull(),status: text("status").notNull().default("open"),approvalId: uuid("approval_id").references(() => approvals.id),resolvedAt: timestamp("resolved_at", { withTimezone: true }),@@ -37,6 +37,6 @@ export const budgetIncidents = pgTable(table.policyId,table.windowStart,table.thresholdType,- ).where(sql`${table.status} <> 'dismissed'`),+ ).where(sql`${table.status} = 'open'`),}),);diff --git a/packages/db/src/schema/budget_policies.ts b/packages/db/src/schema/budget_policies.tsindex 3713889b7d..07da0521cb 100644--- a/packages/db/src/schema/budget_policies.ts+++ b/packages/db/src/schema/budget_policies.ts@@ -1,4 +1,5 @@-import { boolean, index, integer, pgTable, text, timestamp, uuid, uniqueIndex } from "drizzle-orm/pg-core";+import { sql } from "drizzle-orm";+import { check, boolean, index, integer, pgTable, text, timestamp, uuid, uniqueIndex, numeric } from "drizzle-orm/pg-core";import { companies } from "./companies.js";export const budgetPolicies = pgTable(@@ -11,16 +12,21 @@ export const budgetPolicies = pgTable(metric: text("metric").notNull().default("billed_cents"),windowKind: text("window_kind").notNull(),amount: integer("amount").notNull().default(0),+ reservationCents: numeric("reservation_cents", { precision: 24, scale: 7 }).notNull().default("0"),warnPercent: integer("warn_percent").notNull().default(80),hardStopEnabled: boolean("hard_stop_enabled").notNull().default(true),+ unpricedUsagePolicy: text("unpriced_usage_policy").notNull().default("block"),notifyEnabled: boolean("notify_enabled").notNull().default(true),isActive: boolean("is_active").notNull().default(true),+ enforcementVersion: integer("enforcement_version").notNull().default(0),+ enforcementDeliveredVersion: integer("enforcement_delivered_version").notNull().default(0),createdByUserId: text("created_by_user_id"),updatedByUserId: text("updated_by_user_id"),createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ reservationNonnegative: check("budget_policies_reservation_nonnegative", sql`${table.reservationCents} >= 0`),companyScopeActiveIdx: index("budget_policies_company_scope_active_idx").on(table.companyId,table.scopeType,diff --git a/packages/db/src/schema/companies.ts b/packages/db/src/schema/companies.tsindex c911fd9aa1..e31abb5449 100644--- a/packages/db/src/schema/companies.ts+++ b/packages/db/src/schema/companies.ts@@ -1,5 +1,5 @@import type { InteractionResolverGovernance } from "@paperclipai/shared";-import { pgTable, uuid, text, integer, timestamp, boolean, jsonb, uniqueIndex } from "drizzle-orm/pg-core";+import { numeric, pgTable, uuid, text, integer, timestamp, boolean, jsonb, uniqueIndex } from "drizzle-orm/pg-core";export const companies = pgTable("companies",@@ -13,7 +13,8 @@ export const companies = pgTable(issuePrefix: text("issue_prefix").notNull().default("PAP"),issueCounter: integer("issue_counter").notNull().default(0),budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0),- spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0),+ spendMonthUtc: text("spend_month_utc"),+ spentMonthlyCents: numeric("spent_monthly_cents", { precision: 24, scale: 7, mode: "number" }).notNull().default(0),defaultResponsibleUserId: text("default_responsible_user_id"),requireBoardApprovalForNewAgents: boolean("require_board_approval_for_new_agents").notNull()diff --git a/packages/db/src/schema/cost_events.ts b/packages/db/src/schema/cost_events.tsindex 9ca547651f..1abe90c7b8 100644--- a/packages/db/src/schema/cost_events.ts+++ b/packages/db/src/schema/cost_events.ts@@ -1,4 +1,5 @@-import { pgTable, uuid, text, timestamp, integer, index } from "drizzle-orm/pg-core";+import { sql } from "drizzle-orm";+import { pgTable, uuid, text, timestamp, integer, index, numeric, uniqueIndex, check, jsonb } from "drizzle-orm/pg-core";import { companies } from "./companies.js";import { agents } from "./agents.js";import { issues } from "./issues.js";@@ -17,6 +18,11 @@ export const costEvents = pgTable(goalId: uuid("goal_id").references(() => goals.id),heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id),billingCode: text("billing_code"),+ idempotencyKey: text("idempotency_key"),+ receiptHash: text("receipt_hash"),+ providerRequestId: text("provider_request_id"),+ reportedCostCents: numeric("reported_cost_cents", { precision: 24, scale: 7 }),+ pricingProvenance: jsonb("pricing_provenance").$type<Record<string, unknown>>(),provider: text("provider").notNull(),biller: text("biller").notNull().default("unknown"),billingType: text("billing_type").notNull().default("unknown"),@@ -25,11 +31,16 @@ export const costEvents = pgTable(inputTokens: integer("input_tokens").notNull().default(0),cachedInputTokens: integer("cached_input_tokens").notNull().default(0),outputTokens: integer("output_tokens").notNull().default(0),- costCents: integer("cost_cents").notNull(),+ costCents: numeric("cost_cents", { precision: 24, scale: 7, mode: "number" }).notNull(),occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(),createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ receiptUniqueIdx: uniqueIndex("cost_events_company_receipt_idx").on(table.companyId, table.idempotencyKey),+ providerRequestIdx: index("cost_events_provider_request_idx").on(table.companyId, table.biller, table.providerRequestId),+ nonnegativeAmounts: check("cost_events_nonnegative_amounts", sql`${table.costCents} >= 0 and ${table.inputTokens} >= 0 and ${table.cachedInputTokens} >= 0 and ${table.outputTokens} >= 0`),+ companyProjectOccurredIdx: index("cost_events_company_project_occurred_idx").on(table.companyId, table.projectId, table.occurredAt),+ unpricedIdx: index("cost_events_unpriced_idx").on(table.companyId, table.occurredAt, table.id).where(sql`${table.costStatus} = 'unpriced' and ${table.billingType} <> 'subscription_included'`),companyOccurredIdx: index("cost_events_company_occurred_idx").on(table.companyId, table.occurredAt),companyAgentOccurredIdx: index("cost_events_company_agent_occurred_idx").on(table.companyId,diff --git a/packages/db/src/schema/finance_events.ts b/packages/db/src/schema/finance_events.tsindex 976efa3ff4..bb7247497c 100644--- a/packages/db/src/schema/finance_events.ts+++ b/packages/db/src/schema/finance_events.ts@@ -1,4 +1,4 @@-import { pgTable, uuid, text, timestamp, integer, index, boolean, jsonb } from "drizzle-orm/pg-core";+import { pgTable, uuid, text, timestamp, integer, numeric, index, uniqueIndex, boolean, jsonb } from "drizzle-orm/pg-core";import { companies } from "./companies.js";import { agents } from "./agents.js";import { issues } from "./issues.js";@@ -18,6 +18,8 @@ export const financeEvents = pgTable(goalId: uuid("goal_id").references(() => goals.id),heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id),costEventId: uuid("cost_event_id").references(() => costEvents.id),+ idempotencyKey: text("idempotency_key"),+ receiptHash: text("receipt_hash"),billingCode: text("billing_code"),description: text("description"),eventKind: text("event_kind").notNull(),@@ -30,7 +32,7 @@ export const financeEvents = pgTable(model: text("model"),quantity: integer("quantity"),unit: text("unit"),- amountCents: integer("amount_cents").notNull(),+ amountCents: numeric("amount_cents", { precision: 24, scale: 7, mode: "number" }).notNull(),currency: text("currency").notNull().default("USD"),estimated: boolean("estimated").notNull().default(false),externalInvoiceId: text("external_invoice_id"),@@ -39,6 +41,7 @@ export const financeEvents = pgTable(createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ receiptUniqueIdx: uniqueIndex("finance_events_company_receipt_idx").on(table.companyId, table.idempotencyKey),companyOccurredIdx: index("finance_events_company_occurred_idx").on(table.companyId, table.occurredAt),companyBillerOccurredIdx: index("finance_events_company_biller_occurred_idx").on(table.companyId,diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.tsindex 93e988b3e5..ccb30944b9 100644--- a/packages/db/src/schema/heartbeat_runs.ts+++ b/packages/db/src/schema/heartbeat_runs.ts@@ -39,6 +39,12 @@ export const heartbeatRuns = pgTable(wakeupRequestId: uuid("wakeup_request_id").references(() => agentWakeupRequests.id),exitCode: integer("exit_code"),signal: text("signal"),+ costAccountingPending: boolean("cost_accounting_pending").notNull().default(false),+ costAccountedAt: timestamp("cost_accounted_at", { withTimezone: true }),+ accountingProjectionVersion: text("accounting_projection_version"),+ accountingLastAttemptAt: timestamp("accounting_last_attempt_at", { withTimezone: true }),+ accountingLastError: text("accounting_last_error"),+ accountingAttemptCount: integer("accounting_attempt_count").notNull().default(0),usageJson: jsonb("usage_json").$type<Record<string, unknown>>(),resultJson: jsonb("result_json").$type<Record<string, unknown>>(),runtimeMode: text("runtime_mode").notNull().default("legacy"),@@ -98,6 +104,7 @@ export const heartbeatRuns = pgTable(updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),},(table) => ({+ costAccountingPendingIdx: index("heartbeat_runs_cost_accounting_pending_idx").on(table.updatedAt, table.id).where(sql`${table.costAccountingPending} = true`),executionStatusDeliveryIdx: index("heartbeat_runs_execution_status_delivery_idx").on(table.executionStatusDeliveryId).where(sql`${table.executionStatusDeliveryId} is not null`),executionControlDeadlineIdx: index("heartbeat_runs_execution_control_deadline_idx")diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.tsindex c2ffc238b9..9c9ed62c40 100644--- a/packages/db/src/schema/index.ts+++ b/packages/db/src/schema/index.ts@@ -223,6 +223,7 @@ export * from "./company_skill_sources.js";export * from "./public_mcp.js";+export * from "./accounting.js";export * from "./ai_connection_routing.js";export { toolConnectionAppSnapshots } from "./tool_connection_app_snapshots.js";export { toolConnectionAppSyncs } from "./tool_connection_app_syncs.js";diff --git a/packages/db/src/schema/status_cards.ts b/packages/db/src/schema/status_cards.tsindex 90f250b7ca..06efaa0368 100644--- a/packages/db/src/schema/status_cards.ts+++ b/packages/db/src/schema/status_cards.ts@@ -1,5 +1,5 @@import { sql } from "drizzle-orm";-import { boolean, index, integer, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";+import { boolean, index, integer, numeric, jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";import type { CompanySearchQuery, StatusCardRefreshPolicy } from "@paperclipai/shared";import { agents } from "./agents.js";import { companies } from "./companies.js";@@ -81,7 +81,7 @@ export const statusCardUpdates = pgTable(changes: jsonb("changes").$type<StatusCardUpdateChange[]>().notNull().default(sql`'[]'::jsonb`),inputTokens: integer("input_tokens").notNull().default(0),outputTokens: integer("output_tokens").notNull().default(0),- costCents: integer("cost_cents").notNull().default(0),+ costCents: numeric("cost_cents", { precision: 24, scale: 7, mode: "number" }).notNull().default(0),model: text("model"),queryVersion: integer("query_version"),changeSummary: text("change_summary"),diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/managed_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/managed_provider_backend.rsindex c5b5fc2f46..e5cecabdc9 100644--- a/packages/paperclip-runner/runner/crates/runner-core/src/managed_provider_backend.rs+++ b/packages/paperclip-runner/runner/crates/runner-core/src/managed_provider_backend.rs@@ -385,6 +385,14 @@ struct ManagedDurableState {model_request_count: u64,#[serde(default)]provider_usage: Option<Value>,+ // Persisted independently of turn/retry state so warm run attachment can+ // subtract prior runs without resetting this run during crash recovery.+ #[serde(default)]+ accounting_baseline: Option<Value>,+ #[serde(default)]+ accounting_latest: Option<Value>,+ #[serde(default)]+ accounting_latest_complete: bool,#[serde(default)]claude_managed_skills: Option<Vec<ClaudeManagedSkillRef>>,#[serde(default)]@@ -510,6 +518,9 @@ impl ManagedDurableState {durable_event_cursor: None,model_request_count: 0,provider_usage: None,+ accounting_baseline: Some(zero_managed_usage()),+ accounting_latest: Some(zero_managed_usage()),+ accounting_latest_complete: true,claude_managed_skills: None,claude_managed_skill_cleanup: None,active_turn_id: None,@@ -1047,6 +1058,13 @@ impl ManagedProviderCommandExecutor {// Checkpoint validation must use the attachment's run identity.// The durable runner separately activates the external authority// after this command succeeds, then rotates the full config.+ if state.run_id != run_id {+ state.accounting_baseline = if state.accounting_latest_complete {+ state.accounting_latest.clone()+ } else {+ None+ };+ }state.run_id = run_id.clone();self.config.run_id = run_id;}@@ -1575,7 +1593,26 @@ impl ManagedProviderCommandExecutor {}}if method == "thread/tokenUsage/updated" {- state.push(managed_usage_event(&state.descriptor, ¶ms))?;+ let current =+ complete_managed_usage(&state.descriptor, ¶ms).filter(|current| {+ state.accounting_latest.as_ref().is_none_or(|previous| {+ managed_usage_delta(previous, current).is_some()+ })+ });+ let delta = current.as_ref().and_then(|current| {+ state+ .accounting_baseline+ .as_ref()+ .and_then(|baseline| managed_usage_delta(baseline, current))+ });+ let mut usage_event = managed_usage_event(&state.descriptor, ¶ms);+ usage_event.payload["runDeltaAvailable"] = json!(delta.is_some());+ usage_event.payload["runDelta"] = delta.unwrap_or(Value::Null);+ state.accounting_latest_complete = current.is_some();+ if current.is_some() {+ state.accounting_latest = current;+ }+ state.push(usage_event)?;state.model_request_count =usage_request_count(¶ms).unwrap_or(state.model_request_count);return Ok(());@@ -2003,6 +2040,111 @@ fn usage_request_count(params: &Value) -> Option<u64> {.and_then(Value::as_u64)}+fn zero_managed_usage() -> Value {+ json!({"inputTokens": 0, "outputTokens": 0, "cacheReadTokens": 0,+ "cacheWriteTokens": 0, "activeSeconds": 0.0, "requests": 0, "providerCostUsd": 0.0})+}++fn complete_managed_usage(descriptor: &ManagedProviderDescriptor, params: &Value) -> Option<Value> {+ let usage = params.get("usage").unwrap_or(params);+ if descriptor.kind() == ManagedProviderKind::AwsAgentcore {+ // An interrupted invocation may return old numeric totals while its+ // metadata is pending, or a ceiling estimate with lower-bound tokens.+ // Neither is a complete receipt, even when every counter is present.+ for report in [params, usage] {+ if report+ .get(AGENTCORE_USAGE_RECONCILIATION_FIELD)+ .is_some_and(|state| {+ state.as_str() != Some(AGENTCORE_USAGE_RECONCILIATION_OBSERVED)+ })+ || report+ .get("tokenCountsLowerBound")+ .is_some_and(|value| value.as_bool() != Some(false))+ || report.get(AGENTCORE_PENDING_INVOCATION_FIELD).is_some()+ || report.get(AGENTCORE_PENDING_CEILING_FIELD).is_some()+ {+ return None;+ }+ }+ }+ let count = |camel: &str, snake: &str| usage.get(camel).or_else(|| usage.get(snake));+ for (camel, snake) in [+ ("inputTokens", "input_tokens"),+ ("outputTokens", "output_tokens"),+ ("cacheReadInputTokens", "cache_read_input_tokens"),+ ] {+ if count(camel, snake)?.as_u64()? > 9_007_199_254_740_991 {+ return None;+ }+ }+ if let Some(cache) = usage.get("cache_creation") {+ cache.as_object()?;+ for key in ["ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"] {+ if let Some(value) = cache.get(key) {+ if value.as_u64()? > 9_007_199_254_740_991 {+ return None;+ }+ }+ }+ } else if let Some(value) = count("cacheWriteInputTokens", "cache_write_input_tokens") {+ if value.as_u64()? > 9_007_199_254_740_991 {+ return None;+ }+ } else if descriptor.kind() == ManagedProviderKind::AwsAgentcore {+ return None;+ }+ if let Some(value) = count("activeSeconds", "active_seconds") {+ let value = value.as_f64()?;+ if !value.is_finite() || value < 0.0 {+ return None;+ }+ }+ let price = if descriptor.kind() == ManagedProviderKind::AwsAgentcore {+ usage.get("estimatedCostUsd")?.as_f64()?+ } else {+ let cost = usage.get("list_cost").or_else(|| usage.get("listCost"))?;+ if cost.get("currency")?.as_str()? != "USD" {+ return None;+ }+ cost.get("amount")?.as_str()?.parse::<f64>().ok()? / 100.0+ };+ if !price.is_finite() || price < 0.0 {+ return None;+ }+ let mut measurement = managed_usage_event(descriptor, params).payload["cumulative"].clone();+ measurement["providerCostUsd"] = json!(price);+ // Also reject integer overflow or values that cannot survive JSON/JS intact.+ managed_usage_delta(&zero_managed_usage(), &measurement)?;+ Some(measurement)+}++fn managed_usage_delta(baseline: &Value, current: &Value) -> Option<Value> {+ let mut delta = serde_json::Map::new();+ for key in [+ "inputTokens",+ "outputTokens",+ "cacheReadTokens",+ "cacheWriteTokens",+ "requests",+ ] {+ let prior = baseline.get(key)?.as_u64()?;+ let next = current.get(key)?.as_u64()?;+ if next > 9_007_199_254_740_991 || prior > 9_007_199_254_740_991 {+ return None;+ }+ delta.insert(key.to_owned(), json!(next.checked_sub(prior)?));+ }+ for key in ["activeSeconds", "providerCostUsd"] {+ let prior = baseline.get(key)?.as_f64()?;+ let next = current.get(key)?.as_f64()?;+ if !prior.is_finite() || !next.is_finite() || prior < 0.0 || next < prior {+ return None;+ }+ delta.insert(key.to_owned(), json!(next - prior));+ }+ Some(Value::Object(delta))+}+fn managed_usage_event(descriptor: &ManagedProviderDescriptor,params: &Value,@@ -2613,6 +2755,13 @@ mod tests {executor.state.as_mut().unwrap().active_turn_id = Some("active".to_owned());assert!(executor.attach(&payload).is_err());executor.state.as_mut().unwrap().active_turn_id = None;+ let usage = |input, cents| ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: json!({"usage": {"input_tokens": input, "output_tokens": 8,+ "cache_read_input_tokens": 13, "list_cost": {"currency": "USD", "amount": cents}}}),+ };+ executor.project_event(usage(21, "25")).unwrap();+ executor.state.as_mut().unwrap().pending_events.clear();payload["paperclipNextAuthority"] = json!({"identity": {"normalizedSessionId": config.normalized_session_id, "runId": "next-run"}});@@ -2620,6 +2769,13 @@ mod tests {let mut next_config = config.clone();next_config.run_id = "next-run".to_owned();executor.rotate_authority(&next_config);+ executor.project_event(usage(40, "50")).unwrap();+ let state = executor.state.as_mut().unwrap();+ let receipt = &state.pending_events.back().unwrap().payload["runDelta"];+ assert_eq!(receipt["inputTokens"], json!(19));+ assert_eq!(receipt["providerCostUsd"], json!(0.25));+ state.pending_events.clear();+ executor.save_state().unwrap();assert_eq!(executor.state.as_ref().unwrap().provider_session_id,session_id@@ -2648,6 +2804,14 @@ mod tests {);payload["authorizedTools"] = claude_prepare_payload()["authorizedTools"].clone();executor.attach(&payload).unwrap();+ // Same-run reconnect is not a new billing baseline, even after recovery.+ executor.project_event(usage(50, "75")).unwrap();+ executor.project_event(usage(50, "75")).unwrap();+ let state = executor.state.as_mut().unwrap();+ let receipt = &state.pending_events.back().unwrap().payload["runDelta"];+ assert_eq!(receipt["inputTokens"], json!(29));+ assert_eq!(receipt["providerCostUsd"], json!(0.5));+ state.pending_events.clear();assert_eq!(executor.provider.as_mut().unwrap().read().unwrap()["tools"],json!([])@@ -2658,6 +2822,34 @@ mod tests {.unwrap().validate(&next_config).unwrap();+ // An incomplete last report cannot become the next run's baseline.+ executor+ .project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: json!({"usage": {"input_tokens": 60}}),+ })+ .unwrap();+ executor.state.as_mut().unwrap().pending_events.clear();+ payload["paperclipNextAuthority"]["identity"]["runId"] = json!("third-run");+ executor.attach(&payload).unwrap();+ assert!(executor+ .state+ .as_ref()+ .unwrap()+ .accounting_baseline+ .is_none());+ executor.project_event(usage(70, "100")).unwrap();+ assert_eq!(+ executor+ .state+ .as_ref()+ .unwrap()+ .pending_events+ .back()+ .unwrap()+ .payload["runDelta"],+ Value::Null+ );fs::remove_dir_all(directory).unwrap();}@@ -2731,6 +2923,230 @@ mod tests {);}+ #[test]+ fn managed_usage_publishes_a_fresh_run_receipt_for_each_provider() {+ for payload in [claude_prepare_payload(), agentcore_prepare_payload()] {+ let directory =+ std::env::temp_dir().join(format!("managed-receipt-{}", Uuid::new_v4()));+ let config = test_config(&directory);+ let mut executor =+ ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.prepare(&payload).unwrap();+ executor+ .project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: json!({"usage": {+ "inputTokens": 21, "outputTokens": 8, "cacheReadInputTokens": 13,+ "cacheWriteInputTokens": 5, "estimatedCostUsd": 0.25,+ "list_cost": {"currency": "USD", "amount": "25"}+ }}),+ })+ .unwrap();+ let event = executor+ .state+ .as_ref()+ .unwrap()+ .pending_events+ .back()+ .unwrap();+ assert_eq!(event.payload["runDeltaAvailable"], json!(true));+ assert_eq!(event.payload["runDelta"]["inputTokens"], json!(21));+ assert_eq!(event.payload["runDelta"]["providerCostUsd"], json!(0.25));+ fs::remove_dir_all(directory).unwrap();+ }+ }++ #[test]+ fn agentcore_pending_or_lower_bound_usage_never_certifies_a_run() {+ for wrapped in [false, true] {+ for price in [0.0, 0.25] {+ for marker in [+ json!({"usageReconciliation": AGENTCORE_USAGE_RECONCILIATION_PENDING}),+ json!({"usageReconciliation": AGENTCORE_USAGE_RECONCILIATION_CONSERVATIVE}),+ json!({"usageReconciliation": "unknown"}),+ json!({"usageReconciliation": null}),+ json!({"tokenCountsLowerBound": true}),+ json!({"tokenCountsLowerBound": "false"}),+ json!({"pendingInvocationId": "unresolved-invocation"}),+ json!({"pendingEstimatedCeilingUsd": 1.0}),+ ] {+ let directory =+ std::env::temp_dir().join(format!("managed-pending-{}", Uuid::new_v4()));+ let config = test_config(&directory);+ let mut executor =+ ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.prepare(&agentcore_prepare_payload()).unwrap();+ let usage = json!({"inputTokens": 10, "outputTokens": 2,+ "cacheReadInputTokens": 0, "cacheWriteInputTokens": 0,+ "estimatedCostUsd": price});+ let mut params = if wrapped {+ json!({"usage": usage})+ } else {+ usage.clone()+ };+ params+ .as_object_mut()+ .unwrap()+ .extend(marker.as_object().unwrap().clone());+ executor+ .project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params,+ })+ .unwrap();+ let state = executor.state.as_ref().unwrap();+ let receipt = &state.pending_events.back().unwrap().payload;+ assert_eq!(receipt["runDeltaAvailable"], json!(false), "{marker}");+ assert_eq!(receipt["runDelta"], Value::Null, "{marker}");+ assert!(!state.accounting_latest_complete);+ executor.save_state().unwrap();+ executor =+ ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.restore().unwrap();+ executor+ .project_event(ProviderEvent::Notification {+ method: "turn/completed".to_owned(),+ params: json!({"turn": {"id": "interrupted", "status": "interrupted"}}),+ })+ .unwrap();+ assert!(!executor.state.as_ref().unwrap().accounting_latest_complete);+ let mut observed = usage;+ observed["usageReconciliation"] =+ json!(AGENTCORE_USAGE_RECONCILIATION_OBSERVED);+ observed["tokenCountsLowerBound"] = json!(false);+ executor+ .project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: observed,+ })+ .unwrap();+ assert_eq!(+ executor+ .state+ .as_ref()+ .unwrap()+ .pending_events+ .back()+ .unwrap()+ .payload["runDeltaAvailable"],+ json!(true)+ );+ fs::remove_dir_all(directory).unwrap();+ }+ }+ }+ }++ #[test]+ fn managed_accounting_rejects_partial_invalid_or_regressing_totals() {+ let descriptor =+ ManagedProviderDescriptor::parse(claude_prepare_payload()["provider"].clone()).unwrap();+ let good = json!({"usage": {"input_tokens": 21, "output_tokens": 8,+ "cache_read_input_tokens": 13, "list_cost": {"currency": "USD", "amount": "25"}}});+ for (field, value) in [+ ("input_tokens", Value::Null),+ ("output_tokens", json!(-1)),+ ("cache_read_input_tokens", json!(9007199254740992_u64)),+ ("cache_creation", json!({"ephemeral_1h_input_tokens": -1})),+ ("list_cost", json!({"currency": "EUR", "amount": "25"})),+ ("list_cost", json!({"currency": "USD", "amount": "NaN"})),+ ("list_cost", Value::Null),+ ] {+ let mut bad = good.clone();+ bad["usage"][field] = value;+ assert!(+ complete_managed_usage(&descriptor, &bad).is_none(),+ "{field}"+ );+ }+ let current = complete_managed_usage(&descriptor, &good).unwrap();+ for field in [+ "inputTokens",+ "outputTokens",+ "cacheReadTokens",+ "cacheWriteTokens",+ "requests",+ "activeSeconds",+ "providerCostUsd",+ ] {+ let mut baseline = current.clone();+ baseline[field] = current[field]+ .as_u64()+ .map(|value| json!(value + 1))+ .unwrap_or_else(|| json!(current[field].as_f64().unwrap() + 1.0));+ assert!(+ managed_usage_delta(&baseline, ¤t).is_none(),+ "{field}"+ );+ }+ }++ #[test]+ fn managed_usage_keeps_high_water_across_partial_reports_and_recovery() {+ let directory = std::env::temp_dir().join(format!("managed-high-water-{}", Uuid::new_v4()));+ let config = test_config(&directory);+ let mut executor = ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.prepare(&claude_prepare_payload()).unwrap();+ for (input, output, price, complete) in [+ (100, Some(8), "100", true),+ (50, Some(8), "50", false),+ (150, None, "150", false),+ (75, Some(8), "75", false),+ (200, Some(8), "200", true),+ ] {+ executor.project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: json!({"usage": {"input_tokens": input, "output_tokens": output,+ "cache_read_input_tokens": 0, "list_cost": {"currency": "USD", "amount": price}}}),+ }).unwrap();+ let state = executor.state.as_mut().unwrap();+ assert_eq!(+ state.pending_events.back().unwrap().payload["runDeltaAvailable"],+ json!(complete)+ );+ assert_eq!(state.accounting_latest_complete, complete);+ assert_eq!(+ state.accounting_latest.as_ref().unwrap()["inputTokens"],+ json!(if input == 200 { 200 } else { 100 })+ );+ state.pending_events.clear();+ executor.save_state().unwrap();+ executor = ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.restore().unwrap();+ }+ fs::remove_dir_all(directory).unwrap();+ }++ #[test]+ fn restored_legacy_managed_state_never_certifies_a_session_total_as_this_run() {+ let directory =+ std::env::temp_dir().join(format!("managed-legacy-receipt-{}", Uuid::new_v4()));+ let config = test_config(&directory);+ let mut executor = ManagedProviderCommandExecutor::with_runner_config(&directory, &config);+ executor.prepare(&claude_prepare_payload()).unwrap();+ let mut old = serde_json::to_value(executor.state.as_ref().unwrap()).unwrap();+ old.as_object_mut().unwrap().remove("accountingBaseline");+ old.as_object_mut().unwrap().remove("accountingLatest");+ executor.state = Some(serde_json::from_value(old).unwrap());+ executor+ .project_event(ProviderEvent::Notification {+ method: "thread/tokenUsage/updated".to_owned(),+ params: json!({"usage": {"input_tokens": 21, "output_tokens": 8,+ "cache_read_input_tokens": 13, "list_cost": {"currency": "USD", "amount": "25"}}}),+ })+ .unwrap();+ let event = executor+ .state+ .as_ref()+ .unwrap()+ .pending_events+ .back()+ .unwrap();+ assert_eq!(event.payload["runDeltaAvailable"], json!(false));+ assert_eq!(event.payload["runDelta"], Value::Null);+ fs::remove_dir_all(directory).unwrap();+ }+#[test]fn claude_usage_maps_nested_cache_creation_token_buckets() {let descriptor = ManagedProviderDescriptor::ClaudeManaged(ClaudeManagedProviderConfig {diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.tsindex 7c3c089623..5b92af0a3e 100644--- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts+++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts@@ -1789,6 +1789,10 @@ export function rehydrateRunnerdUsageNotification(tokenUsage: {total: record(rawParams.cumulative),runDelta: record(rawParams.runDelta),+ // Normalized counters may contain placeholder zeroes. Keep the runner's+ // authority beside the counters so ACPX/managed driver projections and+ // durable replay cannot certify an incomplete delta as a free receipt.+ runDeltaComplete: rawParams.runDeltaAvailable === true,},};}diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.tsindex e76409e7ab..df65c4450a 100644--- a/packages/paperclip-runner/src/native-session-runtime.ts+++ b/packages/paperclip-runner/src/native-session-runtime.ts@@ -1621,7 +1621,8 @@ function isZeroWorkAcpxUsage(payload: Record<string, unknown>): boolean {const usage = objectRecord(payload.usage);if (usage === null ||- Object.keys(usage).some((key) => key !== "total" && key !== "runDelta")+ (Object.hasOwn(usage, "runDeltaComplete") && usage.runDeltaComplete !== true) ||+ Object.keys(usage).some((key) => key !== "total" && key !== "runDelta" && key !== "runDeltaComplete")) {return false;}diff --git a/packages/shared/src/accounting.ts b/packages/shared/src/accounting.tsnew file mode 100644index 0000000000..2f9eca6318--- /dev/null+++ b/packages/shared/src/accounting.ts@@ -0,0 +1,115 @@+import { z } from "zod";+import { centsToUnits, normalizeCents } from "./money.js";++export const exactCentsSchema = z.union([z.string().max(160), z.number().finite()]).transform((value, ctx) => {+ try {+ if ((typeof value === "number" ? value < 0 : value.startsWith("-")) || centsToUnits(value) < 0n) throw new Error("Money cannot be negative");+ return normalizeCents(value);+ } catch (error) {+ ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : "Invalid money" });+ return z.NEVER;+ }+});+export const pricingProvenanceSchema = z.object({+ source: z.enum(["provider_reported", "provider_invoice", "operator", "rate_card", "unknown"]).default("unknown"),+ version: z.string().max(100).optional(),+ evidence: z.string().max(1000).optional(),+ inputCentsPerMillion: exactCentsSchema.optional(),+ cachedInputCentsPerMillion: exactCentsSchema.optional(),+ outputCentsPerMillion: exactCentsSchema.optional(),+ cacheWriteCentsPerMillion: exactCentsSchema.optional(),+ serviceTier: z.string().max(50).optional(),+ contextTier: z.enum(["short", "long"]).optional(),+});+export const importBillingInvoiceSchema = z.object({+ biller: z.string().trim().min(1).max(150),+ externalId: z.string().trim().min(1).max(200),+ currency: z.string().regex(/^[A-Za-z]{3}$/).transform(value => value.toUpperCase()),+ lines: z.array(z.object({+ externalId: z.string().trim().min(1).max(200),+ kind: z.enum(["inference", "fee", "credit"]).default("inference"),+ amountCents: exactCentsSchema,+ occurredAt: z.iso.datetime({ offset: true }),+ costEventId: z.string().uuid().optional(),+ runId: z.string().uuid().optional(),+ providerRequestId: z.string().min(1).max(250).optional(),+ model: z.string().min(1).max(250).optional(),+ pricing: pricingProvenanceSchema.optional(),+ })).min(1).max(2000),+}).superRefine((invoice, ctx) => {+ if (new Set(invoice.lines.map(line => line.externalId)).size !== invoice.lines.length)+ ctx.addIssue({ code: "custom", path: ["lines"], message: "Invoice line identifiers must be unique" });+});+export const adjustCostSchema = z.object({+ idempotencyKey: z.string().trim().min(1).max(200),+ expectedCents: exactCentsSchema,+ correctedCents: exactCentsSchema,+ invoiceLineId: z.string().uuid().optional(),+ reason: z.string().trim().min(1).max(1000),+ pricing: pricingProvenanceSchema,+});+export const repairAccountingSchema = z.object({ fingerprint: z.string().regex(/^[a-f0-9]{64}$/), reason: z.string().trim().min(1).max(1000) });+export const retryAccountingSchema = z.object({ runId: z.string().uuid() });+export const importProviderCostsSchema = z.object({+ provider: z.enum(["openai", "anthropic"]),+ secretId: z.string().uuid(),+ accountId: z.string().trim().min(1).max(150).regex(/^[a-zA-Z0-9_-]+$/),+ scopeIds: z.array(z.string().trim().min(1).max(150)).min(1).max(25),+ from: z.iso.date(),+ to: z.iso.date(),+}).superRefine((input, ctx) => {+ const duration = Date.parse(input.to) - Date.parse(input.from);+ if (duration <= 0 || duration > 31 * 86400000 || Date.parse(input.to) > Math.floor(Date.now() / 86400000) * 86400000)+ ctx.addIssue({ code: "custom", message: "Choose up to 31 completed UTC days; the end date is exclusive." });+ if (new Set(input.scopeIds).size !== input.scopeIds.length)+ ctx.addIssue({ code: "custom", message: "Project/workspace identifiers must be unique." });+});+export type ImportProviderCosts = z.input<typeof importProviderCostsSchema>;+export type ImportBillingInvoice = z.input<typeof importBillingInvoiceSchema>;+export type AdjustCost = z.input<typeof adjustCostSchema>;+export interface AccountingFinding {+ kind: "company_projection" | "agent_projection" | "runtime_projection" | "missing_receipt" | "missing_acknowledgement" | "legacy_runtime" | "receipt_mismatch";+ entityId: string;+ repairable: boolean;+ actual: Record<string, string>;+ expected: Record<string, string>;+}+export interface AccountingInspection {+ companyId: string;+ fingerprint: string;+ findings: AccountingFinding[];+ checkedAt: string;+}+export interface AccountingHealth {+ companyId: string;+ pendingRunCount: number;+ unpricedEventCount: number;+ oldestPendingAt: string | null;+ pendingCancellationCount: number;+ heldReservationCents: string;+ items: Array<{ runId: string | null; costEventId?: string; agentId: string; state: "waiting_for_receipt" | "retryable" | "unpriced"; lastError: string | null; attempts: number; since: string; lastAttemptAt: string | null }>;+}+export interface BillingInvoice {+ id: string; companyId: string; biller: string; externalId: string; currency: string; createdAt: string;+}+export interface CostAdjustment {+ id: string;+ companyId: string;+ costEventId: string;+ invoiceLineId: string | null;+ idempotencyKey: string;+ receiptHash: string;+ previousCents: string;+ correctedCents: string;+ previousStatus: string;+ previousPricing: Record<string, unknown>;+ pricing: Record<string, unknown>;+ reason: string;+ actorId: string;+ createdAt: string;+}+export interface BillingReconciliation {+ invoice: BillingInvoice;+ lines: Array<{ id: string; externalId: string; kind: string; amountCents: string; status: string;+ matchedEventId: string | null; recordedCents: string | null; differenceCents: string | null }>;+}diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.tsindex 3e83f26313..fed7872474 100644--- a/packages/shared/src/constants.ts+++ b/packages/shared/src/constants.ts@@ -833,7 +833,7 @@ export const BILLING_TYPES = [] as const;export type BillingType = (typeof BILLING_TYPES)[number];-export const COST_STATUSES = ["reported", "unpriced"] as const;+export const COST_STATUSES = ["reported", "estimated", "unpriced"] as const;export type CostStatus = (typeof COST_STATUSES)[number];export const FINANCE_EVENT_KINDS = [diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 0e40261c5a..ed816ce500 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1258,6 +1258,8 @@ export type {CostSummary,IssueCostSummary,CostByAgent,+ CostByUser,+ CostByUserReport,CostByProviderModel,CostByBiller,CostByAgentModel,@@ -2827,6 +2829,8 @@ export * from "./public-mcp.js";export * from "./mcp-setup.js";+export * from "./money.js";+export * from "./accounting.js";export * from "./ai-provider-routing.js";export { aiConnectionRouterSlug, aiConnectionRouterAppDefinition, aiConnectionRouterPluginKey } from "./ai-connection-router.js";export { isAppAggregator, aggregatorManagementUrl, aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema, type AggregatorAppSnapshot, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "./aggregator-apps.js";diff --git a/packages/shared/src/money.ts b/packages/shared/src/money.tsnew file mode 100644index 0000000000..156663aa93--- /dev/null+++ b/packages/shared/src/money.ts@@ -0,0 +1,53 @@+/** Monetary storage uses nanodollars: 10^7 units per cent, 10^9 per USD.+ * Numbers are accepted only at compatibility boundaries. All arithmetic uses+ * integers; decimal inputs are rounded once, half away from zero. */+export const MONEY_SCALE = 10_000_000n;+export const MAX_MONEY_UNITS = 10n ** 24n - 1n;+export type MoneyInput = string | number;++function decimalUnits(value: MoneyInput, places: number): bigint {+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("Money must be finite");+ if (typeof value === "number" && Math.abs(value) > Number.MAX_SAFE_INTEGER) throw new Error("Use a decimal string for large monetary values");+ const text = String(value);+ if (text.length > 160) throw new Error("Money exceeds supported precision");+ const match = /^([+-]?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(text);+ if (!match) throw new Error("Invalid decimal money amount");+ const exponent = Number(match[4] ?? 0);+ if (!Number.isInteger(exponent) || Math.abs(exponent) > 100) throw new Error("Money exponent is out of range");+ const digits = BigInt(match[2] + (match[3] ?? ""));+ const shift = places + exponent - (match[3]?.length ?? 0);+ const divisor = shift < 0 ? 10n ** BigInt(-shift) : 1n;+ const magnitude = shift >= 0 ? digits * 10n ** BigInt(shift) : (digits + divisor / 2n) / divisor;+ if (magnitude > MAX_MONEY_UNITS) throw new Error("Money exceeds numeric(24,7) storage");+ return match[1] === "-" ? -magnitude : magnitude;+}++export function centsToUnits(value: MoneyInput): bigint { return decimalUnits(value, 7); }+export function usdToUnits(value: MoneyInput): bigint { return decimalUnits(value, 9); }+export function unitsToCents(value: bigint): string {+ if (value > MAX_MONEY_UNITS || value < -MAX_MONEY_UNITS) throw new Error("Money exceeds numeric(24,7) storage");+ const magnitude = value < 0n ? -value : value;+ return `${value < 0n ? "-" : ""}${magnitude / MONEY_SCALE}.${String(magnitude % MONEY_SCALE).padStart(7, "0")}`;+}+export function normalizeCents(value: MoneyInput): string { return unitsToCents(centsToUnits(value)); }+export function usdToCents(value: MoneyInput): string { return unitsToCents(usdToUnits(value)); }+/** Exact editable USD value; unlike display formatting, this never rounds cents. */+export function centsToUsd(value: MoneyInput): string {+ const units = centsToUnits(value);+ const magnitude = units < 0n ? -units : units;+ return `${units < 0n ? "-" : ""}${magnitude / 1_000_000_000n}.${String(magnitude % 1_000_000_000n).padStart(9, "0")}`;+}+/** Approximate legacy/UI value. Never use this conversion for a money decision. */+export function centsToNumber(value: MoneyInput): number { return Number(normalizeCents(value)); }+export function addCents(...values: MoneyInput[]): string { return unitsToCents(values.reduce((sum, value) => sum + centsToUnits(value), 0n)); }+export function subtractCents(a: MoneyInput, b: MoneyInput): string { return unitsToCents(centsToUnits(a) - centsToUnits(b)); }+export function compareCents(a: MoneyInput, b: MoneyInput): number {+ const left = centsToUnits(a), right = centsToUnits(b);+ return left < right ? -1 : left > right ? 1 : 0;+}+export function formatUsdExact(cents: MoneyInput): string {+ const units = centsToUnits(cents);+ const magnitude = units < 0n ? -units : units;+ const rounded = (magnitude + MONEY_SCALE / 2n) / MONEY_SCALE;+ return `${units < 0n ? "-" : ""}$${rounded / 100n}.${String(rounded % 100n).padStart(2, "0")}`;+}diff --git a/packages/shared/src/types/budget.ts b/packages/shared/src/types/budget.tsindex 6907796ad2..7b3fe924d5 100644--- a/packages/shared/src/types/budget.ts+++ b/packages/shared/src/types/budget.ts@@ -16,8 +16,10 @@ export interface BudgetPolicy {metric: BudgetMetric;windowKind: BudgetWindowKind;amount: number;+ reservationCents?: string;warnPercent: number;hardStopEnabled: boolean;+ unpricedUsagePolicy: "block" | "allow";notifyEnabled: boolean;isActive: boolean;createdByUserId: string | null;@@ -35,11 +37,16 @@ export interface BudgetPolicySummary {metric: BudgetMetric;windowKind: BudgetWindowKind;amount: number;+ reservationCents?: string;observedAmount: number;+ observedAmountExact?: string;+ unpricedEventCount: number;+ pendingRunCount: number;remainingAmount: number;utilizationPercent: number;warnPercent: number;hardStopEnabled: boolean;+ unpricedUsagePolicy: "block" | "allow";notifyEnabled: boolean;isActive: boolean;status: "ok" | "warning" | "hard_stop";@@ -85,9 +92,11 @@ export interface BudgetPolicyUpsertInput {scopeId: string;metric?: BudgetMetric;windowKind?: BudgetWindowKind;- amount: number;+ amount?: number;+ reservationCents?: string | number;warnPercent?: number;hardStopEnabled?: boolean;+ unpricedUsagePolicy?: "block" | "allow";notifyEnabled?: boolean;isActive?: boolean;}diff --git a/packages/shared/src/types/cost.ts b/packages/shared/src/types/cost.tsindex 4e55098094..affe210c5b 100644--- a/packages/shared/src/types/cost.ts+++ b/packages/shared/src/types/cost.ts@@ -10,6 +10,7 @@ export interface CostEvent {goalId: string | null;heartbeatRunId: string | null;billingCode: string | null;+ idempotencyKey: string | null;provider: string;biller: string;billingType: BillingType;@@ -19,13 +20,20 @@ export interface CostEvent {cachedInputTokens: number;outputTokens: number;costCents: number;+ costCentsExact?: string;occurredAt: Date;createdAt: Date;}export interface CostSummary {+ eventCount: number;+ pendingRunCount: number;+ unpricedEventCount: number;+ estimatedEventCount?: number;+ pricingComplete: boolean;companyId: string;spendCents: number;+ spendCentsExact?: string;budgetCents: number;utilizationPercent: number;}@@ -35,6 +43,7 @@ export interface IssueCostSummary {issueCount: number;includeDescendants: boolean;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -45,13 +54,42 @@ export interface IssueCostSummary {runtimeMs: number;}+export interface CostByUser {+ /** The run's recorded responsible user; null means unattributed. */+ userId: string | null;+ userName: string | null;+ userImage: string | null;+ eventCount: number;+ estimatedEventCount: number;+ unpricedEventCount: number;+ costCents: number;+ costCentsExact: string;+ /** Input excludes cached input, as in other cost reports. */+ inputTokens: number;+ cachedInputTokens: number;+ outputTokens: number;+ /** Distinct recorded runs with cost events in the selected period. */+ runCount: number;+}++export interface CostByUserReport {+ /** Active human members, excluding the synthetic local-board principal. */+ activeUserCount: number;+ /** Includes zero-spend active users, even in single-user companies. */+ rows: CostByUser[];+}+export interface CostByAgent {agentId: string;agentName: string | null;agentAppearance?: AgentAppearance | null;avatarUrl?: string;agentStatus: string | null;+ /** Ledger events in this group and selected date range, not distinct runs. */+ eventCount: number;+ estimatedEventCount: number;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -68,6 +106,7 @@ export interface CostByProviderModel {billingType: BillingType;model: string;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -81,6 +120,7 @@ export interface CostByProviderModel {export interface CostByBiller {biller: string;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -103,7 +143,11 @@ export interface CostByAgentModel {biller: string;billingType: BillingType;model: string;+ /** Ledger events in this group and selected date range, not distinct runs. */+ eventCount: number;+ estimatedEventCount: number;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -118,6 +162,7 @@ export interface CostWindowSpendRow {/** rolling window duration in hours */windowHours: number;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;@@ -128,6 +173,7 @@ export interface CostByProject {projectId: string | null;projectName: string | null;costCents: number;+ costCentsExact?: string;inputTokens: number;cachedInputTokens: number;outputTokens: number;diff --git a/packages/shared/src/types/finance.ts b/packages/shared/src/types/finance.tsindex 75a52084be..5c2208c795 100644--- a/packages/shared/src/types/finance.ts+++ b/packages/shared/src/types/finance.ts@@ -22,39 +22,75 @@ export interface FinanceEvent {quantity: number | null;unit: FinanceUnit | null;amountCents: number;+ amountCentsExact?: string;currency: string;estimated: boolean;externalInvoiceId: string | null;+ idempotencyKey: string | null;metadataJson: Record<string, unknown> | null;occurredAt: Date;createdAt: Date;}+export interface FinanceCurrencySummary {+ currency: string;+ providerReportedCentsExact?: string;+ debitCents: number;+ debitCentsExact?: string;+ creditCents: number;+ creditCentsExact?: string;+ netCents: number;+ netCentsExact?: string;+ estimatedDebitCents: number;+ estimatedDebitCentsExact?: string;+ eventCount: number;+}+export interface FinanceSummary {+ /** Provider cost reports overlap invoices and run estimates; never add these totals. */+ providerReportedCents?: number;+ providerReportedCentsExact?: string;+ /** Compatibility totals below are USD only; no implicit currency conversion. */+ currency: "USD";+ currencies: FinanceCurrencySummary[];companyId: string;debitCents: number;+ debitCentsExact?: string;creditCents: number;+ creditCentsExact?: string;netCents: number;+ netCentsExact?: string;estimatedDebitCents: number;+ estimatedDebitCentsExact?: string;eventCount: number;}export interface FinanceByBiller {+ currency: string;biller: string;debitCents: number;+ debitCentsExact?: string;creditCents: number;+ creditCentsExact?: string;netCents: number;+ netCentsExact?: string;estimatedDebitCents: number;+ estimatedDebitCentsExact?: string;eventCount: number;kindCount: number;}export interface FinanceByKind {+ currency: string;eventKind: FinanceEventKind;debitCents: number;+ debitCentsExact?: string;creditCents: number;+ creditCentsExact?: string;netCents: number;+ netCentsExact?: string;estimatedDebitCents: number;+ estimatedDebitCentsExact?: string;eventCount: number;billerCount: number;}diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.tsindex 449dbc5809..783542ac91 100644--- a/packages/shared/src/types/index.ts+++ b/packages/shared/src/types/index.ts@@ -877,7 +877,7 @@ export type {RoutineExecutionIssueOrigin,RoutineListItem,} from "./routine.js";-export type { CostEvent, CostSummary, IssueCostSummary, CostByAgent, CostByProviderModel, CostByBiller, CostByAgentModel, CostWindowSpendRow, CostByProject } from "./cost.js";+export type { CostEvent, CostSummary, IssueCostSummary, CostByUser, CostByUserReport, CostByAgent, CostByProviderModel, CostByBiller, CostByAgentModel, CostWindowSpendRow, CostByProject } from "./cost.js";export type { FinanceEvent, FinanceSummary, FinanceByBiller, FinanceByKind } from "./finance.js";export type {AgentWakeupResponse,diff --git a/packages/shared/src/validators/budget.ts b/packages/shared/src/validators/budget.tsindex 55f629c8f4..76ad91791c 100644--- a/packages/shared/src/validators/budget.ts+++ b/packages/shared/src/validators/budget.ts@@ -1,3 +1,4 @@+import { exactCentsSchema } from "../accounting.js";import { z } from "zod";import {BUDGET_INCIDENT_RESOLUTION_ACTIONS,@@ -11,18 +12,20 @@ export const upsertBudgetPolicySchema = z.object({scopeId: z.string().guid(),metric: z.enum(BUDGET_METRICS).optional().default("billed_cents"),windowKind: z.enum(BUDGET_WINDOW_KINDS).optional().default("calendar_month_utc"),- amount: z.number().int().nonnegative(),- warnPercent: z.number().int().min(1).max(99).optional().default(80),- hardStopEnabled: z.boolean().optional().default(true),- notifyEnabled: z.boolean().optional().default(true),- isActive: z.boolean().optional().default(true),+ amount: z.number().int().nonnegative().max(2_147_483_647).optional(),+ reservationCents: exactCentsSchema.optional(),+ warnPercent: z.number().int().min(1).max(99).optional(),+ hardStopEnabled: z.boolean().optional(),+ unpricedUsagePolicy: z.enum(["block", "allow"]).optional(),+ notifyEnabled: z.boolean().optional(),+ isActive: z.boolean().optional(),});export type UpsertBudgetPolicy = z.infer<typeof upsertBudgetPolicySchema>;export const resolveBudgetIncidentSchema = z.object({action: z.enum(BUDGET_INCIDENT_RESOLUTION_ACTIONS),- amount: z.number().int().nonnegative().optional(),+ amount: z.number().int().nonnegative().max(2_147_483_647).optional(),decisionNote: z.string().optional().nullable(),}).superRefine((value, ctx) => {if (value.action === "raise_budget_and_resume" && typeof value.amount !== "number") {diff --git a/packages/shared/src/validators/company-skill.ts b/packages/shared/src/validators/company-skill.tsindex b75d5bd3c6..7e64c15846 100644--- a/packages/shared/src/validators/company-skill.ts+++ b/packages/shared/src/validators/company-skill.ts@@ -473,7 +473,7 @@ export const companySkillTestRunTemplateSnapshotSchema = z.object({);export const companySkillTestRunCostSummarySchema = z.object({- costCents: z.number().int().nonnegative(),+ costCents: z.number().nonnegative(),inputTokens: z.number().int().nonnegative(),cachedInputTokens: z.number().int().nonnegative(),outputTokens: z.number().int().nonnegative(),diff --git a/packages/shared/src/validators/cost.ts b/packages/shared/src/validators/cost.tsindex 1ed2263178..3002086c07 100644--- a/packages/shared/src/validators/cost.ts+++ b/packages/shared/src/validators/cost.ts@@ -1,7 +1,9 @@+import { exactCentsSchema, pricingProvenanceSchema } from "../accounting.js";import { z } from "zod";import { BILLING_TYPES, COST_STATUSES } from "../constants.js";export const createCostEventSchema = z.object({+ idempotencyKey: z.string().trim().min(1).max(200).optional().nullable(),agentId: z.string().guid(),issueId: z.string().guid().optional().nullable(),projectId: z.string().guid().optional().nullable(),@@ -13,17 +15,19 @@ export const createCostEventSchema = z.object({billingType: z.enum(BILLING_TYPES).optional().default("unknown"),costStatus: z.enum(COST_STATUSES).optional().default("reported"),model: z.string().min(1),- inputTokens: z.number().int().nonnegative().optional().default(0),- cachedInputTokens: z.number().int().nonnegative().optional().default(0),- outputTokens: z.number().int().nonnegative().optional().default(0),- costCents: z.number().int().nonnegative(),+ inputTokens: z.number().int().nonnegative().max(2_147_483_647).optional().default(0),+ cachedInputTokens: z.number().int().nonnegative().max(2_147_483_647).optional().default(0),+ outputTokens: z.number().int().nonnegative().max(2_147_483_647).optional().default(0),+ costCents: exactCentsSchema,+ providerRequestId: z.string().min(1).max(250).nullable().optional(),+ pricingProvenance: pricingProvenanceSchema.nullable().optional(),occurredAt: z.string().datetime(),}).transform((value) => ({...value,biller: value.biller ?? value.provider,}));-export type CreateCostEvent = z.infer<typeof createCostEventSchema>;+export type CreateCostEvent = z.input<typeof createCostEventSchema>;export const updateBudgetSchema = z.object({budgetMonthlyCents: z.number().int().nonnegative(),diff --git a/packages/shared/src/validators/finance.ts b/packages/shared/src/validators/finance.tsindex f09eebf284..ded2b0bdf2 100644--- a/packages/shared/src/validators/finance.ts+++ b/packages/shared/src/validators/finance.ts@@ -1,7 +1,9 @@+import { exactCentsSchema } from "../accounting.js";import { z } from "zod";import { AGENT_ADAPTER_TYPES, FINANCE_DIRECTIONS, FINANCE_EVENT_KINDS, FINANCE_UNITS } from "../constants.js";export const createFinanceEventSchema = z.object({+ idempotencyKey: z.string().trim().min(1).max(200).optional().nullable(),agentId: z.string().guid().optional().nullable(),issueId: z.string().guid().optional().nullable(),projectId: z.string().guid().optional().nullable(),@@ -20,8 +22,8 @@ export const createFinanceEventSchema = z.object({model: z.string().min(1).optional().nullable(),quantity: z.number().int().nonnegative().optional().nullable(),unit: z.enum(FINANCE_UNITS).optional().nullable(),- amountCents: z.number().int().nonnegative(),- currency: z.string().length(3).optional().default("USD"),+ amountCents: exactCentsSchema,+ currency: z.string().regex(/^[A-Za-z]{3}$/).optional().default("USD"),estimated: z.boolean().optional().default(false),externalInvoiceId: z.string().optional().nullable(),metadataJson: z.record(z.string(), z.unknown()).optional().nullable(),@@ -31,4 +33,4 @@ export const createFinanceEventSchema = z.object({currency: value.currency.toUpperCase(),}));-export type CreateFinanceEvent = z.infer<typeof createFinanceEventSchema>;+export type CreateFinanceEvent = z.input<typeof createFinanceEventSchema>;diff --git a/packages/shared/src/validators/status-card.ts b/packages/shared/src/validators/status-card.tsindex f6b6f1d3f6..0dccd38bed 100644--- a/packages/shared/src/validators/status-card.ts+++ b/packages/shared/src/validators/status-card.ts@@ -101,7 +101,7 @@ export const statusCardSchema = z.object({summaryBody: z.string().nullable().optional(),watchedIssueCount: z.number().int().nonnegative().optional(),todayTokens: z.number().int().nonnegative().optional(),- todayCostCents: z.number().int().nonnegative().optional(),+ todayCostCents: z.number().nonnegative().optional(),});export const statusCardUpdateChangeSchema = z.object({@@ -122,7 +122,7 @@ export const statusCardUpdateSchema = z.object({changes: z.array(statusCardUpdateChangeSchema),inputTokens: z.number().int().nonnegative(),outputTokens: z.number().int().nonnegative(),- costCents: z.number().int().nonnegative(),+ costCents: z.number().nonnegative(),model: z.string().nullable(),queryVersion: z.number().int().nonnegative().nullable(),changeSummary: z.string().nullable(),diff --git a/server/src/__tests__/approvals-service.test.ts b/server/src/__tests__/approvals-service.test.tsindex e944e2b416..d7c6193bbb 100644--- a/server/src/__tests__/approvals-service.test.ts+++ b/server/src/__tests__/approvals-service.test.ts@@ -1,5 +1,11 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { approvalService } from "../services/approvals.ts";+import { companies } from "@paperclipai/db";++vi.mock("../services/budgets.js", () => ({+ budgetService: () => ({ deliverPendingEnforcement: vi.fn(async () => {}) }),+ budgetServiceInTransaction: () => ({ upsertPolicy: vi.fn(async () => {}) }),+}));const mockAgentService = vi.hoisted(() => ({activatePendingApproval: vi.fn(),@@ -39,8 +45,11 @@ function createApproval(status: string): ApprovalRecord {function createDbStub(selectResults: ApprovalRecord[][], updateResults: ApprovalRecord[]) {const pendingSelectResults = [...selectResults];- const selectWhere = vi.fn(async () => pendingSelectResults.shift() ?? []);- const from = vi.fn(() => ({ where: selectWhere }));+ let inTransaction = false;+ const selectWhere = vi.fn(async () => (inTransaction ? pendingSelectResults.shift() : pendingSelectResults[0]) ?? []);+ const from = vi.fn((table) => table === companies+ ? { where: () => ({ for: async () => [{ id: "company-1" }] }) }+ : { where: selectWhere });const select = vi.fn(() => ({ from }));const returning = vi.fn(async () => updateResults);@@ -49,7 +58,10 @@ function createDbStub(selectResults: ApprovalRecord[][], updateResults: Approvalconst update = vi.fn(() => ({ set }));return {- db: { select, update, transaction: vi.fn(async (callback: (db: unknown) => Promise<unknown>) => callback({ select, update })) },+ db: { select, update, transaction: vi.fn(async (callback: (db: unknown) => Promise<unknown>) => {+ inTransaction = true;+ try { return await callback({ select, update }); } finally { inTransaction = false; }+ }) },selectWhere,returning,};diff --git a/server/src/__tests__/budgets-service.test.ts b/server/src/__tests__/budgets-service.test.tsindex 8e2d68ed22..bbc071f57b 100644--- a/server/src/__tests__/budgets-service.test.ts+++ b/server/src/__tests__/budgets-service.test.ts@@ -1,4 +1,5 @@import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {agents,@@ -22,313 +23,8 @@ vi.mock("../services/activity-log.js", () => ({logActivity: mockLogActivity,}));-type SelectResult = unknown[];--function createDbStub(selectResults: SelectResult[]) {- const pendingSelects = [...selectResults];- const selectWhere = vi.fn(() => {- const query = Promise.resolve(pendingSelects.shift() ?? []);- return Object.assign(query, { for: () => query });- });- const selectThen = vi.fn((resolve: (value: unknown[]) => unknown) => Promise.resolve(resolve(pendingSelects.shift() ?? [])));- const selectOrderBy = vi.fn(async () => pendingSelects.shift() ?? []);- const selectFrom = vi.fn(() => ({- where: selectWhere,- then: selectThen,- orderBy: selectOrderBy,- }));- const select = vi.fn(() => ({- from: selectFrom,- }));-- const insertValues = vi.fn();- const insertReturning = vi.fn(async () => pendingInserts.shift() ?? []);- const insert = vi.fn(() => ({- values: insertValues.mockImplementation(() => ({- returning: insertReturning,- })),- }));-- const updateSet = vi.fn();- const updateWhere = vi.fn(async () => pendingUpdates.shift() ?? []);- const update = vi.fn(() => ({- set: updateSet.mockImplementation(() => ({- where: updateWhere,- })),- }));-- const pendingInserts: unknown[][] = [];- const pendingUpdates: unknown[][] = [];-- return {- db: {- select,- insert,- update,- transaction: async (callback: (db: unknown) => Promise<unknown>) => callback({ select, insert, update }),- },- queueInsert: (rows: unknown[]) => {- pendingInserts.push(rows);- },- queueUpdate: (rows: unknown[] = []) => {- pendingUpdates.push(rows);- },- selectWhere,- insertValues,- updateSet,- };-}--describe("budgetService", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("creates a hard-stop incident and pauses an agent when spend exceeds a budget", async () => {- const policy = {- id: "policy-1",- companyId: "company-1",- scopeType: "agent",- scopeId: "agent-1",- metric: "billed_cents",- windowKind: "calendar_month_utc",- amount: 100,- warnPercent: 80,- hardStopEnabled: true,- notifyEnabled: false,- isActive: true,- };-- const dbStub = createDbStub([- [policy],- [{ total: 150 }],- [],- [{- companyId: "company-1",- name: "Budget Agent",- status: "running",- pauseReason: null,- }],- [{ id: "agent-1", companyId: "company-1", status: "running" }],- ]);-- dbStub.queueInsert([{- id: "approval-1",- companyId: "company-1",- status: "pending",- }]);- dbStub.queueInsert([{- id: "incident-1",- companyId: "company-1",- policyId: "policy-1",- approvalId: "approval-1",- }]);- dbStub.queueUpdate([]);- const cancelWorkForScope = vi.fn().mockResolvedValue(undefined);-- const service = budgetService(dbStub.db as any, { cancelWorkForScope });- await service.evaluateCostEvent({- companyId: "company-1",- agentId: "agent-1",- projectId: null,- } as any);-- expect(dbStub.insertValues).toHaveBeenCalledWith(- expect.objectContaining({- companyId: "company-1",- type: "budget_override_required",- status: "pending",- }),- );- expect(dbStub.insertValues).toHaveBeenCalledWith(- expect.objectContaining({- companyId: "company-1",- policyId: "policy-1",- thresholdType: "hard",- amountLimit: 100,- amountObserved: 150,- approvalId: "approval-1",- }),- );- expect(dbStub.updateSet).toHaveBeenCalledWith(- expect.objectContaining({- status: "paused",- pauseReason: "budget",- pausedAt: expect.any(Date),- }),- );- expect(mockLogActivity).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- action: "budget.hard_threshold_crossed",- entityId: "incident-1",- }),- );- expect(cancelWorkForScope).toHaveBeenCalledWith({- companyId: "company-1",- scopeType: "agent",- scopeId: "agent-1",- });- });-- it("blocks new work when an agent hard-stop remains exceeded even if the agent is not paused yet", async () => {- const agentPolicy = {- id: "policy-agent-1",- companyId: "company-1",- scopeType: "agent",- scopeId: "agent-1",- metric: "billed_cents",- windowKind: "calendar_month_utc",- amount: 100,- warnPercent: 80,- hardStopEnabled: true,- notifyEnabled: true,- isActive: true,- };-- const dbStub = createDbStub([- [{- status: "running",- pauseReason: null,- companyId: "company-1",- name: "Budget Agent",- }],- [{- status: "active",- name: "Paperclip",- }],- [],- [agentPolicy],- [{ total: 120 }],- ]);-- const service = budgetService(dbStub.db as any);- const block = await service.getInvocationBlock("company-1", "agent-1");-- expect(block).toEqual({- scopeType: "agent",- scopeId: "agent-1",- scopeName: "Budget Agent",- reason: "Agent cannot start because its budget hard-stop is still exceeded.",- });- });-- it("surfaces a budget-owned company pause distinctly from a manual pause", async () => {- const dbStub = createDbStub([- [{- status: "idle",- pauseReason: null,- companyId: "company-1",- name: "Budget Agent",- }],- [{- status: "paused",- pauseReason: "budget",- name: "Paperclip",- }],- ]);-- const service = budgetService(dbStub.db as any);- const block = await service.getInvocationBlock("company-1", "agent-1");-- expect(block).toEqual({- scopeType: "company",- scopeId: "company-1",- scopeName: "Paperclip",- reason: "Company is paused because its budget hard-stop was reached.",- });- });-- it("uses live observed spend when raising a budget incident", async () => {- const dbStub = createDbStub([- [{- id: "incident-1",- companyId: "company-1",- policyId: "policy-1",- amountObserved: 120,- approvalId: "approval-1",- }],- [{- id: "policy-1",- companyId: "company-1",- scopeType: "company",- scopeId: "company-1",- metric: "billed_cents",- windowKind: "calendar_month_utc",- }],- [{ total: 150 }],- ]);-- const service = budgetService(dbStub.db as any);-- await expect(- service.resolveIncident(- "company-1",- "incident-1",- { action: "raise_budget_and_resume", amount: 140 },- "board-user",- ),- ).rejects.toThrow("New budget must exceed current observed spend");- });-- it("syncs company monthly budget when raising and resuming a company incident", async () => {- const now = new Date();- const dbStub = createDbStub([- [{- id: "incident-1",- companyId: "company-1",- policyId: "policy-1",- scopeType: "company",- scopeId: "company-1",- metric: "billed_cents",- windowKind: "calendar_month_utc",- windowStart: now,- windowEnd: now,- thresholdType: "hard",- amountLimit: 100,- amountObserved: 120,- status: "open",- approvalId: "approval-1",- resolvedAt: null,- createdAt: now,- updatedAt: now,- }],- [{- id: "policy-1",- companyId: "company-1",- scopeType: "company",- scopeId: "company-1",- metric: "billed_cents",- windowKind: "calendar_month_utc",- amount: 100,- }],- [{ total: 120 }],- [{ id: "approval-1", status: "approved" }],- [{- companyId: "company-1",- name: "Paperclip",- status: "paused",- pauseReason: "budget",- pausedAt: now,- }],- ]);-- const service = budgetService(dbStub.db as any);- await service.resolveIncident(- "company-1",- "incident-1",- { action: "raise_budget_and_resume", amount: 175 },- "board-user",- );-- expect(dbStub.updateSet).toHaveBeenCalledWith(- expect.objectContaining({- budgetMonthlyCents: 175,- updatedAt: expect.any(Date),- }),- );- });-});+// Budget behavior is exercised against PostgreSQL below and in+// cost-accounting-reliability.test.ts, including transaction and retry paths.const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;@@ -493,7 +189,7 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {expect(agentAfterHardStop).toMatchObject({ status: "paused", pauseReason: "budget" });expect(agentAfterHardStop?.pausedAt).toBeInstanceOf(Date);expect(cancelWorkForScope).toHaveBeenCalledTimes(2);- expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "agent", scopeId: agentId });+ expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "agent", scopeId: agentId, createdBefore: expect.any(Date), enforcement: { policyId: expect.any(String), version: expect.any(Number) } });const block = await service.getInvocationBlock(companyId, agentId);expect(block).toEqual({@@ -538,6 +234,23 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {}});+ it("distinguishes a company budget pause from a manual company pause", async () => {+ const { companyId, agentId } = await createBudgetFixture();+ const service = budgetService(db);+ await db.update(companies).set({ status: "paused", pauseReason: "budget" }).where(eq(companies.id, companyId));+ expect(await service.getInvocationBlock(companyId, agentId)).toMatchObject({+ scopeType: "company",+ scopeId: companyId,+ reason: "Budget pause requires a policy or an explicit operator resume.",+ });+ await db.update(companies).set({ pauseReason: null }).where(eq(companies.id, companyId));+ expect(await service.getInvocationBlock(companyId, agentId)).toMatchObject({+ scopeType: "company",+ scopeId: companyId,+ reason: "Company is paused and cannot start new work.",+ });+ });+it("hard-stops project work until a valid budget raise resumes it and overview reconciles ledger spend", async () => {const { companyId, agentId, projectId } = await createBudgetFixture();const cancelWorkForScope = vi.fn().mockResolvedValue(undefined);@@ -578,7 +291,7 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {.from(projects);expect(projectAfterHardStop?.pauseReason).toBe("budget");expect(projectAfterHardStop?.pausedAt).toBeInstanceOf(Date);- expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "project", scopeId: projectId });+ expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "project", scopeId: projectId, createdBefore: expect.any(Date), enforcement: { policyId: expect.any(String), version: expect.any(Number) } });const overviewWhileBlocked = await service.overview(companyId);expect(overviewWhileBlocked.pausedProjectCount).toBe(1);diff --git a/server/src/__tests__/costs-service.test.ts b/server/src/__tests__/costs-service.test.tsindex a8ea5fa299..0ea925ebb0 100644--- a/server/src/__tests__/costs-service.test.ts+++ b/server/src/__tests__/costs-service.test.ts@@ -221,6 +221,21 @@ describe("cost routes", () => {});});+ it("requires an explicit all-time request and rejects conflicting ranges", () => {+ const { parseCostDateRange } = loadCostParsers();+ expect(parseCostDateRange({})).toBeUndefined();+ expect(parseCostDateRange({ period: "all" })).toEqual({ allTime: true });+ for (const input of [+ { from: "2026-09-02", to: "2026-09-01" },+ { from: ["2026-09-01"] },+ { from: "2026-02-30" },+ { from: "" },+ { from: "09/01/2026" },+ { period: "all", from: "2026-09-01" },+ { period: "unknown" },+ ]) expect(() => parseCostDateRange(input)).toThrow();+ });+it("returns 400 for an invalid 'from' date string", async () => {const { parseCostDateRange } = loadCostParsers();expect(() => parseCostDateRange({ from: "not-a-date" })).toThrow(/invalid 'from' date/i);@@ -270,7 +285,7 @@ describe("cost routes", () => {it("returns 400 for invalid finance event list limits", async () => {const { parseCostLimit } = loadCostParsers();- expect(() => parseCostLimit({ limit: "0" })).toThrow(/invalid 'limit'/i);+ for (const limit of ["0", "25garbage", "1.5", ["25"], "501"]) expect(() => parseCostLimit({ limit })).toThrow(/invalid 'limit'/i);});it("accepts valid finance event list limits", async () => {@@ -352,7 +367,8 @@ describe("cost routes", () => {});it("allows authorized board users to update an agent budget and budget policy", async () => {- mockAgentService.update.mockResolvedValueOnce({+ mockAgentService.getById.mockResolvedValueOnce({ id: "agent-1", companyId: "company-1", name: "Budget Agent", budgetMonthlyCents: 100, spentMonthlyCents: 0 });+ mockAgentService.getById.mockResolvedValueOnce({id: "agent-1",companyId: "company-1",name: "Budget Agent",@@ -373,30 +389,22 @@ describe("cost routes", () => {.send({ budgetMonthlyCents: 2500 });expect(res.status).toBe(200);- expect(mockAgentService.update).toHaveBeenCalledWith("agent-1", { budgetMonthlyCents: 2500 });+ expect(res.body.budgetMonthlyCents).toBe(2500);+ expect(mockAgentService.update).not.toHaveBeenCalled();+ expect(mockBudgetService.upsertPolicy).toHaveBeenCalledTimes(1);expect(mockBudgetService.upsertPolicy).toHaveBeenCalledWith("company-1",{scopeType: "agent",scopeId: "agent-1",amount: 2500,+ isActive: true,windowKind: "calendar_month_utc",},"board-user",);- expect(mockLogActivity).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- companyId: "company-1",- actorType: "user",- actorId: "board-user",- agentId: null,- action: "agent.budget_updated",- entityType: "agent",- entityId: "agent-1",- details: { budgetMonthlyCents: 2500 },- }),- );+ // Policy mutation owns the atomic entity update and activity log.+ expect(mockLogActivity).not.toHaveBeenCalled();});});@@ -543,7 +551,9 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {const [byAgentModelRow] = await costs.byAgentModel(companyId, range);expect(byAgentRow?.costCents).toBe(4_000_000_000);- expect(byAgentRow?.inputTokens).toBe(4_000_000_000);+ // Historical OpenAI input includes these ten cached tokens.+ expect(byAgentRow?.inputTokens).toBe(3_999_999_990);+ expect(byAgentRow!.inputTokens + byAgentRow!.cachedInputTokens).toBe(4_000_000_000);expect(byProjectRow?.costCents).toBe(4_000_000_000);expect(byAgentModelRow?.costCents).toBe(4_000_000_000);});@@ -692,7 +702,8 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {issueCount: 3,includeDescendants: true,costCents: 600,- inputTokens: 60,+ costCentsExact: "600.0000000",+ inputTokens: 54,cachedInputTokens: 6,outputTokens: 12,runCount: 0,diff --git a/server/src/__tests__/heartbeat-list.test.ts b/server/src/__tests__/heartbeat-list.test.tsindex c73d2b7b66..a36a71da1e 100644--- a/server/src/__tests__/heartbeat-list.test.ts+++ b/server/src/__tests__/heartbeat-list.test.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";-import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";+import { costEvents, agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";import {getEmbeddedPostgresTestSupport,startEmbeddedPostgresTestDatabase,@@ -26,6 +26,7 @@ describeEmbeddedPostgres("heartbeat list", () => {}, 20_000);afterEach(async () => {+ await db.delete(costEvents);await db.delete(heartbeatRuns);await db.delete(agents);await db.delete(companies);diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.tsindex bbc199d50b..6ee95a7657 100644--- a/server/src/__tests__/heartbeat-process-recovery.test.ts+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts@@ -33,7 +33,9 @@ import {agentWakeupRequests,approvals,authUsers,+ budgetIncidents,budgetPolicies,+ budgetReservations,chatActions,chatConversations,chatDeliveries,@@ -601,6 +603,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {await db.delete(issueTreeHolds);await db.delete(agentTaskSessions);await db.delete(issueApprovals);+ await db.delete(budgetIncidents);await db.delete(approvals);await db.update(issues).set({ lastStatusDecisionId: null });await db.delete(statusDecisionEffects);@@ -7462,6 +7465,34 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {}});+ it("persists a failed capture before heartbeat failure finalization settles an older receipt", async () => {+ const { companyId, agentId, runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });+ await db.insert(budgetPolicies).values({ companyId, scopeType: "company", scopeId: companyId,+ metric: "billed_cents", windowKind: "calendar_month_utc", amount: 100, reservationCents: "10.0000000", isActive: true });+ mockAdapterExecute.mockImplementationOnce(async (raw?: unknown) => {+ const input = raw as { onUsage: (receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => Promise<void> };+ await input.onUsage({ costUsd: 0, complete: true });+ const transaction = vi.spyOn(db, "transaction").mockRejectedValueOnce(new Error("Database temporarily unavailable"));+ const rename = vi.spyOn(fs, "rename").mockRejectedValueOnce(new Error("Receipt disk full"));+ try {+ // A paid capture and the first database fence write both fail. The+ // heartbeat catch must retry the fence before terminalizing.+ await input.onUsage({ costUsd: 0.25, usage: { inputTokens: 10, outputTokens: 2 }, complete: true });+ throw new Error("Expected capture to reject");+ } finally { transaction.mockRestore(); rename.mockRestore(); }+ });+ const heartbeat = heartbeatService(db);+ await heartbeat.resumeQueuedRuns();+ await heartbeat.drainActiveRunExecutions();+ expect(mockAdapterExecute).toHaveBeenCalledTimes(1);+ expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountedAt: null,+ costAccountingPending: true, accountingLastError: "usage_capture_failed",+ usageJson: { accountingReceiptReady: false, accountingCaptureFailed: true } });+ expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);+ expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("held");+ expect(Number((await db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId)))[0]?.totalCostCents ?? 0)).toBe(0);+ });+it("stops controller renewal and releases execution controls when teardown deadline cleanup throws", async () => {const { runId, issueId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });mockAdapterExecute.mockImplementationOnce(async () => {@@ -7798,6 +7829,36 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {},);+ it.each([{}, { command: "/nonexistent-paperclip-bootstrap-command" }])("releases holds for real process bootstrap failures: %j", async (config) => {+ const { execute } = await import("../adapters/process/execute.js");+ mockAdapterExecute.mockImplementationOnce(execute);+ const { runId, agentId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });+ await db.update(agents).set({ adapterType: "process", adapterConfig: config }).where(eq(agents.id, agentId));+ const heartbeat = heartbeatService(db);+ await heartbeat.resumeQueuedRuns();+ await heartbeat.drainActiveRunExecutions();+ expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountingPending: false, costAccountedAt: expect.any(Date) });+ expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("released");+ expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);+ });++ it("releases the dispatch reservation after a proven pre-provider adapter failure", async () => {+ mockAdapterExecute.mockResolvedValueOnce({+ exitCode: 1, signal: null, timedOut: false,+ errorMessage: "Provider startup failed", provider: "test", model: "test-model",+ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },+ });+ const { runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });+ const heartbeat = heartbeatService(db);+ await heartbeat.resumeQueuedRuns();+ await heartbeat.drainActiveRunExecutions();+ const run = await heartbeat.getRun(runId);+ expect(run).toMatchObject({ status: "failed", costAccountingPending: false });+ expect(run?.costAccountedAt).not.toBeNull();+ expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });+ expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);+ });+it.each(["single Stop", "agent pause"] as const)("fences adapter registration while an earlier no-owner %s waits to commit",async (operation) => {@@ -7922,6 +7983,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {releaseAdapter();await heartbeat.drainActiveRunExecutions();const settledRun = await heartbeat.getRun(runId);+ expect(settledRun?.costAccountingPending).toBe(false);+ expect(settledRun?.costAccountedAt).not.toBeNull();+ expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });+ expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);expect({status: settledRun?.status,errorCode: settledRun?.errorCode,@@ -11313,6 +11378,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {await waitForRunToSettle(heartbeat, sourceRun.id, 5_000);}expect(sourceRun?.id).not.toBe(runId);+ // Durable accounting is bookkeeping, not evidence that the agent acted+ // on its plan. A receipt must not suppress plan-only recovery.+ expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, String(sourceRunId)))).toHaveLength(1);expect(sourceRun?.livenessState).toBe("plan_only");if (withLegacyReview) {expect(await db.select().from(issues).where(eq(issues.id, legacyReviewId))).toEqual(legacyReviewBefore);diff --git a/server/src/__tests__/plugin-managed-agents.test.ts b/server/src/__tests__/plugin-managed-agents.test.tsindex 30a4725f47..95abe9db66 100644--- a/server/src/__tests__/plugin-managed-agents.test.ts+++ b/server/src/__tests__/plugin-managed-agents.test.ts@@ -11,6 +11,7 @@ import {agentInstructionHeads,agents,approvals,+ budgetPolicies,companies,createDb,pluginEntities,@@ -107,6 +108,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {await db.delete(pluginManagedResources);await db.delete(pluginCompanySettings);await db.delete(approvals);+ await db.delete(budgetPolicies);await db.delete(principalPermissionGrants);await db.delete(agents);await db.delete(plugins);@@ -499,6 +501,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {const relinked = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });expect(relinked.status).toBe("relinked");expect(relinked.agentId).toBe(agentId);+ expect(relinked.agent?.urlKey).toBe("renamed-wiki-agent");const [binding] = await db.select().from(pluginEntities);expect(binding?.data).toMatchObject({ agentId });diff --git a/server/src/__tests__/routines-routes.test.ts b/server/src/__tests__/routines-routes.test.tsindex 2faeaa9eaf..5d92575459 100644--- a/server/src/__tests__/routines-routes.test.ts+++ b/server/src/__tests__/routines-routes.test.ts@@ -166,10 +166,10 @@ function registerModuleMocks() {}async function createApp(actor: Record<string, unknown>) {- const [{ errorHandler }, { routineRoutes }] = await Promise.all([- vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),- vi.importActual<typeof import("../routes/routines.js")>("../routes/routines.js"),- ]);+ // Load the route after its mocks are installed. Concurrent importActual+ // calls through the middleware barrel can cache unmocked dependencies.+ const { errorHandler } = await import("../middleware/error-handler.js");+ const { routineRoutes } = await import("../routes/routines.js");const app = express();app.use(express.json({ verify: (req, _res, buf) => { (req as any).rawBody = buf; } }));app.use((req, _res, next) => {diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.tsindex f6f8e20dbb..4de339d035 100644--- a/server/src/__tests__/server-startup-feedback-export.test.ts+++ b/server/src/__tests__/server-startup-feedback-export.test.ts@@ -57,6 +57,7 @@ const {reason: null,}));const heartbeatServiceMock = {+ reconcileCostAccounting: vi.fn(async () => ({ scanned: 0, accounted: 0 })),resolveSchedulingSuppression: resolveHeartbeatSchedulingSuppressionMock,recoverNativeRunsAfterRestart: vi.fn(async () => ({restartKind: "hard",@@ -559,11 +560,13 @@ describe("startServer feedback export wiring", () => {}) as typeof setInterval);try {await startServer();+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);expect(heartbeatServiceMock.sweepStaleIssueLocks).toHaveBeenCalledTimes(1);expect(intervalCallback).not.toBeNull();intervalCallback?.();await new Promise<void>((resolve) => setImmediate(resolve));expect(heartbeatServiceMock.sweepStaleIssueLocks).toHaveBeenCalledTimes(2);+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);expect(retiredDetector).not.toHaveBeenCalled();} finally {delete (runtime as Partial<typeof runtime>).reconcileProductivityReviews;@@ -660,6 +663,7 @@ describe("startServer feedback export wiring", () => {// reaped at startup and on the interval.expect(heartbeatServiceFactoryMock).toHaveBeenCalledTimes(1);expect(heartbeatServiceMock.sweepPendingCleanupLeases).toHaveBeenCalled();+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);expect(intervalCallback).not.toBeNull();intervalCallback?.();await Promise.resolve();@@ -667,12 +671,33 @@ describe("startServer feedback export wiring", () => {expect(externalObjectsServiceMock.refreshDueObjectsForActiveCompanies).toHaveBeenCalledTimes(1);expect(routineServiceMock.tickScheduledTriggers).not.toHaveBeenCalled();+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);expect(environmentCustomImagesServiceMock.cleanupExpiredSetupSessions).not.toHaveBeenCalled();} finally {setIntervalSpy.mockRestore();}});+ it.each([false, true])("retries failed accounting recovery with heartbeat scheduling enabled: %s", async (enabled) => {+ loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: enabled }));+ heartbeatServiceMock.reconcileCostAccounting.mockRejectedValueOnce(new Error("temporary ledger outage"));+ let tick: (() => void) | undefined;+ const timer = vi.spyOn(globalThis, "setInterval").mockImplementation(((callback: () => void) => {+ tick = callback;+ return 1 as unknown as ReturnType<typeof setInterval>;+ }) as typeof setInterval);+ try {+ expect((await startServer()).server).toBe(fakeServer);+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);+ expect(tick).toBeDefined();+ tick?.();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);+ } finally {+ timer.mockRestore();+ }+ });+it("does not replay hot-restart adoption when the orphan reaper retries", async () => {loadConfigMock.mockReturnValue(buildTestConfig({heartbeatSchedulerEnabled: true,diff --git a/server/src/index.ts b/server/src/index.tsindex 91a19f0cbd..6412a8b35b 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -879,6 +879,7 @@ async function startServerWithDatabaseTeardown(const heartbeat = config.heartbeatSchedulerEnabled? heartbeatService(db as any, { pluginWorkerManager }): null;+ const accountingHeartbeat = heartbeat ?? heartbeatService(db as any, { pluginWorkerManager });const decisionServiceOptions = {wakeOriginAgent: createDecisionWakeOriginAgent(heartbeat?.wakeup ?? null),};@@ -1230,8 +1231,7 @@ async function startServerWithDatabaseTeardown(// so a just-failed lease does not draw a retry on every tick. The startup// sweep passes zero, so a restart retries a stranded orphan at once.const ENVIRONMENT_LEASE_CLEANUP_SWEEP_BACKOFF_MS = 5 * 60 * 1000;- const environmentLeaseCleanupHeartbeat =- heartbeat ?? heartbeatService(db as any, { pluginWorkerManager });+ const environmentLeaseCleanupHeartbeat = accountingHeartbeat;const chatCompletionDeliveries = chatCompletionDeliveryService(db as any, environmentLeaseCleanupHeartbeat);// Activity publication happens after the status transaction commits. This is// a best-effort fast path; the durable outbox and sweeps remain authoritative.@@ -1449,6 +1449,7 @@ async function startServerWithDatabaseTeardown(},"worktree run-execution cutoff state",);+ await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));const heartbeatSchedulingSuppression = await heartbeat.resolveSchedulingSuppression();// Reap orphaned runs before timer ticks start so wakeups cannot coalesce@@ -1464,8 +1465,7 @@ async function startServerWithDatabaseTeardown(// workers before cleanup or retry admission, including unmanaged installs.await app.locals.bundledPluginsStartup;try {- const nativeRecovery =- await heartbeat.recoverNativeRunsAfterRestart();+ const nativeRecovery = await heartbeat.recoverNativeRunsAfterRestart();if (nativeRecovery.dispositions.length > 0) {logger.info({@@ -1763,6 +1763,9 @@ async function startServerWithDatabaseTeardown(}));trackHeartbeatSchedulerWork(chatCompletionDeliveries.sweepPending().catch((err) => logger.error({ err }, "chat completion delivery failed")));++ trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));+trackHeartbeatSchedulerWork(connectionDeliveries.sweepPending().catch((err) => logger.error({ err }, "connection continuation delivery failed")));trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "tool review recovery failed")));trackHeartbeatSchedulerWork(app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "gateway token cleanup failed")));@@ -1839,8 +1842,10 @@ async function startServerWithDatabaseTeardown(// is still required. A failed acquire can leak a paid provider sandbox, so// this path retries the teardown at startup and on the interval, exactly as// the enabled path does.+ await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));await runEnvironmentLeaseCleanupSweep(0);startHeartbeatSchedulerInterval(() => {+ trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));scheduleExternalObjectRefreshSweep(new Date());scheduleEnvironmentLeaseCleanupSweep();scheduleGitHubConnectionEventPoll();diff --git a/server/src/modules/run-dispatch/adapters/postgres.ts b/server/src/modules/run-dispatch/adapters/postgres.tsindex acd38a9819..570784d2e9 100644--- a/server/src/modules/run-dispatch/adapters/postgres.ts+++ b/server/src/modules/run-dispatch/adapters/postgres.ts@@ -15,9 +15,11 @@ import {issues,} from "@paperclipai/db";import { ISSUE_DISPOSITION_REPAIR_RETRY_REASON } from "@paperclipai/shared";+import { withAccountingTransaction } from "../../../services/accounting-transaction.js";+import type { ActivityPublication } from "../../../services/activity-log.js";import { parseObject } from "../../../adapters/utils.js";import { evaluateAgentInvokabilityFromDb } from "../../../services/agent-invokability.js";-import { budgetService } from "../../../services/budgets.js";+import { budgetService, budgetServiceInTransaction } from "../../../services/budgets.js";import { isCompletedOnboardingHandoffWake } from "../../../services/chat-completion-delivery.js";import { isHeartbeatWakeOnDemandEnabled } from "../../../services/heartbeat-policy.js";import { collectDispositionRepairSourceState } from "../../../services/recovery/disposition-repair.js";@@ -190,7 +192,7 @@ export function createPostgresRunDispatchAdapter(async function withIssueThenRunLocks<T>(input: { runId: string; companyId: string },onMissing: () => T,- operation: (tx: Db, run: HeartbeatRun) => Promise<T>,+ operation: (tx: Db, run: HeartbeatRun, publications: ActivityPublication[]) => Promise<T>,): Promise<T> {// Queue editing and claiming already use issue -> wake -> run. Read the// immutable issue reference without a lock first, then acquire issue ->@@ -206,8 +208,9 @@ export function createPostgresRunDispatchAdapter(const hintedIssueId = readNonEmptyString(parseObject(hint.contextSnapshot).issueId);const result: { kind: "missing" | "retry" } | { kind: "value"; value: T } =- await db.transaction(async (tx) => {- const typedTx = tx as unknown as Db;+ await withAccountingTransaction(db, input.companyId, async (typedTx, publications) => {+ // Budget gates mutate policy state. Acquire company before issue/run,+ // matching receipt writers (including their attribution FK locks).if (hintedIssueId) {await typedTx.select({ id: issues.id })@@ -231,7 +234,7 @@ export function createPostgresRunDispatchAdapter(const lockedIssueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId);if (lockedIssueId !== hintedIssueId) return { kind: "retry" as const };- return { kind: "value" as const, value: await operation(typedTx, run) };+ return { kind: "value" as const, value: await operation(typedTx, run, publications) };});if (result.kind === "missing") return onMissing();@@ -247,12 +250,13 @@ export function createPostgresRunDispatchAdapter(input: LoadGateFactsInput,now: Date,tx?: unknown,+ publications?: ActivityPublication[],): Promise<LoadGateFactsResult> {// Semantic adapter operations pass their transaction here so the fact// read and the state transition share one unit of work. This helper is// deliberately not exposed through the module's public API.const dbOrTx = (tx as Db | undefined) ?? db;- const budgetsForRead = tx ? budgetService(dbOrTx) : budgets;+ const budgetsForRead = tx ? budgetServiceInTransaction(dbOrTx, publications) : budgets;const treeControlForRead = tx ? issueTreeControlService(dbOrTx) : treeControlSvc;const issuesSvcForRead = tx ? issueService(dbOrTx) : issuesSvc;@@ -747,7 +751,7 @@ export function createPostgresRunDispatchAdapter(): Promise<PromoteScheduledRetryOutcome> {const now = input.now;- const promoteLockedRun = async (tx: Db, run: HeartbeatRun) => {+ const promoteLockedRun = async (tx: Db, run: HeartbeatRun, publications: ActivityPublication[]) => {if (run.status !== "scheduled_retry" ||!run.scheduledRetryAt ||@@ -768,6 +772,7 @@ export function createPostgresRunDispatchAdapter(},now,tx,+ publications,);if (!factsResult.agentFound) {@@ -1010,7 +1015,7 @@ export function createPostgresRunDispatchAdapter(input: DispatchResolvedInteractionInput<T>,): Promise<DispatchResolvedInteractionOutcome<T>> {const dispatchLockedRun = async (tx: Db, run: HeartbeatRun) => {- if (run.status !== input.expectedStatus) {+ if (run.status !== input.expectedStatus || run.resultJson?.cancellation || run.resultJson?.startupCancellation) {return { dispatched: false as const, cancellation: { outcome: "lost_race" as const } };}const { issueId, decision: initialDecision } = await decideCurrentRunStaleness(diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.tsindex e280fe2a80..eb63b74170 100644--- a/server/src/routes/agents.ts+++ b/server/src/routes/agents.ts@@ -546,7 +546,7 @@ export function agentRoutes(const KNOWN_INSTRUCTIONS_BUNDLE_KEY_SET: ReadonlySet<string> = new Set(KNOWN_INSTRUCTIONS_BUNDLE_KEYS);const router = Router();- const svc = agentService(db);+ const svc = agentService(db, { cancelWorkForScope: scope => heartbeat.cancelBudgetScopeWork(scope) });const access = accessService(db);const approvalsSvc = approvalService(db);const budgets = budgetService(db);diff --git a/server/src/routes/companies.ts b/server/src/routes/companies.tsindex dc048a4403..8de78282c2 100644--- a/server/src/routes/companies.ts+++ b/server/src/routes/companies.ts@@ -55,6 +55,7 @@ import {accessService,agentService,budgetService,+ heartbeatService,buildExportFidelityReport,collectExportFidelityCounts,companyArtifactsService,@@ -278,7 +279,9 @@ export function companyRoutes(db: Db, storage?: StorageService, options?: Companconst router = Router();const importTransferSpoolRoot =options?.importTransferSpoolRoot ?? resolveDefaultImportTransferSpoolRoot();- const svc = companyService(db);+ const svc = companyService(db, {+ cancelWorkForScope: (scope) => heartbeatService(db).cancelBudgetScopeWork(scope),+ });const agents = agentService(db);const portability = companyPortabilityService(db, storage);const access = accessService(db);diff --git a/server/src/routes/costs.ts b/server/src/routes/costs.tsindex b66abc0fc0..fc18e07bd9 100644--- a/server/src/routes/costs.ts+++ b/server/src/routes/costs.ts@@ -1,4 +1,10 @@+import { importProviderDailyCosts } from "../services/provider-billing-import.js";+import { importProviderCostsSchema } from "@paperclipai/shared";+import { accountingIntegrityService } from "../services/accounting-integrity.js";+import { billingReconciliationService } from "../services/billing-reconciliation.js";+import { adjustCostSchema, importBillingInvoiceSchema, repairAccountingSchema, retryAccountingSchema } from "@paperclipai/shared";import { Router } from "express";+import { z } from "zod";import type { Db } from "@paperclipai/db";import {createCostEventSchema,@@ -18,28 +24,37 @@ import {issueService,heartbeatService,accessService,- logActivity,} from "../services/index.js";import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";import { fetchCompanyQuotaWindows } from "../services/quota-windows.js";-import { badRequest } from "../errors.js";+import { badRequest, forbidden } from "../errors.js";import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";+const reportDateSchema = z.union([z.iso.datetime({ offset: true }), z.iso.date()]);+export function parseCostDateRange(query: Record<string, unknown>) {+ if (query.period !== undefined && query.period !== "all" && query.period !== "month") throw badRequest("invalid 'period'");+ if (query.period === "all") {+ if (query.from !== undefined || query.to !== undefined) throw badRequest("all-time period cannot have date bounds");+ return { allTime: true };+ }+ if (query.from !== undefined && !reportDateSchema.safeParse(query.from).success) throw badRequest("invalid 'from' date");+ if (query.to !== undefined && !reportDateSchema.safeParse(query.to).success) throw badRequest("invalid 'to' date");const fromRaw = query.from as string | undefined;const toRaw = query.to as string | undefined;const from = fromRaw ? new Date(fromRaw) : undefined;const to = toRaw ? new Date(toRaw) : undefined;if (from && isNaN(from.getTime())) throw badRequest("invalid 'from' date");if (to && isNaN(to.getTime())) throw badRequest("invalid 'to' date");+ if (from && to && from > to) throw badRequest("from must not be after to");return (from || to) ? { from, to } : undefined;}export function parseCostLimit(query: Record<string, unknown>) {- const raw = Array.isArray(query.limit) ? query.limit[0] : query.limit;+ const raw = query.limit;if (raw == null || raw === "") return 100;- const limit = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10);- if (!Number.isFinite(limit) || limit <= 0 || limit > 500) {+ const limit = typeof raw === "number" || typeof raw === "string" ? Number(raw) : Number.NaN;+ if (!Number.isInteger(limit) || limit <= 0 || limit > 500) {throw badRequest("invalid 'limit' value");}return limit;@@ -120,22 +135,11 @@ export function costRoutes(return;}+ const actor = getActorInfo(req);const event = await costs.createEvent(companyId, {...req.body,occurredAt: new Date(req.body.occurredAt),- });-- const actor = getActorInfo(req);- await logActivity(db, {- companyId,- actorType: actor.actorType,- actorId: actor.actorId,- agentId: actor.agentId,- action: "cost.reported",- entityType: "cost_event",- entityId: event.id,- details: { costCents: event.costCents, model: event.model },- });+ }, { actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId });res.status(201).json(event);});@@ -145,27 +149,11 @@ export function costRoutes(assertCompanyAccess(req, companyId);assertBoard(req);+ const actor = getActorInfo(req);const event = await finance.createEvent(companyId, {...req.body,occurredAt: new Date(req.body.occurredAt),- });-- const actor = getActorInfo(req);- await logActivity(db, {- companyId,- actorType: actor.actorType,- actorId: actor.actorId,- agentId: actor.agentId,- action: "finance_event.reported",- entityType: "finance_event",- entityId: event.id,- details: {- amountCents: event.amountCents,- biller: event.biller,- eventKind: event.eventKind,- direction: event.direction,- },- });+ }, { actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId });res.status(201).json(event);});@@ -189,6 +177,14 @@ export function costRoutes(res.json(summary);});+ router.get("/companies/:companyId/costs/by-user", async (req, res) => {+ const companyId = req.params.companyId as string;+ assertCompanyAccess(req, companyId);+ if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;+ const range = parseCostDateRange(req.query);+ res.json(await costs.byUser(companyId, range));+ });+router.get("/companies/:companyId/costs/by-agent", async (req, res) => {const companyId = req.params.companyId as string;assertCompanyAccess(req, companyId);@@ -331,34 +327,19 @@ export function costRoutes(assertBoard(req);const companyId = req.params.companyId as string;assertCompanyAccess(req, companyId);- const company = await companies.update(companyId, { budgetMonthlyCents: req.body.budgetMonthlyCents });- if (!company) {- res.status(404).json({ error: "Company not found" });- return;- }-- await logActivity(db, {- companyId,- actorType: "user",- actorId: req.actor.userId ?? "board",- action: "company.budget_updated",- entityType: "company",- entityId: companyId,- details: { budgetMonthlyCents: req.body.budgetMonthlyCents },- });-await budgets.upsertPolicy(companyId,{scopeType: "company",scopeId: companyId,amount: req.body.budgetMonthlyCents,+ isActive: req.body.budgetMonthlyCents > 0,windowKind: "calendar_month_utc",},req.actor.userId ?? "board",);- res.json(company);+ res.json(await companies.getById(companyId));});router.patch("/agents/:agentId/budgets", validate(updateBudgetSchema), async (req, res) => {@@ -368,37 +349,63 @@ export function costRoutes(assertBoard(req);- const updated = await agents.update(agentId, { budgetMonthlyCents: req.body.budgetMonthlyCents });- if (!updated) {- res.status(404).json({ error: "Agent not found" });- return;- }-- const actor = getActorInfo(req);- await logActivity(db, {- companyId: updated.companyId,- actorType: actor.actorType,- actorId: actor.actorId,- agentId: actor.agentId,- action: "agent.budget_updated",- entityType: "agent",- entityId: updated.id,- details: { budgetMonthlyCents: updated.budgetMonthlyCents },- });-await budgets.upsertPolicy(- updated.companyId,+ agent.companyId,{scopeType: "agent",- scopeId: updated.id,- amount: updated.budgetMonthlyCents,+ scopeId: agent.id,+ amount: req.body.budgetMonthlyCents,+ isActive: req.body.budgetMonthlyCents > 0,windowKind: "calendar_month_utc",},req.actor.type === "board" ? req.actor.userId ?? "board" : null,);- res.json(updated);+ res.json(await agents.getById(agentId));});+ const integrity = accountingIntegrityService(db, budgetHooks);+ const billing = billingReconciliationService(db, budgetHooks);+ // Operational accounting evidence and repairs are board-only. These payloads+ // can contain company-wide billing identifiers even for an agent's own run.+ router.use("/companies/:companyId/accounting", (req, _res, next) => {+ assertCompanyAccess(req, req.params.companyId as string); assertBoard(req); next();+ });+ router.post("/companies/:companyId/accounting/provider-costs/import", (req, _res, next) => {+ // Unlike ledger inspection, this operation discloses a stored credential+ // to a provider. Ordinary company membership does not authorize that use.+ const companyId = req.params.companyId as string;+ assertCompanyAccess(req, companyId);+ assertBoard(req);+ const membership = req.actor.memberships?.find((item) => item.companyId === companyId);+ if (req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin+ && !(membership?.status === "active" && ["owner", "admin"].includes(String(membership.membershipRole)))) {+ throw forbidden("Company admin access required to import provider billing.");+ }+ next();+ }, validate(importProviderCostsSchema), async (req, res) => {+ const companyId = req.params.companyId as string;+ assertCompanyAccess(req, companyId);+ assertBoard(req);+ const result = await importProviderDailyCosts(db, companyId, req.body, getActorInfo(req).actorId);+ res.json(result);+ });++ router.get("/companies/:companyId/accounting/health", async (req, res) => res.json(await integrity.health(req.params.companyId as string)));+ router.get("/companies/:companyId/accounting/inspect", async (req, res) => res.json(await integrity.inspect(req.params.companyId as string)));+ router.post("/companies/:companyId/accounting/repair", validate(repairAccountingSchema), async (req, res) =>+ res.json(await integrity.repair(req.params.companyId as string, req.body.fingerprint, req.body.reason, getActorInfo(req).actorId)));+ router.post("/companies/:companyId/accounting/retry", validate(retryAccountingSchema), async (req, res) =>+ res.json(await integrity.retry(req.params.companyId as string, req.body.runId, getActorInfo(req).actorId)));+ router.get("/companies/:companyId/accounting/invoices", async (req, res) => res.json(await billing.list(req.params.companyId as string)));+ router.post("/companies/:companyId/accounting/invoices", validate(importBillingInvoiceSchema), async (req, res) =>+ res.status(201).json(await billing.importInvoice(req.params.companyId as string, req.body, getActorInfo(req).actorId)));+ router.get("/companies/:companyId/accounting/invoices/:invoiceId", async (req, res) =>+ res.json(await billing.reconcile(req.params.companyId as string, req.params.invoiceId as string)));+ router.get("/companies/:companyId/accounting/events/:eventId/adjustments", async (req, res) =>+ res.json(await billing.adjustments(req.params.companyId as string, req.params.eventId as string)));+ router.post("/companies/:companyId/accounting/events/:eventId/adjustments", validate(adjustCostSchema), async (req, res) =>+ res.status(201).json(await billing.adjust(req.params.companyId as string, req.params.eventId as string, req.body, getActorInfo(req).actorId)));+return router;}diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.tsindex a5bd3f0ad7..90825cb1ed 100644--- a/server/src/routes/openapi.ts+++ b/server/src/routes/openapi.ts@@ -127,6 +127,11 @@ import {updateBudgetSchema,upsertBudgetPolicySchema,resolveBudgetIncidentSchema,+ repairAccountingSchema,+ retryAccountingSchema,+ importBillingInvoiceSchema,+ importProviderCostsSchema,+ adjustCostSchema,// SidebarupsertSidebarOrderPreferenceSchema,// Announcements@@ -1327,6 +1332,7 @@ const PUBLIC_OPERATIONS = new Set([]);const BOARD_ONLY_PREFIXES = [+ "/api/companies/{companyId}/accounting/","/api/announcements/","/api/auth/","/api/admin/",@@ -5324,9 +5330,16 @@ registry.registerPath({// ─── Costs ───────────────────────────────────────────────────────────────────+const costReportQuerySchema = z.object({+ period: z.enum(["month", "all"]).optional().describe("Defaults to the current UTC month. All-time cannot be combined with date bounds."),+ from: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional().describe("Inclusive start bound."),+ to: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional().describe("Inclusive end bound; must not precede from."),+});+const costSummaryPaths = ["summary","by-agent",+ "by-user","by-agent-model","by-provider","by-biller",@@ -5345,7 +5358,12 @@ for (const segment of costSummaryPaths) {path: `/api/companies/{companyId}/costs/${segment}`,tags: ["costs"],summary: `Cost report: ${segment}`,- request: { params: z.object({ companyId: z.string() }) },+ request: {+ params: z.object({ companyId: z.string() }),+ ...(!["window-spend", "quota-windows"].includes(segment) ? {+ query: segment === "finance-events" ? costReportQuerySchema.extend({ limit: z.coerce.number().int().min(1).max(500).optional() }) : costReportQuerySchema,+ } : {}),+ },responses: { 200: r.ok(), 401: r.unauthorized },});}@@ -5355,11 +5373,12 @@ registry.registerPath({path: "/api/companies/{companyId}/cost-events",tags: ["costs"],summary: "Record a cost event",+ description: "Amounts are USD cents, including fractional cents. Decimal strings preserve exact nanodollar precision. Reuse the idempotency key and original receipt on retries; conflicting reuse returns 409.",request: {params: z.object({ companyId: z.string() }),body: jsonBody(createCostEventSchema),},- responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 409: r.conflict },});registry.registerPath({@@ -5367,13 +5386,47 @@ registry.registerPath({path: "/api/companies/{companyId}/finance-events",tags: ["costs"],summary: "Record a finance event",+ description: "Amounts accept exact decimal cents in the recorded currency. Credits use a nonnegative amount with direction credit. No currency conversion is inferred. Receipt-key conflicts return 409.",request: {params: z.object({ companyId: z.string() }),body: jsonBody(createFinanceEventSchema),},- responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },+ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 409: r.conflict },});+for (const [suffix, summary] of [+ ["health", "Inspect pending receipts, unpriced charges, cancellation backlog, and held reservations"],+ ["inspect", "Independently compare ledger evidence and stored totals"],+ ["invoices", "List imported provider invoices"],+ ["invoices/{invoiceId}", "Review exact invoice matches and unresolved differences"],+ ["events/{eventId}/adjustments", "Read append-only correction history and prior pricing evidence"],+] as const) {+ registry.registerPath({+ method: "get", path: `/api/companies/{companyId}/accounting/${suffix}`, tags: ["costs"], summary,+ description: "Company-scoped board access is required. Board viewers may inspect; agents cannot access operator accounting evidence.",+ request: { params: z.object({ companyId: z.string(),+ ...(suffix.includes("invoiceId") ? { invoiceId: z.string() } : {}),+ ...(suffix.includes("eventId") ? { eventId: z.string() } : {}),+ }) },+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },+ });+}++for (const operation of [+ { suffix: "repair", schema: repairAccountingSchema, status: 200, summary: "Repair reviewed ledger projections", description: "Requires an audit reason and the current inspection fingerprint. A stale inspection returns 409. Missing evidence is never invented." },+ { suffix: "retry", schema: retryAccountingSchema, status: 200, summary: "Retry accounting for a company-owned run", description: "Retries accounting only. Provider work is never re-executed; incomplete evidence remains pending." },+ { suffix: "provider-costs/import", schema: importProviderCostsSchema, status: 200, summary: "Import a scoped provider cost report", description: "Reads up to 31 completed UTC days from OpenAI or Anthropic with a company admin credential. Requires explicit provider account and project/workspace identifiers. All pages validate before writing. Reimports append only the difference; run costs are not repriced. Report totals remain separate from invoices." },+ { suffix: "invoices", schema: importBillingInvoiceSchema, status: 201, summary: "Import normalized invoice evidence", description: "Idempotent by company, biller, and external invoice ID. Conflicting reuse returns 409. Import atomically creates finance timeline events and does not reprice run costs." },+ { suffix: "events/{eventId}/adjustments", schema: adjustCostSchema, status: 201, summary: "Apply a reviewed cost correction", description: "Requires the expected exact cents, an idempotency key, reason, and pricing evidence. Original amounts and pricing revisions remain in history. Stale reviews return 409; ambiguous or contradictory invoice evidence returns 422." },+] as const) {+ registry.registerPath({+ method: "post", path: `/api/companies/{companyId}/accounting/${operation.suffix}`, tags: ["costs"],+ summary: operation.summary, description: `${operation.description} Company-scoped board write access is required; viewers and agents cannot mutate accounting.`,+ request: { params: z.object({ companyId: z.string(), ...(operation.suffix.includes("eventId") ? { eventId: z.string() } : {}) }), body: jsonBody(operation.schema) },+ responses: { [operation.status]: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 422: r.unprocessable },+ });+}+registry.registerPath({method: "post",path: "/api/companies/{companyId}/budgets/policies",diff --git a/server/src/services/accounting-integrity.ts b/server/src/services/accounting-integrity.tsnew file mode 100644index 0000000000..ad13779619--- /dev/null+++ b/server/src/services/accounting-integrity.ts@@ -0,0 +1,121 @@+import { and, eq, sql } from "drizzle-orm";+import { agents, agentRuntimeState, companies, heartbeatRuns, type Db } from "@paperclipai/db";+import { normalizeCents, usdToCents, type AccountingFinding, type AccountingHealth, type AccountingInspection } from "@paperclipai/shared";+import { conflict, notFound } from "../errors.js";+import { receiptFingerprint } from "./receipt-fingerprint.js";+import { withAccountingReadSnapshot, withAccountingTransaction } from "./accounting-transaction.js";+import { logActivity } from "./activity-log.js";+import { accountRunCost } from "./run-cost-accounting.js";+import type { BudgetServiceHooks } from "./budgets.js";++/** Independent aggregation: deliberately does not reuse writer projections. */+async function inspect(tx: Db, companyId: string): Promise<AccountingInspection> {+ const findings: AccountingFinding[] = [];+ const monthly = await tx.execute<{ kind: "company_projection" | "agent_projection"; id: string; actual: string; expected: string }>(sql`+ with month_events as (select agent_id, cost_cents from cost_events where company_id = ${companyId}+ and occurred_at >= date_trunc('month', now() at time zone 'UTC') at time zone 'UTC'+ and occurred_at < (date_trunc('month', now() at time zone 'UTC') + interval '1 month') at time zone 'UTC')+ select 'company_projection' as kind, id, spent_monthly_cents::text as actual,+ (select coalesce(sum(cost_cents),0)::text from month_events) as expected from companies where id = ${companyId}+ union all select 'agent_projection', a.id, a.spent_monthly_cents::text,+ coalesce((select sum(e.cost_cents) from month_events e where e.agent_id = a.id),0)::text from agents a where a.company_id = ${companyId}`);+ for (const row of monthly) if (normalizeCents(row.actual) !== normalizeCents(row.expected)) findings.push({ kind: row.kind, entityId: row.id, repairable: true,+ actual: { cents: normalizeCents(row.actual) }, expected: { cents: normalizeCents(row.expected) } });+ const runtime = await tx.execute<{ id: string; baseline: string | null; actual: Record<string, string>; expected: Record<string, string> }>(sql`+ with totals as (select r.agent_id, sum(e.cost_cents) as cents, sum(e.input_tokens) as input, sum(e.cached_input_tokens) as cached, sum(e.output_tokens) as output+ from heartbeat_runs r join cost_events e on e.heartbeat_run_id = r.id and e.company_id = r.company_id+ where r.company_id = ${companyId} and r.accounting_projection_version = 'v2' and r.cost_accounted_at is not null group by r.agent_id)+ select a.agent_id as id, b.agent_id as baseline,+ jsonb_build_object('cents', a.total_cost_cents::text, 'input', a.total_input_tokens::text, 'cached', a.total_cached_input_tokens::text, 'output', a.total_output_tokens::text) as actual,+ jsonb_build_object('cents', (coalesce(b.cost_cents,0) + coalesce(t.cents,0))::text, 'input', (coalesce(b.input_tokens,0) + coalesce(t.input,0))::text,+ 'cached', (coalesce(b.cached_input_tokens,0) + coalesce(t.cached,0))::text, 'output', (coalesce(b.output_tokens,0) + coalesce(t.output,0))::text) as expected+ from agent_runtime_state a left join accounting_runtime_baselines b on b.agent_id = a.agent_id and b.company_id = a.company_id+ left join totals t on t.agent_id = a.agent_id where a.company_id = ${companyId} order by a.agent_id`);+ for (const row of runtime) {+ if (!row.baseline) { findings.push({ kind: "legacy_runtime", entityId: row.id, repairable: false, actual: row.actual, expected: {} }); continue; }+ row.actual.cents = normalizeCents(row.actual.cents); row.expected.cents = normalizeCents(row.expected.cents);+ if (Object.keys(row.expected).some(key => row.actual[key] !== row.expected[key])) findings.push({ kind: "runtime_projection", entityId: row.id, repairable: true, actual: row.actual, expected: row.expected });+ }+ const incomplete = await tx.execute<{ id: string; acknowledged: boolean; events: number }>(sql`+ select r.id, r.cost_accounted_at is not null as acknowledged, count(e.id)::int as events from heartbeat_runs r+ left join cost_events e on e.heartbeat_run_id = r.id and e.company_id = r.company_id and e.idempotency_key like ('heartbeat:' || r.id::text || ':%')+ where r.company_id = ${companyId} and r.status in ('succeeded','failed','timed_out','cancelled','interrupted')+ and (r.cost_accounting_pending or r.accounting_projection_version = 'v2')+ and r.result_json->'executionRecovery'->>'providerWorkStarted' is distinct from 'false'+ and r.usage_json->>'accountingProviderWorkStarted' is distinct from 'false'+ group by r.id having r.cost_accounted_at is null or count(e.id) = 0 order by r.id`);+ for (const row of incomplete) findings.push({ kind: row.acknowledged ? "missing_receipt" : "missing_acknowledgement", entityId: row.id, repairable: false,+ actual: { acknowledged: String(row.acknowledged), events: String(row.events) }, expected: { acknowledged: "true", events: ">=1" } });+ // Verify new run receipts independently of the projections. Corrections+ // change effective valuation, while reported_cost_cents preserves the+ // provider amount this acknowledgement originally consumed.+ const receipts = await tx.execute<{ id: string; usage: Record<string, unknown>; actual: Record<string, string> }>(sql`+ select r.id, r.usage_json as usage, jsonb_build_object('cents', sum(coalesce(e.reported_cost_cents,e.cost_cents))::text,+ 'input', sum(e.input_tokens)::text, 'cached', sum(e.cached_input_tokens)::text, 'output', sum(e.output_tokens)::text) as actual+ from heartbeat_runs r join cost_events e on e.heartbeat_run_id = r.id and e.company_id = r.company_id and e.idempotency_key like ('heartbeat:' || r.id::text || ':%')+ where r.company_id = ${companyId} and r.accounting_projection_version = 'v2' and r.cost_accounted_at is not null group by r.id order by r.id`);+ for (const row of receipts) {+ const usage = row.usage ?? {};+ const cost = usage.cacheAdjustedCostUsd ?? usage.costUsdExact ?? usage.costUsd ?? 0;+ let cents: string;+ try { cents = usage.billingType === "subscription_included" ? "0.0000000" : usdToCents(String(cost)); }+ catch { cents = "invalid receipt"; }+ const expected = { cents, input: String(usage.inputTokens ?? 0), cached: String(usage.cachedInputTokens ?? 0), output: String(usage.outputTokens ?? 0) };+ row.actual.cents = normalizeCents(row.actual.cents);+ if (Object.entries(expected).some(([key,value]) => row.actual[key] !== value)) findings.push({ kind: "receipt_mismatch", entityId: row.id, repairable: false, actual: row.actual, expected });+ }+ findings.sort((a,b) => a.kind.localeCompare(b.kind) || a.entityId.localeCompare(b.entityId));+ return { companyId, findings, fingerprint: receiptFingerprint({ companyId, findings }), checkedAt: new Date().toISOString() };+}++export function accountingIntegrityService(db: Db, hooks: BudgetServiceHooks = {}) {+ return {+ inspect: (companyId: string) => withAccountingReadSnapshot(db, companyId, tx => inspect(tx, companyId)),+ repair: (companyId: string, fingerprint: string, reason: string, actorId: string) => withAccountingTransaction(db, companyId, async (tx, publications) => {+ if (!reason.trim()) throw conflict("A repair reason is required");+ const before = await inspect(tx, companyId);+ if (before.fingerprint !== fingerprint) throw conflict("Accounting changed since inspection; inspect again before repairing");+ for (const finding of before.findings.filter(f => f.repairable)) {+ if (finding.kind === "company_projection") await tx.update(companies).set({ spentMonthlyCents: sql`${finding.expected.cents}::numeric`, updatedAt: new Date() }).where(eq(companies.id, companyId));+ if (finding.kind === "agent_projection") await tx.update(agents).set({ spentMonthlyCents: sql`${finding.expected.cents}::numeric`, updatedAt: new Date() }).where(and(eq(agents.id, finding.entityId), eq(agents.companyId, companyId)));+ if (finding.kind === "runtime_projection") await tx.update(agentRuntimeState).set({ totalCostCents: sql`${finding.expected.cents}::numeric`,+ totalInputTokens: sql`${finding.expected.input}::bigint`, totalCachedInputTokens: sql`${finding.expected.cached}::bigint`, totalOutputTokens: sql`${finding.expected.output}::bigint`, updatedAt: new Date(),+ }).where(and(eq(agentRuntimeState.agentId, finding.entityId), eq(agentRuntimeState.companyId, companyId)));+ }+ await logActivity(tx, { companyId, actorType: "user", actorId, action: "accounting.projections_repaired", entityType: "company", entityId: companyId,+ details: { fingerprint, reason, repairs: before.findings.filter(f => f.repairable) } }, publications);+ return inspect(tx, companyId);+ }),+ retry: async (companyId: string, runId: string, actorId: string) => {+ const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId)));+ if (!run) throw notFound("Accounting run not found");+ await logActivity(db, { companyId, actorType: "user", actorId, action: "accounting.retry_requested", entityType: "heartbeat_run", entityId: runId });+ try { return { accounted: await accountRunCost(db, runId, hooks) }; }+ catch (error) {+ await db.update(heartbeatRuns).set({ accountingLastAttemptAt: new Date(), accountingAttemptCount: sql`${heartbeatRuns.accountingAttemptCount} + 1`,+ accountingLastError: error instanceof Error ? error.message.slice(0,1000) : "Accounting retry failed",+ }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));+ throw error;+ }+ },+ health: (companyId: string): Promise<AccountingHealth> => withAccountingReadSnapshot(db, companyId, async tx => {+ const [counts] = await tx.execute<{ pending: number; unpriced: number; oldest: string | null; cancellations: number; reserved: string }>(sql`+ select (select count(*)::int from heartbeat_runs where company_id = ${companyId} and cost_accounting_pending and status in ('succeeded','failed','timed_out','cancelled','interrupted')) as pending,+ (select count(*)::int from cost_events where company_id = ${companyId} and cost_status = 'unpriced' and billing_type <> 'subscription_included') as unpriced,+ (select min(coalesce(finished_at,created_at))::text from heartbeat_runs where company_id = ${companyId} and cost_accounting_pending and status in ('succeeded','failed','timed_out','cancelled','interrupted')) as oldest,+ (select count(*)::int from budget_policies where company_id = ${companyId} and enforcement_version > enforcement_delivered_version) as cancellations,+ (select coalesce(sum(amount_cents),0)::text from budget_reservations where company_id = ${companyId} and state = 'held') as reserved`);+ const pending = await tx.execute<{ runId: string; agentId: string; state: "waiting_for_receipt" | "retryable"; lastError: string | null; attempts: number; since: string; lastAttemptAt: string | null }>(sql`+ select id as "runId", agent_id as "agentId", case when usage_json->>'accountingReceiptReady' = 'false'+ and usage_json->>'accountingProviderWorkStarted' is distinct from 'false'+ and result_json->'executionRecovery'->>'providerWorkStarted' is distinct from 'false' then 'waiting_for_receipt' else 'retryable' end as state,+ accounting_last_error as "lastError", accounting_attempt_count as attempts, coalesce(finished_at,created_at)::text as since, accounting_last_attempt_at::text as "lastAttemptAt"+ from heartbeat_runs where company_id = ${companyId} and cost_accounting_pending and status in ('succeeded','failed','timed_out','cancelled','interrupted') order by coalesce(finished_at,created_at),id limit 100`);+ const unpriced = await tx.execute<{ runId: string | null; costEventId: string; agentId: string; since: string }>(sql`+ select heartbeat_run_id as "runId", id as "costEventId", agent_id as "agentId", occurred_at::text as since from cost_events+ where company_id = ${companyId} and cost_status = 'unpriced' and billing_type <> 'subscription_included' order by occurred_at,id limit 100`);+ return { companyId, pendingRunCount: counts.pending, unpricedEventCount: counts.unpriced, oldestPendingAt: counts.oldest, pendingCancellationCount: counts.cancellations,+ heldReservationCents: normalizeCents(counts.reserved), items: [...pending, ...unpriced.map(row => ({ ...row, state: "unpriced" as const, lastError: null, attempts: 0, lastAttemptAt: null }))] };+ }),+ };+}diff --git a/server/src/services/accounting-transaction.ts b/server/src/services/accounting-transaction.tsnew file mode 100644index 0000000000..d7e206e78c--- /dev/null+++ b/server/src/services/accounting-transaction.ts@@ -0,0 +1,40 @@+import { eq } from "drizzle-orm";+import { companies, type Db } from "@paperclipai/db";+import { publishActivity, type ActivityPublication } from "./activity-log.js";+import { notFound } from "../errors.js";+import { logger } from "../middleware/logger.js";++/** Serialize ledger and budget mutations in one company. Always acquire this+ * before locking a run or a policy, so concurrent writers use one lock order.+ * NO KEY UPDATE permits FK KEY SHARE locks held by recovery callers. */+export async function withAccountingTransaction<T>(db: Db, companyId: string, work: (tx: Db, publications: ActivityPublication[]) => Promise<T>): Promise<T> {+ const publications: ActivityPublication[] = [];+ const result = await db.transaction(async (transaction) => {+ const tx = transaction as unknown as Db;+ const [company] = await tx.select({ id: companies.id }).from(companies)+ .where(eq(companies.id, companyId)).for("no key update");+ if (!company) throw notFound("Company not found");+ return work(tx, publications);+ });+ publishAccountingActivities(companyId, publications);+ return result;+}++/** Consistent operator reports must not wait for or delay accounting writers.+ * Reads see one committed snapshot; repairs still revalidate under the lock. */+export function withAccountingReadSnapshot<T>(db: Db, companyId: string, work: (tx: Db) => Promise<T>): Promise<T> {+ return db.transaction(async transaction => {+ const tx = transaction as unknown as Db;+ const [company] = await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, companyId));+ if (!company) throw notFound("Company not found");+ return work(tx);+ }, { isolationLevel: "repeatable read", accessMode: "read only" });+}++/** Database history is durable even when the live subscriber channel fails. */+export function publishAccountingActivities(companyId: string, publications: ActivityPublication[]) {+ for (const publication of publications) {+ try { publishActivity(publication); }+ catch (error) { logger.warn({ err: error, companyId }, "Accounting committed; live activity publication failed"); }+ }+}diff --git a/server/src/services/agents.ts b/server/src/services/agents.tsindex eb1bdacefc..38ad38a81a 100644--- a/server/src/services/agents.ts+++ b/server/src/services/agents.ts@@ -1,3 +1,6 @@+import { budgetServiceInTransaction, deliverBudgetEnforcement, type BudgetServiceHooks } from "./budgets.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import type { ActivityPublication } from "./activity-log.js";import { agentAppearanceSchema, randomAgentAppearance, resolveAgentAppearance, agentAvatarUrl } from "@paperclipai/shared";import { createHash, randomBytes } from "node:crypto";import { and, desc, eq, gte, inArray, lt, ne, or, sql } from "drizzle-orm";@@ -342,7 +345,7 @@ export function deduplicateAgentName(return `${candidateName} ${Date.now()}`;}-export function agentService(db: Db) {+export function agentService(db: Db, budgetHooks: BudgetServiceHooks = {}) {const secretsSvc = secretService(db);function currentUtcMonthWindow(now = new Date()) {@@ -791,7 +794,7 @@ export function agentService(db: Db) {const beforeConfig = shouldRecordRevision ? buildConfigSnapshot(existing) : null;type AgentUpdateResult = Awaited<ReturnType<typeof getById>>;- const applyUpdate = async (txDb: Db): Promise<AgentUpdateResult> => {+ const applyUpdate = async (txDb: Db, publications: ActivityPublication[] = []): Promise<AgentUpdateResult> => {const current = data.status !== undefined? await txDb.select().from(agents).where(eq(agents.id, id)).for("update").then(rows => rows[0] ?? null): existing;@@ -843,6 +846,11 @@ export function agentService(db: Db) {);}+ if (normalizedPatch.budgetMonthlyCents !== undefined) {+ await budgetServiceInTransaction(txDb, publications).upsertPolicy(existing.companyId, {+ scopeType: "agent", scopeId: id, amount: normalizedPatch.budgetMonthlyCents, isActive: normalizedPatch.budgetMonthlyCents > 0, windowKind: "calendar_month_utc",+ }, options?.recordRevision?.createdByUserId ?? null);+ }const normalizedUpdated = await agentService(txDb).getById(updated.id);if (!normalizedUpdated) {throw notFound("Agent not found");@@ -869,6 +877,12 @@ export function agentService(db: Db) {return normalizedUpdated;};+ if (normalizedPatch.budgetMonthlyCents !== undefined) {+ const result = await withAccountingTransaction(db, existing.companyId, applyUpdate);+ await deliverBudgetEnforcement(db, budgetHooks, existing.companyId);+ return result;+ }+const transaction = (db as unknown as {transaction?: (callback: (tx: unknown) => Promise<AgentUpdateResult>) => Promise<AgentUpdateResult>;}).transaction;@@ -1075,7 +1089,7 @@ export function agentService(db: Db) {});}- return db.transaction(async (tx) => {+ return withAccountingTransaction(db, existing.companyId, async (tx) => {await tx.select({ id: agents.id }).from(agents)diff --git a/server/src/services/approvals.ts b/server/src/services/approvals.tsindex 4fbbf0a23e..e2e16a5bc5 100644--- a/server/src/services/approvals.ts+++ b/server/src/services/approvals.ts@@ -5,7 +5,8 @@ import { approvalComments, approvals } from "@paperclipai/db";import { notFound, unprocessable } from "../errors.js";import { redactCurrentUserText } from "../log-redaction.js";import { agentService } from "./agents.js";-import { budgetService } from "./budgets.js";+import { budgetService, budgetServiceInTransaction } from "./budgets.js";+import { withAccountingTransaction } from "./accounting-transaction.js";import { notifyHireApproved } from "./hire-hook.js";import { instanceSettingsService } from "./instance-settings.js";@@ -142,10 +143,12 @@ export function approvalService(db: Db) {approve: async (id: string, decidedByUserId: string, decisionNote?: string | null) => {const now = new Date();- const result = await db.transaction(async tx => {- const txDb = tx as unknown as Db;+ const existing = await getExistingApproval(id);+ // Receipt writers lock company before agent. Hire approval must use that+ // order too, including activation of an existing pending agent.+ const result = await withAccountingTransaction(db, existing.companyId, async (txDb, publications) => {const agentsSvc = agentService(txDb);- const budgets = budgetService(txDb);+ const budgets = budgetServiceInTransaction(txDb, publications);const { approval: updated, applied } = await resolveApproval(id,"approved",@@ -210,6 +213,7 @@ export function approvalService(db: Db) {return { approval: updated, applied, hireApprovedAgentId };});if (result.hireApprovedAgentId) {+ await budgetService(db).deliverPendingEnforcement(result.approval.companyId);void notifyHireApproved(db, {companyId: result.approval.companyId,agentId: result.hireApprovedAgentId,diff --git a/server/src/services/billing-reconciliation.ts b/server/src/services/billing-reconciliation.tsnew file mode 100644index 0000000000..bf4b2678c3--- /dev/null+++ b/server/src/services/billing-reconciliation.ts@@ -0,0 +1,167 @@+import { createFinanceEventInTransaction } from "./finance.js";+import { and, desc, eq, sql } from "drizzle-orm";+import { agentRuntimeState, costEvents, costAdjustments, billingInvoices, billingInvoiceLines, financeEvents, heartbeatRuns, type Db } from "@paperclipai/db";+import { adjustCostSchema, importBillingInvoiceSchema, normalizeCents, subtractCents, type AdjustCost, type ImportBillingInvoice } from "@paperclipai/shared";+import { conflict, notFound, unprocessable } from "../errors.js";+import { withAccountingReadSnapshot, withAccountingTransaction } from "./accounting-transaction.js";+import { receiptFingerprint } from "./receipt-fingerprint.js";+import { logActivity } from "./activity-log.js";+import { updateMonthlySpendProjections } from "./costs.js";+import { budgetServiceInTransaction, deliverBudgetEnforcement, type BudgetServiceHooks } from "./budgets.js";++async function invoiceCostCandidates(tx: Db, companyId: string, biller: string, line: {+ costEventId?: string | null; runId?: string | null; providerRequestId?: string | null; model?: string | null;+}) {+ if (!(line.costEventId || line.runId || line.providerRequestId)) return [];+ return tx.select({ id: costEvents.id, cents: sql<string>`${costEvents.costCents}::text`, status: costEvents.costStatus })+ .from(costEvents).where(and(eq(costEvents.companyId, companyId), eq(costEvents.biller, biller),+ line.costEventId ? eq(costEvents.id, line.costEventId) : undefined,+ line.runId ? eq(costEvents.heartbeatRunId, line.runId) : undefined,+ line.providerRequestId ? eq(costEvents.providerRequestId, line.providerRequestId) : undefined,+ line.model ? eq(costEvents.model, line.model) : undefined)).limit(2);+}++export function billingReconciliationService(db: Db, hooks: BudgetServiceHooks = {}) {+ return {+ importInvoice: (companyId: string, raw: ImportBillingInvoice, actorId: string) => withAccountingTransaction(db, companyId, async (tx, publications) => {+ const input = importBillingInvoiceSchema.parse(raw);+ // Line order in an export is not part of invoice identity.+ input.lines.sort((a,b) => a.externalId.localeCompare(b.externalId));+ const receiptHash = receiptFingerprint(input);+ const [existing] = await tx.select().from(billingInvoices).where(and(eq(billingInvoices.companyId, companyId), eq(billingInvoices.biller, input.biller), eq(billingInvoices.externalId, input.externalId)));+ if (existing) {+ if (existing.receiptHash !== receiptHash) throw conflict("Invoice identifier already has different contents");+ return existing;+ }+ // Validate explicit references, even on non-USD invoices that we cannot+ // compare with the USD cost ledger. Never infer cross-company matches.+ for (const line of input.lines) {+ if (line.costEventId) {+ const [event] = await tx.select({ id: costEvents.id }).from(costEvents).where(and(eq(costEvents.companyId, companyId), eq(costEvents.id, line.costEventId)));+ if (!event) throw notFound("Invoice cost event not found");+ }+ if (line.runId) {+ const [run] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, line.runId)));+ if (!run) throw notFound("Invoice run not found");+ }+ }+ const [invoice] = await tx.insert(billingInvoices).values({ companyId, biller: input.biller, externalId: input.externalId, currency: input.currency, receiptHash, importedBy: actorId }).returning();+ await tx.insert(billingInvoiceLines).values(input.lines.map(line => ({ ...line, companyId, invoiceId: invoice.id, occurredAt: new Date(line.occurredAt), pricing: line.pricing ?? {} })));+ const matches = [];+ const matchCounts = new Map<string, number>();+ for (const line of input.lines) {+ const candidates = line.kind === "inference" ? await invoiceCostCandidates(tx, companyId, input.biller, line) : [];+ matches.push({ line, candidates });+ if (candidates.length === 1) matchCounts.set(candidates[0].id, (matchCounts.get(candidates[0].id) ?? 0) + 1);+ }+ for (const { line, candidates } of matches) {+ // Ambiguous evidence cannot authorize another debit. Keep every line+ // for reconciliation, including differences from an existing charge.+ if (candidates.length > 1 || candidates.length === 1 && matchCounts.get(candidates[0].id)! > 1) continue;+ const costEventId = line.costEventId ?? candidates[0]?.id;+ if (line.kind === "inference" && costEventId) {+ const [recorded] = await tx.select({ id: financeEvents.id }).from(financeEvents).where(and(+ eq(financeEvents.companyId, companyId), eq(financeEvents.costEventId, costEventId),+ eq(financeEvents.biller, input.biller), eq(financeEvents.currency, input.currency),+ eq(financeEvents.eventKind, "inference_charge"), eq(financeEvents.direction, "debit"),+ sql`${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report'`,+ )).limit(1);+ if (recorded) continue;+ }+ await createFinanceEventInTransaction(tx, publications, companyId, {+ idempotencyKey: `invoice:${invoice.id}:${receiptFingerprint(line.externalId)}`,+ biller: input.biller, externalInvoiceId: input.externalId,+ eventKind: line.kind === "inference" ? "inference_charge" : line.kind === "credit" ? "credit_refund" : "platform_fee",+ direction: line.kind === "credit" ? "credit" : "debit",+ amountCents: line.amountCents, currency: input.currency, occurredAt: new Date(line.occurredAt),+ description: `Invoice ${input.externalId} · ${line.externalId}`.slice(0, 500),+ costEventId, heartbeatRunId: line.runId,+ metadataJson: { source: "provider_invoice", invoiceId: invoice.id, externalLineId: line.externalId },+ }, { actorType: "user", actorId });+ }+ await logActivity(tx, { companyId, actorType: "user", actorId, action: "accounting.invoice_imported", entityType: "billing_invoice", entityId: invoice.id,+ details: { biller: invoice.biller, externalId: invoice.externalId, currency: invoice.currency, lineCount: input.lines.length, receiptHash } }, publications);+ return invoice;+ }),+ list: (companyId: string) => db.select().from(billingInvoices).where(eq(billingInvoices.companyId, companyId)).orderBy(desc(billingInvoices.createdAt)).limit(100),+ reconcile: (companyId: string, invoiceId: string) => withAccountingReadSnapshot(db, companyId, async tx => {+ const [invoice] = await tx.select().from(billingInvoices).where(and(eq(billingInvoices.companyId, companyId), eq(billingInvoices.id, invoiceId)));+ if (!invoice) throw notFound("Invoice not found");+ const lines = await tx.select().from(billingInvoiceLines).where(and(eq(billingInvoiceLines.companyId, companyId), eq(billingInvoiceLines.invoiceId, invoiceId))).orderBy(billingInvoiceLines.externalId);+ const rows = [];+ for (const line of lines) {+ const candidates = invoice.currency !== "USD" || line.kind !== "inference" ? []+ : await invoiceCostCandidates(tx, companyId, invoice.biller, line);+ const match = candidates.length === 1 ? candidates[0] : null;+ const differenceCents = match ? subtractCents(line.amountCents, match.cents) : null;+ const status = invoice.currency !== "USD" ? "unsupported_currency" : line.kind !== "inference" ? "non_inference"+ : candidates.length > 1 ? "ambiguous" : !match ? "unmatched" : differenceCents === "0.0000000" && match.status !== "unpriced" ? "matched" : "difference";+ rows.push({ ...line, amountCents: normalizeCents(line.amountCents), status, matchedEventId: match?.id ?? null,+ recordedCents: match ? normalizeCents(match.cents) : null, differenceCents });+ }+ // Multiple invoice lines cannot independently revalue the same charge.+ const counts = new Map<string, number>();+ for (const row of rows) if (row.matchedEventId) counts.set(row.matchedEventId, (counts.get(row.matchedEventId) ?? 0) + 1);+ for (const row of rows) if (row.matchedEventId && counts.get(row.matchedEventId)! > 1) row.status = "ambiguous";+ return { invoice, lines: rows };+ }),+ adjustments: (companyId: string, eventId: string) => db.select().from(costAdjustments).where(and(eq(costAdjustments.companyId, companyId), eq(costAdjustments.costEventId, eventId))).orderBy(desc(costAdjustments.createdAt)),+ adjust: async (companyId: string, eventId: string, raw: AdjustCost, actorId: string) => {+ const input = adjustCostSchema.parse(raw);+ const result = await withAccountingTransaction(db, companyId, async (tx, publications) => {+ const hash = receiptFingerprint({ eventId, ...input });+ const [existing] = await tx.select().from(costAdjustments).where(and(eq(costAdjustments.companyId, companyId), eq(costAdjustments.idempotencyKey, input.idempotencyKey)));+ if (existing) {+ if (existing.receiptHash !== hash) throw conflict("Correction key already has different contents");+ return existing;+ }+ const [event] = await tx.select({ event: costEvents, exact: sql<string>`${costEvents.costCents}::text` }).from(costEvents)+ .where(and(eq(costEvents.companyId, companyId), eq(costEvents.id, eventId))).for("update");+ if (!event) throw notFound("Cost event not found");+ if (normalizeCents(event.exact) !== input.expectedCents) throw conflict("Charge changed since review; review it again");+ if (input.invoiceLineId) {+ const reportLine = await tx.select({ line: billingInvoiceLines, invoice: billingInvoices }).from(billingInvoiceLines)+ .innerJoin(billingInvoices, eq(billingInvoices.id, billingInvoiceLines.invoiceId)).where(and(eq(billingInvoiceLines.id, input.invoiceLineId), eq(billingInvoiceLines.companyId, companyId), eq(billingInvoices.companyId, companyId)));+ const row = reportLine[0];+ if (!row) throw notFound("Invoice line not found");+ if (row.invoice.currency !== "USD" || row.line.kind !== "inference" || row.invoice.biller !== event.event.biller+ || normalizeCents(row.line.amountCents) !== input.correctedCents+ || row.line.costEventId && row.line.costEventId !== eventId+ || row.line.runId && row.line.runId !== event.event.heartbeatRunId+ || row.line.providerRequestId && row.line.providerRequestId !== event.event.providerRequestId+ || row.line.model && row.line.model !== event.event.model) throw unprocessable("Invoice line does not support this correction");+ const review = await billingReconciliationService(tx).reconcile(companyId, row.invoice.id);+ const reviewedLine = review.lines.find(line => line.id === input.invoiceLineId);+ if (!reviewedLine || !["matched", "difference"].includes(reviewedLine.status) || reviewedLine.matchedEventId !== eventId)+ throw unprocessable("Invoice match is ambiguous or unverified; review an explicit correction without attaching this line");+ const [used] = await tx.select().from(costAdjustments).where(and(eq(costAdjustments.companyId, companyId), eq(costAdjustments.invoiceLineId, input.invoiceLineId)));+ if (used) throw conflict("Invoice line has already been applied");+ }+ const [adjustment] = await tx.insert(costAdjustments).values({ companyId, costEventId: eventId, invoiceLineId: input.invoiceLineId,+ idempotencyKey: input.idempotencyKey, receiptHash: hash, previousCents: input.expectedCents, correctedCents: input.correctedCents,+ previousStatus: event.event.costStatus, previousPricing: event.event.pricingProvenance ?? {},+ reason: input.reason, actorId, pricing: input.pricing }).returning();+ // Original provider value and fingerprint remain immutable. cost_cents+ // is the effective valuation, backed by this append-only correction.+ const [updated] = await tx.update(costEvents).set({ costCents: sql`${input.correctedCents}::numeric`,+ reportedCostCents: event.event.reportedCostCents ?? normalizeCents(event.exact), costStatus: input.pricing.source === "rate_card" ? "estimated" : "reported", pricingProvenance: input.pricing,+ }).where(eq(costEvents.id, eventId)).returning();+ await updateMonthlySpendProjections(tx, companyId, updated.agentId, subtractCents(input.correctedCents, input.expectedCents), updated.occurredAt);+ if (updated.heartbeatRunId) {+ const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, updated.heartbeatRunId), eq(heartbeatRuns.companyId, companyId)));+ if (run?.costAccountedAt && run.accountingProjectionVersion === "v2") await tx.update(agentRuntimeState)+ .set({ totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${subtractCents(input.correctedCents, input.expectedCents)}::numeric`, updatedAt: new Date() })+ .where(and(eq(agentRuntimeState.agentId, updated.agentId), eq(agentRuntimeState.companyId, companyId)));+ }+ const budgets = budgetServiceInTransaction(tx, publications);+ await budgets.evaluateCostEvent(updated);+ await budgets.getInvocationBlock(companyId, updated.agentId, { projectId: updated.projectId });+ await logActivity(tx, { companyId, actorType: "user", actorId, action: "accounting.charge_corrected", entityType: "cost_event", entityId: eventId,+ details: { adjustmentId: adjustment.id, previousCents: input.expectedCents, correctedCents: input.correctedCents, reason: input.reason, pricing: input.pricing } }, publications);+ return adjustment;+ });+ await deliverBudgetEnforcement(db, hooks, companyId);+ return result;+ },+ };+}diff --git a/server/src/services/browser-use.ts b/server/src/services/browser-use.tsindex 6a20765906..849b1d8bb0 100644--- a/server/src/services/browser-use.ts+++ b/server/src/services/browser-use.ts@@ -16,9 +16,7 @@ import {issues,heartbeatRuns,agents,- companies,costEvents,- financeEvents,} from "@paperclipai/db";import {BROWSER_USE_IDLE_MS,@@ -41,7 +39,9 @@ import { secretService } from "./secrets.js";import { budgetService, type BudgetServiceHooks } from "./budgets.js";import { issueTreeControlService } from "./issue-tree-control.js";import { accessService } from "./access.js";-import { getMonthlySpendTotal } from "./costs.js";+import { createCostEventInTransaction } from "./costs.js";+import { createFinanceEventInTransaction } from "./finance.js";+import { withAccountingTransaction } from "./accounting-transaction.js";import { logActivity } from "./activity-log.js";import { browserUseViewports } from "./browser-use-viewport.js";import { forbidden, notFound, conflict } from "../errors.js";@@ -911,36 +911,32 @@ export function browserUseService(const cents = Math.max(0, Math.round(Number(summary.totalCostUsd) * 100));if (!Number.isSafeInteger(cents))throw new BrowserUseError(502, "Browser Use returned invalid usage.");- const [issue] = await db- .select({ projectId: issues.projectId })- .from(issues)- .where(and(eq(issues.id, s.issueId), eq(issues.companyId, s.companyId)));- const event = await db.transaction(async (tx) => {+ const event = await withAccountingTransaction(db, s.companyId, async (tx, publications) => {+ const [issue] = await tx+ .select({ projectId: issues.projectId })+ .from(issues)+ .where(and(eq(issues.id, s.issueId), eq(issues.companyId, s.companyId)));const [current] = await tx.select().from(runs).where(eq(runs.id, run.id)).for("update");if (cents <= current.accountedCents) return null;- const [e] = await tx- .insert(costEvents)- .values({- companyId: s.companyId,- agentId: s.agentId,- issueId: s.issueId,- projectId: issue?.projectId,- heartbeatRunId: run.heartbeatRunId,- provider: "browser-use-cloud",- biller: "browser-use-cloud",- billingType: "metered_api",- model: summary.model,- costCents: cents - current.accountedCents,- occurredAt: new Date(),- billingCode: `browser-use-cloud:${run.id}`,- })- .returning();- await tx.insert(financeEvents).values({- companyId: e.companyId,+ const e = await createCostEventInTransaction(tx, s.companyId, {+ agentId: s.agentId,+ issueId: s.issueId,+ projectId: issue?.projectId,+ heartbeatRunId: run.heartbeatRunId,+ provider: "browser-use-cloud",+ biller: "browser-use-cloud",+ billingType: "metered_api",+ model: summary.model,+ costCents: cents - current.accountedCents,+ occurredAt: new Date(),+ billingCode: `browser-use-cloud:${run.id}`,+ idempotencyKey: `browser-use-cloud:${run.id}:${cents}`,+ }, publications);+ await createFinanceEventInTransaction(tx, publications, s.companyId, {agentId: e.agentId,issueId: e.issueId,projectId: e.projectId,@@ -963,23 +959,6 @@ export function browserUseService(.where(eq(runs.id, run.id));return e;});- await db- .update(agents)- .set({- spentMonthlyCents: await getMonthlySpendTotal(db, {- companyId: s.companyId,- agentId: s.agentId,- }),- })- .where(and(eq(agents.companyId, s.companyId), eq(agents.id, s.agentId)));- await db- .update(companies)- .set({- spentMonthlyCents: await getMonthlySpendTotal(db, {- companyId: s.companyId,- }),- })- .where(eq(companies.id, s.companyId));// Re-evaluate on retries too: accounting may have committed immediately// before a crash interrupted budget enforcement.const lastEvent =diff --git a/server/src/services/budget-reservations.ts b/server/src/services/budget-reservations.tsnew file mode 100644index 0000000000..fb12471849--- /dev/null+++ b/server/src/services/budget-reservations.ts@@ -0,0 +1,68 @@+import { and, eq, sql } from "drizzle-orm";+import { agents, budgetPolicies, budgetReservations, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";+import { centsToUnits, unitsToCents } from "@paperclipai/shared";+import { conflict, notFound } from "../errors.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { budgetServiceInTransaction, budgetPoliciesForRun, computeObservedSpend } from "./budgets.js";++/** Reserve before dispatch, under the same company lock as charges and policy+ * changes. Estimates constrain admission; they cannot cap a provider's bill.+ * A reservation survives timeouts and restarts until accounting proves closure. */+export async function reserveRunBudget(db: Db, companyId: string, runId: string, projectId: string | null, ledgerScope: Record<string, unknown> = {}, recoveryLeaseOwner?: string) {+ return withAccountingTransaction(db, companyId, async (tx, publications) => {+ const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))).for("update");+ if (!run) throw notFound("Run not found");+ if (run.resultJson?.cancellation || run.resultJson?.startupCancellation) throw conflict("Run cancellation already requested");+ if (run.costAccountedAt || !["queued", "running"].includes(run.status)) throw conflict("Run can no longer start provider work");+ const [existing] = await tx.select().from(budgetReservations).where(and(eq(budgetReservations.companyId, companyId), eq(budgetReservations.runId, runId)));+ if (existing) {+ // The native coordinator fences recovery ownership. Reuse the original+ // hold only for that live owner, never for an ordinary duplicate dispatch.+ const [owner] = recoveryLeaseOwner && run.runtimeMode === "native" && existing.state === "held"+ && existing.projectId === projectId ? await tx.select({ runId: nativeRunFinalizations.runId })+ .from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, companyId),+ eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.leaseOwner, recoveryLeaseOwner),+ sql`${nativeRunFinalizations.leaseExpiresAt} > now()`)).for("update") : [];+ if (owner) {+ // Recovery has already made this run queued/running, so its own pending+ // accounting is excluded. Current overruns, other unfinished runs and+ // scope pauses still apply before any more paid work starts.+ const block = await budgetServiceInTransaction(tx, publications).getInvocationBlock(companyId, run.agentId, { projectId });+ if (block) throw conflict(block.reason);+ const [agent] = await tx.select({ status: agents.status }).from(agents)+ .where(and(eq(agents.companyId, companyId), eq(agents.id, run.agentId)));+ if (agent?.status === "paused") throw conflict("Agent is paused and cannot start new work");+ return { ...existing, reused: true };+ }+ throw conflict("Provider dispatch has already reserved this run");+ }+ const block = await budgetServiceInTransaction(tx, publications).getInvocationBlock(companyId, run.agentId, { projectId });+ if (block) throw conflict(block.reason);+ const policies = await tx.select().from(budgetPolicies).where(and(+ eq(budgetPolicies.companyId, companyId), eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true),+ eq(budgetPolicies.metric, "billed_cents"), sql`${budgetPolicies.amount} > 0`,+ budgetPoliciesForRun(companyId, run.agentId, projectId),+ ));+ const amount = policies.reduce((max, policy) => { const next = centsToUnits(policy.reservationCents); return next > max ? next : max; }, 0n);+ for (const policy of policies) {+ const [held] = await tx.select({ amount: sql<string>`coalesce(sum(${budgetReservations.amountCents}), 0)::text` }).from(budgetReservations).where(and(+ eq(budgetReservations.companyId, companyId), eq(budgetReservations.state, "held"),+ policy.scopeType === "agent" ? eq(budgetReservations.agentId, run.agentId) : undefined,+ policy.scopeType === "project" ? eq(budgetReservations.projectId, projectId!) : undefined,+ ));+ const observed = await computeObservedSpend(tx, policy);+ // Even zero-estimate runs cannot enter a scope whose available capacity+ // is completely reserved. Outstanding reservations carry across months.+ const committed = centsToUnits(observed.totalExact) + centsToUnits(held.amount);+ const limit = centsToUnits(policy.amount);+ if (committed >= limit || committed + amount > limit) throw conflict("Available budget is reserved by unfinished runs");+ }+ // A zero-valued row also fences duplicate dispatch when estimates are off.+ const [reservation] = await tx.insert(budgetReservations).values({ companyId, runId, agentId: run.agentId, projectId,+ amountCents: unitsToCents(amount), providerStartedAt: new Date() }).returning();+ await tx.update(heartbeatRuns).set({ costAccountingPending: true,+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ accountingReceiptReady: false, ledgerScope: { ...(run.usageJson?.ledgerScope as object ?? {}), ...ledgerScope, projectId } })}::jsonb`,+ }).where(eq(heartbeatRuns.id, runId));+ return { ...reservation, reused: false };+ });+}diff --git a/server/src/services/budgets.ts b/server/src/services/budgets.tsindex 8938cb4b7c..9d15daab21 100644--- a/server/src/services/budgets.ts+++ b/server/src/services/budgets.ts@@ -1,4 +1,5 @@-import { and, desc, eq, gte, inArray, lt, ne, sql } from "drizzle-orm";+import { compareCents, normalizeCents } from "@paperclipai/shared";+import { and, desc, eq, gte, inArray, lt, ne, sql, or, isNull, type SQL } from "drizzle-orm";import type { Db } from "@paperclipai/db";import { recordAgentStatusEvent } from "./resource-lifecycle-events.js";import {@@ -8,6 +9,8 @@ import {budgetPolicies,companies,costEvents,+ heartbeatRuns,+ nativeRunFinalizations,projects,} from "@paperclipai/db";import type {@@ -23,8 +26,10 @@ import type {BudgetThresholdType,BudgetWindowKind,} from "@paperclipai/shared";-import { notFound, unprocessable } from "../errors.js";-import { logActivity } from "./activity-log.js";+import { HttpError, notFound, unprocessable } from "../errors.js";+import { logger } from "../middleware/logger.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { logActivity, type LogActivityInput, type ActivityPublication } from "./activity-log.js";type ScopeRecord = {companyId: string;@@ -40,6 +45,10 @@ export type BudgetEnforcementScope = {companyId: string;scopeType: BudgetScopeType;scopeId: string;+ /** Snapshot taken under the company lock, before a later budget grant can admit new work. */+ createdBefore?: Date;+ /** Revalidated at the durable cancellation write, under the admission lock. */+ enforcement?: { policyId: string; version: number };};export type BudgetServiceHooks = {@@ -65,13 +74,13 @@ function resolveWindow(windowKind: BudgetWindowKind, now = new Date()) {}function budgetStatusFromObserved(- observedAmount: number,+ observedAmount: string,amount: number,warnPercent: number,): BudgetPolicySummary["status"] {if (amount <= 0) return "ok";- if (observedAmount >= amount) return "hard_stop";- if (observedAmount >= Math.ceil((amount * warnPercent) / 100)) return "warning";+ if (compareCents(observedAmount, amount) >= 0) return "hard_stop";+ if (compareCents(observedAmount, Math.ceil((amount * warnPercent) / 100)) >= 0) return "warning";return "ok";}@@ -141,29 +150,84 @@ async function resolveScopeRecord(db: Db, scopeType: BudgetScopeType, scopeId: s};}-async function computeObservedAmount(- db: Db,- policy: Pick<PolicyRow, "companyId" | "scopeType" | "scopeId" | "windowKind" | "metric">,-) {- if (policy.metric !== "billed_cents") return 0;-- const conditions = [eq(costEvents.companyId, policy.companyId)];- if (policy.scopeType === "agent") conditions.push(eq(costEvents.agentId, policy.scopeId));- if (policy.scopeType === "project") conditions.push(eq(costEvents.projectId, policy.scopeId));- const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);- if (policy.windowKind === "calendar_month_utc") {- conditions.push(gte(costEvents.occurredAt, start));- conditions.push(lt(costEvents.occurredAt, end));+// Keep a large dashboard from filling the database pool with queued reads.+async function mapBudgetReads<T, R>(rows: T[], read: (row: T) => Promise<R>): Promise<R[]> {+ const result: R[] = [];+ for (let start = 0; start < rows.length; start += 4) {+ result.push(...await Promise.all(rows.slice(start, start + 4).map(read)));}+ return result;+}- const [row] = await db- .select({- total: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::double precision`,- })- .from(costEvents)- .where(and(...conditions));+/** Filter in PostgreSQL so one run never loads unrelated agents' policies. */+export function budgetPoliciesForRun(companyId: string, agentId: string, projectId: string | null) {+ return or(+ and(eq(budgetPolicies.scopeType, "company"), eq(budgetPolicies.scopeId, companyId)),+ and(eq(budgetPolicies.scopeType, "agent"), eq(budgetPolicies.scopeId, agentId)),+ projectId ? and(eq(budgetPolicies.scopeType, "project"), eq(budgetPolicies.scopeId, projectId)) : undefined,+ );+}- return Number(row?.total ?? 0);+type SpendPolicy = Pick<PolicyRow, "companyId" | "scopeType" | "scopeId" | "windowKind" | "metric">;+type ObservedSpend = { windowStart: Date; windowEnd: Date; total: number; totalExact: string; unpricedEventCount: number; pendingRunCount: number; recoveringRunCount: number };++/** One ledger scan and one pending-run scan for the affected policies. The+ * company lock still protects decisions; nothing is cached across mutations.+ * Each aggregate keeps its own scope/window, including mixed lifetime and+ * monthly policies. An outer predicate excludes rows no policy needs. */+async function computeObservedSpends(db: Db, policies: SpendPolicy[]): Promise<ObservedSpend[]> {+ const now = new Date();+ const windows = policies.map(policy => resolveWindow(policy.windowKind as BudgetWindowKind, now));+ const billable = policies.map((policy, index) => ({ policy, index })).filter(({ policy }) => policy.metric === "billed_cents");+ const ledgerColumns: Record<string, SQL> = {};+ const pendingColumns: Record<string, SQL> = {};+ const ledgerPredicates: SQL[] = [], pendingPredicates: SQL[] = [];+ for (const { policy, index } of billable) {+ const { start, end } = windows[index];+ const ledger = and(+ eq(costEvents.companyId, policy.companyId),+ policy.scopeType === "agent" ? eq(costEvents.agentId, policy.scopeId) : undefined,+ policy.scopeType === "project" ? eq(costEvents.projectId, policy.scopeId) : undefined,+ policy.windowKind === "calendar_month_utc" ? and(gte(costEvents.occurredAt, start), lt(costEvents.occurredAt, end)) : undefined,+ )!;+ const pending = and(+ eq(heartbeatRuns.companyId, policy.companyId), eq(heartbeatRuns.costAccountingPending, true),+ inArray(heartbeatRuns.status, ["succeeded", "failed", "timed_out", "cancelled", "interrupted"]),+ policy.scopeType === "agent" ? eq(heartbeatRuns.agentId, policy.scopeId) : undefined,+ policy.scopeType === "project" ? sql`${heartbeatRuns.usageJson}->'ledgerScope'->>'projectId' = ${policy.scopeId}` : undefined,+ policy.windowKind === "calendar_month_utc" ? sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.createdAt}) >= ${start.toISOString()}::timestamptz+ and coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.createdAt}) < ${end.toISOString()}::timestamptz` : undefined,+ )!;+ ledgerPredicates.push(ledger); pendingPredicates.push(pending);+ ledgerColumns[`total${index}`] = sql`coalesce(sum(${costEvents.costCents}) filter (where ${ledger}), 0)::text`;+ ledgerColumns[`unpriced${index}`] = sql`count(*) filter (where ${ledger} and ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`;+ pendingColumns[`pending${index}`] = sql`count(*) filter (where ${pending})::int`;+ pendingColumns[`recovering${index}`] = sql`count(*) filter (where ${pending} and ${heartbeatRuns.runtimeMode} = 'native'+ and exists (select 1 from ${nativeRunFinalizations} where ${nativeRunFinalizations.runId} = ${heartbeatRuns.id}+ and ${nativeRunFinalizations.companyId} = ${heartbeatRuns.companyId}+ and ${nativeRunFinalizations.resultId} is null and ${nativeRunFinalizations.phase} <> 'terminal_failure'))::int`;+ }+ const [ledger = {}] = billable.length ? await db.select(ledgerColumns).from(costEvents).where(or(...ledgerPredicates)) : [];+ const [pending = {}] = billable.length ? await db.select(pendingColumns).from(heartbeatRuns).where(or(...pendingPredicates)) : [];+ return policies.map((_, index) => ({+ windowStart: windows[index].start, windowEnd: windows[index].end,+ total: Number(ledger[`total${index}`] ?? 0), totalExact: normalizeCents(String(ledger[`total${index}`] ?? 0)),+ unpricedEventCount: Number(ledger[`unpriced${index}`] ?? 0), pendingRunCount: Number(pending[`pending${index}`] ?? 0),+ recoveringRunCount: Number(pending[`recovering${index}`] ?? 0),+ }));+}++export async function computeObservedSpend(db: Db, policy: SpendPolicy) {+ return (await computeObservedSpends(db, [policy]))[0];+}++function observedBlocks(policy: PolicyRow, observed: Awaited<ReturnType<typeof computeObservedSpend>>) {+ if (!policy.isActive || !policy.hardStopEnabled || policy.amount <= 0) return false;+ return compareCents(observed.totalExact, policy.amount) >= 0 || (observed.pendingRunCount - observed.recoveringRunCount) > 0 || (policy.unpricedUsagePolicy !== "allow" && observed.unpricedEventCount > 0);+}+async function policyBlocks(db: Db, policy: PolicyRow) {+ if (!policy.isActive || !policy.hardStopEnabled || policy.amount <= 0) return false;+ return observedBlocks(policy, await computeObservedSpend(db, policy));}function buildApprovalPayload(input: {@@ -171,6 +235,7 @@ function buildApprovalPayload(input: {scopeName: string;thresholdType: BudgetThresholdType;amountObserved: number;+ amountObservedExact: string;windowStart: Date;windowEnd: Date;}) {@@ -183,11 +248,12 @@ function buildApprovalPayload(input: {thresholdType: input.thresholdType,budgetAmount: input.policy.amount,observedAmount: input.amountObserved,+ observedAmountExact: input.amountObservedExact,warnPercent: input.policy.warnPercent,windowStart: input.windowStart.toISOString(),windowEnd: input.windowEnd.toISOString(),policyId: input.policy.id,- guidance: "Raise the budget and resume the scope, or keep the scope paused.",+ guidance: "Resolve pending or unpriced accounting, raise the budget, or keep the scope paused.",};}@@ -211,7 +277,9 @@ async function markApprovalStatus(.where(eq(approvals.id, approvalId));}-export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {+/** Internal: caller must hold the company accounting transaction lock. */+export function budgetServiceInTransaction(db: Db, publications: ActivityPublication[] = []) {+ const recordActivity = (input: LogActivityInput) => logActivity(db, input, publications);async function pauseScopeForBudget(policy: PolicyRow) {const now = new Date();if (policy.scopeType === "agent") {@@ -235,7 +303,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {pausedAt: now,updatedAt: now,})- .where(eq(projects.id, policy.scopeId));+ .where(and(eq(projects.id, policy.scopeId), or(isNull(projects.pausedAt), eq(projects.pauseReason, "budget"))));return;}@@ -247,19 +315,24 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {pausedAt: now,updatedAt: now,})- .where(eq(companies.id, policy.scopeId));+ .where(and(eq(companies.id, policy.scopeId), or(eq(companies.status, "active"), and(eq(companies.status, "paused"), eq(companies.pauseReason, "budget")))));}async function pauseAndCancelScopeForBudget(policy: PolicyRow) {await pauseScopeForBudget(policy);- await hooks.cancelWorkForScope?.({- companyId: policy.companyId,- scopeType: policy.scopeType as BudgetScopeType,- scopeId: policy.scopeId,- });+ await db.update(budgetPolicies).set({+ enforcementVersion: sql`${budgetPolicies.enforcementVersion} + 1`,+ }).where(eq(budgetPolicies.id, policy.id));}async function resumeScopeFromBudget(policy: PolicyRow) {+ const policies = await db.select().from(budgetPolicies).where(and(+ eq(budgetPolicies.companyId, policy.companyId), eq(budgetPolicies.scopeType, policy.scopeType),+ eq(budgetPolicies.scopeId, policy.scopeId), eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true),+ ));+ for (const candidate of policies) {+ if (await policyBlocks(db, candidate)) return;+ }const now = new Date();if (policy.scopeType === "agent") {await db.transaction(async tx => {@@ -294,7 +367,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {pausedAt: null,updatedAt: now,})- .where(and(eq(companies.id, policy.scopeId), eq(companies.pauseReason, "budget")));+ .where(and(eq(companies.id, policy.scopeId), eq(companies.status, "paused"), eq(companies.pauseReason, "budget")));}async function getPolicyRow(policyId: string) {@@ -317,8 +390,9 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {async function buildPolicySummary(policy: PolicyRow): Promise<BudgetPolicySummary> {const scope = await resolveScopeRecord(db, policy.scopeType as BudgetScopeType, policy.scopeId);- const observedAmount = await computeObservedAmount(db, policy);- const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);+ const observed = await computeObservedSpend(db, policy);+ const { total: observedAmount, totalExact: observedAmountExact, unpricedEventCount, pendingRunCount } = observed;+ const { windowStart: start, windowEnd: end } = observed;const amount = policy.isActive ? policy.amount : 0;const utilizationPercent =amount > 0 ? Number(((observedAmount / amount) * 100).toFixed(2)) : 0;@@ -332,14 +406,19 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {windowKind: policy.windowKind as BudgetWindowKind,amount,observedAmount,+ observedAmountExact,+ reservationCents: policy.reservationCents,+ unpricedEventCount,+ pendingRunCount,+ unpricedUsagePolicy: policy.unpricedUsagePolicy as "block" | "allow",remainingAmount: amount > 0 ? Math.max(0, amount - observedAmount) : 0,utilizationPercent,warnPercent: policy.warnPercent,hardStopEnabled: policy.hardStopEnabled,notifyEnabled: policy.notifyEnabled,isActive: policy.isActive,- status: policy.isActive- ? budgetStatusFromObserved(observedAmount, amount, policy.warnPercent)+ status: observedBlocks(policy, observed) ? "hard_stop" : policy.isActive+ ? budgetStatusFromObserved(observedAmountExact, amount, policy.warnPercent): "ok",paused: scope.paused,pauseReason: scope.pauseReason,@@ -351,9 +430,9 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {async function createIncidentIfNeeded(policy: PolicyRow,thresholdType: BudgetThresholdType,- amountObserved: number,+ observed: Awaited<ReturnType<typeof computeObservedSpend>>,) {- const { start, end } = resolveWindow(policy.windowKind as BudgetWindowKind);+ const { windowStart: start, windowEnd: end } = observed;const existing = await db.select().from(budgetIncidents)@@ -362,18 +441,21 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {eq(budgetIncidents.policyId, policy.id),eq(budgetIncidents.windowStart, start),eq(budgetIncidents.thresholdType, thresholdType),- ne(budgetIncidents.status, "dismissed"),+ or(eq(budgetIncidents.status, "open"), and(eq(budgetIncidents.status, "dismissed"), eq(budgetIncidents.amountLimit, policy.amount))),),)+ .orderBy(desc(budgetIncidents.createdAt)).then((rows) => rows[0] ?? null);if (existing) return { incident: existing, created: false };+ const { total: amountObserved, totalExact: amountObservedExact } = observed;const scope = await resolveScopeRecord(db, policy.scopeType as BudgetScopeType, policy.scopeId);const payload = buildApprovalPayload({policy,scopeName: normalizeScopeName(policy.scopeType as BudgetScopeType, scope.name),thresholdType,amountObserved,+ amountObservedExact,windowStart: start,windowEnd: end,});@@ -406,7 +488,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {windowEnd: end,thresholdType,amountLimit: policy.amount,- amountObserved,+ amountObserved: sql`${amountObservedExact}::numeric`,status: "open",approvalId: approval?.id ?? null,})@@ -436,11 +518,14 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {policyId: string,approvalStatus: "approved" | "rejected" | null,decidedByUserId: string | null,+ thresholdType?: BudgetThresholdType,) {+ const condition = and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open"),+ thresholdType ? eq(budgetIncidents.thresholdType, thresholdType) : undefined);const openRows = await db.select().from(budgetIncidents)- .where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open")));+ .where(condition);await db.update(budgetIncidents)@@ -449,7 +534,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {resolvedAt: new Date(),updatedAt: new Date(),})- .where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open")));+ .where(condition);if (!approvalStatus || !decidedByUserId) return;for (const row of openRows) {@@ -467,40 +552,87 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {: [];const approvalStatusById = new Map(approvalRows.map((row) => [row.id, row.status]));- return Promise.all(- rows.map(async (row) => {- const scope = await resolveScopeRecord(db, row.scopeType as BudgetScopeType, row.scopeId);- return {- id: row.id,- companyId: row.companyId,- policyId: row.policyId,- scopeType: row.scopeType as BudgetScopeType,- scopeId: row.scopeId,- scopeName: normalizeScopeName(row.scopeType as BudgetScopeType, scope.name),- metric: row.metric as BudgetMetric,- windowKind: row.windowKind as BudgetWindowKind,- windowStart: row.windowStart,- windowEnd: row.windowEnd,- thresholdType: row.thresholdType as BudgetThresholdType,- amountLimit: row.amountLimit,- amountObserved: row.amountObserved,- status: row.status as BudgetIncident["status"],- approvalId: row.approvalId ?? null,- approvalStatus: row.approvalId ? approvalStatusById.get(row.approvalId) ?? null : null,- resolvedAt: row.resolvedAt ?? null,- createdAt: row.createdAt,- updatedAt: row.updatedAt,- };- }),- );+ return mapBudgetReads(rows, async (row) => {+ const scope = await resolveScopeRecord(db, row.scopeType as BudgetScopeType, row.scopeId);+ return {+ id: row.id,+ companyId: row.companyId,+ policyId: row.policyId,+ scopeType: row.scopeType as BudgetScopeType,+ scopeId: row.scopeId,+ scopeName: normalizeScopeName(row.scopeType as BudgetScopeType, scope.name),+ metric: row.metric as BudgetMetric,+ windowKind: row.windowKind as BudgetWindowKind,+ windowStart: row.windowStart,+ windowEnd: row.windowEnd,+ thresholdType: row.thresholdType as BudgetThresholdType,+ amountLimit: row.amountLimit,+ amountObserved: row.amountObserved,+ status: row.status as BudgetIncident["status"],+ approvalId: row.approvalId ?? null,+ approvalStatus: row.approvalId ? approvalStatusById.get(row.approvalId) ?? null : null,+ resolvedAt: row.resolvedAt ?? null,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ };+ });+ }++ async function reconcileScope(companyId: string, scopeType: BudgetScopeType, scopeId: string) {+ const scope = await resolveScopeRecord(db, scopeType, scopeId);+ if (scope.companyId !== companyId) throw notFound("Budget scope not found");+ const policies = await db.select().from(budgetPolicies).where(and(+ eq(budgetPolicies.companyId, companyId), eq(budgetPolicies.scopeType, scopeType), eq(budgetPolicies.scopeId, scopeId),+ ));+ let recoveringPolicy: PolicyRow | undefined;+ for (const policy of policies) {+ const observed = await computeObservedSpend(db, policy);+ if (observedBlocks(policy, observed)) {+ await createIncidentIfNeeded(policy, "hard", observed);+ await pauseAndCancelScopeForBudget(policy);+ const title = scopeType === "company" ? "Company" : scopeType === "agent" ? "Agent" : "Project";+ if (observed.pendingRunCount > 0) {+ return { scopeType, scopeId, scopeName: scope.name, reason: `${title} cannot start work while completed runs await accounting.` };+ }+ if (policy.unpricedUsagePolicy !== "allow" && observed.unpricedEventCount > 0) {+ return { scopeType, scopeId, scopeName: scope.name, reason: `${title} cannot start work because recorded usage has no reliable price.` };+ }+ return { scopeType, scopeId, scopeName: scope.name, reason: scopeType === "project"+ ? "Project cannot start work because its budget hard-stop is still exceeded."+ : `${title} is paused because its budget hard-stop was reached.` };+ }+ // An open native coordinator must finish the original run's accounting.+ // Deny fresh work without pausing/cancelling that recovery or its hold.+ if (policy.isActive && policy.hardStopEnabled && policy.amount > 0 && observed.recoveringRunCount > 0) recoveringPolicy ??= policy;+ // A closed UTC window, inactive policy, or budget raise releases only+ // budget-owned pauses. Manual pauses remain operator decisions.+ await resolveOpenIncidentsForPolicy(policy.id, "approved", "budget_service", "hard");+ if (!policy.isActive || !policy.notifyEnabled || compareCents(observed.totalExact, Math.ceil(policy.amount * policy.warnPercent / 100)) < 0) {+ await resolveOpenIncidentsForPolicy(policy.id, "approved", "budget_service", "soft");+ }+ }+ // Agent status has its own admission gate and error code. Preserve a+ // manual pause without misclassifying it as a budget failure.+ if (scopeType !== "agent" && scope.paused && scope.pauseReason !== "budget") {+ return { scopeType, scopeId, scopeName: scope.name, reason: `${scopeType === "company" ? "Company" : "Project"} is paused and cannot start new work.` };+ }+ if (scope.paused && scope.pauseReason === "budget" && !policies.length) {+ return { scopeType, scopeId, scopeName: scope.name, reason: "Budget pause requires a policy or an explicit operator resume." };+ }+ if (scope.pauseReason === "budget" && policies[0]) await resumeScopeFromBudget(policies[0]);+ if (recoveringPolicy) return { scopeType, scopeId, scopeName: scope.name,+ reason: "New work must wait while a native run recovers its unfinished accounting." };+ return null;}return {+ reconcileScope,listPolicies: async (companyId: string): Promise<BudgetPolicy[]> => {const rows = await listPolicyRows(companyId);return rows.map((row) => ({...row,scopeType: row.scopeType as BudgetScopeType,+ unpricedUsagePolicy: row.unpricedUsagePolicy as "block" | "allow",metric: row.metric as BudgetMetric,windowKind: row.windowKind as BudgetWindowKind,}));@@ -516,10 +648,9 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {throw unprocessable("Budget scope does not belong to company");}+ if (input.reservationCents !== undefined && compareCents(input.reservationCents, 0) < 0) throw unprocessable("Reservation cannot be negative");const metric = input.metric ?? "billed_cents";const windowKind = input.windowKind ?? (input.scopeType === "project" ? "lifetime" : "calendar_month_utc");- const amount = Math.max(0, Math.floor(input.amount));- const nextIsActive = amount > 0 && (input.isActive ?? true);const existing = await db.select().from(budgetPolicies)@@ -534,15 +665,22 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {).then((rows) => rows[0] ?? null);+ if (!existing && input.amount === undefined) throw unprocessable("Amount is required for a new budget policy");+ const amount = Math.max(0, Math.floor(input.amount ?? existing!.amount));+ // A saved zero disables enforcement. Raising it is an explicit limit+ // setting; editing a disabled positive policy must preserve that choice.+ const nextIsActive = amount > 0 && (input.isActive ?? (existing?.amount === 0 ? true : existing?.isActive) ?? true);const now = new Date();const row = existing? await db.update(budgetPolicies).set({amount,+ reservationCents: normalizeCents(input.reservationCents ?? existing.reservationCents ?? 0),warnPercent: input.warnPercent ?? existing.warnPercent,hardStopEnabled: input.hardStopEnabled ?? existing.hardStopEnabled,notifyEnabled: input.notifyEnabled ?? existing.notifyEnabled,+ unpricedUsagePolicy: input.unpricedUsagePolicy ?? existing.unpricedUsagePolicy,isActive: nextIsActive,updatedByUserId: actorUserId,updatedAt: now,@@ -559,9 +697,11 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {metric,windowKind,amount,+ reservationCents: normalizeCents(input.reservationCents ?? 0),warnPercent: input.warnPercent ?? 80,hardStopEnabled: input.hardStopEnabled ?? true,notifyEnabled: input.notifyEnabled ?? true,+ unpricedUsagePolicy: input.unpricedUsagePolicy ?? "block",isActive: nextIsActive,createdByUserId: actorUserId,updatedByUserId: actorUserId,@@ -589,28 +729,33 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {.where(eq(agents.id, input.scopeId));}- if (amount > 0) {- const observedAmount = await computeObservedAmount(db, row);- if (observedAmount < amount) {+ if (row.isActive && amount > 0) {+ const observed = await computeObservedSpend(db, row);+ if (!observedBlocks(row, observed)) {await resumeScopeFromBudget(row);- await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId);+ await resolveOpenIncidentsForPolicy(row.id, "approved", actorUserId ?? "budget_service", "hard");+ if (row.notifyEnabled && compareCents(observed.totalExact, Math.ceil(row.amount * row.warnPercent / 100)) >= 0) {+ await createIncidentIfNeeded(row, "soft", observed);+ } else {+ await resolveOpenIncidentsForPolicy(row.id, null, null, "soft");+ }} else {const softThreshold = Math.ceil((row.amount * row.warnPercent) / 100);- if (row.notifyEnabled && observedAmount >= softThreshold) {- await createIncidentIfNeeded(row, "soft", observedAmount);+ if (row.notifyEnabled && compareCents(observed.totalExact, softThreshold) >= 0 && (!row.hardStopEnabled || compareCents(observed.totalExact, row.amount) < 0)) {+ await createIncidentIfNeeded(row, "soft", observed);}- if (row.hardStopEnabled && observedAmount >= row.amount) {+ if (observedBlocks(row, observed)) {await resolveOpenSoftIncidents(row.id);- await createIncidentIfNeeded(row, "hard", observedAmount);+ await createIncidentIfNeeded(row, "hard", observed);await pauseAndCancelScopeForBudget(row);}}} else {await resumeScopeFromBudget(row);- await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId);+ await resolveOpenIncidentsForPolicy(row.id, "approved", actorUserId ?? "budget_service");}- await logActivity(db, {+ await recordActivity({companyId,actorType: "user",actorId: actorUserId ?? "board",@@ -630,7 +775,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {overview: async (companyId: string): Promise<BudgetOverview> => {const rows = await listPolicyRows(companyId);- const policies = await Promise.all(rows.map((row) => buildPolicySummary(row)));+ const policies = await mapBudgetReads(rows, buildPolicySummary);const activeIncidentRows = await db.select().from(budgetIncidents)@@ -641,8 +786,8 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {companyId,policies,activeIncidents,- pausedAgentCount: policies.filter((policy) => policy.scopeType === "agent" && policy.paused).length,- pausedProjectCount: policies.filter((policy) => policy.scopeType === "project" && policy.paused).length,+ pausedAgentCount: new Set(policies.filter((policy) => policy.scopeType === "agent" && policy.paused).map((policy) => policy.scopeId)).size,+ pausedProjectCount: new Set(policies.filter((policy) => policy.scopeType === "project" && policy.paused).map((policy) => policy.scopeId)).size,pendingApprovalCount: activeIncidents.filter((incident) => incident.approvalStatus === "pending").length,};},@@ -655,26 +800,21 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {and(eq(budgetPolicies.companyId, event.companyId),eq(budgetPolicies.isActive, true),- inArray(budgetPolicies.scopeType, ["company", "agent", "project"]),+ budgetPoliciesForRun(event.companyId, event.agentId, event.projectId),),);- const relevantPolicies = candidatePolicies.filter((policy) => {- if (policy.scopeType === "company") return policy.scopeId === event.companyId;- if (policy.scopeType === "agent") return policy.scopeId === event.agentId;- if (policy.scopeType === "project") return Boolean(event.projectId) && policy.scopeId === event.projectId;- return false;- });-- for (const policy of relevantPolicies) {- if (policy.metric !== "billed_cents" || policy.amount <= 0) continue;- const observedAmount = await computeObservedAmount(db, policy);+ const policies = candidatePolicies.filter(policy => policy.metric === "billed_cents" && policy.amount > 0);+ const observations = await computeObservedSpends(db, policies);+ for (const [index, policy] of policies.entries()) {+ const observed = observations[index];+ const observedAmount = observed.total;const softThreshold = Math.ceil((policy.amount * policy.warnPercent) / 100);- if (policy.notifyEnabled && observedAmount >= softThreshold) {- const softIncident = await createIncidentIfNeeded(policy, "soft", observedAmount);+ if (policy.notifyEnabled && compareCents(observed.totalExact, softThreshold) >= 0 && (!policy.hardStopEnabled || compareCents(observed.totalExact, policy.amount) < 0)) {+ const softIncident = await createIncidentIfNeeded(policy, "soft", observed);if (softIncident?.created) {- await logActivity(db, {+ await recordActivity({companyId: policy.companyId,actorType: "system",actorId: "budget_service",@@ -691,12 +831,12 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {}}- if (policy.hardStopEnabled && observedAmount >= policy.amount) {+ if (observedBlocks(policy, observed)) {await resolveOpenSoftIncidents(policy.id);- const hardIncident = await createIncidentIfNeeded(policy, "hard", observedAmount);+ const hardIncident = await createIncidentIfNeeded(policy, "hard", observed);await pauseAndCancelScopeForBudget(policy);if (hardIncident?.created) {- await logActivity(db, {+ await recordActivity({companyId: policy.companyId,actorType: "system",actorId: "budget_service",@@ -721,147 +861,18 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {agentId: string,context?: { issueId?: string | null; projectId?: string | null },) => {- const agent = await db- .select({- status: agents.status,- pauseReason: agents.pauseReason,- companyId: agents.companyId,- name: agents.name,- })- .from(agents)- .where(eq(agents.id, agentId))- .then((rows) => rows[0] ?? null);- if (!agent || agent.companyId !== companyId) throw notFound("Agent not found");-- const company = await db- .select({- status: companies.status,- pauseReason: companies.pauseReason,- name: companies.name,- })- .from(companies)- .where(eq(companies.id, companyId))- .then((rows) => rows[0] ?? null);- if (!company) throw notFound("Company not found");- if (company.status === "paused") {- return {- scopeType: "company" as const,- scopeId: companyId,- scopeName: company.name,- reason:- company.pauseReason === "budget"- ? "Company is paused because its budget hard-stop was reached."- : "Company is paused and cannot start new work.",- };- }-- const companyPolicy = await db- .select()- .from(budgetPolicies)- .where(- and(- eq(budgetPolicies.companyId, companyId),- eq(budgetPolicies.scopeType, "company"),- eq(budgetPolicies.scopeId, companyId),- eq(budgetPolicies.isActive, true),- eq(budgetPolicies.metric, "billed_cents"),- ),- )- .then((rows) => rows[0] ?? null);- if (companyPolicy && companyPolicy.hardStopEnabled && companyPolicy.amount > 0) {- const observed = await computeObservedAmount(db, companyPolicy);- if (observed >= companyPolicy.amount) {- return {- scopeType: "company" as const,- scopeId: companyId,- scopeName: company.name,- reason: "Company cannot start new work because its budget hard-stop is exceeded.",- };- }- }-- if (agent.status === "paused" && agent.pauseReason === "budget") {- return {- scopeType: "agent" as const,- scopeId: agentId,- scopeName: agent.name,- reason: "Agent is paused because its budget hard-stop was reached.",- };- }-- const agentPolicy = await db- .select()- .from(budgetPolicies)- .where(- and(- eq(budgetPolicies.companyId, companyId),- eq(budgetPolicies.scopeType, "agent"),- eq(budgetPolicies.scopeId, agentId),- eq(budgetPolicies.isActive, true),- eq(budgetPolicies.metric, "billed_cents"),- ),- )- .then((rows) => rows[0] ?? null);- if (agentPolicy && agentPolicy.hardStopEnabled && agentPolicy.amount > 0) {- const observed = await computeObservedAmount(db, agentPolicy);- if (observed >= agentPolicy.amount) {- return {- scopeType: "agent" as const,- scopeId: agentId,- scopeName: agent.name,- reason: "Agent cannot start because its budget hard-stop is still exceeded.",- };- }+ const scopes: Array<{ scopeType: BudgetScopeType; scopeId: string }> = [+ { scopeType: "company", scopeId: companyId }, { scopeType: "agent", scopeId: agentId },+ ...(context?.projectId ? [{ scopeType: "project" as const, scopeId: context.projectId }] : []),+ ];+ for (const { scopeType, scopeId } of scopes) {+ if ((await resolveScopeRecord(db, scopeType, scopeId)).companyId !== companyId) throw notFound("Budget scope not found");}-- const candidateProjectId = context?.projectId ?? null;- if (!candidateProjectId) return null;-- const project = await db- .select({- id: projects.id,- name: projects.name,- companyId: projects.companyId,- pauseReason: projects.pauseReason,- pausedAt: projects.pausedAt,- })- .from(projects)- .where(eq(projects.id, candidateProjectId))- .then((rows) => rows[0] ?? null);-- if (!project || project.companyId !== companyId) return null;- const projectPolicy = await db- .select()- .from(budgetPolicies)- .where(- and(- eq(budgetPolicies.companyId, companyId),- eq(budgetPolicies.scopeType, "project"),- eq(budgetPolicies.scopeId, project.id),- eq(budgetPolicies.isActive, true),- eq(budgetPolicies.metric, "billed_cents"),- ),- )- .then((rows) => rows[0] ?? null);- if (projectPolicy && projectPolicy.hardStopEnabled && projectPolicy.amount > 0) {- const observed = await computeObservedAmount(db, projectPolicy);- if (observed >= projectPolicy.amount) {- return {- scopeType: "project" as const,- scopeId: project.id,- scopeName: project.name,- reason: "Project cannot start work because its budget hard-stop is still exceeded.",- };- }+ for (const { scopeType, scopeId } of scopes) {+ const block = await reconcileScope(companyId, scopeType, scopeId);+ if (block) return block;}-- if (!project.pausedAt || project.pauseReason !== "budget") return null;- return {- scopeType: "project" as const,- scopeId: project.id,- scopeName: project.name,- reason: "Project is paused because its budget hard-stop was reached.",- };+ return null;},resolveIncident: async (@@ -881,8 +892,12 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {const policy = await getPolicyRow(incident.policyId);if (input.action === "raise_budget_and_resume") {const nextAmount = Math.max(0, Math.floor(input.amount ?? 0));- const currentObserved = await computeObservedAmount(db, policy);- if (nextAmount <= currentObserved) {+ const observed = await computeObservedSpend(db, policy);+ if (policy.unpricedUsagePolicy !== "allow" && observed.unpricedEventCount > 0) {+ throw unprocessable("Resolve unpriced usage or explicitly allow it in the budget policy before resuming");+ }+ if (observed.pendingRunCount > 0) throw unprocessable("Completed runs must finish accounting before resuming");+ if (compareCents(observed.totalExact, nextAmount) >= 0) {throw unprocessable("New budget must exceed current observed spend");}@@ -934,7 +949,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {await markApprovalStatus(db, incident.approvalId ?? null, "rejected", input.decisionNote, actorUserId);}- await logActivity(db, {+ await recordActivity({companyId: incident.companyId,actorType: "user",actorId: actorUserId,@@ -959,3 +974,78 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {},};}++/** Fence the durable stop intent against policy edits and admission. External+ * process shutdown must happen after this transaction, without holding locks+ * that the executor needs to persist its final usage receipt. */+export async function withCurrentBudgetEnforcement<T>(db: Db, scope: BudgetEnforcementScope, work: (tx: Db) => Promise<T>): Promise<T | null> {+ return withAccountingTransaction(db, scope.companyId, async (tx) => {+ if (scope.enforcement) {+ const [policy] = await tx.select().from(budgetPolicies).where(and(+ eq(budgetPolicies.id, scope.enforcement.policyId), eq(budgetPolicies.companyId, scope.companyId),+ ));+ if (!policy || policy.scopeType !== scope.scopeType || policy.scopeId !== scope.scopeId+ || policy.enforcementVersion !== scope.enforcement.version || !(await policyBlocks(tx, policy))) return null;+ }+ return work(tx);+ });+}++/** Cancellation is an at-least-once external effect. A failed delivery never+ * rolls back committed spend, and its version remains pending for recovery. */+export async function deliverBudgetEnforcement(db: Db, hooks: BudgetServiceHooks, companyId?: string) {+ if (!hooks.cancelWorkForScope) return;+ const pending = await db.select().from(budgetPolicies).where(and(+ sql`${budgetPolicies.enforcementVersion} > ${budgetPolicies.enforcementDeliveredVersion}`,+ companyId ? eq(budgetPolicies.companyId, companyId) : undefined,+ ));+ for (const policy of pending) {+ try {+ const cancellation = await withAccountingTransaction(db, policy.companyId, async (tx) => {+ const [current] = await tx.select().from(budgetPolicies).where(eq(budgetPolicies.id, policy.id));+ if (!current || current.enforcementVersion !== policy.enforcementVersion || !(await policyBlocks(tx, current))) return null;+ return { companyId: policy.companyId, scopeType: policy.scopeType as BudgetScopeType, scopeId: policy.scopeId, createdBefore: new Date(), enforcement: { policyId: policy.id, version: policy.enforcementVersion } };+ });+ if (cancellation) await hooks.cancelWorkForScope(cancellation);+ await db.update(budgetPolicies).set({ enforcementDeliveredVersion: policy.enforcementVersion })+ .where(and(eq(budgetPolicies.id, policy.id), eq(budgetPolicies.enforcementVersion, policy.enforcementVersion)));+ } catch (error) {+ logger.warn({ err: error, policyId: policy.id }, "Budget cancellation delivery pending; accounting is committed");+ }+ }+}++export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {+ const reads = budgetServiceInTransaction(db);+ async function mutate<T>(companyId: string, work: (service: ReturnType<typeof budgetServiceInTransaction>) => Promise<T>) {+ const result = await withAccountingTransaction(db, companyId, (tx, publications) => work(budgetServiceInTransaction(tx, publications)));+ await deliverBudgetEnforcement(db, hooks, companyId);+ return result;+ }+ return {+ ...reads,+ deliverPendingEnforcement: (companyId?: string) => deliverBudgetEnforcement(db, hooks, companyId),+ reconcilePolicies: async () => {+ const scopes = await db.selectDistinct({ companyId: budgetPolicies.companyId, scopeType: budgetPolicies.scopeType, scopeId: budgetPolicies.scopeId })+ .from(budgetPolicies).orderBy(budgetPolicies.companyId, budgetPolicies.scopeType, budgetPolicies.scopeId);+ // Each scope commits independently: deleted targets and a failed scope+ // must not roll back recovery or cancellation delivery for other work.+ for (const scope of scopes) {+ try {+ await mutate(scope.companyId, (service) => service.reconcileScope(scope.companyId, scope.scopeType as BudgetScopeType, scope.scopeId));+ } catch (error) {+ if (error instanceof HttpError && error.status === 404) continue;+ logger.warn({ err: error, ...scope }, "Budget scope recovery pending; continuing remaining scopes");+ }+ }+ },+ upsertPolicy: (companyId: string, input: BudgetPolicyUpsertInput, actorUserId: string | null) =>+ mutate(companyId, (service) => service.upsertPolicy(companyId, input, actorUserId)),+ evaluateCostEvent: (event: typeof costEvents.$inferSelect) =>+ mutate(event.companyId, (service) => service.evaluateCostEvent(event)),+ getInvocationBlock: (companyId: string, agentId: string, context?: { issueId?: string | null; projectId?: string | null }) =>+ mutate(companyId, (service) => service.getInvocationBlock(companyId, agentId, context)),+ resolveIncident: (companyId: string, incidentId: string, input: BudgetIncidentResolutionInput, actorUserId: string) =>+ mutate(companyId, (service) => service.resolveIncident(companyId, incidentId, input, actorUserId)),+ };+}diff --git a/server/src/services/codex-pricing.ts b/server/src/services/codex-pricing.tsnew file mode 100644index 0000000000..b5d6c4df6b--- /dev/null+++ b/server/src/services/codex-pricing.ts@@ -0,0 +1,98 @@+import { centsToUsd, unitsToCents, usdToUnits } from "@paperclipai/shared";+import type { AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";++// Immutable, reviewed rate card. Existing receipts retain their selected rates.+// https://developers.openai.com/api/docs/pricing (retrieved 2026-09-30)+const VERSION = "openai-standard-2026-09-30";+const RATES: Record<string, readonly [string, string, string, string]> = {+ "gpt-6-astra": ["10", "1", "12.5", "50"],+ "gpt-6-sol": ["2", "0.2", "2.5", "10"],+ "gpt-6.1-sol": ["2", "0.1", "2.5", "10"],+ "gpt-6-luna": ["0.1", "0.01", "0.125", "0.5"],+ "gpt-5.6-sol": ["4", "0.4", "5", "20"],+};++/** Price new, direct-API receipts only. A token-price estimate is not an invoice.+ * Run totals cannot establish per-request context length or cache-write splits;+ * preserve those assumptions instead of inferring a long request from a long run. */+export function priceCodexReceipt(+ receipt: AdapterUsageCheckpoint,+): AdapterUsageCheckpoint {+ if (+ !receipt.complete ||+ receipt.costUsd != null ||+ receipt.costUsdExact != null ||+ receipt.cacheAdjustedCostUsd != null ||+ receipt.provider !== "openai" ||+ receipt.biller !== "openai" ||+ !["api", "metered_api"].includes(receipt.billingType ?? "") ||+ receipt.usageBasis !== "per_run" ||+ !receipt.usage ||+ receipt.usageByModel?.length+ )+ return receipt;+ const model = receipt.model ?? "";+ const rates = Object.hasOwn(RATES, model) ? RATES[model] : undefined;+ if (!rates) return receipt;+ const usage = receipt.usage;+ const counts = [+ usage.inputTokens - (usage.cacheWriteTokens ?? 0),+ usage.cachedInputTokens ?? 0,+ usage.cacheWriteTokens ?? 0,+ usage.outputTokens,+ ];+ if (counts.some((n) => !Number.isSafeInteger(n) || n < 0)) return receipt;+ const context = receipt.pricingContext;+ if (+ context?.serviceTier &&+ !["standard", "default", "priority", "fast", "flex", "batch"].includes(+ context.serviceTier,+ )+ )+ return receipt;+ const tierNumerator =+ context?.serviceTier === "priority" || context?.serviceTier === "fast"+ ? 2n+ : 1n;+ const tierDenominator =+ context?.serviceTier === "flex" || context?.serviceTier === "batch"+ ? 2n+ : 1n;+ const units = counts.reduce((total, count, index) => {+ const longNumerator =+ context?.contextTier === "long" ? (index === 3 ? 3n : 4n) : 2n;+ return (+ total ++ BigInt(count) * usdToUnits(rates[index]) * tierNumerator * longNumerator+ );+ }, 0n);+ const divisor = 1_000_000n * tierDenominator * 2n;+ const costCents = unitsToCents((units + divisor / 2n) / divisor);+ const assumptions = [+ !context?.serviceTier+ ? "standard processing assumed"+ : `${context.serviceTier} processing`,+ !context?.contextTier+ ? "short per-request context assumed"+ : `${context.contextTier} per-request context`,+ usage.cacheWriteTokens === undefined+ ? "cache writes not separately reported"+ : "cache writes reported",+ ];+ return {+ ...receipt,+ costUsdExact: centsToUsd(costCents),+ costStatus: "estimated",+ pricingProvenance: {+ source: "rate_card",+ version: VERSION,+ evidence: `https://developers.openai.com/api/docs/pricing; ${assumptions.join("; ")}`,+ inputCentsPerMillion: unitsToCents(usdToUnits(rates[0])),+ cachedInputCentsPerMillion: unitsToCents(usdToUnits(rates[1])),+ cacheWriteCentsPerMillion: unitsToCents(usdToUnits(rates[2])),+ outputCentsPerMillion: unitsToCents(usdToUnits(rates[3])),+ serviceTier: context?.serviceTier ?? "standard",+ contextTier: context?.contextTier ?? "short",+ },+ };+}diff --git a/server/src/services/companies.ts b/server/src/services/companies.tsindex b0838f14ac..6107065242 100644--- a/server/src/services/companies.ts+++ b/server/src/services/companies.ts@@ -1,3 +1,5 @@+import { publishAccountingActivities } from "./accounting-transaction.js";+import { budgetServiceInTransaction, deliverBudgetEnforcement, type BudgetServiceHooks } from "./budgets.js";import { and, count, eq, gte, inArray, isNull, lt, notInArray, sql } from "drizzle-orm";import type { Db } from "@paperclipai/db";import {@@ -18,6 +20,8 @@ import {heartbeatRunEvents,costEvents,financeEvents,+ budgetPolicies,+ budgetIncidents,issueReadStates,approvalComments,approvals,@@ -47,7 +51,7 @@ import {} from "./issue-prefix.js";import { environmentService } from "./environments.js";import { heartbeatService } from "./heartbeat.js";-import { logActivity } from "./activity-log.js";+import { logActivity, type ActivityPublication } from "./activity-log.js";import { builtInAgentService } from "./built-in-agents.js";@@ -66,7 +70,7 @@ const SYSTEM_COMPANY_ACTOR: CompanyActivityActor = {runId: null,};-export function companyService(db: Db) {+export function companyService(db: Db, budgetHooks: BudgetServiceHooks = {}) {const environmentsSvc = environmentService(db);const heartbeat = heartbeatService(db);const builtInAgents = builtInAgentService(db);@@ -332,12 +336,16 @@ export function companyService(db: Db) {data: Partial<typeof companies.$inferInsert> & { logoAssetId?: string | null },actor: CompanyActivityActor = SYSTEM_COMPANY_ACTOR,) => {+ const budgetPublications: ActivityPublication[] = [];const result = await db.transaction(async (tx) => {const existing = await getCompanyQuery(tx).where(eq(companies.id, id)).then((rows) => rows[0] ?? null);if (!existing) return null;+ if (data.budgetMonthlyCents !== undefined) {+ await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, id)).for("no key update");+ }const { logoAssetId, ...companyPatch } = data;const willReactivate = existing.status !== "active" && companyPatch.status === "active";const willArchive = existing.status !== "archived" && companyPatch.status === "archived";@@ -431,6 +439,13 @@ export function companyService(db: Db) {await tx.delete(assets).where(eq(assets.id, existing.logoAssetId));}+ if (data.budgetMonthlyCents !== undefined) {+ await budgetServiceInTransaction(tx as unknown as Db, budgetPublications).upsertPolicy(id, {+ scopeType: "company", scopeId: id, amount: data.budgetMonthlyCents, isActive: data.budgetMonthlyCents > 0, windowKind: "calendar_month_utc",+ }, actor.actorType === "user" ? actor.actorId : null);+ const [budgetUpdated] = await tx.select().from(companies).where(eq(companies.id, id));+ Object.assign(updated, budgetUpdated);+ }const [hydrated] = await hydrateCompanySpend([{...updated,logoAssetId: logoAssetId === undefined ? existing.logoAssetId : logoAssetId,@@ -448,6 +463,8 @@ export function companyService(db: Db) {};});if (!result) return null;+ publishAccountingActivities(id, budgetPublications);+ if (data.budgetMonthlyCents !== undefined) await deliverBudgetEnforcement(db, budgetHooks, id);// Post-commit, fire-and-forget, and BEFORE any finalization that// could throw: a Cloud-pinned primary company that crossed the// archived boundary (either direction) rings the harness so the@@ -537,6 +554,18 @@ export function companyService(db: Db) {remove: (id: string) =>db.transaction(async (tx) => {+ // Exclude accounting writers before taking child locks. KEY SHARE must+ // remain compatible: native writers can already hold a child row while+ // saving a company-scoped result. FOR UPDATE would deadlock that save.+ const [existing] = await tx.select({ id: companies.id }).from(companies)+ .where(eq(companies.id, id)).for("no key update");+ if (!existing) return null;+ // Finance can reference costs and both can reference runs. Incidents+ // reference policies and approvals; delete these dependents first.+ await tx.delete(financeEvents).where(eq(financeEvents.companyId, id));+ await tx.delete(costEvents).where(eq(costEvents.companyId, id));+ await tx.delete(budgetIncidents).where(eq(budgetIncidents.companyId, id));+ await tx.delete(budgetPolicies).where(eq(budgetPolicies.companyId, id));// Delete from child tables in dependency orderconst companyRunIds = await tx.select({ id: heartbeatRuns.id })@@ -557,8 +586,6 @@ export function companyService(db: Db) {await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id));await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id));await tx.delete(issueComments).where(eq(issueComments.companyId, id));- await tx.delete(costEvents).where(eq(costEvents.companyId, id));- await tx.delete(financeEvents).where(eq(financeEvents.companyId, id));await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));await tx.delete(approvals).where(eq(approvals.companyId, id));await tx.delete(companySecrets).where(eq(companySecrets.companyId, id));diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.tsindex 98d5400060..0db8d650ff 100644--- a/server/src/services/company-skills.ts+++ b/server/src/services/company-skills.ts@@ -6623,7 +6623,7 @@ export function companySkillService(db: Db) {const rows = await db.select({issueId: costEvents.issueId,- costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,+ costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::double precision`,inputTokens: sql<number>`coalesce(sum(${costEvents.inputTokens}), 0)::int`,cachedInputTokens: sql<number>`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`,outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::int`,diff --git a/server/src/services/cost-date-range.ts b/server/src/services/cost-date-range.tsnew file mode 100644index 0000000000..c7f60b9006--- /dev/null+++ b/server/src/services/cost-date-range.ts@@ -0,0 +1,12 @@+export interface CostDateRange {+ from?: Date;+ to?: Date;+ allTime?: boolean;+}++/** Default reports match the UTC month used by monetary budgets. Explicit+ * bounds preserve the existing inclusive API; all-time must be requested. */+export function resolveCostDateRange(range?: CostDateRange, now = new Date()): CostDateRange {+ if (range?.allTime || range?.from || range?.to) return range;+ return { from: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)), to: now };+}diff --git a/server/src/services/costs.ts b/server/src/services/costs.tsindex 1dd0144f7d..92aca5b858 100644--- a/server/src/services/costs.ts+++ b/server/src/services/costs.ts@@ -1,21 +1,32 @@-import { agentAvatarUrl, resolveAgentAppearance } from "@paperclipai/shared";-import { and, desc, eq, gte, isNotNull, isNull, lt, lte, sql } from "drizzle-orm";+import { receiptFingerprint } from "./receipt-fingerprint.js";+import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, normalizeCents, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";+import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, ne, sql } from "drizzle-orm";import { alias } from "drizzle-orm/pg-core";import type { Db } from "@paperclipai/db";-import { activityLog, agents, companies, costEvents, heartbeatRuns, issues, projects } from "@paperclipai/db";-import { notFound, unprocessable } from "../errors.js";-import { budgetService, type BudgetServiceHooks } from "./budgets.js";+import { activityLog, agents, agentRuntimeState, authUsers, companies, companyMemberships, costEvents, heartbeatRuns, issues, projects, goals } from "@paperclipai/db";+import { notFound, unprocessable, conflict } from "../errors.js";+import { budgetService, budgetServiceInTransaction, type BudgetServiceHooks } from "./budgets.js";+import { logActivity, type LogActivityInput, type ActivityPublication } from "./activity-log.js";+import { withAccountingReadSnapshot, withAccountingTransaction } from "./accounting-transaction.js";import { visibleIssueCondition } from "./issue-visibility.js";-export interface CostDateRange {- from?: Date;- to?: Date;-}+import { resolveCostDateRange, type CostDateRange } from "./cost-date-range.js";+export type { CostDateRange } from "./cost-date-range.js";const METERED_BILLING_TYPE = "metered_api";const SUBSCRIPTION_BILLING_TYPES = ["subscription_included", "subscription_overage"] as const;-function sumAsNumber(column: typeof costEvents.costCents | typeof costEvents.inputTokens | typeof costEvents.cachedInputTokens | typeof costEvents.outputTokens) {+// Pre-receipt Codex events stored cache reads inside input; Pi/OpenCode used+// provider-qualified model IDs and already excluded cache reads. Normalize each+// historical row before aggregation so mixed old/new groups share the current+// exclusive-input contract. Preserve the original ledger and monetary amounts.+const ordinaryInputTokens = sql<number>`case+ when ${costEvents.receiptHash} is null and ${costEvents.provider} = 'openai'+ and ${costEvents.model} not like 'openai/_%'+ then greatest(0, ${costEvents.inputTokens} - ${costEvents.cachedInputTokens})+ else ${costEvents.inputTokens} end`;++function sumAsNumber(column: typeof costEvents.costCents | typeof costEvents.inputTokens | typeof costEvents.cachedInputTokens | typeof costEvents.outputTokens | ReturnType<typeof sql>) {return sql<number>`coalesce(sum(${column}), 0)::double precision`;}@@ -28,6 +39,26 @@ function currentUtcMonthWindow(now = new Date()) {};}+/** Increment an initialized month under the company lock. On upgrade or UTC+ * rollover, initialize from the ledger in the same transaction exactly once.+ * Reports, budgets and the integrity checker continue reading the ledger. */+export async function updateMonthlySpendProjections(db: Db, companyId: string, agentId: string, amountCents: MoneyInput, occurredAt: Date) {+ const { start, end } = currentUtcMonthWindow();+ const month = start.toISOString().slice(0, 10);+ const delta = occurredAt >= start && occurredAt < end ? normalizeCents(amountCents) : "0.0000000";+ for (const table of [companies, agents] as const) {+ const id = table === companies ? companyId : agentId;+ const companyCondition = table === companies ? eq(companies.id, companyId) : eq(agents.companyId, companyId);+ await db.update(table).set({+ spentMonthlyCents: sql`case when ${table.spendMonthUtc} = ${month} then ${table.spentMonthlyCents} + ${delta}::numeric else (+ select coalesce(sum(${costEvents.costCents}),0) from ${costEvents} where ${costEvents.companyId} = ${companyId}+ and ${costEvents.occurredAt} >= ${start.toISOString()}::timestamptz and ${costEvents.occurredAt} < ${end.toISOString()}::timestamptz+ ${table === agents ? sql`and ${costEvents.agentId} = ${agentId}` : sql``}) end`,+ spendMonthUtc: month, updatedAt: new Date(),+ }).where(and(eq(table.id, id), companyCondition));+ }+}+export async function getMonthlySpendTotal(db: Db,scope: { companyId: string; agentId?: string | null },@@ -50,60 +81,88 @@ export async function getMonthlySpendTotal(return Number(row?.total ?? 0);}+export async function createCostEventInTransaction(db: Db, companyId: string, data: Omit<typeof costEvents.$inferInsert, "companyId" | "receiptHash" | "costCents"> & { costCents: MoneyInput }, publications: ActivityPublication[] = [], actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId">) {+ const parsed = createCostEventSchema.safeParse({ ...data, occurredAt: data.occurredAt.toISOString() });+ if (!parsed.success) throw unprocessable("Invalid cost receipt", parsed.error.flatten());+ const values = {+ ...parsed.data,+ issueId: parsed.data.issueId ?? null,+ projectId: parsed.data.projectId ?? null,+ goalId: parsed.data.goalId ?? null,+ heartbeatRunId: parsed.data.heartbeatRunId ?? null,+ billingCode: parsed.data.billingCode ?? null,+ idempotencyKey: parsed.data.idempotencyKey ?? null,+ costCents: normalizeCents(parsed.data.costCents),+ occurredAt: new Date(parsed.data.occurredAt),+ };+ const receiptHash = receiptFingerprint(values);+ // Older receipts hashed the numeric API value. Retain replay compatibility+ // only when the decimal value survives that representation exactly.+ let legacyHash: string | null = null;+ try {+ if (normalizeCents(Number(values.costCents)) === values.costCents) legacyHash = receiptFingerprint({ ...values, costCents: Number(values.costCents) });+ } catch { /* The legacy number may round beyond the decimal storage limit. */ }+ if (values.idempotencyKey) {+ const [existing] = await db.select().from(costEvents).where(and(+ eq(costEvents.companyId, companyId), eq(costEvents.idempotencyKey, values.idempotencyKey),+ ));+ if (existing) {+ if (existing.receiptHash !== receiptHash && existing.receiptHash !== legacyHash) throw conflict("Idempotency key already used for a different cost receipt");+ const [exact] = await db.select({ costCents: sql<string>`${costEvents.costCents}::text` }).from(costEvents).where(eq(costEvents.id, existing.id));+ return { ...existing, costCentsExact: normalizeCents(exact.costCents) };+ }+ }+ const links = [+ [agents, values.agentId, "Agent"], [issues, values.issueId, "Issue"],+ [projects, values.projectId, "Project"], [goals, values.goalId, "Goal"],+ [heartbeatRuns, values.heartbeatRunId, "Heartbeat run"],+ ] as const;+ for (const [table, id, label] of links) {+ if (!id) continue;+ const [row] = await db.select({ companyId: table.companyId }).from(table).where(eq(table.id, id));+ if (!row) throw notFound(`${label} not found`);+ if (row.companyId !== companyId) throw unprocessable(`${label} does not belong to company`);+ }+ if (values.heartbeatRunId) {+ const [run] = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(eq(heartbeatRuns.id, values.heartbeatRunId));+ if (run.agentId !== values.agentId) throw unprocessable("Heartbeat run does not belong to agent");+ }+ const [event] = await db.insert(costEvents).values({ ...values, costCents: sql`${values.costCents}::numeric`, reportedCostCents: values.costCents, id: data.id, companyId, receiptHash }).returning();+ await updateMonthlySpendProjections(db, companyId, event.agentId, values.costCents, event.occurredAt);+ // Separately reported charges linked to an already-accounted run contribute+ // to lifetime totals too. Before acknowledgement, accountRunCost includes+ // all of the run's events atomically when it initializes the projection.+ if (event.heartbeatRunId) {+ const [run] = await db.select({ acknowledged: heartbeatRuns.costAccountedAt, version: heartbeatRuns.accountingProjectionVersion })+ .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, event.heartbeatRunId), eq(heartbeatRuns.companyId, companyId)));+ if (run.acknowledged && run.version === "v2") await db.update(agentRuntimeState).set({+ totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${values.costCents}::numeric`,+ totalInputTokens: sql`${agentRuntimeState.totalInputTokens} + ${event.inputTokens}`,+ totalCachedInputTokens: sql`${agentRuntimeState.totalCachedInputTokens} + ${event.cachedInputTokens}`,+ totalOutputTokens: sql`${agentRuntimeState.totalOutputTokens} + ${event.outputTokens}`,+ updatedAt: new Date(),+ }).where(and(eq(agentRuntimeState.agentId, event.agentId), eq(agentRuntimeState.companyId, companyId)));+ }+ await budgetServiceInTransaction(db, publications).evaluateCostEvent(event);+ await logActivity(db, {+ companyId, actorType: actor?.actorType ?? "system", actorId: actor?.actorId ?? "cost_accounting", agentId: actor?.agentId ?? event.agentId,+ runId: event.heartbeatRunId, action: "cost.reported", entityType: "cost_event", entityId: event.id,+ details: { costCents: event.costCents, costCentsExact: values.costCents, model: event.model, costStatus: event.costStatus },+ }, publications);+ return { ...event, costCentsExact: values.costCents };+}+export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {const budgets = budgetService(db, budgetHooks);return {- createEvent: async (companyId: string, data: Omit<typeof costEvents.$inferInsert, "companyId">) => {- const agent = await db- .select()- .from(agents)- .where(eq(agents.id, data.agentId))- .then((rows) => rows[0] ?? null);-- if (!agent) throw notFound("Agent not found");- if (agent.companyId !== companyId) {- throw unprocessable("Agent does not belong to company");- }-- const event = await db- .insert(costEvents)- .values({- ...data,- companyId,- biller: data.biller ?? data.provider,- billingType: data.billingType ?? "unknown",- cachedInputTokens: data.cachedInputTokens ?? 0,- })- .returning()- .then((rows) => rows[0]);-- const [agentMonthSpend, companyMonthSpend] = await Promise.all([- getMonthlySpendTotal(db, { companyId, agentId: event.agentId }),- getMonthlySpendTotal(db, { companyId }),- ]);-- await db- .update(agents)- .set({- spentMonthlyCents: agentMonthSpend,- updatedAt: new Date(),- })- .where(eq(agents.id, event.agentId));-- await db- .update(companies)- .set({- spentMonthlyCents: companyMonthSpend,- updatedAt: new Date(),- })- .where(eq(companies.id, companyId));-- await budgets.evaluateCostEvent(event);-+ createEvent: async (companyId: string, data: Omit<typeof costEvents.$inferInsert, "companyId" | "receiptHash" | "costCents"> & { costCents: MoneyInput }, actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId">) => {+ if (data.idempotencyKey?.startsWith("heartbeat:")) throw unprocessable("The heartbeat idempotency namespace is reserved for run receipts");+ const event = await withAccountingTransaction(db, companyId, (tx, publications) => createCostEventInTransaction(tx, companyId, data, publications, actor));+ await budgets.deliverPendingEnforcement(companyId);return event;},- summary: async (companyId: string, range?: CostDateRange) => {+ summary: async (companyId: string, range?: CostDateRange) => withAccountingReadSnapshot(db, companyId, async (db) => {const company = await db.select().from(companies)@@ -112,17 +171,28 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {if (!company) throw notFound("Company not found");+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));- const [{ total }] = await db+ const [{ total, totalExact, eventCount, unpricedEventCount, estimatedEventCount }] = await db.select({+ eventCount: sql<number>`count(*)::int`,+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,+ unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,total: sumAsNumber(costEvents.costCents),+ totalExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,}).from(costEvents).where(and(...conditions));+ const pendingConditions = [eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.costAccountingPending, true),+ inArray(heartbeatRuns.status, ["succeeded", "failed", "timed_out", "cancelled", "interrupted"])];+ if (range?.from) pendingConditions.push(sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.createdAt}) >= ${range.from.toISOString()}::timestamptz`);+ if (range?.to) pendingConditions.push(sql`coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.createdAt}) <= ${range.to.toISOString()}::timestamptz`);+ const [pending] = await db.select({ count: sql<number>`count(*)::int` }).from(heartbeatRuns).where(and(...pendingConditions));+ const pendingRunCount = pending?.count ?? 0;const spendCents = Number(total);const utilization =company.budgetMonthlyCents > 0@@ -131,11 +201,17 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {return {companyId,+ eventCount,+ unpricedEventCount,+ estimatedEventCount,+ pendingRunCount,+ pricingComplete: unpricedEventCount === 0 && pendingRunCount === 0,spendCents,+ spendCentsExact: normalizeCents(totalExact),budgetCents: company.budgetMonthlyCents,utilizationPercent: Number(utilization.toFixed(2)),};- },+ }),issueTreeSummary: async (companyId: string,@@ -238,7 +314,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {.select({issueCount: sql<number>`count(distinct ${issues.id})::int`,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),})@@ -270,6 +347,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {issueCount: Number(costRow?.issueCount ?? 0),includeDescendants: true,costCents: Number(costRow?.costCents ?? 0),+ costCentsExact: normalizeCents(costRow?.costCentsExact ?? 0),inputTokens: Number(costRow?.inputTokens ?? 0),cachedInputTokens: Number(costRow?.cachedInputTokens ?? 0),outputTokens: Number(costRow?.outputTokens ?? 0),@@ -278,7 +356,79 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {};},+ byUser: (companyId: string, range?: CostDateRange): Promise<CostByUserReport> => withAccountingReadSnapshot(db, companyId, async tx => {+ // Keep membership, identity and spend in one non-blocking read snapshot.+ const members = await tx.select({+ userId: companyMemberships.principalId,+ status: companyMemberships.status,+ userName: authUsers.name,+ userImage: authUsers.image,+ }).from(companyMemberships)+ .leftJoin(authUsers, eq(authUsers.id, companyMemberships.principalId))+ .where(and(+ eq(companyMemberships.companyId, companyId),+ eq(companyMemberships.principalType, "user"),+ ne(companyMemberships.principalId, "local-board"),+ ));+ const activeMembers = members.filter(member => member.status === "active");+ const activeUserCount = activeMembers.length;++ const bounds = resolveCostDateRange(range);+ const conditions = [eq(costEvents.companyId, companyId)];+ if (bounds.from) conditions.push(gte(costEvents.occurredAt, bounds.from));+ if (bounds.to) conditions.push(lte(costEvents.occurredAt, bounds.to));+ const totals = await tx.select({+ userId: companyMemberships.principalId,+ eventCount: sql<number>`count(*)::int`,+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,+ unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,+ costCents: sumAsNumber(costEvents.costCents),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),+ cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),+ outputTokens: sumAsNumber(costEvents.outputTokens),+ runCount: sql<number>`count(distinct ${heartbeatRuns.id})::int`,+ }).from(costEvents)+ .leftJoin(heartbeatRuns, and(+ eq(heartbeatRuns.id, costEvents.heartbeatRunId),+ eq(heartbeatRuns.companyId, costEvents.companyId),+ eq(heartbeatRuns.agentId, costEvents.agentId),+ ))+ // Never resolve names through a foreign-company run or membership. Retain+ // former members' historical spend; missing attribution remains in the total.+ // The synthetic Board principal is not a person. Any historical charges+ // attached to it remain in Unattributed so the report still reconciles.+ .leftJoin(companyMemberships, and(+ eq(companyMemberships.companyId, companyId),+ eq(companyMemberships.principalType, "user"),+ ne(companyMemberships.principalId, "local-board"),+ eq(companyMemberships.principalId, heartbeatRuns.responsibleUserId),+ ))+ .where(and(...conditions))+ .groupBy(companyMemberships.principalId)+ .orderBy(desc(sql`sum(${costEvents.costCents})`), companyMemberships.principalId);+ const directory = new Map(members.map(member => [member.userId, member]));+ const rows: CostByUserReport["rows"] = totals.map(row => ({+ ...row,+ userName: row.userId ? directory.get(row.userId)?.userName ?? "Former user" : null,+ userImage: row.userId ? directory.get(row.userId)?.userImage ?? null : null,+ costCentsExact: normalizeCents(row.costCentsExact),+ }));+ const represented = new Set(rows.map(row => row.userId));+ for (const member of activeMembers.sort((a, b) => (a.userName ?? a.userId).localeCompare(b.userName ?? b.userId))) {+ if (represented.has(member.userId)) continue;+ rows.push({+ userId: member.userId, userName: member.userName ?? "Unknown user", userImage: member.userImage,+ eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0,+ costCents: 0, costCentsExact: "0.0000000",+ inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, runCount: 0,+ });+ }+ return { activeUserCount, rows };+ }),+byAgent: async (companyId: string, range?: CostDateRange) => {+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));@@ -289,8 +439,11 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {agentName: agents.name,agentAppearance: agents.appearance,agentStatus: agents.status,+ eventCount: sql<number>`count(*)::int`,+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),apiRunCount:@@ -300,7 +453,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {subscriptionCachedInputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::double precision`,subscriptionInputTokens:- sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::double precision`,+ sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${ordinaryInputTokens} else 0 end), 0)::double precision`,subscriptionOutputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::double precision`,})@@ -316,6 +469,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {},byProvider: async (companyId: string, range?: CostDateRange) => {+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));@@ -327,7 +481,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {billingType: costEvents.billingType,model: costEvents.model,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),apiRunCount:@@ -337,7 +492,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {subscriptionCachedInputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::double precision`,subscriptionInputTokens:- sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::double precision`,+ sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${ordinaryInputTokens} else 0 end), 0)::double precision`,subscriptionOutputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::double precision`,})@@ -348,6 +503,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {},byBiller: async (companyId: string, range?: CostDateRange) => {+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));@@ -356,7 +512,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {.select({biller: costEvents.biller,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),apiRunCount:@@ -366,7 +523,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {subscriptionCachedInputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::double precision`,subscriptionInputTokens:- sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::double precision`,+ sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${ordinaryInputTokens} else 0 end), 0)::double precision`,subscriptionOutputTokens:sql<number>`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::double precision`,providerCount: sql<number>`count(distinct ${costEvents.provider})::int`,@@ -390,15 +547,17 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {{ label: "7d", hours: 168 },] as const;+ const now = new Date();const results = await Promise.all(windows.map(async ({ label, hours }) => {- const since = new Date(Date.now() - hours * 60 * 60 * 1000);+ const since = new Date(now.getTime() - hours * 60 * 60 * 1000);const rows = await db.select({provider: costEvents.provider,biller: sql<string>`case when count(distinct ${costEvents.biller}) = 1 then min(${costEvents.biller}) else 'mixed' end`,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),})@@ -407,6 +566,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {and(eq(costEvents.companyId, companyId),gte(costEvents.occurredAt, since),+ lte(costEvents.occurredAt, now),),).groupBy(costEvents.provider)@@ -418,6 +578,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {window: label as string,windowHours: hours,costCents: row.costCents,+ costCentsExact: normalizeCents(row.costCentsExact),inputTokens: row.inputTokens,cachedInputTokens: row.cachedInputTokens,outputTokens: row.outputTokens,@@ -429,6 +590,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {},byAgentModel: async (companyId: string, range?: CostDateRange) => {+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));@@ -446,8 +608,11 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {biller: costEvents.biller,billingType: costEvents.billingType,model: costEvents.model,+ eventCount: sql<number>`count(*)::int`,+ estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,costCents: sumAsNumber(costEvents.costCents),- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),})@@ -473,9 +638,9 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {byProject: async (companyId: string, range?: CostDateRange) => {const issueIdAsText = sql<string>`${issues.id}::text`;const runProjectLinks = db- .selectDistinctOn([activityLog.runId, issues.projectId], {+ .select({runId: activityLog.runId,- projectId: issues.projectId,+ projectId: sql<string>`min(${issues.projectId}::text)::uuid`.as("linked_project_id"),}).from(activityLog).innerJoin(@@ -493,10 +658,12 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {isNotNull(issues.projectId),),)- .orderBy(activityLog.runId, issues.projectId, desc(activityLog.createdAt))+ .groupBy(activityLog.runId)+ .having(sql`count(distinct ${issues.projectId}) = 1`).as("run_project_links");- const effectiveProjectId = sql<string | null>`coalesce(${costEvents.projectId}, ${runProjectLinks.projectId})`;+ const effectiveProjectId = sql<string | null>`coalesce(${costEvents.projectId}, case when ${costEvents.receiptHash} is null then ${runProjectLinks.projectId} end)`;+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(costEvents.companyId, companyId)];if (range?.from) conditions.push(gte(costEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(costEvents.occurredAt, range.to));@@ -505,18 +672,19 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {return db.select({- projectId: effectiveProjectId,+ projectId: projects.id,projectName: projects.name,costCents: costCentsExpr,- inputTokens: sumAsNumber(costEvents.inputTokens),+ costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,+ inputTokens: sumAsNumber(ordinaryInputTokens),cachedInputTokens: sumAsNumber(costEvents.cachedInputTokens),outputTokens: sumAsNumber(costEvents.outputTokens),}).from(costEvents).leftJoin(runProjectLinks, eq(costEvents.heartbeatRunId, runProjectLinks.runId))- .innerJoin(projects, sql`${projects.id} = ${effectiveProjectId}`)- .where(and(...conditions, sql`${effectiveProjectId} is not null`))- .groupBy(effectiveProjectId, projects.name)+ .leftJoin(projects, and(eq(projects.companyId, companyId), sql`${projects.id} = ${effectiveProjectId}`))+ .where(and(...conditions))+ .groupBy(projects.id, projects.name).orderBy(desc(costCentsExpr));},};diff --git a/server/src/services/dashboard.ts b/server/src/services/dashboard.tsindex 57ae04dac7..9da5d08aa4 100644--- a/server/src/services/dashboard.ts+++ b/server/src/services/dashboard.ts@@ -1,4 +1,4 @@-import { and, eq, gte, sql } from "drizzle-orm";+import { and, eq, gte, lte, sql } from "drizzle-orm";import type { Db } from "@paperclipai/db";import { agents, approvals, companies, costEvents, heartbeatRuns, issues } from "@paperclipai/db";import { notFound } from "../errors.js";@@ -96,6 +96,7 @@ export function dashboardService(db: Db) {and(eq(costEvents.companyId, companyId),gte(costEvents.occurredAt, monthStart),+ lte(costEvents.occurredAt, now),),));diff --git a/server/src/services/email-channels.ts b/server/src/services/email-channels.tsindex de3e9eb300..62db025fd6 100644--- a/server/src/services/email-channels.ts+++ b/server/src/services/email-channels.ts@@ -1,7 +1,7 @@import { HttpError } from "../errors.js";import { createHash, randomUUID } from "node:crypto";import WebSocket from "ws";-import { and, asc, eq, inArray, isNull, ne, sql } from "drizzle-orm";+import { and, asc, eq, getTableColumns, inArray, isNull, ne, sql } from "drizzle-orm";import {type Db,agents,@@ -27,6 +27,7 @@ import {companyMemberships,instanceUserRoles,} from "@paperclipai/db";+import { compareCents } from "@paperclipai/shared";import type {AgentPermissions,EmailEndpointSetupInput,@@ -522,7 +523,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {);await authorizeRead(endpoint.companyId, issueId, actor);const [agent] = await db- .select()+ .select({ ...getTableColumns(agents), spentMonthlyCentsExact: sql<string>`${agents.spentMonthlyCents}::text` }).from(agents).where(and(@@ -534,7 +535,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {!agent ||["paused", "terminated", "pending_approval"].includes(agent.status) ||(agent.budgetMonthlyCents > 0 &&- agent.spentMonthlyCents >= agent.budgetMonthlyCents)+ compareCents(agent.spentMonthlyCentsExact, agent.budgetMonthlyCents) >= 0))throw forbidden("Agent is not available to send email");if (!actor.runId)diff --git a/server/src/services/finance.ts b/server/src/services/finance.tsindex 766bea7b1f..7f38228173 100644--- a/server/src/services/finance.ts+++ b/server/src/services/finance.ts@@ -1,12 +1,14 @@-import { and, desc, eq, gte, lte, sql } from "drizzle-orm";+import { and, desc, eq, getTableColumns, gte, lte, sql } from "drizzle-orm";import type { Db } from "@paperclipai/db";import { agents, costEvents, financeEvents, goals, heartbeatRuns, issues, projects } from "@paperclipai/db";-import { notFound, unprocessable } from "../errors.js";+import { notFound, unprocessable, conflict } from "../errors.js";-export interface FinanceDateRange {- from?: Date;- to?: Date;-}+import { resolveCostDateRange, type CostDateRange as FinanceDateRange } from "./cost-date-range.js";+import { createFinanceEventSchema, normalizeCents, subtractCents, type MoneyInput } from "@paperclipai/shared";+import { receiptFingerprint } from "./receipt-fingerprint.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { logActivity, type LogActivityInput, type ActivityPublication } from "./activity-log.js";+export type { CostDateRange as FinanceDateRange } from "./cost-date-range.js";async function assertBelongsToCompany(db: Db,@@ -28,19 +30,29 @@ async function assertBelongsToCompany(}function rangeConditions(companyId: string, range?: FinanceDateRange) {+ range = resolveCostDateRange(range);const conditions: ReturnType<typeof eq>[] = [eq(financeEvents.companyId, companyId)];if (range?.from) conditions.push(gte(financeEvents.occurredAt, range.from));if (range?.to) conditions.push(lte(financeEvents.occurredAt, range.to));return conditions;}-export function financeService(db: Db) {- const debitExpr = sql<number>`coalesce(sum(case when ${financeEvents.direction} = 'debit' then ${financeEvents.amountCents} else 0 end), 0)::double precision`;- const creditExpr = sql<number>`coalesce(sum(case when ${financeEvents.direction} = 'credit' then ${financeEvents.amountCents} else 0 end), 0)::double precision`;- const estimatedDebitExpr = sql<number>`coalesce(sum(case when ${financeEvents.direction} = 'debit' and ${financeEvents.estimated} = true then ${financeEvents.amountCents} else 0 end), 0)::double precision`;-- return {- createEvent: async (companyId: string, data: Omit<typeof financeEvents.$inferInsert, "companyId">) => {+export async function createFinanceEventInTransaction(tx: Db, publications: ActivityPublication[], companyId: string, data: Omit<typeof financeEvents.$inferInsert, "companyId" | "receiptHash" | "amountCents"> & { amountCents: MoneyInput }, actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId">) {+ const db = tx;+ const parsed = createFinanceEventSchema.safeParse({ ...data, occurredAt: data.occurredAt.toISOString() });+ if (!parsed.success) throw unprocessable("Invalid finance receipt", parsed.error.flatten());+ const values = { ...parsed.data, amountCents: normalizeCents(parsed.data.amountCents), occurredAt: new Date(parsed.data.occurredAt) };+ const receiptHash = receiptFingerprint(values);+ let legacyHash: string | null = null;+ try { if (normalizeCents(Number(values.amountCents)) === values.amountCents) legacyHash = receiptFingerprint({ ...values, amountCents: Number(values.amountCents) }); } catch { /* Decimal exceeds the legacy number range. */ }+ if (values.idempotencyKey) {+ const [existing] = await db.select().from(financeEvents).where(and(eq(financeEvents.companyId, companyId), eq(financeEvents.idempotencyKey, values.idempotencyKey)));+ if (existing) {+ if (existing.receiptHash !== receiptHash && existing.receiptHash !== legacyHash) throw conflict("Idempotency key already used for a different finance receipt");+ const [exact] = await db.select({ amount: sql<string>`${financeEvents.amountCents}::text` }).from(financeEvents).where(eq(financeEvents.id, existing.id));+ return { ...existing, amountCentsExact: normalizeCents(exact.amount) };+ }+ }if (data.agentId) await assertBelongsToCompany(db, agents, data.agentId, companyId, "Agent");if (data.issueId) await assertBelongsToCompany(db, issues, data.issueId, companyId, "Issue");if (data.projectId) await assertBelongsToCompany(db, projects, data.projectId, companyId, "Project");@@ -51,35 +63,60 @@ export function financeService(db: Db) {const event = await db.insert(financeEvents).values({- ...data,- companyId,- currency: data.currency ?? "USD",- direction: data.direction ?? "debit",- estimated: data.estimated ?? false,+ ...values, amountCents: sql`${values.amountCents}::numeric`, companyId, receiptHash, id: data.id,}).returning().then((rows) => rows[0]);- return event;- },+ await logActivity(db, {+ companyId, actorType: actor?.actorType ?? "system", actorId: actor?.actorId ?? "finance_accounting", agentId: actor?.agentId,+ action: "finance_event.reported", entityType: "finance_event", entityId: event.id,+ details: { amountCents: event.amountCents, amountCentsExact: values.amountCents, currency: event.currency, biller: event.biller, eventKind: event.eventKind, direction: event.direction },+ }, publications);+ return { ...event, amountCentsExact: values.amountCents };+}++export function financeService(db: Db) {+ const debitExpr = sql<string>`coalesce(sum(case when ${financeEvents.direction} = 'debit' and ${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report' then ${financeEvents.amountCents} else 0 end), 0)`;+ const creditExpr = sql<string>`coalesce(sum(case when ${financeEvents.direction} = 'credit' and ${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report' then ${financeEvents.amountCents} else 0 end), 0)`;+ const estimatedDebitExpr = sql<string>`coalesce(sum(case when ${financeEvents.direction} = 'debit' and ${financeEvents.estimated} = true and ${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report' then ${financeEvents.amountCents} else 0 end), 0)`;++ return {+ createEvent: async (companyId: string, data: Omit<typeof financeEvents.$inferInsert, "companyId" | "receiptHash" | "amountCents"> & { amountCents: MoneyInput }, actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId">) => withAccountingTransaction(db, companyId, (tx, publications) => createFinanceEventInTransaction(tx, publications, companyId, data, actor)),summary: async (companyId: string, range?: FinanceDateRange) => {const conditions = rangeConditions(companyId, range);- const [row] = await db+ const rows = await db.select({- debitCents: debitExpr,- creditCents: creditExpr,- estimatedDebitCents: estimatedDebitExpr,+ currency: financeEvents.currency,+ providerReportedCentsExact: sql<string>`coalesce(sum(case when ${financeEvents.metadataJson}->>'source' = 'provider_cost_report' then case when ${financeEvents.direction} = 'credit' then -${financeEvents.amountCents} else ${financeEvents.amountCents} end else 0 end), 0)::text`,+ debitCents: sql<number>`${debitExpr}::double precision`,+ debitCentsExact: sql<string>`${debitExpr}::text`,+ creditCents: sql<number>`${creditExpr}::double precision`,+ creditCentsExact: sql<string>`${creditExpr}::text`,+ estimatedDebitCents: sql<number>`${estimatedDebitExpr}::double precision`,+ estimatedDebitCentsExact: sql<string>`${estimatedDebitExpr}::text`,eventCount: sql<number>`count(*)::int`,}).from(financeEvents)- .where(and(...conditions));+ .where(and(...conditions))+ .groupBy(financeEvents.currency)+ .orderBy(financeEvents.currency);+ const row = rows.find((row) => row.currency === "USD");return {companyId,+ currency: "USD" as const,+ providerReportedCentsExact: normalizeCents(row?.providerReportedCentsExact ?? 0),+ providerReportedCents: Number(row?.providerReportedCentsExact ?? 0),+ currencies: rows.map((row) => ({ ...row, netCents: Number(subtractCents(row.debitCentsExact, row.creditCentsExact)), netCentsExact: subtractCents(row.debitCentsExact, row.creditCentsExact) })),debitCents: Number(row?.debitCents ?? 0),creditCents: Number(row?.creditCents ?? 0),- netCents: Number(row?.debitCents ?? 0) - Number(row?.creditCents ?? 0),+ netCents: Number(subtractCents(row?.debitCentsExact ?? 0, row?.creditCentsExact ?? 0)),+ netCentsExact: subtractCents(row?.debitCentsExact ?? 0, row?.creditCentsExact ?? 0),+ debitCentsExact: normalizeCents(row?.debitCentsExact ?? 0),+ creditCentsExact: normalizeCents(row?.creditCentsExact ?? 0),+ estimatedDebitCentsExact: normalizeCents(row?.estimatedDebitCentsExact ?? 0),estimatedDebitCents: Number(row?.estimatedDebitCents ?? 0),eventCount: Number(row?.eventCount ?? 0),};@@ -87,44 +124,56 @@ export function financeService(db: Db) {byBiller: async (companyId: string, range?: FinanceDateRange) => {const conditions = rangeConditions(companyId, range);+ conditions.push(sql`${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report'`);return db.select({+ currency: financeEvents.currency,biller: financeEvents.biller,- debitCents: debitExpr,- creditCents: creditExpr,- estimatedDebitCents: estimatedDebitExpr,+ debitCents: sql<number>`${debitExpr}::double precision`,+ debitCentsExact: sql<string>`${debitExpr}::text`,+ creditCents: sql<number>`${creditExpr}::double precision`,+ creditCentsExact: sql<string>`${creditExpr}::text`,+ estimatedDebitCents: sql<number>`${estimatedDebitExpr}::double precision`,+ estimatedDebitCentsExact: sql<string>`${estimatedDebitExpr}::text`,eventCount: sql<number>`count(*)::int`,kindCount: sql<number>`count(distinct ${financeEvents.eventKind})::int`,netCents: sql<number>`(${debitExpr} - ${creditExpr})::double precision`,+ netCentsExact: sql<string>`(${debitExpr} - ${creditExpr})::text`,}).from(financeEvents).where(and(...conditions))- .groupBy(financeEvents.biller)+ .groupBy(financeEvents.biller, financeEvents.currency).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::double precision`), financeEvents.biller);},byKind: async (companyId: string, range?: FinanceDateRange) => {const conditions = rangeConditions(companyId, range);+ conditions.push(sql`${financeEvents.metadataJson}->>'source' is distinct from 'provider_cost_report'`);return db.select({+ currency: financeEvents.currency,eventKind: financeEvents.eventKind,- debitCents: debitExpr,- creditCents: creditExpr,- estimatedDebitCents: estimatedDebitExpr,+ debitCents: sql<number>`${debitExpr}::double precision`,+ debitCentsExact: sql<string>`${debitExpr}::text`,+ creditCents: sql<number>`${creditExpr}::double precision`,+ creditCentsExact: sql<string>`${creditExpr}::text`,+ estimatedDebitCents: sql<number>`${estimatedDebitExpr}::double precision`,+ estimatedDebitCentsExact: sql<string>`${estimatedDebitExpr}::text`,eventCount: sql<number>`count(*)::int`,billerCount: sql<number>`count(distinct ${financeEvents.biller})::int`,netCents: sql<number>`(${debitExpr} - ${creditExpr})::double precision`,+ netCentsExact: sql<string>`(${debitExpr} - ${creditExpr})::text`,}).from(financeEvents).where(and(...conditions))- .groupBy(financeEvents.eventKind)+ .groupBy(financeEvents.eventKind, financeEvents.currency).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::double precision`), financeEvents.eventKind);},list: async (companyId: string, range?: FinanceDateRange, limit: number = 100) => {const conditions = rangeConditions(companyId, range);return db- .select()+ .select({ ...getTableColumns(financeEvents), amountCentsExact: sql<string>`${financeEvents.amountCents}::text` }).from(financeEvents).where(and(...conditions)).orderBy(desc(financeEvents.occurredAt), desc(financeEvents.createdAt))diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex 1bfc1cf4f7..75edc6d8f5 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -22,8 +22,11 @@ import {type NativeWorkspaceFinalizationOwnership,} from "./native-runtime/native-workspace-finalization-ownership.js";import { hasStopOnlyCleanup, settleStopOnlyCleanup } from "./sandbox-stop-and-retain.js";+import { reserveRunBudget } from "./budget-reservations.js";+import { accountRunCost, createCostAccountingReconciler } from "./run-cost-accounting.js";+import { createRunUsageRecorder } from "./usage-receipts.js";import { applyWorkspaceRestoreFailure } from "@paperclipai/adapter-utils/workspace-restore-result";-import { hasWorkspaceRestoreFailure } from "@paperclipai/shared";+import { compareCents, hasWorkspaceRestoreFailure } from "@paperclipai/shared";import { externalConversationStateSql, nonIdleSlackIssueCondition } from "./slack-conversation-state.js";import { settleSlackConversation } from "./slack-conversation-lifecycle.js";import { publicChatTaskUrl } from "./chat-task-url.js";@@ -90,7 +93,7 @@ import {} from "@paperclipai/adapter-utils/execution-target";import { agentService } from "./agents.js";import { agentInstructionWorkingCopyService, instructionWorkingCopyGuidance } from "./agent-instruction-working-copies.js";-import { normalizeLegacyRunnerProvider } from "@paperclipai/adapter-utils";+import { normalizeLegacyRunnerProvider, resolveManagedOpenAiBilling } from "@paperclipai/adapter-utils";import fs from "node:fs/promises";import path from "node:path";import { execFile as execFileCallback } from "node:child_process";@@ -318,7 +321,6 @@ import {appendWithByteCap,MAX_EXCERPT_BYTES,} from "../adapters/utils.js";-import { costService } from "./costs.js";import {authorizeChatConversationForBoundRun,isExternalChatWaitAuthorizationContention,@@ -350,7 +352,7 @@ import {import { reportRunFailure } from "./run-failure-report.js";import { collectRunFailureSecretValues, type RunFailureReportOptions } from "./run-failure-diagnostics.js";import { companySkillService } from "./company-skills.js";-import { budgetService, type BudgetEnforcementScope } from "./budgets.js";+import { budgetService, withCurrentBudgetEnforcement, type BudgetEnforcementScope } from "./budgets.js";import { secretService, type MissingRuntimeBinding } from "./secrets.js";import {resolveDefaultAgentWorkspaceDir,@@ -691,6 +693,7 @@ const HEARTBEAT_MAX_CONCURRENT_RUNS_MAX = 50;const LIVENESS_BOOKKEEPING_ACTIVITY_ACTIONS = ["environment.lease_acquired","environment.lease_released",+ "cost.reported",];const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";const EXTERNAL_ATTACHMENT_OMISSIONS_KEY = "externalAttachmentOmissions";@@ -5344,21 +5347,23 @@ function resolveLedgerBiller(result: AdapterExecutionResult): string {);}-function normalizeBilledCostCents(+export function normalizeBilledCostCents(costUsd: number | null | undefined,billingType: BillingType,): number {if (billingType === "subscription_included") return 0;if (typeof costUsd !== "number" || !Number.isFinite(costUsd)) return 0;- return Math.max(0, Math.round(costUsd * 100));+ return Math.max(0, Number((costUsd * 100).toFixed(7)));}export function resolveLedgerCostStatus(input: {costUsd: number | null | undefined;+ billingType?: BillingType;inputTokens: number;cachedInputTokens: number;outputTokens: number;}): CostStatus {+ if (input.billingType === "subscription_included") return "reported";// A paused turn can have neither a token receipt nor a cost receipt. Zero// normalized counters do not establish that its billed cost was zero.return typeof input.costUsd === "number" &&@@ -5564,12 +5569,13 @@ function readRawUsageTotals(usageJson: unknown): UsageTotals | null {};}-function deriveNormalizedUsageDelta(+export function normalizeAdapterRunUsage(current: UsageTotals | null,previous: UsageTotals | null,+ usageBasis?: "per_run" | "session_cumulative" | null,): UsageTotals | null {if (!current) return null;- if (!previous) return { ...current };+ if (!previous || usageBasis !== "session_cumulative") return { ...current };const inputTokens =current.inputTokens >= previous.inputTokens@@ -12172,7 +12178,7 @@ export function heartbeatService(// Adapters that declare per-run usage (e.g. the ACPX lane reports each// turn's tokens, not session totals) must not be session-delta'd, or// consecutive runs would be undercounted.- if (!sessionId || !rawUsage || usageBasis === "per_run") {+ if (!sessionId || !rawUsage || usageBasis !== "session_cumulative") {return {normalizedUsage: rawUsage,previousRawUsage: null as UsageTotals | null,@@ -12185,7 +12191,7 @@ export function heartbeatService(});const previousRawUsage = readRawUsageTotals(previousRun?.usageJson);return {- normalizedUsage: deriveNormalizedUsageDelta(rawUsage, previousRawUsage),+ normalizedUsage: normalizeAdapterRunUsage(rawUsage, previousRawUsage, usageBasis),previousRawUsage,derivedFromSessionTotals: previousRawUsage !== null,};@@ -12949,6 +12955,10 @@ export function heartbeatService(.where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null);+ // Preserve the receipt-source fence when finalization enriches usage. A+ // late spool replay must still be able to complete an unfinished receipt.+ if (patch?.usageJson && previousStatus?.usageJson) patch = { ...patch, usageJson: { ...previousStatus.usageJson, ...patch.usageJson } };+// Cancelling a queued run that never acquired provider execution is// positive bootstrap evidence. It must not hold unrelated queued messages.if (previousStatus && (status === "cancelled" || status === "interrupted")) {@@ -13043,6 +13053,10 @@ export function heartbeatService(patch = { ...patch, resultJson: cancellationResultJson(previousStatus, status, patch?.resultJson, patch?.errorCode, patch?.error) };}+ // Preserve the receipt-source fence when finalization enriches usage. A+ // late spool replay must still be able to complete an unfinished receipt.+ if (patch?.usageJson && previousStatus?.usageJson) patch = { ...patch, usageJson: { ...previousStatus.usageJson, ...patch.usageJson } };+// Cancelling a queued run that never acquired provider execution is// positive bootstrap evidence. It must not hold unrelated queued messages.if (@@ -16428,9 +16442,8 @@ export function heartbeatService(.then((rows) => rows[0] ?? null);}- // No code path raises the `ai_connection_busy` error any more. This- // function stays because a stored run row can still carry that error code- // from an earlier release.+ // Credential rotation can briefly contend with a fresh runtime read. Keep+ // the task on its automatic pre-provider retry path while the lock clears.async function finalizeAiConnectionBusyDeferral(run: typeof heartbeatRuns.$inferSelect,error: HttpError,@@ -16952,7 +16965,7 @@ export function heartbeatService(if (checkCostCap && policy.maxDailyCostCents !== null) {const [row] = await client.select({- total: sql<number>`coalesce(sum(${costEvents.costCents})::bigint, 0)`,+ total: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,}).from(costEvents).where(@@ -16964,7 +16977,7 @@ export function heartbeatService(),);const observed = Number(row?.total ?? 0);- if (observed >= policy.maxDailyCostCents) {+ if (compareCents(String(row?.total ?? 0), policy.maxDailyCostCents) >= 0) {return {reason: "heartbeat.daily_cost_limit",observed,@@ -20030,32 +20043,7 @@ export function heartbeatService(normalizedUsage?: UsageTotals | null,) {await ensureRuntimeState(agent);- const usage = normalizedUsage ?? normalizeUsageTotals(result.usage);- const inputTokens = usage?.inputTokens ?? 0;- const outputTokens = usage?.outputTokens ?? 0;- const cachedInputTokens = usage?.cachedInputTokens ?? 0;- const billingType = normalizeLedgerBillingType(result.billingType);- const billedCostUsd = resolveCacheAdjustedCostUsd(result);- const additionalCostCents = normalizeBilledCostCents(- billedCostUsd,- billingType,- );- const hasTokenUsage =- inputTokens > 0 || outputTokens > 0 || cachedInputTokens > 0;- const costStatus = resolveLedgerCostStatus({- costUsd: billedCostUsd,- inputTokens,- cachedInputTokens,- outputTokens,- });- const provider = result.provider ?? "unknown";- const biller = resolveLedgerBiller(result);- const ledgerScope = await resolveLedgerScopeForRun(- db,- agent.companyId,- run,- );-+ await accountRunCost(db, run.id, budgetHooks);await db.update(agentRuntimeState).set({@@ -20064,34 +20052,10 @@ export function heartbeatService(lastRunId: run.id,lastRunStatus: run.status,lastError: run.error ?? null,- totalInputTokens: sql`${agentRuntimeState.totalInputTokens} + ${inputTokens}`,- totalOutputTokens: sql`${agentRuntimeState.totalOutputTokens} + ${outputTokens}`,- totalCachedInputTokens: sql`${agentRuntimeState.totalCachedInputTokens} + ${cachedInputTokens}`,- totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${additionalCostCents}`,updatedAt: new Date(),}).where(eq(agentRuntimeState.agentId, agent.id));- if (additionalCostCents > 0 || hasTokenUsage) {- const costs = costService(db, budgetHooks);- await costs.createEvent(agent.companyId, {- heartbeatRunId: run.id,- agentId: agent.id,- issueId: ledgerScope.issueId,- projectId: ledgerScope.projectId,- billingCode: ledgerScope.billingCode,- provider,- biller,- billingType,- costStatus,- model: result.model ?? "unknown",- inputTokens,- cachedInputTokens,- outputTokens,- costCents: additionalCostCents,- occurredAt: new Date(),- });- }}// A 403 from claimQueuedRun comes from the run's own persisted identity@@ -20402,6 +20366,7 @@ export function heartbeatService(}let legacyAdapterEntered = false;+ let persistUsageCaptureFailure: (() => Promise<void>) | undefined;let run = await getRun(runId);if (!run) return;if (run.status !== "queued" && run.status !== "running") return;@@ -21126,6 +21091,13 @@ export function heartbeatService(issueContext.executionWorkspacePreference,}: null;+ const storedLedgerScope = parseObject(parseObject(run.usageJson).ledgerScope);+ const runLedgerScope = Object.keys(storedLedgerScope).length > 0+ ? storedLedgerScope+ : await resolveLedgerScopeForRun(db, agent.companyId, run);+ await db.update(heartbeatRuns).set({+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ ledgerScope: runLedgerScope })}::jsonb`,+ }).where(eq(heartbeatRuns.id, run.id));const continuationSummary = issueRef && !isConversation(issueContext)? await getIssueContinuationSummaryDocument(db, issueRef.id): null;@@ -22907,7 +22879,7 @@ export function heartbeatService(},);}- const dispatchResolvedInteractionContinuationWithAtomicGate = async <T>(+ const dispatchResolvedInteractionContinuationAfterAdmission = async <T>(dispatch: (markDispatchStarted: () => void) => Promise<T>,): Promise<{ dispatched: true; resultPromise: Promise<T> } | { dispatched: false }@@ -22973,6 +22945,30 @@ export function heartbeatService(}return { dispatched: false };};+ const dispatchResolvedInteractionContinuationWithAtomicGate = async <T>(+ dispatch: (markDispatchStarted: () => void) => Promise<T>,+ ) => {+ // Admission can wait for accounting locks. Finish that wait before the+ // final ownership gate, whose callback must enter the adapter directly.+ const reservation = await reserveRunBudget(db, run.companyId, run.id,+ readNonEmptyString(runLedgerScope.projectId), runLedgerScope, runOptions.nativeLeaseOwner);+ let entered = false;+ try {+ return await dispatchResolvedInteractionContinuationAfterAdmission((markDispatchStarted) => {+ entered = true;+ return dispatch(markDispatchStarted);+ });+ } finally {+ if (!entered && !reservation.reused) {+ await db.update(heartbeatRuns).set({ costAccountingPending: true,+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || '{"accountingProviderWorkStarted":false}'::jsonb`,+ }).where(and(eq(heartbeatRuns.id, run.id), isNull(heartbeatRuns.costAccountedAt)));+ await accountRunCost(db, run.id, budgetHooks).catch((err) => {+ logger.warn({ err, runId: run.id }, "Undispatched reservation release remains pending");+ });+ }+ }+ };if (!executionTarget || executionTarget.kind === "local") {try {runScratch = await prepareHeartbeatRunScratch({@@ -24800,6 +24796,8 @@ export function heartbeatService(adapterFinalizeOutcome = status;};+ const usageRecorder = await createRunUsageRecorder(db, { companyId: run.companyId, runId: run.id, adapterType: agent.adapterType });+ persistUsageCaptureFailure = usageRecorder.persistFailure;let adapterResult: AdapterExecutionResult;const runGoalControlRequestId = readNonEmptyString(context.goalControlRequestId,@@ -24882,8 +24880,8 @@ export function heartbeatService();const guardedDispatch =await dispatchResolvedInteractionContinuationWithAtomicGate(- (markDispatchStarted) =>- executePaperclipNativeSession({+ (markDispatchStarted) => {+ return executePaperclipNativeSession({db,execution: nativeExecution,getFreshSessionHandoff: getNativeFreshSessionHandoff,@@ -24940,11 +24938,14 @@ export function heartbeatService(hasChanges: () => instructionCopies.hasChanges({ companyId: agent.companyId, runId: run.id, target: executionTarget }),collectStopped: collectStoppedInstructions,} : undefined,++ onUsage: async receipt => { await usageRecorder.capture(receipt); },preparationSpans: nativeRunnerPreparationSpans,// Bootstrap with executable/home discovery while keeping// configured provider values and the server-selected// workspace boundary authoritative.managedGitHub: !useHostGitHub && githubSelection.configured,+ billingIdentity: managedAiRuntime ? { provider: managedAiRuntime.attribution.provider, biller: managedAiRuntime.attribution.provider === "openai" ? resolveManagedOpenAiBilling(managedAiRuntime.config.managedAiRouting)?.biller ?? managedAiRuntime.attribution.provider : managedAiRuntime.attribution.provider, billingType: managedAiRuntime.attribution.method === "subscription" ? "subscription_included" : "metered_api" } : undefined,managedAiCredentialIdentity: managedAiRuntime?.identity,managedAiCredentialHome: managedAiRuntime ? String((managedAiRuntime.config.env as Record<string, unknown>).CODEX_HOME) : undefined,runnerEnvironment: {@@ -25017,7 +25018,8 @@ export function heartbeatService(markDispatchStarted();await persistRunProcessMetadata(run.id, meta);},- }),+ });+ },);if (!guardedDispatch.dispatched) return;nativeDispatchStarted = true;@@ -25133,6 +25135,7 @@ export function heartbeatService(onLog,onMeta: onAdapterMeta,onEvent: onAdapterEvent,+ onUsage: async receipt => { await usageRecorder.capture(receipt); },onExecutionPhase: executionControl.phases.enter,startupTraceContext: getStartupTraceContext(),onRuntimeProgress: async (progress) => {@@ -25197,6 +25200,17 @@ export function heartbeatService(if (tail) await appendIdentityRedactedLog(stream, tail);}if (instructionSave) adapterResult.resultJson = { ...adapterResult.resultJson, instructionSave };++ if (parseObject(adapterResult.executionRecovery).providerWorkStarted !== false) {+ const captured = await usageRecorder.complete(adapterResult);+ adapterResult = { ...adapterResult, ...captured, usageComplete: captured.complete };+ } else {+ // Stop may already own the terminal result. Preserve its metadata+ // while durably recording the proof needed to release admission.+ await db.update(heartbeatRuns).set({ costAccountingPending: true,+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || '{"accountingProviderWorkStarted":false}'::jsonb`,+ }).where(and(eq(heartbeatRuns.id, run.id), isNull(heartbeatRuns.costAccountedAt)));+ }adapterResult = applyWorkspaceRestoreFailure(adapterResult);// A returned result can include a failed restore. Keep the workspace// barrier closed until required files have been restored.@@ -25637,65 +25651,67 @@ export function heartbeatService(? "timed_out": "failed";- const cacheAdjustedCostUsd = resolveCacheAdjustedCostUsd(adapterResult);- const usageJson =- normalizedUsage ||- adapterResult.costUsd != null ||- cacheAdjustedCostUsd != null- ? ({- ...(normalizedUsage ?? {}),- ...(rawUsage- ? {- rawInputTokens: rawUsage.inputTokens,- rawInputIncludesCached: false,- rawCachedInputTokens: rawUsage.cachedInputTokens,- rawOutputTokens: rawUsage.outputTokens,- }- : {}),- ...(sessionUsageResolution.derivedFromSessionTotals- ? { usageSource: "session_delta" }- : adapterResult.usageBasis === "per_run"- ? { usageSource: "per_run" }- : {}),- ...((nextSessionState.displayId ??- nextSessionState.legacySessionId)- ? {- persistedSessionId:- nextSessionState.displayId ??- nextSessionState.legacySessionId,- }- : {}),- sessionReused:- runtimeForAdapter.sessionId != null ||- runtimeForAdapter.sessionDisplayId != null,- taskSessionReused: taskSessionForRun != null,- freshSession:- runtimeForAdapter.sessionId == null &&- runtimeForAdapter.sessionDisplayId == null,- sessionRotated: sessionCompaction.rotate,- sessionRotationReason: sessionCompaction.reason,- configFreshness: configFreshnessResultMetadata,- provider:- readNonEmptyString(adapterResult.provider) ?? "unknown",- biller: resolveLedgerBiller(adapterResult),- model: readNonEmptyString(adapterResult.model) ?? "unknown",- ...(adapterResult.costUsd != null- ? { costUsd: adapterResult.costUsd }- : {}),- ...(cacheAdjustedCostUsd != null- ? { cacheAdjustedCostUsd }- : {}),- costStatus: resolveLedgerCostStatus({- costUsd: cacheAdjustedCostUsd,- inputTokens: normalizedUsage?.inputTokens ?? 0,- cachedInputTokens: normalizedUsage?.cachedInputTokens ?? 0,- outputTokens: normalizedUsage?.outputTokens ?? 0,- }),- billingType: normalizeLedgerBillingType(- adapterResult.billingType,- ),- } as Record<string, unknown>)- : null;+ const cacheAdjustedCostUsd = adapterResult.costUsdExact != null && adapterResult.cacheAdjustedCostUsd == null+ ? null : resolveCacheAdjustedCostUsd(adapterResult);+ const usageJson: Record<string, unknown> = {+ accountingReceiptReady: adapterResult.usageComplete !== false,+ costUsdExact: adapterResult.costUsdExact ?? null,+ providerRequestId: adapterResult.providerRequestId ?? null,+ ...(normalizedUsage ?? {}),+ ...(adapterResult.usageByModel ? { usageByModel: adapterResult.usageByModel } : {}),+ ...(rawUsage+ ? {+ rawInputTokens: rawUsage.inputTokens,+ rawInputIncludesCached: false,+ rawCachedInputTokens: rawUsage.cachedInputTokens,+ rawOutputTokens: rawUsage.outputTokens,+ }+ : {}),+ ...(sessionUsageResolution.derivedFromSessionTotals+ ? { usageSource: "session_delta" }+ : adapterResult.usageBasis === "per_run"+ ? { usageSource: "per_run" }+ : {}),+ ...((nextSessionState.displayId ??+ nextSessionState.legacySessionId)+ ? {+ persistedSessionId:+ nextSessionState.displayId ??+ nextSessionState.legacySessionId,+ }+ : {}),+ sessionReused:+ runtimeForAdapter.sessionId != null ||+ runtimeForAdapter.sessionDisplayId != null,+ taskSessionReused: taskSessionForRun != null,+ freshSession:+ runtimeForAdapter.sessionId == null &&+ runtimeForAdapter.sessionDisplayId == null,+ sessionRotated: sessionCompaction.rotate,+ sessionRotationReason: sessionCompaction.reason,+ configFreshness: configFreshnessResultMetadata,+ provider:+ readNonEmptyString(adapterResult.provider) ?? "unknown",+ biller: resolveLedgerBiller(adapterResult),+ model: readNonEmptyString(adapterResult.model) ?? "unknown",+ ...(adapterResult.costUsd != null+ ? { costUsd: adapterResult.costUsd }+ : {}),+ ...(cacheAdjustedCostUsd != null+ ? { cacheAdjustedCostUsd }+ : {}),+ pricingProvenance: adapterResult.pricingProvenance,+ costStatus: adapterResult.costStatus ?? resolveLedgerCostStatus({+ costUsd: cacheAdjustedCostUsd ?? (adapterResult.costUsdExact != null ? Number(adapterResult.costUsdExact) : null),+ billingType: normalizeLedgerBillingType(adapterResult.billingType),+ inputTokens: normalizedUsage?.inputTokens ?? 0,+ cachedInputTokens: normalizedUsage?.cachedInputTokens ?? 0,+ outputTokens: normalizedUsage?.outputTokens ?? 0,+ }),+ billingType: normalizeLedgerBillingType(+ adapterResult.billingType,+ ),+ };const persistedResultJson = cancellationResultJson(latestRun ?? run, outcome, mergeHeartbeatRunResultJson(mergeRunStopMetadataForAgent(agent, outcome, {@@ -25719,13 +25735,17 @@ export function heartbeatService(adapterResult.summary ?? null,), runErrorCode, runErrorMessage);+ const ledgerScope = runLedgerScope;const finalRunPatch: Partial<typeof heartbeatRuns.$inferInsert> = {+ // Accounting must acknowledge even a proven pre-provider failure:+ // that transaction releases the reservation without creating a charge.+ costAccountingPending: true,finishedAt: new Date(),error: runErrorMessage,errorCode: runErrorCode,exitCode: adapterResult.exitCode,signal: adapterResult.signal,- usageJson,+ usageJson: { ...usageJson, ledgerScope },resultJson: persistedResultJson,sessionIdAfter:nextSessionState.displayId ?? nextSessionState.legacySessionId,@@ -25763,6 +25783,8 @@ export function heartbeatService(.set({...finalRunPatch,resultJson: cancellationResultJson(persistedRunWrite.run, status, finalRunPatch.resultJson, runErrorCode, runErrorMessage),++ usageJson: { ...parseObject(persistedRunWrite.run.usageJson), ...parseObject(finalRunPatch.usageJson) },finishedAt:persistedRunWrite.run.finishedAt ?? finalRunPatch.finishedAt,updatedAt: new Date(),@@ -25777,6 +25799,9 @@ export function heartbeatService(.then((rows) => rows[0] ?? null);}if (!persistedRun) {+ await accountRunCost(db, run.id, budgetHooks).catch((err) => {+ logger.error({ err, runId: run.id }, "Late run accounting queued for recovery");+ });logger.info({runId: run.id,@@ -25789,6 +25814,10 @@ export function heartbeatService(}}if (persistedRun) {+ // Accounting recovery is independent of workspace or issue finalization.+ await accountRunCost(db, persistedRun.id, budgetHooks).catch((err) => {+ logger.error({ err, runId: run.id }, "Run accounting queued for recovery");+ });persistedRun =(await classifyAndPersistRunLiveness(persistedRun,@@ -26158,6 +26187,7 @@ export function heartbeatService(wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),});} catch (err) {+ await persistUsageCaptureFailure?.();if (err instanceof NativeControllerDetachedForRestartError) {nativeSessionResumeScheduled = true;return;@@ -29512,7 +29542,7 @@ export function heartbeatService(return { scanned: candidates.length, dispatched, recovered, deferred };}- async function listProjectScopedRunIds(companyId: string, projectId: string) {+ async function listProjectScopedRunIds(companyId: string, projectId: string, createdBefore?: Date) {const runIssueId = sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`;@@ -29533,6 +29563,7 @@ export function heartbeatService(.where(and(eq(heartbeatRuns.companyId, companyId),+ createdBefore ? lt(heartbeatRuns.createdAt, createdBefore) : undefined,inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES,]),@@ -29546,6 +29577,7 @@ export function heartbeatService(async function listProjectScopedWakeupIds(companyId: string,projectId: string,+ database: Db = db,) {const wakeIssueId = sql<string | null@@ -29554,7 +29586,7 @@ export function heartbeatService(string | null>`coalesce(${agentWakeupRequests.payload} ->> 'projectId', ${issues.projectId}::text)`;- const rows = await db+ const rows = await database.selectDistinctOn([agentWakeupRequests.id], {id: agentWakeupRequests.id,})@@ -29584,63 +29616,72 @@ export function heartbeatService(async function cancelPendingWakeupsForBudgetScope(scope: BudgetEnforcementScope,) {- const now = new Date();- let wakeupIds: string[] = [];+ return withCurrentBudgetEnforcement(db, scope, async (tx) => {+ const now = new Date();+ let wakeupIds: string[] = [];- if (scope.scopeType === "company") {- wakeupIds = await db- .select({ id: agentWakeupRequests.id })- .from(agentWakeupRequests)- .where(- and(- eq(agentWakeupRequests.companyId, scope.companyId),- inArray(agentWakeupRequests.status, [- "queued",- "deferred_issue_execution",- ]),- sql`${agentWakeupRequests.runId} is null`,- ),- )- .then((rows) => rows.map((row) => row.id));- } else if (scope.scopeType === "agent") {- wakeupIds = await db- .select({ id: agentWakeupRequests.id })- .from(agentWakeupRequests)- .where(- and(- eq(agentWakeupRequests.companyId, scope.companyId),- eq(agentWakeupRequests.agentId, scope.scopeId),- inArray(agentWakeupRequests.status, [- "queued",- "deferred_issue_execution",- ]),- sql`${agentWakeupRequests.runId} is null`,- ),- )- .then((rows) => rows.map((row) => row.id));- } else {- wakeupIds = await listProjectScopedWakeupIds(- scope.companyId,- scope.scopeId,- );- }+ if (scope.scopeType === "company") {+ wakeupIds = await tx+ .select({ id: agentWakeupRequests.id })+ .from(agentWakeupRequests)+ .where(+ and(+ eq(agentWakeupRequests.companyId, scope.companyId),+ inArray(agentWakeupRequests.status, [+ "queued",+ "deferred_issue_execution",+ ]),+ sql`${agentWakeupRequests.runId} is null`,+ ),+ )+ .then((rows) => rows.map((row) => row.id));+ } else if (scope.scopeType === "agent") {+ wakeupIds = await tx+ .select({ id: agentWakeupRequests.id })+ .from(agentWakeupRequests)+ .where(+ and(+ eq(agentWakeupRequests.companyId, scope.companyId),+ eq(agentWakeupRequests.agentId, scope.scopeId),+ inArray(agentWakeupRequests.status, [+ "queued",+ "deferred_issue_execution",+ ]),+ sql`${agentWakeupRequests.runId} is null`,+ ),+ )+ .then((rows) => rows.map((row) => row.id));+ } else {+ wakeupIds = await listProjectScopedWakeupIds(+ scope.companyId,+ scope.scopeId,+ tx,+ );+ }- if (wakeupIds.length === 0) return 0;+ if (wakeupIds.length === 0) return 0;- await db- .update(agentWakeupRequests)- .set({- status: "cancelled",- finishedAt: now,- error: "Cancelled due to budget pause",- updatedAt: now,- })- .where(inArray(agentWakeupRequests.id, wakeupIds));+ await tx+ .update(agentWakeupRequests)+ .set({+ status: "cancelled",+ finishedAt: now,+ error: "Cancelled due to budget pause",+ updatedAt: now,+ })+ .where(and(+ inArray(agentWakeupRequests.id, wakeupIds),+ inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]),+ isNull(agentWakeupRequests.runId),+ scope.createdBefore ? lt(agentWakeupRequests.createdAt, scope.createdBefore) : undefined,+ ));- return wakeupIds.length;+ return wakeupIds.length;+ });}type CancelRunOptions = {+ budgetEnforcement?: BudgetEnforcementScope;/** Optional board request identity, atomically reserved for native Stop. */cancellationRequestId?: string;cancellationRequestedByUserId?: string | null;@@ -29725,25 +29766,40 @@ export function heartbeatService(// Established legacy processes must still be stopped if the database is// unavailable. Only native or not-yet-dispatched preparation needs this// additional durable fence before its existing cancellation path.- if (!options.cancellationRequestId && (run.runtimeMode === "native" || (!run.runtimeModeResolvedAt && !running && !control))) {- const [fenced] = await db.update(heartbeatRuns).set({- // Record handoff intent before native cancellation can finalize and release- // the run. Only its audited stop acknowledgement suppresses recovery.- resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ||- ${JSON.stringify(options.errorCode === "issue_reassigned" && options.resultJson?.reassignmentStopConfirmed === true- ? { reassignmentStopRequested: true } : {})}::jsonb ||- ${JSON.stringify({ cancellation })}::jsonb ||- jsonb_build_object('startupCancellation', jsonb_build_object(- 'requestedAt', ${new Date().toISOString()}::text,- 'beforeNativeSelection', ${heartbeatRuns.runtimeMode} = 'legacy'- and ${heartbeatRuns.runtimeModeResolvedAt} is null- and ${heartbeatRuns.executionStage} = 'preparing'- and coalesce(${heartbeatRuns.runnerProfileJson}->'adapterDispatch'->>'adapterType' = 'paperclip_runner', false)- ))`,- }).where(and(eq(heartbeatRuns.id, runId), inArray(heartbeatRuns.status,- pendingNativeRetry ? [...CANCELLABLE_HEARTBEAT_RUN_STATUSES, "failed"] : [...CANCELLABLE_HEARTBEAT_RUN_STATUSES],- ))).returning();- if (!fenced) return getRun(runId);+ if (options.budgetEnforcement || (!options.cancellationRequestId && (run.runtimeMode === "native" || (!run.runtimeModeResolvedAt && !running && !control)))) {+ const fence = async (tx: Db) => {+ const [fenced] = await tx.update(heartbeatRuns).set({+ // Record handoff intent before native cancellation can finalize and release+ // the run. Only its audited stop acknowledgement suppresses recovery.+ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ||+ ${JSON.stringify(options.errorCode === "issue_reassigned" && options.resultJson?.reassignmentStopConfirmed === true+ ? { reassignmentStopRequested: true } : {})}::jsonb ||+ ${JSON.stringify({ cancellation })}::jsonb ||+ jsonb_build_object('startupCancellation', jsonb_build_object(+ 'requestedAt', ${new Date().toISOString()}::text,+ 'beforeNativeSelection', ${heartbeatRuns.runtimeMode} = 'legacy'+ and ${heartbeatRuns.runtimeModeResolvedAt} is null+ and ${heartbeatRuns.executionStage} = 'preparing'+ and coalesce(${heartbeatRuns.runnerProfileJson}->'adapterDispatch'->>'adapterType' = 'paperclip_runner', false)+ ))`,+ }).where(and(eq(heartbeatRuns.id, runId), inArray(heartbeatRuns.status,+ pendingNativeRetry ? [...CANCELLABLE_HEARTBEAT_RUN_STATUSES, "failed"] : [...CANCELLABLE_HEARTBEAT_RUN_STATUSES],+ ))).returning();+ return fenced ?? null;+ };+ let fenced: typeof run | null;+ try {+ fenced = options.budgetEnforcement+ ? await withCurrentBudgetEnforcement(db, options.budgetEnforcement, fence)+ : await fence(db);+ } catch (error) {+ stopOwnership?.release();+ throw error;+ }+ if (!fenced) {+ stopOwnership?.release();+ return getRun(runId);+ }run = fenced;}const resultJson = { ...(agent@@ -30118,35 +30174,15 @@ export function heartbeatService(}async function cancelBudgetScopeWork(scope: BudgetEnforcementScope) {- if (scope.scopeType === "agent") {- await cancelActiveForAgentInternal(- scope.scopeId,- "Cancelled due to budget pause",- );- await cancelPendingWakeupsForBudgetScope(scope);- return;- }-- const runIds =- scope.scopeType === "company"- ? await db- .select({ id: heartbeatRuns.id })- .from(heartbeatRuns)- .where(- and(- eq(heartbeatRuns.companyId, scope.companyId),- inArray(heartbeatRuns.status, [- ...CANCELLABLE_HEARTBEAT_RUN_STATUSES,- ]),- ),- )- .then((rows) => rows.map((row) => row.id))- : await listProjectScopedRunIds(scope.companyId, scope.scopeId);-- for (const runId of runIds) {- await cancelRunInternal(runId, "Cancelled due to budget pause");- }-+ const runIds = scope.scopeType === "project"+ ? await listProjectScopedRunIds(scope.companyId, scope.scopeId, scope.createdBefore)+ : await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.companyId, scope.companyId),+ scope.scopeType === "agent" ? eq(heartbeatRuns.agentId, scope.scopeId) : undefined,+ scope.createdBefore ? lt(heartbeatRuns.createdAt, scope.createdBefore) : undefined,+ inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]),+ )).then((rows) => rows.map((row) => row.id));+ for (const runId of runIds) await cancelRunInternal(runId, "Cancelled due to budget pause", { budgetEnforcement: scope });await cancelPendingWakeupsForBudgetScope(scope);}@@ -30515,6 +30551,7 @@ export function heartbeatService(scanSilentActiveRuns,reconcileTaskWatchdogs,+ reconcileCostAccounting: createCostAccountingReconciler(db, budgetHooks),buildRunOutputSilence,diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.tsindex 38dc5e3aeb..ed6f95e1e6 100644--- a/server/src/services/native-runtime/native-session-executor.test.ts+++ b/server/src/services/native-runtime/native-session-executor.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { readFileSync } from "node:fs";+import { PgDialect } from "drizzle-orm/pg-core";+import type { SQL } from "drizzle-orm";import {access,cp,@@ -195,6 +197,18 @@ const state = vi.hoisted(() => ({release: null as null | (() => void),}));+const accountingEvents = vi.hoisted(() => ({ committed: undefined as undefined | ((event: PrpEvent) => Promise<void>), duplicate: undefined as undefined | ((event: PrpEvent) => Promise<void>) }));+vi.mock("./paperclip-control-plane-port.js", async importOriginal => {+ const original = await importOriginal<typeof import("./paperclip-control-plane-port.js")>();+ return { ...original, PaperclipControlPlanePort: class extends original.PaperclipControlPlanePort {+ constructor(...args: ConstructorParameters<typeof original.PaperclipControlPlanePort>) {+ super(...args);+ accountingEvents.committed = args[2]?.onCommittedEvent;+ accountingEvents.duplicate = args[2]?.onDuplicateEvent;+ }+ } };+});+const grokCopyBack = vi.hoisted(() => vi.fn(async (_input: { readSandboxAuth: () => Promise<Buffer>; hostHomeDir: string }) => undefined));vi.mock("@paperclipai/adapter-grok-local/server", async importOriginal => ({...await importOriginal<typeof import("@paperclipai/adapter-grok-local/server")>(),@@ -309,6 +323,7 @@ import {nativeUsageCostUsd,nativeUsageBiller,normalizeNativeUsage,+ resolveNativeBilling,parseRemoteRunnerProcessIdentity,REMOTE_RUNNER_CHILD_LAUNCH_SCRIPT,verifyRemoteRunnerReattachment,@@ -984,6 +999,18 @@ describe("native incomplete-bootstrap evidence", () => {});describe("native provider usage normalization", () => {+ it.each([+ {}, { inputTokens: 1 }, { outputTokens: 1 },+ { inputTokens: 0, outputTokens: -1 }, { inputTokens: 0.5, outputTokens: 1 },+ { inputTokens: 10, outputTokens: 1, cacheReadTokens: 20 },+ { inputTokens: 10, outputTokens: 1, cacheReadTokens: -1 },+ ])("does not invent complete native counters from %j", runDelta => {+ expect(normalizeNativeUsage({ runDelta, total: { inputTokens: 100, outputTokens: 10 } }, { inputIncludesCacheReads: true })).toBeUndefined();+ });+ it("does not use a cumulative price or protocol-default zero for an incomplete delta", () => {+ expect(nativeUsageCostUsd({ runDelta: { inputTokens: 10, outputTokens: 1 }, providerCostUsd: 100 })).toBeUndefined();+ expect(nativeUsageCostUsd({ runDelta: { providerCostUsd: 0 } })).toBeUndefined();+ });it.each([["cursor", "cursor"], ["copilot", "github"], ["pi", "openrouter"]] as const)("keeps %s cost unknown and attributes its actual biller", (agent, biller) => {const provider = { kind: "acpx", agent, model: "exact-model" } as NativeExecutionInput["provider"];expect(nativeUsageBiller(provider)).toBe(biller);@@ -991,6 +1018,35 @@ describe("native provider usage normalization", () => {expect(nativeUsageCostUsd(usage, provider)).toBeUndefined();expect(normalizeNativeUsage(usage)).toMatchObject({ inputTokens: 100, outputTokens: 12 });});++ it("retains cache writes and avoids counting Codex cache hits twice", () => {+ expect(normalizeNativeUsage({ runDelta: { inputTokens: 120, cacheReadTokens: 100, cacheWriteTokens: 5, outputTokens: 10 } }, { inputIncludesCacheReads: true }))+ .toEqual({ inputTokens: 20, cachedInputTokens: 100, cacheWriteTokens: 5, outputTokens: 10 });+ });+ it("does not treat a protocol-default price as free usage", () => {+ expect(nativeUsageCostUsd({ runDelta: { inputTokens: 20, outputTokens: 10, providerCostUsd: 0 } })).toBeUndefined();+ });+ it("reports the actual runtime billing identity", () => {+ expect(resolveNativeBilling({ kind: "opencode", model: "openrouter/deepseek/test", permissionMode: "allow" }))+ .toEqual({ provider: "deepseek", biller: "openrouter", billingType: "unknown" });+ expect(resolveNativeBilling({ kind: "acpx", agent: "claude", model: "claude-test", permissionMode: "approve-all",+ profile: { driverKind: "acpx_runtime", protocolVersion: 1, acpxVersion: "0.13.1", agent: "claude", agentProfileVersion: 1,+ agentServerPackage: "@zed-industries/claude-agent-acp", agentServerVersion: "1", agentRuntimePackage: null,+ agentRuntimeVersion: null, commandDigest: "fixture" },+ }, { ANTHROPIC_API_KEY: "test" }))+ .toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api" });+ });++ it("prefers the adjusted turn price to cumulative session prices", () => {+ expect(nativeUsageCostUsd({ providerCostUsd: 10, runDelta: { inputTokens: 10, providerCostUsd: 2, cacheAdjustedCostUsd: 1 } })).toBe(1);+ });+ it.each(["OPENAI_BASE_URL", "OPENAI_API_BASE", "OPENAI_API_BASE_URL"])("does not price native or managed proxy traffic as direct OpenAI using %s", key => {+ const provider = { kind: "codex", model: "gpt-6-astra" } as Parameters<typeof resolveNativeBilling>[0];+ expect(resolveNativeBilling(provider, { OPENAI_API_KEY: "fixture", [key]: "https://proxy.example/v1" }).biller).toBe("unknown");+ expect(resolveNativeBilling(provider, { [key]: "https://proxy.example/v1" }, { provider: "openai", biller: "openai", billingType: "metered_api" }).biller).toBe("unknown");+ expect(resolveNativeBilling(provider, {}, { provider: "openai", biller: "openai", billingType: "metered_api" })).toMatchObject({ biller: "openai", billingType: "metered_api" });+ });+it("reads remote runner run-delta tokens and provider cost", () => {const usage = {total: {@@ -4852,6 +4908,7 @@ function leaseDb(updates: Array<{ table: unknown; values: Record<string, unknown> }> = [],runnerProfileJson: Record<string, unknown> = {},runStatus = "running",+ priorAccountingEvents: PrpEvent[] = [],): Db {const coordinator: LeaseCoordinator = {runId: boundExecution.binding.runId,@@ -4910,13 +4967,15 @@ function leaseDb(checkoutRunId: null,},]- : [];+ : table === heartbeatRunEvents+ ? priorAccountingEvents.map((event, seq) => ({ seq, eventType: event.eventType, sourceSeq: event.sourceSeq, payload: { prpEvent: event } }))+ : [];const query = {then: Promise.resolve(rows).then.bind(Promise.resolve(rows)),where: () => query,orderBy: () => query,for: () => query,- limit: () => Promise.resolve(rows),+ limit: () => query,};return query;},@@ -4924,7 +4983,9 @@ function leaseDb(const insert = (table: unknown) => ({values: (values: Record<string, unknown>) => {updates.push({ table, values });- return { returning: async () => [values] };+ const query = { returning: async () => [values], onConflictDoUpdate: () => query, onConflictDoNothing: () => query,+ then: Promise.resolve([values]).then.bind(Promise.resolve([values])) };+ return query;},});const tx = {@@ -5177,6 +5238,268 @@ describe("native startup restart detachment", () => {});});+describe("native terminal-turn accounting", () => {+ it.each(["claude", "codex"].flatMap(agent => [false, true].flatMap(restart =>+ [false, true].flatMap(partialFirst => [false, true].map(zeroFirst => ({ agent, restart, partialFirst, zeroFirst }))),+ )))("accumulates ACPX turns for $agent (restart: $restart, partial: $partialFirst, zero first: $zeroFirst)", async ({ agent, restart, partialFirst, zeroFirst }) => {+ const { rehydrateRunnerdUsageNotification } = await import("@paperclipai/paperclip-runner/live");+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const event = (eventType: string, turnId: string, sourceSeq: number, payload: object = {}) => ({+ eventType, turnId, sourceSeq, sourceInstanceId: "provider", emittedAt: new Date().toISOString(), payload,+ }) as unknown as PrpEvent;+ const usage = (turnId: string, inputTokens: number, outputTokens: number, complete: boolean) => ({+ kind: "usage", usage: rehydrateRunnerdUsageNotification({ provider: "acpx", runDeltaAvailable: complete,+ cumulative: { inputTokens: 0, outputTokens: 0, providerCostUsd: 10 },+ runDelta: { inputTokens, outputTokens, cacheReadTokens: 0, cacheWriteTokens: 0, providerCostUsd: 0 },+ }, "session", turnId).tokenUsage,+ });+ const first = [event("turn.started", "first", 1), event("item.completed", "first", 2, usage("first", zeroFirst ? 0 : 12, zeroFirst ? 0 : 4, !partialFirst)), event("turn.failed", "first", 3)];+ const second = [event("turn.started", "second", 4), event("item.completed", "second", 5, usage("second", 20, 6, true)), event("turn.completed", "second", 6)];+ state.execute.mockReset().mockImplementationOnce(async () => {+ for (const entry of [...(restart ? [] : first), ...second]) await accountingEvents.committed!(entry);+ for (const entry of [...first, ...second]) await accountingEvents.duplicate!(entry);+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, turnId: "second",+ normalizedSessionId: "session", providerSessionId: null, driverKind: "acpx_runtime", driverVersion: "1",+ nativeEventCount: 6, highestContiguousSourceSeq: 6, usage: null };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(execution, {}, {}, [], {}, "running", restart ? first : []),+ execution: { ...execution, provider: { kind: "acpx", agent, model: agent === "codex" ? "gpt-6-astra" : "claude-sonnet-4-6" } } as NativeExecutionInput,+ runnerInstanceId: "runner", runnerEnvironment: { OPENAI_API_KEY: "fixture" }, onUsage });+ expect(result).toMatchObject({ usageComplete: !partialFirst,+ usage: { inputTokens: partialFirst || zeroFirst ? 20 : 32, outputTokens: partialFirst || zeroFirst ? 6 : 10 } });+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: !partialFirst }));+ if (partialFirst) expect(result.costStatus).toBe("unpriced");+ if (zeroFirst && !partialFirst) {+ expect(result.costUsdExact).toBeUndefined();+ expect(result.costUsd).toBeNull();+ }+ if (agent === "codex" && !partialFirst) {+ const { priceCodexReceipt } = await import("../codex-pricing.js");+ const priced = priceCodexReceipt(onUsage.mock.calls.at(-1)![0]);+ expect(priced.costStatus).toBe("estimated");+ expect(Number(priced.costUsdExact)).toBeCloseTo(zeroFirst ? 0.0005 : 0.00082, 9);+ }+ });++ it.each(["claude", "codex"].flatMap(agent =>+ ["missing", "partial", "complete_zero", "later_partial", "recovered"].map(scenario => ({ agent, scenario })),+ ))("honors runner completeness for ACPX $agent ($scenario)", async ({ agent, scenario }) => {+ const { rehydrateRunnerdUsageNotification } = await import("@paperclipai/paperclip-runner/live");+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const complete = ["complete_zero", "recovered"].includes(scenario);+ const zero = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, providerCostUsd: 0 };+ const full = { ...zero, inputTokens: 12, outputTokens: 4 };+ const reports = scenario === "complete_zero" ? [{ runDelta: zero, runDeltaAvailable: true }]+ : scenario === "later_partial" ? [{ runDelta: full, runDeltaAvailable: true }, { runDelta: zero, runDeltaAvailable: false }]+ : scenario === "recovered" ? [{ runDelta: zero, runDeltaAvailable: false }, { runDelta: full, runDeltaAvailable: true }]+ : [{ runDelta: scenario === "partial" ? { ...zero, inputTokens: 12 } : zero, runDeltaAvailable: false }];+ state.execute.mockReset().mockImplementationOnce(async () => {+ for (const observe of [accountingEvents.committed!, accountingEvents.duplicate!]) {+ for (const report of reports) {+ const notification = rehydrateRunnerdUsageNotification({ provider: "acpx", cumulative: { ...full, providerCostUsd: 10 }, ...report }, "session", "turn");+ await observe({ eventType: "item.completed", turnId: "turn", payload: { kind: "usage", usage: notification.tokenUsage } } as unknown as PrpEvent);+ }+ await observe({ eventType: "turn.completed", turnId: "turn", payload: {} } as unknown as PrpEvent);+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete }));+ if (!complete) expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ costUsd: null, costStatus: "unpriced" }));+ }+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, turnId: "turn",+ normalizedSessionId: "session", providerSessionId: null, driverKind: "acpx_runtime", driverVersion: "1", nativeEventCount: 2, highestContiguousSourceSeq: 2,+ usage: { runDelta: full, runDeltaComplete: true } };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution,+ provider: { kind: "acpx", agent, model: agent === "codex" ? "gpt-6-astra" : "claude-sonnet-4-6" } } as NativeExecutionInput,+ runnerInstanceId: "runner", onUsage });+ expect(result).toMatchObject({ usageComplete: complete });+ if (!complete) expect(result).toMatchObject({ costUsd: null, costStatus: "unpriced" });+ else expect(result.usage).toMatchObject({ inputTokens: scenario === "complete_zero" ? 0 : 12, outputTokens: scenario === "complete_zero" ? 0 : 4 });+ });++ it.each([0, 0.25])("keeps interrupted AgentCore accounting pending despite cumulative cost %s", async providerCostUsd => {+ const { rehydrateRunnerdUsageNotification } = await import("@paperclipai/paperclip-runner/live");+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const total = { inputTokens: 10, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0, providerCostUsd };+ const notification = rehydrateRunnerdUsageNotification({ provider: "aws_agentcore", cumulative: total, runDelta: null, runDeltaAvailable: false }, "session", "turn");+ state.execute.mockReset().mockImplementationOnce(async () => {+ for (const observe of [accountingEvents.committed!, accountingEvents.duplicate!]) {+ await observe({ eventType: "item.completed", turnId: "turn", payload: { kind: "usage", usage: notification.tokenUsage } } as unknown as PrpEvent);+ await observe({ eventType: "turn.interrupted", turnId: "turn", payload: {} } as unknown as PrpEvent);+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: false, costStatus: "unpriced" }));+ }+ return { result: { summary: "interrupted" }, terminal: { runTerminalState: "cancelled" }, turnId: "turn",+ normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 2, highestContiguousSourceSeq: 2, usage: { total } };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution, provider: { kind: "aws_agentcore", model: "managed-model", agentCoreProfile: { profileId: "agentcore-test" } } } as unknown as NativeExecutionInput, runnerInstanceId: "runner", onUsage });+ expect(result).toMatchObject({ usageComplete: false, costStatus: "unpriced", billingType: "metered_api" });+ });++ it.each(["claude_managed", "aws_agentcore"] as const)("settles fresh runner receipts for %s and preserves estimated pricing", async kind => {+ const { rehydrateRunnerdUsageNotification } = await import("@paperclipai/paperclip-runner/live");+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const total = { inputTokens: 121, outputTokens: 18, cacheReadTokens: 33, cacheWriteTokens: 15, providerCostUsd: 1.25 };+ const delta = { inputTokens: 21, outputTokens: 8, cacheReadTokens: 13, cacheWriteTokens: 5, providerCostUsd: 0.25 };+ const notification = rehydrateRunnerdUsageNotification({ provider: kind, cumulative: total, runDelta: delta, runDeltaAvailable: true }, "session", "turn");+ state.execute.mockReset().mockImplementationOnce(async () => {+ for (const observe of [accountingEvents.committed!, accountingEvents.duplicate!]) {+ await observe({ eventType: "item.completed", turnId: "turn", payload: { kind: "usage", usage: notification.tokenUsage } } as unknown as PrpEvent);+ await observe({ eventType: "turn.completed", turnId: "turn", payload: {} } as unknown as PrpEvent);+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true, costUsd: 0.25,+ costStatus: kind === "aws_agentcore" ? "estimated" : undefined,+ usage: { inputTokens: 26, outputTokens: 8, cachedInputTokens: 13, cacheWriteTokens: 5 } }));+ }+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" },+ turnId: "turn", normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 2, highestContiguousSourceSeq: 2, usage: { total } };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution, provider: { kind, model: "managed-model", managedProfile: { profileId: "managed-test" }, agentCoreProfile: { profileId: "agentcore-test" } } } as unknown as NativeExecutionInput, runnerInstanceId: "runner", onUsage });+ expect(result).toMatchObject({ usageComplete: true, costUsd: 0.25, billingType: "metered_api", costStatus: kind === "aws_agentcore" ? "estimated" : undefined });+ });++ it.each([+ { provider: "codex", restart: false }, { provider: "codex", restart: true },+ { provider: "opencode", restart: false }, { provider: "opencode", restart: true },+ ] as const)("preserves earlier turns for $provider (restart: $restart)", async ({ provider, restart }) => {+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const event = (eventType: string, turnId: string, sourceSeq: number, payload: object = {}) => ({+ eventType, turnId, sourceSeq, sourceInstanceId: "provider", emittedAt: new Date().toISOString(), payload,+ }) as unknown as PrpEvent;+ const first = [event("turn.started", "first", 1), event("item.completed", "first", 2, { kind: "usage", usage: {+ runDelta: { inputTokens: 10, cacheReadTokens: 3, cacheWriteTokens: 1, outputTokens: 2, providerCostUsd: 0.25 },+ } }), event("turn.failed", "first", 3)];+ const second = [event("turn.started", "second", 4), event("item.completed", "second", 5, { kind: "usage", usage: {+ runDelta: { inputTokens: 20, cacheReadTokens: 6, cacheWriteTokens: 2, outputTokens: 4, providerCostUsd: 0.5 },+ } }), event("turn.completed", "second", 6)];+ state.execute.mockReset().mockImplementationOnce(async () => {+ for (const entry of [...(restart ? [] : first), ...second]) await accountingEvents.committed!(entry);+ for (const entry of provider === "opencode" ? [...first, ...second] : second) await accountingEvents.duplicate!(entry);+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, turnId: "second",+ normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 6,+ highestContiguousSourceSeq: 6, usage: null };+ });+ const result = await executePaperclipNativeSession({+ db: leaseDb(execution, {}, {}, [], {}, "running", restart ? first : []),+ execution: { ...execution, provider: { kind: provider, model: provider === "opencode" ? "openai/test" : "gpt-6-astra" } } as NativeExecutionInput,+ runnerInstanceId: "runner", onUsage,+ });+ const usage = provider === "opencode"+ ? { inputTokens: 33, cachedInputTokens: 9, cacheWriteTokens: 3, outputTokens: 6 }+ : { inputTokens: 14, cachedInputTokens: 6, cacheWriteTokens: 2, outputTokens: 4 };+ expect(result).toMatchObject({ usageComplete: true, costUsd: provider === "opencode" ? 0.75 : 0.5, usage });+ if (provider === "opencode") expect(result.costUsdExact).toBe("0.750000000");+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true, costUsd: result.costUsd, usage }));+ });++ it.each(["missing_usage", "partial_usage", "missing_terminal", "unknown_price", "late_update"] as const)("keeps OpenCode retry accounting conservative (%s)", async scenario => {+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ let seq = 0;+ const emit = (eventType: string, turnId: string, payload: object = {}) => accountingEvents.committed!({+ eventType, turnId, sourceSeq: ++seq, sourceInstanceId: "provider", emittedAt: new Date().toISOString(), payload,+ } as unknown as PrpEvent);+ const usage = (inputTokens: number, outputTokens: number | undefined, providerCostUsd: number | undefined) => ({+ kind: "usage", usage: { runDelta: { inputTokens, outputTokens, providerCostUsd } },+ });+ state.execute.mockReset().mockImplementationOnce(async () => {+ await emit("turn.started", "first");+ if (scenario !== "missing_usage") await emit("item.completed", "first",+ usage(10, scenario === "partial_usage" ? undefined : 2, scenario === "unknown_price" ? undefined : 0.25));+ if (scenario !== "missing_terminal") await emit("turn.failed", "first");+ await emit("turn.started", "second");+ expect(onUsage.mock.calls.at(-1)![0].complete).toBe(false);+ await emit("item.completed", "second", usage(20, 4, 0.5));+ await emit("turn.completed", "second");+ if (scenario === "late_update") await emit("item.completed", "first", usage(12, 4, 0.35));+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, turnId: "second",+ normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: seq,+ highestContiguousSourceSeq: seq, usage: null };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(),+ execution: { ...execution, provider: { kind: "opencode", model: "openai/test" } } as NativeExecutionInput,+ runnerInstanceId: "runner", onUsage });+ const complete = ["unknown_price", "late_update"].includes(scenario);+ const cost = ["missing_usage", "unknown_price"].includes(scenario) ? 0.5 : scenario === "late_update" ? 0.85 : 0.75;+ expect(result).toMatchObject({ usageComplete: complete, costUsd: cost });+ expect(result.costStatus).toBe(scenario === "late_update" ? undefined : "unpriced");+ expect(onUsage.mock.calls.at(-1)![0]).toMatchObject({ complete, costUsd: cost, costStatus: result.costStatus });+ if (scenario === "late_update") expect(result.usage).toMatchObject({ inputTokens: 32, outputTokens: 8 });+ });++ it.each(["committed", "duplicate"] as const)("saves completed usage before returning to result commitment (%s)", async mode => {+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const failure = new Error("stopped after result commit, before executor returns");+ state.execute.mockReset().mockImplementationOnce(async () => {+ const observe = accountingEvents[mode]!;+ await observe({ eventType: "item.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { kind: "usage", usage: { runDelta: { inputTokens: 120, cacheReadTokens: 100, outputTokens: 10, providerCostUsd: 0.25 } } } } as unknown as PrpEvent);+ await observe({ eventType: "turn.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { status: "completed" } } as unknown as PrpEvent);+ // The runtime cannot call completeRun until appendEvent has returned.+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true, costUsd: 0.25, usage: { inputTokens: 20, cachedInputTokens: 100, outputTokens: 10 } }));+ throw failure;+ });+ await expect(executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution, provider: { kind: "codex", model: "gpt-6-astra" } } as NativeExecutionInput, runnerInstanceId: "runner", onUsage })).rejects.toBe(failure);+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true }));+ });+ it("clears provisional unpriced status when direct database persistence receives complete usage", async () => {+ const updates: Array<{ table: unknown; values: Record<string, unknown> }> = [];+ state.execute.mockReset().mockImplementationOnce(async () => {+ await accountingEvents.committed!({ eventType: "item.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { kind: "usage", usage: { runDelta: { inputTokens: 10, outputTokens: 2, providerCostUsd: 0.25 } } } } as unknown as PrpEvent);+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" },+ turnId: "turn", normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };+ });+ await executePaperclipNativeSession({ db: leaseDb(execution, {}, {}, updates), execution, runnerInstanceId: "runner" });+ const dialect = new PgDialect();+ const writes = updates.filter(update => update.values.usageJson).map(update =>+ JSON.parse(dialect.sqlToQuery(update.values.usageJson as SQL).params[0] as string) as Record<string, unknown>);+ expect(writes[0]).toMatchObject({ accountingReceiptReady: false, costStatus: "unpriced" });+ // Apply the same JSON merge as the database: omitted keys retain the old value.+ expect(Object.assign({}, ...writes)).toMatchObject({ accountingReceiptReady: true, costStatus: null, costUsd: 0.25 });+ });++ it.each(["stale_warm_zero", "partial", "fresh", "fresh_zero", "new_turn", "later_partial", "merged_partial"])("requires fresh complete usage at native completion (%s)", async scenario => {+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const usage = { inputTokens: 120, cacheReadTokens: 100, outputTokens: 10, providerCostUsd: 0 };+ const runDelta = scenario === "partial" ? { inputTokens: 120 } : scenario === "fresh_zero" ? { inputTokens: 0, outputTokens: 0 } : usage;+ state.execute.mockReset().mockImplementationOnce(async () => {+ if (scenario !== "stale_warm_zero") await accountingEvents.committed!({ eventType: "item.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { kind: "usage", usage: { runDelta, runDeltaComplete: scenario !== "merged_partial" } } } as unknown as PrpEvent);+ if (scenario === "new_turn") await accountingEvents.committed!({ eventType: "turn.started", turnId: "next-turn", emittedAt: new Date().toISOString(), payload: {} } as unknown as PrpEvent);+ if (scenario === "later_partial") await accountingEvents.committed!({ eventType: "item.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { kind: "usage", usage: { runDelta: { inputTokens: 130 } } } } as unknown as PrpEvent);+ await accountingEvents.committed!({ eventType: "turn.completed", turnId: scenario === "new_turn" ? "next-turn" : "turn", emittedAt: new Date().toISOString(), payload: {} } as unknown as PrpEvent);+ if (!["fresh", "fresh_zero"].includes(scenario)) expect(onUsage.mock.calls.every(([receipt]) => !receipt.complete)).toBe(true);+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" },+ turnId: scenario === "new_turn" ? "next-turn" : "turn", normalizedSessionId: "session",+ providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 1,+ highestContiguousSourceSeq: 1,+ usage: { runDelta: scenario === "stale_warm_zero" ? { inputTokens: 0, outputTokens: 0, providerCostUsd: 0 } : runDelta },+ };+ });+ const result = await executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution, provider: { kind: "codex", model: "gpt-6-astra" } } as NativeExecutionInput, runnerInstanceId: "runner", runnerEnvironment: { OPENAI_API_KEY: "fixture" }, onUsage });+ const complete = ["fresh", "fresh_zero"].includes(scenario);+ expect(result.usageComplete).toBe(complete);+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete }));+ if (!complete) {+ expect(result.costStatus).toBe("unpriced");+ expect(result.costUsd).toBeNull();+ expect(onUsage.mock.calls.at(-1)![0]).toMatchObject({ costUsd: null, costStatus: "unpriced" });+ }+ });+ beforeEach(() => vi.spyOn(issueServiceModule, "issueService").mockReturnValue({ update: vi.fn(async () => ({ status: "blocked", statusVersion: 1 })) } as unknown as ReturnType<typeof issueServiceModule.issueService>));+ afterEach(() => vi.restoreAllMocks());+ it.each(["turn.failed", "turn.cancelled", "turn.interrupted", "missing_terminal", "session_total", "empty_usage", "different_turn"])("preserves run usage for %s without certifying incomplete evidence", async (scenario) => {+ const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});+ const failure = new Error("provider_transport_failed: no semantic result");+ state.execute.mockReset().mockImplementationOnce(async () => {+ const usage = { inputTokens: 120, cacheReadTokens: 100, outputTokens: 10, providerCostUsd: 0.25 };+ await accountingEvents.committed!({ eventType: "item.completed", turnId: "turn", emittedAt: new Date().toISOString(), payload: { kind: "usage", usage: scenario === "session_total" ? { total: usage } : { runDelta: scenario === "empty_usage" ? { requests: 1 } : usage } } } as unknown as PrpEvent);+ if (scenario !== "missing_terminal") await accountingEvents.committed!({ eventType: scenario.startsWith("turn.") ? scenario : "turn.failed", turnId: scenario === "different_turn" ? "another-turn" : "turn", emittedAt: new Date().toISOString(), payload: { status: "failed" } } as unknown as PrpEvent);+ throw failure;+ });+ await expect(executePaperclipNativeSession({ db: leaseDb(), execution: { ...execution, provider: { kind: "codex", model: "gpt-6-astra" } } as NativeExecutionInput, runnerInstanceId: "runner", onUsage })).rejects.toBe(failure);+ if (scenario === "session_total") expect(onUsage).not.toHaveBeenCalled();+ else if (scenario === "empty_usage") expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: false, usage: undefined, costUsd: null, costStatus: "unpriced" }));+ else {+ expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: scenario.startsWith("turn."), costUsd: 0.25, usageBasis: "per_run", usage: { inputTokens: 20, cachedInputTokens: 100, outputTokens: 10 } }));+ expect(onUsage.mock.calls[0]?.[0]).toMatchObject({ complete: false });+ }+ });+});+describe("native resumed preparation timing", () => {it("keeps answered-question ingress at the run root rather than charging it to preparation", async () => {const answeredAtMs = Date.now();diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.tsindex 5331ccfeba..d4dec4ee16 100644--- a/server/src/services/native-runtime/native-session-executor.ts+++ b/server/src/services/native-runtime/native-session-executor.ts@@ -11,6 +11,7 @@ import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server";+import { inferOpenAiCompatibleBiller, type AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";import {isSupportedRemoteCodexVersion,@@ -65,7 +66,7 @@ import type {AdapterExecutionResult,AdapterRuntimeEvent,} from "../../adapters/index.js";-import type { NativeFinalizationResult } from "@paperclipai/shared";+import { usdToUnits, type NativeFinalizationResult } from "@paperclipai/shared";import type {HarnessRuntimeRequestResolution,NativeExecutionInput,@@ -7320,6 +7321,7 @@ export async function executePaperclipNativeSession(input: {collectStopped: () => Promise<void>;};/** Persist task-level continuity before a durable goal can outlive this run. */+ onUsage?: (receipt: AdapterUsageCheckpoint) => Promise<void>;onGoalCheckpoint?: (snapshot: PersistedNativeSession) => Promise<void>;sessionGoalControl?: NativeSessionGoalControl | null;resumeSessionGoalHeartbeat?: boolean;@@ -7331,6 +7333,7 @@ export async function executePaperclipNativeSession(input: {/** Private grant materialization; never a user-configured host path. */managedAiCredentialHome?: string;managedAiCredentialIdentity?: string;+ billingIdentity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">;runnerExecutionTarget?: AdapterExecutionTarget | null;/** Resolved per-run authorization; not an independent instance setting. */runnerIngressAuthorized?: boolean;@@ -7912,6 +7915,76 @@ async function executePaperclipNativeSessionWithinScope(binding: { ...input.execution.binding, normalizedSessionId: nativeSessionKey(input.execution), runnerSourceInstanceId: effectiveRunnerInstanceId },resolve: resolveNativeRuntimeRequest,});+ let observedAccountingUsage: Record<string, unknown> | null = null;+ let observedAccountingTurn: string | undefined;+ let nativeAccountingComplete = false;+ // OpenCode and ACPX report their current turn; Codex reports a cumulative run delta.+ // Rebuild per-turn state from the durable event log when a controller resumes.+ const turnAccounting = ["opencode", "acpx"].includes(input.execution.provider.kind) ? createNativeTurnAccounting(input.execution.provider) : null;+ if (turnAccounting) {+ const history = await input.db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(+ eq(heartbeatRunEvents.companyId, input.execution.binding.companyId), eq(heartbeatRunEvents.runId, input.execution.binding.runId),+ or(sql`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'kind' = 'usage'`,+ inArray(heartbeatRunEvents.eventType, ["turn.started", "turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"])),+ )).orderBy(heartbeatRunEvents.seq);+ for (const row of history) turnAccounting.observe(record(row.payload).prpEvent as PrpEvent);+ }+ const persistAccountingUsage = async (usage: Record<string, unknown> | null, complete: boolean) => {+ const accountingUsage = normalizeNativeUsage(usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" });+ const accountingCost = accountingUsage ? nativeUsageCostUsd(usage, input.execution.provider) : undefined;+ complete = complete && accountingUsage !== undefined;+ const costStatus = complete && usage?.accountingCostIncomplete !== true+ ? input.execution.provider.kind === "aws_agentcore" ? "estimated" as const : undefined+ : "unpriced" as const;+ const billing = resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity);+ const costUsdExact = typeof usage?.accountingCostUsdExact === "string" ? usage.accountingCostUsdExact : undefined;+ await input.onUsage?.({ usage: accountingUsage, ...billing, complete, usageBasis: "per_run", costUsdExact,+ model: input.execution.provider.model ?? "unknown", costUsd: accountingCost ?? null, costStatus });+ if (!input.onUsage) await input.db.update(heartbeatRuns).set({+ costAccountingPending: true,+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({+ ...accountingUsage, ...billing, accountingReceiptReady: complete, model: input.execution.provider.model ?? "unknown",+ costUsd: accountingCost ?? null, costUsdExact: costUsdExact ?? null, costStatus: costStatus ?? null, usageSource: "per_run",+ })}::jsonb`,+ }).where(and(eq(heartbeatRuns.id, input.execution.binding.runId), eq(heartbeatRuns.companyId, input.execution.binding.companyId), isNull(heartbeatRuns.costAccountedAt)));+ };+ // appendEvent awaits this receipt before the runtime may commit completeRun.+ // Replayed events must rebuild it too after a stop between event and receipt.+ const observeAccountingEvent = async (event: PrpEvent) => {+ if (turnAccounting) {+ if (!turnAccounting.observe(event)) return;+ const snapshot = turnAccounting.snapshot();+ observedAccountingUsage = snapshot.usage;+ observedAccountingTurn = snapshot.turnId;+ await persistAccountingUsage(snapshot.usage, snapshot.complete);+ return;+ }+ const payload = record(event.payload);+ const usage = record(payload.usage);+ const delta = record(usage.runDelta);+ if (event.eventType === "turn.started") {+ observedAccountingTurn = undefined;+ if (observedAccountingUsage) await persistAccountingUsage(observedAccountingUsage, false);+ }+ // A warm attachment seeds a zero snapshot before any provider report.+ // Only a fresh run delta for this turn can close its accounting. A later+ // malformed report invalidates completeness instead of retaining a+ // smaller earlier total or falling back to cumulative session usage.+ if (payload.kind === "usage") {+ observedAccountingTurn = undefined;+ if (Object.hasOwn(usage, "runDelta")) {+ observedAccountingUsage = { runDelta: delta, runDeltaComplete: usage.runDeltaComplete };+ if (normalizeNativeUsage(observedAccountingUsage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })) {+ observedAccountingTurn = event.turnId;+ }+ }+ if (observedAccountingUsage) await persistAccountingUsage(observedAccountingUsage, false);+ }+ if (["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"].includes(event.eventType)+ && observedAccountingUsage && observedAccountingTurn !== undefined && event.turnId === observedAccountingTurn) {+ await persistAccountingUsage(observedAccountingUsage, true);+ }+ };let completedConversationReply: PrpEvent | null = null;const controlPlane = new PaperclipControlPlanePort(input.db,@@ -7929,6 +8002,7 @@ async function executePaperclipNativeSessionWithinScope({privateKeyPem: input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY,onCommittedEvent: async (event) => {+ await observeAccountingEvent(event);await toolTrace.observe(event);if (event.eventType === "item.completed" &&record(event.payload).kind === "agentMessage" &&@@ -8136,6 +8210,7 @@ async function executePaperclipNativeSessionWithinScope();},onDuplicateEvent: async (event) => {+ await observeAccountingEvent(event);// A crash can happen after the event commit but before its callback// finishes. Recover only idempotent durable projections here; activity,// publication, logging, trace, and metric effects remain committed-only.@@ -8687,6 +8762,19 @@ async function executePaperclipNativeSessionWithinScope(},{ parentName: "task.run" },);+ // Persist provider accounting before any workspace/issue finalization. A+ // detached controller or failed finalizer must not lose a completed turn.+ // session.usage() may be an attachment baseline, a partial report, or a+ // cumulative session total. Use the observed run delta, and require its+ // turn to match the terminal result before certifying it as complete.+ if (turnAccounting) {+ const snapshot = turnAccounting.finish(native.turnId);+ observedAccountingUsage = snapshot.usage;+ nativeAccountingComplete = snapshot.complete && snapshot.turnId === native.turnId;+ } else nativeAccountingComplete = observedAccountingUsage !== null+ && observedAccountingTurn !== undefined && observedAccountingTurn === native.turnId;+ native = { ...native, usage: observedAccountingUsage };+ await persistAccountingUsage(native.usage, nativeAccountingComplete);try {await completeManagedNativeCredentialTurn(managedCredentialSession);} catch {@@ -9325,10 +9413,16 @@ async function executePaperclipNativeSessionWithinScope(summary: native.result.summary,sessionId: native.normalizedSessionId,sessionDisplayId: native.providerSessionId ?? native.normalizedSessionId,- provider: nativeUsageBiller(input.execution.provider),+ ...resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity),model: input.execution.provider.model,- usage: normalizeNativeUsage(native.usage),- costUsd: nativeUsageCostUsd(native.usage, input.execution.provider),+ usage: normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" }),+ costUsd: normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })+ ? nativeUsageCostUsd(native.usage, input.execution.provider) ?? null : null,+ costUsdExact: typeof native.usage?.accountingCostUsdExact === "string" ? native.usage.accountingCostUsdExact : undefined,+ costStatus: nativeAccountingComplete && native.usage?.accountingCostIncomplete !== true+ ? input.execution.provider.kind === "aws_agentcore" ? "estimated" : undefined+ : "unpriced",+ usageComplete: nativeAccountingComplete,usageBasis: "per_run",nativeFinalization: finalization,};@@ -9359,6 +9453,9 @@ function numericUsageField(function nativeUsageMeasurement(usage: Record<string, unknown>) {const nestedUsage = record(usage.usage);+ // An explicit partial delta must not fall through to a full session total.+ if (Object.hasOwn(usage, "runDelta")) return record(usage.runDelta);+ if (Object.hasOwn(nestedUsage, "runDelta")) return record(nestedUsage.runDelta);const candidates = [record(usage.runDelta),record(nestedUsage.runDelta),@@ -9393,6 +9490,74 @@ export function nativeUsageBiller(provider: NativeExecutionInput["provider"]): sreturn "openai";}+function createNativeTurnAccounting(provider: NativeExecutionInput["provider"]) {+ const turns = new Map<string, { usage: Record<string, unknown> | null; terminal: boolean }>();+ const sequences = new Map<string, number>();+ let currentTurn: string | undefined;+ const terminalTypes = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"];+ const snapshot = () => {+ if (turns.size === 0) return { usage: null, turnId: undefined, complete: false };+ let inputTokens = 0, outputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0;+ let cost = 0n, costKnown = false, costIncomplete = false, complete = true;+ for (const [turnId, turn] of turns) {+ const normalized = normalizeNativeUsage(turn.usage);+ complete &&= turnId !== "unattributed" && turn.terminal && normalized !== undefined;+ inputTokens += (normalized?.inputTokens ?? 0) - (normalized?.cacheWriteTokens ?? 0);+ outputTokens += normalized?.outputTokens ?? 0;+ cacheReadTokens += normalized?.cachedInputTokens ?? 0;+ cacheWriteTokens += normalized?.cacheWriteTokens ?? 0;+ const price = nativeUsageCostUsd(turn.usage, provider);+ if (price === undefined) costIncomplete = true;+ else { cost += usdToUnits(price); costKnown = true; }+ }+ // A free empty attempt contributes no price evidence for later paid work.+ // Keep an incomplete zero subtotal absent so complete aggregate tokens can+ // still receive an estimate. Preserve positive known spend and true zero totals.+ const retainCost = costKnown && (!costIncomplete || cost > 0n);+ const runDelta = { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens,+ ...(retainCost ? { providerCostUsd: Number(cost) / 1_000_000_000 } : {}) };+ const current = currentTurn ? turns.get(currentTurn) : undefined;+ return { usage: { runDelta, accountingCostIncomplete: costIncomplete,+ ...(retainCost ? { accountingCostUsdExact: `${cost / 1_000_000_000n}.${String(cost % 1_000_000_000n).padStart(9, "0")}` } : {}) },+ turnId: current && normalizeNativeUsage(current.usage) ? currentTurn : undefined, complete };+ };+ return {+ observe(event: PrpEvent) {+ if (!event) return false;+ const payload = record(event.payload);+ const terminal = terminalTypes.includes(event.eventType);+ if (payload.kind !== "usage" && event.eventType !== "turn.started" && !terminal) return false;+ // Historical replay can revisit an earlier report after restoration.+ // Re-persist its aggregate, but never rewind or count that report twice.+ if (event.sourceInstanceId && Number.isSafeInteger(event.sourceSeq)) {+ if (event.sourceSeq <= (sequences.get(event.sourceInstanceId) ?? -1)) return true;+ sequences.set(event.sourceInstanceId, event.sourceSeq);+ }+ const key = event.turnId ?? "unattributed";+ const turn = turns.get(key) ?? { usage: null, terminal: false };+ if (event.eventType === "turn.started") {+ currentTurn = event.turnId;+ turn.usage = null;+ turn.terminal = false;+ } else if (payload.kind === "usage" && (!currentTurn || !turns.has(key))) currentTurn = event.turnId;+ if (payload.kind === "usage") {+ const usage = record(payload.usage);+ turn.usage = Object.hasOwn(usage, "runDelta")+ ? { runDelta: record(usage.runDelta), runDeltaComplete: usage.runDeltaComplete } : null;+ }+ if (terminal) turn.terminal = true;+ turns.set(key, turn);+ return true;+ },+ snapshot,+ finish(turnId: string | null) {+ const turn = turnId ? turns.get(turnId) : undefined;+ if (turn) turn.terminal = true;+ return snapshot();+ },+ };+}+export function nativeUsageCostUsd(usage: Record<string, unknown> | null,provider?: NativeExecutionInput["provider"],@@ -9403,50 +9568,73 @@ export function nativeUsageCostUsd(if (provider?.kind === "acpx" && ["cursor", "copilot", "pi"].includes(provider.agent)) return undefined;if (!usage) return undefined;const measurement = nativeUsageMeasurement(usage);- const direct =- numericUsageField(usage, [- "providerCostUsd",- "cacheAdjustedCostUsd",- "costUsd",- ]) ??- numericUsageField(measurement, [- "providerCostUsd",- "cacheAdjustedCostUsd",- "costUsd",- ]);- if (direct !== undefined) return direct;- const cost = record(usage.cost);+ const hasRunDelta = Object.hasOwn(usage, "runDelta") || Object.hasOwn(record(usage.usage), "runDelta");+ const direct = numericUsageField(measurement, ["cacheAdjustedCostUsd", "providerCostUsd", "costUsd"])+ ?? (hasRunDelta ? undefined : numericUsageField(usage, ["cacheAdjustedCostUsd", "providerCostUsd", "costUsd"]));+ // PRP currently defaults an absent providerCostUsd to zero. That zero is+ // not proof of a free request when the runtime observed token consumption.+ if (direct !== undefined && direct > 0) return direct;+ const normalized = normalizeNativeUsage(usage);+ if (direct === 0 && normalized && Object.values(normalized).every(value => value === 0)) return 0;+ const cost = record(hasRunDelta ? measurement.cost : usage.cost);const currency =typeof cost.currency === "string" ? cost.currency.toUpperCase() : "USD";if (currency !== "USD") return undefined;return numericUsageField(cost, ["amount", "total"]);}-export function normalizeNativeUsage(usage: Record<string, unknown> | null) {- if (!usage) return undefined;+/** Billing identity follows the selected runtime and resolved credentials.+ * Unknown authentication remains unknown; a provider name does not prove billing mode. */+export function resolveNativeBilling(provider: NativeExecutionInput["provider"], env: NodeJS.ProcessEnv = {}, identity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">): Pick<AdapterExecutionResult, "provider" | "biller" | "billingType"> {+ if (identity) return identity.provider === "openai" && identity.billingType === "metered_api"+ ? { ...identity, biller: inferOpenAiCompatibleBiller(env, identity.biller ?? "unknown") }+ : identity;+ if (provider.kind === "claude_managed") return { provider: "anthropic", biller: "anthropic", billingType: "metered_api" };+ if (provider.kind === "aws_agentcore") return { provider: "aws_agentcore", biller: "aws_agentcore", billingType: "metered_api" };+ if (provider.kind === "acpx" && ["cursor", "copilot"].includes(provider.agent)) {+ const biller = nativeUsageBiller(provider);+ return { provider: biller, biller, billingType: "unknown" };+ }+ if (provider.kind === "acpx" && provider.agent === "claude") {+ if (env.CLAUDE_CODE_USE_BEDROCK === "1") return { provider: "anthropic", biller: "aws_bedrock", billingType: "metered_api" };+ return { provider: "anthropic", biller: "anthropic", billingType: env.ANTHROPIC_API_KEY ? "metered_api" : env.CLAUDE_CODE_OAUTH_TOKEN ? "subscription_included" : "unknown" };+ }+ if (provider.kind === "opencode" || (provider.kind === "acpx" && provider.agent === "pi")) {+ const parts = (provider.model ?? "").split("/");+ const biller = parts.length > 1 ? parts[0] : provider.kind === "acpx" ? nativeUsageBiller(provider) : "unknown";+ const modelProvider = biller === "openrouter" && parts.length > 2 ? parts[1] : biller;+ return { provider: modelProvider, biller, billingType: "unknown" };+ }+ if (provider.kind !== "codex" && !(provider.kind === "acpx" && provider.agent === "codex"))+ return { provider: "unknown", biller: "unknown", billingType: "unknown" };+ return { provider: "openai", biller: env.OPENAI_API_KEY ? inferOpenAiCompatibleBiller(env, "openai") : "unknown", billingType: env.OPENAI_API_KEY ? "metered_api" : "unknown" };+}++export function normalizeNativeUsage(usage: Record<string, unknown> | null, options: { inputIncludesCacheReads?: boolean } = {}) {+ if (!usage || usage.runDeltaComplete === false || record(usage.usage).runDeltaComplete === false) return undefined;const measurement = nativeUsageMeasurement(usage);const cache = record(measurement.cache);- const cachedInputTokens =- numericUsageField(measurement, [- "cachedInputTokens",- "cacheReadInputTokens",- "cacheReadTokens",- "cachedReadTokens",- ]) ?? numericUsageField(cache, ["read"]);+ const count = (source: Record<string, unknown>, keys: string[]) => {+ for (const key of keys) {+ if (source[key] === undefined) continue;+ const value = source[key];+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : NaN;+ }+ return undefined;+ };+ const input = count(measurement, ["inputTokens", "input", "promptTokens"]);+ const outputTokens = count(measurement, ["outputTokens", "output", "completionTokens"]);+ const cachedInputTokens = count(measurement, ["cachedInputTokens", "cacheReadInputTokens", "cacheReadTokens", "cachedReadTokens"]) ?? count(cache, ["read"]);+ const cacheWriteTokens = count(measurement, ["cacheWriteTokens", "cacheCreationInputTokens", "cachedWriteTokens"]) ?? count(cache, ["write"]);+ if (input === undefined || outputTokens === undefined+ || ![input, outputTokens, cachedInputTokens ?? 0, cacheWriteTokens ?? 0].every(Number.isSafeInteger)) return undefined;+ const inputTokens = input - (options.inputIncludesCacheReads ? cachedInputTokens ?? 0 : 0)+ + (options.inputIncludesCacheReads ? 0 : cacheWriteTokens ?? 0);+ if (!Number.isSafeInteger(inputTokens) || inputTokens < (cacheWriteTokens ?? 0)) return undefined;return {- inputTokens:- numericUsageField(measurement, [- "inputTokens",- "input",- "promptTokens",- ]) ?? 0,- outputTokens:- numericUsageField(measurement, [- "outputTokens",- "output",- "completionTokens",- ]) ?? 0,+ inputTokens, outputTokens,...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),+ ...(cacheWriteTokens === undefined ? {} : { cacheWriteTokens }),};}diff --git a/server/src/services/plugin-managed-agents.ts b/server/src/services/plugin-managed-agents.tsindex f86f7a439d..4c4e2ee1ae 100644--- a/server/src/services/plugin-managed-agents.ts+++ b/server/src/services/plugin-managed-agents.ts@@ -337,7 +337,7 @@ export function pluginManagedAgentService(// and its canonical history. Transfer only its proven stable-key marker to// the replacement installation, atomically with the new scoped bindings.await upsertBinding(companyId, declaration, agentId, {}, adapterType, tx);- const [relinked] = await tx.update(agents).set({+ await tx.update(agents).set({metadata: managedMetadata(options.pluginId, options.pluginKey, declaration, agent.metadata),updatedAt: new Date(),}).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))).returning();@@ -346,6 +346,8 @@ export function pluginManagedAgentService(action: "plugin.managed_agent.relinked", entityType: "agent", entityId: agentId,details: { sourcePluginKey: options.pluginKey, managedResourceKey: declaration.agentKey, previousPluginId },});+ const relinked = await agentService(tx as unknown as Db).getById(agentId);+ if (!relinked) throw notFound("Managed agent not found after relink");return relinked as Agent;});}diff --git a/server/src/services/provider-billing-import.ts b/server/src/services/provider-billing-import.tsnew file mode 100644index 0000000000..b7bf3a1387--- /dev/null+++ b/server/src/services/provider-billing-import.ts@@ -0,0 +1,376 @@+import { z } from "zod";+import { and, eq, gte, inArray, lt } from "drizzle-orm";+import {+ companySecrets,+ providerBillingSnapshots,+ type Db,+} from "@paperclipai/db";+import {+ centsToUnits,+ usdToUnits,+ unitsToCents,+ importProviderCostsSchema,+ type ImportProviderCosts,+} from "@paperclipai/shared";+import { secretService } from "./secrets.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { createFinanceEventInTransaction } from "./finance.js";+import { forbidden, unprocessable } from "../errors.js";++const pageSchema = z.object({+ data: z+ .array(+ z.object({+ start_time: z.number().int().optional(),+ end_time: z.number().int().optional(),+ starting_at: z.iso.datetime({ offset: true }).optional(),+ ending_at: z.iso.datetime({ offset: true }).optional(),+ results: z+ .array(+ z.object({+ project_id: z.string().nullable().optional(),+ workspace_id: z.string().nullable().optional(),+ amount: z.union([+ z.string(),+ z.object({ value: z.number().finite(), currency: z.string() }),+ ]),+ currency: z.string().optional(),+ }),+ )+ .max(5000),+ }),+ )+ .max(31),+ has_more: z.boolean(),+ next_page: z.string().max(4000).nullable().optional(),+});+export interface DailyProviderCost {+ day: string;+ scopeId: string;+ amountCents: string;+}++async function boundedJson(response: Response) {+ if (!response.ok || !response.body)+ throw unprocessable(+ "Provider billing is unavailable. Check the admin credential and selected account.",+ );+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ for (;;) {+ const next = await reader.read();+ if (next.done) break;+ size += next.value.byteLength;+ if (size > 2_000_000)+ throw unprocessable(+ "Provider billing response is too large; use a shorter period.",+ );+ chunks.push(next.value);+ }+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));+ } finally {+ await reader.cancel().catch(() => undefined);+ }+}++/** Complete every page before writing. Group only by project/workspace so a+ * provider's line-item changes cannot manufacture duplicate charges. */+export async function fetchProviderDailyCosts(+ input: ImportProviderCosts,+ credential: string,+ fetcher = fetch,+): Promise<DailyProviderCost[]> {+ const parsed = importProviderCostsSchema.parse(input);+ const from = Date.parse(parsed.from),+ to = Date.parse(parsed.to);+ const base = new URL(+ parsed.provider === "openai"+ ? "https://api.openai.com/v1/organization/costs"+ : "https://api.anthropic.com/v1/organizations/cost_report",+ );+ base.searchParams.set(+ parsed.provider === "openai" ? "start_time" : "starting_at",+ parsed.provider === "openai"+ ? String(from / 1000)+ : new Date(from).toISOString(),+ );+ base.searchParams.set(+ parsed.provider === "openai" ? "end_time" : "ending_at",+ parsed.provider === "openai"+ ? String(to / 1000)+ : new Date(to).toISOString(),+ );+ base.searchParams.set("bucket_width", "1d");+ base.searchParams.set("limit", "31");+ base.searchParams.append(+ "group_by[]",+ parsed.provider === "openai" ? "project_id" : "workspace_id",+ );+ const headers: Record<string, string> =+ parsed.provider === "openai"+ ? {+ Authorization: `Bearer ${credential}`,+ "OpenAI-Organization": parsed.accountId,+ }+ : { "x-api-key": credential, "anthropic-version": "2023-06-01" };+ headers["User-Agent"] = "Paperclip/1.0 (https://paperclip.ing)";+ const totals = new Map<string, bigint>();+ const seen = new Set<string>();+ const days = new Set<number>();+ // Missing requested scopes in an otherwise complete daily report mean zero.+ for (let time = from; time < to; time += 86400000)+ for (const scope of parsed.scopeIds)+ totals.set(`${new Date(time).toISOString().slice(0, 10)}:${scope}`, 0n);+ const cursors = new Set<string>();+ const signal = AbortSignal.timeout(30_000);+ if (parsed.provider === "anthropic") {+ const identity = z.object({ id: z.string() }).parse(+ await boundedJson(+ await fetcher("https://api.anthropic.com/v1/organizations/me", {+ headers,+ signal,+ redirect: "error",+ }),+ ),+ );+ if (identity.id !== parsed.accountId)+ throw unprocessable(+ "The admin credential belongs to a different provider organization.",+ );+ }+ for (let page = 0; page < 100; page++) {+ const response = await fetcher(base, {+ headers,+ signal,+ redirect: "error",+ });+ const body = pageSchema.parse(await boundedJson(response));+ for (const bucket of body.data) {+ const start =+ parsed.provider === "openai"+ ? (bucket.start_time ?? NaN) * 1000+ : Date.parse(bucket.starting_at ?? "");+ const end =+ parsed.provider === "openai"+ ? (bucket.end_time ?? NaN) * 1000+ : Date.parse(bucket.ending_at ?? "");+ if (+ !Number.isFinite(start) ||+ start < from ||+ end > to ||+ end - start !== 86400000 ||+ start % 86400000 !== 0+ )+ throw unprocessable("Provider returned an unexpected billing period.");+ days.add(start);+ for (const result of bucket.results) {+ const scopeField = parsed.provider === "openai" ? "project_id" : "workspace_id";+ if (!Object.hasOwn(result, scopeField)) {+ throw unprocessable("Provider report is missing the requested project/workspace grouping.");+ }+ const scope =+ (parsed.provider === "openai"+ ? result.project_id+ : result.workspace_id) ?? "default";+ if (!parsed.scopeIds.includes(scope)) continue;+ const identity = `${new Date(start).toISOString().slice(0, 10)}:${scope}`;+ if (seen.has(identity))+ throw unprocessable("Provider returned overlapping billing buckets.");+ seen.add(identity);+ const currency =+ typeof result.amount === "object"+ ? result.amount.currency+ : result.currency;+ if (currency?.toUpperCase() !== "USD")+ throw unprocessable("Only USD provider cost reports are supported.");+ const units =+ parsed.provider === "openai" && typeof result.amount === "object"+ ? usdToUnits(result.amount.value)+ : parsed.provider === "anthropic" &&+ typeof result.amount === "string"+ ? centsToUnits(result.amount)+ : -1n;+ if (units < 0n)+ throw unprocessable("Provider returned an invalid billing amount.");+ totals.set(identity, units);+ }+ }+ if (!body.has_more) {+ if (days.size !== (to - from) / 86400000)+ throw unprocessable(+ "Provider report is incomplete; no financial events were changed.",+ );+ return [...totals].map(([key, value]) => ({+ day: key.slice(0, 10),+ scopeId: key.slice(11),+ amountCents: unitsToCents(value),+ }));+ }+ if (!body.next_page || cursors.has(body.next_page))+ throw unprocessable("Provider returned an invalid billing cursor.");+ cursors.add(body.next_page);+ base.searchParams.set("page", body.next_page);+ }+ throw unprocessable("Provider billing report exceeded the page limit.");+}++export async function importProviderDailyCosts(+ db: Db,+ companyId: string,+ raw: ImportProviderCosts,+ actorId: string,+ fetcher = fetch,+) {+ const input = importProviderCostsSchema.parse(raw);+ const [secret] = await db+ .select()+ .from(companySecrets)+ .where(+ and(+ eq(companySecrets.id, input.secretId),+ eq(companySecrets.companyId, companyId),+ ),+ );+ if (!secret || secret.scope !== "company")+ throw forbidden("Select a company billing credential.");+ // Metadata is an explicit operator designation, not the secret-storage+ // provider (which may be local encryption, AWS, etc.). Never send a generic+ // company secret to an external API merely because the caller knows its ID.+ const designation = secret.providerMetadata?.providerBilling;+ if (!designation || typeof designation !== "object" || Array.isArray(designation)+ || !("provider" in designation) || designation.provider !== input.provider+ || !("accountId" in designation) || designation.accountId !== input.accountId) {+ throw forbidden("Select a company secret designated for this billing provider and account.");+ }+ const credential = await secretService(db).resolveSecretValue(+ companyId,+ secret.id,+ "latest",+ {+ accessContext: {+ consumerType: "system",+ consumerId: "provider-billing-import",+ actorType: "user",+ actorId,+ },+ },+ );+ // Compare database revisions, not application clocks: concurrent importers+ // can run on different hosts or start in the same millisecond.+ const snapshots = await db+ .select()+ .from(providerBillingSnapshots)+ .where(+ and(+ eq(providerBillingSnapshots.companyId, companyId),+ eq(providerBillingSnapshots.provider, input.provider),+ eq(providerBillingSnapshots.accountId, input.accountId),+ inArray(providerBillingSnapshots.scopeId, input.scopeIds),+ gte(providerBillingSnapshots.day, input.from),+ lt(providerBillingSnapshots.day, input.to),+ ),+ );+ const expectedRevisions = new Map(+ snapshots.map((row) => [`${row.day}:${row.scopeId}`, row.revision]),+ );+ const daily = await fetchProviderDailyCosts(input, credential, fetcher);+ return applyProviderDailyCosts(+ db,+ companyId,+ input,+ daily,+ actorId,+ expectedRevisions,+ );+}++export async function applyProviderDailyCosts(+ db: Db,+ companyId: string,+ input: ImportProviderCosts,+ daily: DailyProviderCost[],+ actorId: string,+ expectedRevisions?: ReadonlyMap<string, number>,+) {+ return withAccountingTransaction(db, companyId, async (tx, publications) => {+ let eventsCreated = 0;+ for (const day of daily) {+ const where = and(+ eq(providerBillingSnapshots.companyId, companyId),+ eq(providerBillingSnapshots.provider, input.provider),+ eq(providerBillingSnapshots.accountId, input.accountId),+ eq(providerBillingSnapshots.scopeId, day.scopeId),+ eq(providerBillingSnapshots.day, day.day),+ );+ const [previous] = await tx+ .select()+ .from(providerBillingSnapshots)+ .where(where);+ const delta =+ centsToUnits(day.amountCents) -+ centsToUnits(previous?.amountCents ?? "0");+ if (previous && delta === 0n) continue;+ if (+ expectedRevisions &&+ (previous?.revision ?? 0) !==+ (expectedRevisions.get(`${day.day}:${day.scopeId}`) ?? 0)+ )+ throw unprocessable(+ "A newer provider report was imported. Fetch the report again.",+ );+ const revision = (previous?.revision ?? 0) + 1;+ const [snapshot] = previous+ ? await tx+ .update(providerBillingSnapshots)+ .set({+ amountCents: day.amountCents,+ revision,+ updatedAt: new Date(),+ })+ .where(where)+ .returning()+ : await tx+ .insert(providerBillingSnapshots)+ .values({+ companyId,+ provider: input.provider,+ accountId: input.accountId,+ ...day,+ revision,+ })+ .returning();+ if (!delta) continue;+ await createFinanceEventInTransaction(+ tx,+ publications,+ companyId,+ {+ idempotencyKey: `provider-report:${snapshot.id}:${revision}`,+ biller: input.provider,+ eventKind: "inference_charge",+ direction: delta < 0n ? "credit" : "debit",+ currency: "USD",+ amountCents: unitsToCents(delta < 0n ? -delta : delta),+ occurredAt: new Date(`${day.day}T00:00:00.000Z`),+ description:+ `${input.provider} cost report · ${day.scopeId} · ${day.day}${revision > 1 ? " (correction)" : ""}`.slice(+ 0,+ 500,+ ),+ metadataJson: {+ source: "provider_cost_report",+ accountId: input.accountId,+ scopeId: day.scopeId,+ revision,+ totalCents: day.amountCents,+ },+ },+ { actorType: "user", actorId },+ );+ eventsCreated++;+ }+ return { daysRead: daily.length, eventsCreated };+ });+}diff --git a/server/src/services/receipt-fingerprint.ts b/server/src/services/receipt-fingerprint.tsnew file mode 100644index 0000000000..d70acc6b33--- /dev/null+++ b/server/src/services/receipt-fingerprint.ts@@ -0,0 +1,12 @@+import { createHash } from "node:crypto";++function canonical(value: unknown): unknown {+ if (value instanceof Date) return value.toISOString();+ if (Array.isArray(value)) return value.map(canonical);+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]));+ return value;+}++export function receiptFingerprint(value: unknown): string {+ return createHash("sha256").update(JSON.stringify(canonical(value))).digest("hex");+}diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.tsindex b58f44380f..89fcb42b80 100644--- a/server/src/services/recovery/service.ts+++ b/server/src/services/recovery/service.ts@@ -3835,6 +3835,12 @@ export function recoveryService(current.companyId,current.id,);+ // Budget admission may wait behind another recovery worker. Read the+ // execution paths after the persisted counter so a newly reserved+ // successor cannot be mistaken for permission to schedule the next one.+ const currentState = await collectDispositionRepairSourceState(db, { issue: current });+ if (currentState.hasActiveExecutionPath || currentState.hasDurableWaitingPath) return "skipped";+ if (!episode && currentState.fingerprint !== state.fingerprint) return "skipped";const runAttempt =previousAttempt?.fingerprint === state.fingerprint? previousAttempt.attemptdiff --git a/server/src/services/run-cost-accounting.ts b/server/src/services/run-cost-accounting.tsnew file mode 100644index 0000000000..6a3b4263b0--- /dev/null+++ b/server/src/services/run-cost-accounting.ts@@ -0,0 +1,200 @@+import { usdToUnits, unitsToCents } from "@paperclipai/shared";+import { and, asc, eq, inArray, sql } from "drizzle-orm";+import { accountingRuntimeBaselines, budgetReservations, agentRuntimeState, agents, costEvents, heartbeatRuns, nativeRunFinalizations, issues, projects, type Db } from "@paperclipai/db";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { conflict } from "../errors.js";+import { createCostEventInTransaction } from "./costs.js";+import { budgetService, deliverBudgetEnforcement, type BudgetServiceHooks } from "./budgets.js";+import { logger } from "../middleware/logger.js";+import { promises as fs } from "node:fs";+import { replayUsageReceipts, indexPendingUsageReceipts, recoverPendingRunUsageReceipts, type UsageReceiptIndex } from "./usage-receipts.js";++const terminalStatuses = ["succeeded", "failed", "timed_out", "cancelled", "interrupted"];+const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};+const text = (value: unknown) => typeof value === "string" && value.length > 0 ? value : null;+const amount = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;++/** The run's persisted usage is a durable receipt. Ledger, runtime totals, and+ * acknowledgement commit together, including after a restart or failed run. */+export async function accountRunCost(db: Db, runId: string, hooks: BudgetServiceHooks = {}, receiptIndex?: UsageReceiptIndex) {+ const [identity] = await db.select({ companyId: heartbeatRuns.companyId, status: heartbeatRuns.status,+ pending: heartbeatRuns.costAccountingPending, accountedAt: heartbeatRuns.costAccountedAt,+ issueId: sql<string | null>`${heartbeatRuns.usageJson}->'ledgerScope'->>'issueId'`,+ }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));+ if (!identity) return false;+ // Finalization can call twice. Avoid disk work for settled or active runs,+ // but retain the locked recheck, stale-marker cleanup, and stop delivery.+ const index = identity.pending && !identity.accountedAt && terminalStatuses.includes(identity.status)+ ? receiptIndex ?? await indexPendingUsageReceipts() : undefined;+ let recoveredFiles: string[] = [];+ const accounted = await withAccountingTransaction(db, identity.companyId, async (tx, publications) => {+ // Native recovery owns the issue before updating its run. Acquire the+ // charge's issue FK lock first so inserting it cannot reverse that order.+ const issueId = text(identity.issueId);+ if (issueId) await tx.select({ id: issues.id }).from(issues).where(and(+ eq(issues.companyId, identity.companyId), eq(issues.id, issueId),+ )).for("key share");+ let [run] = await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("update");+ if (!run?.costAccountingPending || !terminalStatuses.includes(run.status)) return false;+ if (run.costAccountedAt) {+ await tx.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, run.id));+ return false;+ }+ // The bounded global replay can leave a newer receipt behind an older+ // complete snapshot. Drain this run under the accounting lock before+ // deciding completeness, and retain disk evidence until the outer commit.+ recoveredFiles = await recoverPendingRunUsageReceipts(tx, { companyId: identity.companyId, runId }, undefined, { retainFiles: true, index });+ [run] = await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));+ if (text(object(object(run.usageJson).ledgerScope).issueId) !== issueId) {+ throw conflict("Run cost attribution changed. Retry accounting.");+ }+ // A failed capture may follow an older complete attempt. Neither replay+ // nor terminal status can certify that the missing work was free.+ if (object(run.usageJson).accountingCaptureFailed === true) return false;+ const preProviderFailure = object(object(run.resultJson).executionRecovery).providerWorkStarted === false+ || object(run.usageJson).accountingProviderWorkStarted === false;+ // A failed native turn is not necessarily the end of this heartbeat: the+ // coordinator can resume the same run. Only its closed provider boundary+ // authorizes acknowledgement; finalization may still run after a result.+ if (run.runtimeMode === "native" && !preProviderFailure) {+ const [coordinator] = await tx.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id));+ if (coordinator && !coordinator.resultId && coordinator.phase !== "terminal_failure") return false;+ }+ // A stop can mark the run terminal before the provider's shutdown receipt+ // arrives. Keep the debt pending instead of acknowledging an invented zero+ // and permanently discarding that late receipt.+ if (!preProviderFailure && object(run.usageJson).accountingReceiptReady === false) return false;+ // Acknowledgement is part of the same transaction. Budget checks inside+ // this transaction must not mistake this receipt for missing accounting.+ await tx.update(heartbeatRuns).set({ costAccountingPending: false, costAccountedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));+ await tx.update(budgetReservations).set({ state: preProviderFailure ? "released" : "settled", settledAt: new Date() })+ .where(and(eq(budgetReservations.companyId, run.companyId), eq(budgetReservations.runId, run.id), eq(budgetReservations.state, "held")));+ if (preProviderFailure) return true;+ const usage = object(run.usageJson);+ const scope = object(usage.ledgerScope);+ // Deleted attribution targets become unallocated; a deletion must never+ // prevent recording provider spend. Foreign-company references still fail.+ for (const [table, key] of [[issues, "issueId"], [projects, "projectId"]] as const) {+ const id = text(scope[key]);+ if (id) {+ const [linked] = await tx.select({ id: table.id }).from(table).where(eq(table.id, id));+ if (!linked) scope[key] = null;+ }+ }+ const costUsd = amount(usage.cacheAdjustedCostUsd) ?? text(usage.costUsdExact) ?? amount(usage.costUsd);+ const billingType = text(usage.billingType) ?? "unknown";+ const costUnits = billingType === "subscription_included" ? 0n : usdToUnits(costUsd ?? 0);+ const costCents = unitsToCents(costUnits);+ const [agent] = await tx.select({ adapterType: agents.adapterType }).from(agents).where(eq(agents.id, run.agentId));+ const hasBillableEvidence = agent?.adapterType !== "process" || costUsd !== null || usage.costStatus === "unpriced"+ || ["inputTokens", "cachedInputTokens", "outputTokens"].some(key => (amount(usage[key]) ?? 0) > 0)+ || (text(usage.provider) !== null && usage.provider !== "unknown");+ const receipt = {+ idempotencyKey: `heartbeat:${run.id}:final`,+ agentId: run.agentId, heartbeatRunId: run.id,+ issueId: text(scope.issueId), projectId: text(scope.projectId), billingCode: text(scope.billingCode),+ provider: text(usage.provider) ?? "unknown", biller: text(usage.biller) ?? text(usage.provider) ?? "unknown",+ providerRequestId: text(usage.providerRequestId),+ pricingProvenance: object(usage.pricingProvenance),+ model: text(usage.model) ?? "unknown", billingType,+ costStatus: (costUsd === null || usage.costStatus === "unpriced") && billingType !== "subscription_included" && hasBillableEvidence ? "unpriced" : usage.costStatus === "estimated" ? "estimated" : "reported",+ inputTokens: amount(usage.inputTokens) ?? 0, cachedInputTokens: amount(usage.cachedInputTokens) ?? 0, outputTokens: amount(usage.outputTokens) ?? 0,+ costCents, occurredAt: run.finishedAt ?? run.createdAt,+ };+ const parts = Array.isArray(usage.usageByModel) ? usage.usageByModel.map(object) : [];+ const tokensMatch = ["inputTokens", "cachedInputTokens", "outputTokens"].every((key) =>+ parts.reduce((sum, part) => sum + (amount(object(part.usage)[key]) ?? 0), 0) === (amount(usage[key]) ?? 0));+ const costMatches = costUsd !== null && parts.reduce((sum, part) => sum + usdToUnits(amount(part.costUsd) ?? 0), 0n) === usdToUnits(costUsd);+ const validParts = parts.length > 0 && tokensMatch && costMatches+ && parts.every((part) => text(part.model) && amount(part.costUsd) !== null)+ && new Set(parts.map((part) => part.model)).size === parts.length;+ if (validParts) {+ let allocated = 0n;+ for (const [index, part] of parts.entries()) {+ const partUsage = object(part.usage);+ const remainder = costUnits - allocated;+ const reported = usdToUnits(amount(part.costUsd) ?? 0);+ const partUnits = billingType === "subscription_included" ? 0n : index === parts.length - 1 ? remainder : reported < remainder ? reported : remainder;+ allocated += partUnits;+ const partCents = unitsToCents(partUnits);+ await createCostEventInTransaction(tx, run.companyId, {+ ...receipt, idempotencyKey: `heartbeat:${run.id}:model:${index}`, model: text(part.model)!,+ inputTokens: amount(partUsage.inputTokens) ?? 0, cachedInputTokens: amount(partUsage.cachedInputTokens) ?? 0,+ outputTokens: amount(partUsage.outputTokens) ?? 0, costCents: partCents,+ }, publications);+ }+ } else {+ await createCostEventInTransaction(tx, run.companyId, receipt, publications);+ }+ const [event] = await tx.select({+ inputTokens: sql<string>`coalesce(sum(${costEvents.inputTokens}),0)::text`,+ cachedInputTokens: sql<string>`coalesce(sum(${costEvents.cachedInputTokens}),0)::text`,+ outputTokens: sql<string>`coalesce(sum(${costEvents.outputTokens}),0)::text`,+ costCents: sql<string>`coalesce(sum(${costEvents.costCents}),0)::text`,+ }).from(costEvents).where(and(eq(costEvents.companyId, run.companyId), eq(costEvents.heartbeatRunId, run.id)));+ await tx.insert(agentRuntimeState).values({ agentId: run.agentId, companyId: run.companyId, adapterType: agent.adapterType }).onConflictDoNothing();+ await tx.execute(sql`insert into accounting_runtime_baselines (agent_id,company_id,cost_cents,input_tokens,cached_input_tokens,output_tokens)+ select agent_id,company_id,total_cost_cents,total_input_tokens,total_cached_input_tokens,total_output_tokens+ from agent_runtime_state where agent_id = ${run.agentId} on conflict do nothing`);+ await tx.update(agentRuntimeState).set({+ totalInputTokens: sql`${agentRuntimeState.totalInputTokens} + ${event.inputTokens}`,+ totalCachedInputTokens: sql`${agentRuntimeState.totalCachedInputTokens} + ${event.cachedInputTokens}`,+ totalOutputTokens: sql`${agentRuntimeState.totalOutputTokens} + ${event.outputTokens}`,+ totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${event.costCents}::numeric`,+ updatedAt: new Date(),+ }).where(eq(agentRuntimeState.agentId, run.agentId));+ await tx.update(heartbeatRuns).set({ costAccountingPending: false, costAccountedAt: new Date(), accountingProjectionVersion: "v2", accountingLastError: null, accountingLastAttemptAt: new Date() }).where(eq(heartbeatRuns.id, run.id));+ return true;+ });+ for (const file of recoveredFiles) {+ try { await fs.rm(file, { force: true }); }+ catch (error) { logger.warn({ err: error, runId }, "Accounting committed; recovered receipt cleanup will retry"); }+ }+ await deliverBudgetEnforcement(db, hooks, identity.companyId);+ return accounted;+}++export async function reconcileRunCosts(db: Db, hooks: BudgetServiceHooks = {}) {+ const pending = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.costAccountingPending, true), inArray(heartbeatRuns.status, terminalStatuses),+ sql`${heartbeatRuns.usageJson}->>'accountingCaptureFailed' is distinct from 'true'`,+ sql`(${heartbeatRuns.resultJson}->'executionRecovery'->>'providerWorkStarted' = 'false'+ or ${heartbeatRuns.usageJson}->>'accountingProviderWorkStarted' = 'false'+ or not exists (select 1 from ${nativeRunFinalizations} where ${nativeRunFinalizations.runId} = ${heartbeatRuns.id}+ and ${heartbeatRuns.runtimeMode} = 'native' and ${nativeRunFinalizations.resultId} is null+ and ${nativeRunFinalizations.phase} <> 'terminal_failure'))`,+ sql`(${heartbeatRuns.usageJson}->>'accountingReceiptReady' is distinct from 'false' or ${heartbeatRuns.resultJson}->'executionRecovery'->>'providerWorkStarted' = 'false' or ${heartbeatRuns.usageJson}->>'accountingProviderWorkStarted' = 'false')`,+ )).orderBy(asc(heartbeatRuns.updatedAt), asc(heartbeatRuns.id)).limit(100);+ let accounted = 0;+ const receiptIndex = pending.length > 0 ? await indexPendingUsageReceipts() : undefined;+ for (const run of pending) {+ try { if (await accountRunCost(db, run.id, hooks, receiptIndex)) accounted++; }+ catch (error) {+ // Move failed attempts behind other pending work so a poisoned receipt+ // cannot monopolize the bounded batch on every recovery tick.+ await db.update(heartbeatRuns).set({ updatedAt: new Date(), accountingLastAttemptAt: new Date(), accountingAttemptCount: sql`${heartbeatRuns.accountingAttemptCount} + 1`, accountingLastError: error instanceof Error ? error.message.slice(0, 1000) : "Accounting failed" }).where(eq(heartbeatRuns.id, run.id));+ logger.error({ err: error, runId: run.id }, "Run accounting remains pending for retry");+ }+ }+ await budgetService(db, hooks).reconcilePolicies();+ return { scanned: pending.length, accounted };+}++/** Share one full sweep across overlapping scheduler ticks. Do not enqueue+ * another sweep: the next tick retries after either success or failure. */+export function createCostAccountingReconciler(db: Db, hooks: BudgetServiceHooks = {}) {+ let inFlight: Promise<Awaited<ReturnType<typeof reconcileRunCosts>>> | undefined;+ return () => {+ if (!inFlight) {+ inFlight = (async () => {+ try {+ await replayUsageReceipts(db);+ return await reconcileRunCosts(db, hooks);+ } finally {+ inFlight = undefined;+ }+ })();+ }+ return inFlight;+ };+}diff --git a/server/src/services/runtime-skill-cache.ts b/server/src/services/runtime-skill-cache.tsindex 5bade582ab..010fb28bf1 100644--- a/server/src/services/runtime-skill-cache.ts+++ b/server/src/services/runtime-skill-cache.ts@@ -165,6 +165,18 @@ async function setTreeMode(directory: string, readonly: boolean): Promise<void>if (readonly) await fs.chmod(directory, 0o555);}+// Darwin requires a directory being renamed to be writable by its owner.+// Change only the directory itself, while the publication lock is held; the+// contents remain read-only. Restore the mode even when publication fails.+async function renameCacheDirectory(source: string, destination: string) {+ const stat = await fs.lstat(source);+ const directory = stat.isDirectory() && !stat.isSymbolicLink();+ if (directory) await fs.chmod(source, 0o700);+ let moved = false;+ try { await fs.rename(source, destination); moved = true; }+ finally { if (directory) await fs.chmod(moved ? destination : source, stat.mode & 0o777); }+}+async function removeTree(directory: string): Promise<void> {await setTreeMode(directory, false);await fs.rm(directory, { recursive: true, force: true });@@ -202,9 +214,9 @@ export async function resolveRuntimeSkillCache(if (!await matches(spec, staging)) throw new Error("Runtime skill cache validation failed");// Lifecycle mutations can update the DB while this builder owns the filesystem lock.if (!await stillInstalled()) throw new Error("Skill was renamed or removed during preparation");- await fs.rename(spec.entry, path.join(spec.root, `.invalid-${spec.fingerprint}-${randomUUID()}`))+ await renameCacheDirectory(spec.entry, path.join(spec.root, `.invalid-${spec.fingerprint}-${randomUUID()}`)).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; });- await fs.rename(staging, spec.entry);+ await renameCacheDirectory(staging, spec.entry);return path.join(spec.entry, "files");} finally { await removeTree(staging); }});diff --git a/server/src/services/status-cards.ts b/server/src/services/status-cards.tsindex 025fd0dd18..0838e77c3e 100644--- a/server/src/services/status-cards.ts+++ b/server/src/services/status-cards.ts@@ -179,7 +179,7 @@ export function statusCardService(: Promise.resolve(null),db.select({tokens: sql<number>`coalesce(sum(coalesce(${statusCardUpdates.inputTokens}, 0) + coalesce(${statusCardUpdates.outputTokens}, 0)), 0)::int`,- costCents: sql<number>`coalesce(sum(${statusCardUpdates.costCents}), 0)::int`,+ costCents: sql<number>`coalesce(sum(${statusCardUpdates.costCents}), 0)::double precision`,}).from(statusCardUpdates).where(and(eq(statusCardUpdates.cardId, card.id), gte(statusCardUpdates.startedAt, dayStart)))@@ -877,7 +877,7 @@ export function statusCardService(? await tx.select({inputTokens: sql<number>`coalesce(sum(${costEvents.inputTokens}), 0)::int`,outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::int`,- costCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::int`,+ costCents: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,}).from(costEvents).where(eq(costEvents.heartbeatRunId, actor.runId)): [];const existingUpdate = await tx.select().from(statusCardUpdates)@@ -892,7 +892,7 @@ export function statusCardService(changeSummary: input.changeSummary,inputTokens: Number(usage[0]?.inputTokens ?? 0),outputTokens: Number(usage[0]?.outputTokens ?? 0),- costCents: Number(usage[0]?.costCents ?? 0),+ costCents: sql`${usage[0]?.costCents ?? "0"}::numeric`,};if (existingUpdate) {await tx.update(statusCardUpdates).set(updateValues).where(eq(statusCardUpdates.id, existingUpdate.id));diff --git a/server/src/services/usage-receipts.ts b/server/src/services/usage-receipts.tsnew file mode 100644index 0000000000..7d02f0c047--- /dev/null+++ b/server/src/services/usage-receipts.ts@@ -0,0 +1,311 @@+import { priceCodexReceipt } from "./codex-pricing.js";+import { randomUUID } from "node:crypto";+import { promises as fs } from "node:fs";+import path from "node:path";+import { z } from "zod";+import { and, eq, isNull, sql } from "drizzle-orm";+import { heartbeatRuns, runUsageReceipts, type Db } from "@paperclipai/db";+import type { AdapterExecutionResult, AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";+import { pricingProvenanceSchema, usdToUnits } from "@paperclipai/shared";+import { resolvePaperclipInstanceRoot } from "../home-paths.js";+import { conflict, notFound } from "../errors.js";+import { logger } from "../middleware/logger.js";+import { receiptFingerprint } from "./receipt-fingerprint.js";+import { withAccountingTransaction } from "./accounting-transaction.js";+import { ensureDurableDirectory, syncDirectory } from "../lib/durable-directory.js";++const token = z.number().int().nonnegative().max(2_147_483_647);+const price = z.number().finite().nonnegative().nullable().optional();+const usage = z.object({ inputTokens: token, outputTokens: token, cachedInputTokens: token.optional(), cacheWriteTokens: token.optional() });+const checkpointSchema = z.object({+ attemptId: z.string().uuid().optional(), usage: usage.optional(),+ usageByModel: z.array(z.object({ model: z.string().min(1).max(250), usage, costUsd: z.number().finite().nonnegative() })).max(500).optional(),+ usageBasis: z.enum(["per_run", "session_cumulative"]).nullable().optional(),+ provider: z.string().max(250).nullable().optional(), biller: z.string().max(250).nullable().optional(),+ model: z.string().max(250).nullable().optional(), billingType: z.string().max(100).nullable().optional(),+ costUsd: price, cacheAdjustedCostUsd: price,+ costStatus: z.enum(["reported", "estimated", "unpriced"]).optional(),+ pricingContext: z.object({ serviceTier: z.string().max(50).optional(), contextTier: z.enum(["short", "long"]).optional() }).optional(),+ pricingProvenance: pricingProvenanceSchema.optional(),+ costUsdExact: z.string().max(160).refine(value => { try { return !value.startsWith("-") && usdToUnits(value) >= 0n; } catch { return false; } }, "Invalid exact USD amount").nullable().optional(),+ providerRequestId: z.string().max(250).nullable().optional(), complete: z.boolean(),+});+const envelopeSchema = z.object({+ schema: z.literal("paperclip/accounting-receipt/v1"), id: z.string().uuid(), companyId: z.string().uuid(),+ runId: z.string().uuid(), sourceId: z.string().uuid(), sequence: z.number().int().positive(), receivedAt: z.iso.datetime(),+ adapterType: z.string().max(100), receipt: checkpointSchema,+});+export type UsageReceiptEnvelope = z.infer<typeof envelopeSchema>;+export const usageReceiptSpoolPath = () => path.join(resolvePaperclipInstanceRoot(), "accounting-receipts");++export async function spoolUsageReceipt(envelope: UsageReceiptEnvelope, directory = usageReceiptSpoolPath()) {+ const parsed = envelopeSchema.parse(envelope);+ await ensureDurableDirectory(directory);+ const target = path.join(directory, `${parsed.id}.json`);+ const temporary = `${target}.${randomUUID()}.tmp`;+ const handle = await fs.open(temporary, "wx", 0o600);+ try {+ try { await handle.writeFile(JSON.stringify(parsed)); await handle.sync(); }+ finally { await handle.close(); }+ await fs.rename(temporary, target); await syncDirectory(directory);+ } catch (error) { await fs.rm(temporary, { force: true }); throw error; }+ return target;+}++export async function persistUsageReceipt(db: Db, raw: UsageReceiptEnvelope) {+ const envelope = envelopeSchema.parse(raw);+ const hash = receiptFingerprint(envelope);+ return withAccountingTransaction(db, envelope.companyId, async tx => {+ const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, envelope.runId), eq(heartbeatRuns.companyId, envelope.companyId))).for("update");+ if (!run) throw notFound("Accounting run not found");+ const [existing] = await tx.select().from(runUsageReceipts).where(and(eq(runUsageReceipts.companyId, envelope.companyId), eq(runUsageReceipts.runId, envelope.runId), eq(runUsageReceipts.sourceId, envelope.sourceId), eq(runUsageReceipts.sequence, envelope.sequence)));+ if (existing && existing.receiptHash !== hash) throw conflict("Conflicting usage checkpoint replay");+ if (!existing) await tx.insert(runUsageReceipts).values({+ id: envelope.id, companyId: envelope.companyId, runId: envelope.runId, sourceId: envelope.sourceId,+ sequence: envelope.sequence, receiptHash: hash, receiptJson: envelope, complete: envelope.receipt.complete, receivedAt: new Date(envelope.receivedAt),+ });+ const previous = run.usageJson ?? {};+ // A restarted/replaced controller owns a fresh source. Old spool files+ // remain auditable but cannot overwrite its snapshots or acknowledged work.+ if (run.costAccountedAt || previous.accountingReceiptSourceId !== envelope.sourceId || Number(previous.accountingReceiptSequence ?? 0) >= envelope.sequence) return;+ const receipt = envelope.receipt;+ const billingType = receipt.billingType === "api" ? "metered_api" : receipt.billingType === "subscription" ? "subscription_included" : receipt.billingType ?? "unknown";+ await tx.update(heartbeatRuns).set({+ costAccountingPending: true,+ accountingLastError: previous.accountingCaptureFailed === true ? "usage_capture_failed" : null,+ usageJson: { ...previous, ...receipt.usage,+ provider: receipt.provider ?? "unknown", biller: receipt.biller ?? receipt.provider ?? "unknown", model: receipt.model ?? "unknown", billingType,+ costUsd: receipt.costUsd ?? null, costUsdExact: receipt.costUsdExact ?? null, cacheAdjustedCostUsd: receipt.cacheAdjustedCostUsd ?? null,+ usageByModel: receipt.usageByModel ?? null, usageSource: receipt.usageBasis ?? "per_run", providerRequestId: receipt.providerRequestId ?? null,+ accountingReceiptReady: previous.accountingCaptureFailed !== true && receipt.complete && receipt.usageBasis !== "session_cumulative", accountingReceiptId: envelope.id,+ accountingReceiptSequence: envelope.sequence, accountingReceiptReceivedAt: envelope.receivedAt,+ costStatus: receipt.costStatus ?? null,+ pricingProvenance: receipt.pricingProvenance ?? { source: receipt.costUsd != null || receipt.costUsdExact != null ? "provider_reported" : "unknown", version: "accounting-receipt/v1" },+ },+ }).where(and(eq(heartbeatRuns.id, run.id), isNull(heartbeatRuns.costAccountedAt)));+ });+}++export async function replayUsageReceipts(db: Db, directory = usageReceiptSpoolPath(), limit = 100) {+ let files: string[];+ try { files = (await fs.readdir(directory)).filter(name => name.endsWith(".json")).sort(); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { replayed: 0, failed: 0 }; throw error; }+ let replayed = 0, failed = 0;+ for (const name of files.slice(0, limit)) {+ const file = path.join(directory, name);+ try {+ const info = await fs.lstat(file);+ if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Invalid accounting spool entry");+ await persistUsageReceipt(db, envelopeSchema.parse(JSON.parse(await fs.readFile(file, "utf8"))));+ await fs.rm(file, { force: true }); replayed++;+ } catch (error) {+ failed++;+ // Rotate failures behind fresh entries without discarding the evidence.+ await fs.rename(file, path.join(directory, `retry-${Date.now()}-${randomUUID()}.json`)).catch(() => undefined);+ logger.error({ err: error, receiptFile: name }, "Accounting spool receipt remains pending");+ }+ }+ return { replayed, failed };+}++type ReceiptIdentity = { companyId: unknown; runId: unknown } | null;+export type UsageReceiptIndex = Map<string, ReceiptIdentity>;+function receiptIdentity(raw: unknown): ReceiptIdentity {+ return raw && typeof raw === "object" && "companyId" in raw && "runId" in raw+ ? { companyId: raw.companyId, runId: raw.runId } : null;+}++/** Build once per recovery batch, before acquiring any accounting lock.+ * Spool publications are immutable, uniquely named files. Cache identities,+ * never receipt contents: matching evidence is revalidated during settlement. */+export async function indexPendingUsageReceipts(directory = usageReceiptSpoolPath()): Promise<UsageReceiptIndex> {+ const index: UsageReceiptIndex = new Map();+ let names: string[];+ try { names = await fs.readdir(directory); }+ // Indexing is only an optimization. The locked drain reports missing or+ // unreadable storage through the existing per-run recovery error path.+ catch { return index; }+ for (const name of names.filter(name => name.endsWith(".json"))) {+ const file = path.join(directory, name);+ try {+ const info = await fs.lstat(file);+ if (!info.isFile() || info.size > 1024 * 1024) { index.set(file, null); continue; }+ index.set(file, receiptIdentity(JSON.parse(await fs.readFile(file, "utf8"))));+ } catch (error) {+ if (error instanceof SyntaxError) index.set(file, null);+ // Unreadable or concurrently moved entries remain unknown and are+ // checked again under the lock, preserving per-run failure reporting.+ }+ }+ return index;+}++export async function recoverPendingRunUsageReceipts(db: Db, input: { companyId: string; runId: string }, directory = usageReceiptSpoolPath(), options: { retainFiles?: boolean; index?: UsageReceiptIndex } = {}) {+ // The bounded sweep may not reach this run. Its durable evidence must+ // reach the journal before source replacement or ledger acknowledgement.+ // A failed save aborts the operation so recovery can retry.+ const recovered = new Set<string>();+ // A concurrent failed replay can rename a file after releasing its company+ // lock. Rescan disappearing paths rather than certify an incomplete scan.+ for (let scan = 0; scan < 3; scan++) {+ let names: string[];+ try { names = await fs.readdir(directory); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return [...recovered]; throw error; }+ let moved = false;+ for (const name of names.filter(name => name.endsWith(".json"))) {+ const file = path.join(directory, name);+ if (recovered.has(file)) continue;+ const indexed = options.index?.get(file);+ if (indexed !== undefined && (indexed?.companyId !== input.companyId || indexed?.runId !== input.runId)) continue;+ let raw: unknown;+ try {+ const info = await fs.lstat(file);+ if (!info.isFile() || info.size > 1024 * 1024) continue;+ raw = JSON.parse(await fs.readFile(file, "utf8"));+ } catch (error) {+ // The background replayer can move/remove a file while we scan. Invalid+ // JSON remains on disk for its normal recovery/error reporting path.+ if ((error as NodeJS.ErrnoException).code === "ENOENT") { moved = true; continue; }+ if (error instanceof SyntaxError) continue;+ throw error;+ }+ const identity = receiptIdentity(raw);+ options.index?.set(file, identity);+ if (identity?.companyId !== input.companyId || identity?.runId !== input.runId) continue;+ await persistUsageReceipt(db, envelopeSchema.parse(raw));+ // Settlement uses the caller's transaction: deleting before its commit+ // would lose the only durable evidence if the later ledger write fails.+ recovered.add(file);+ if (!options.retainFiles) await fs.rm(file, { force: true });+ }+ if (!moved) return [...recovered];+ }+ throw new Error("Accounting spool changed during recovery; retry required");+}++export async function createRunUsageRecorder(db: Db, input: { companyId: string; runId: string; adapterType: string }, directory = usageReceiptSpoolPath()) {+ const sourceId = randomUUID();+ // Verify durable storage before starting paid work, including a directory+ // sync. The database binding fences checkpoints from replaced controllers.+ await ensureDurableDirectory(directory);+ const probe = await fs.open(path.join(directory, `${sourceId}.probe`), "wx", 0o600);+ try { await probe.sync(); } finally { await probe.close(); await fs.rm(path.join(directory, `${sourceId}.probe`)); }+ await syncDirectory(directory);+ await recoverPendingRunUsageReceipts(db, input, directory);+ const bound = await db.update(heartbeatRuns).set({ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ accountingReceiptSourceId: sourceId, accountingReceiptSequence: 0, accountingReceiptReady: false })}::jsonb` })+ .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId), isNull(heartbeatRuns.costAccountedAt))).returning({ id: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode, usageJson: heartbeatRuns.usageJson });+ if (bound.length !== 1) throw conflict("Run cannot accept a new usage recorder");+ let sequence = 0;+ let currentAttempt = "default";+ const attempts = new Map<string, AdapterUsageCheckpoint>();+ // Native run deltas retain their baseline across same-run recovery. Restore+ // the previous snapshot as the same attempt, never add it a second time.+ // An empty final result must not erase the last durable observation.+ const priorReceiptId = bound[0].usageJson?.accountingReceiptId;+ if (bound[0].runtimeMode === "native" && typeof priorReceiptId === "string") {+ const [previous] = await db.select().from(runUsageReceipts).where(and(+ eq(runUsageReceipts.id, priorReceiptId), eq(runUsageReceipts.runId, input.runId), eq(runUsageReceipts.companyId, input.companyId),+ ));+ if (previous) attempts.set("default", envelopeSchema.parse(previous.receiptJson).receipt as AdapterUsageCheckpoint);+ }+ let chain = Promise.resolve();+ let captureFailed = bound[0].usageJson?.accountingCaptureFailed === true;+ async function persistFailure() {+ if (!captureFailed) return;+ await withAccountingTransaction(db, input.companyId, async tx => {+ await tx.update(heartbeatRuns).set({+ costAccountingPending: true, accountingLastError: "usage_capture_failed",+ usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || '{"accountingCaptureFailed":true,"accountingReceiptReady":false}'::jsonb`,+ }).where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId),+ isNull(heartbeatRuns.costAccountedAt), sql`${heartbeatRuns.usageJson}->>'accountingReceiptSourceId' = ${sourceId}`));+ });+ }+ function enqueue(action: () => Promise<AdapterUsageCheckpoint>) {+ const result = chain.then(action).catch(async error => {+ captureFailed = true;+ // Persist before exposing rejection: the adapter's flush may throw before+ // complete(), and failure finalization must not settle an older receipt.+ try { await persistFailure(); }+ catch (failure) { logger.error({ err: failure, runId: input.runId }, "Usage capture failure fence requires retry before finalization"); }+ throw error;+ });+ chain = result.then(() => undefined, () => undefined);+ return result;+ }+ async function capture(raw: AdapterUsageCheckpoint) {+ const parsed = checkpointSchema.parse(raw) as AdapterUsageCheckpoint;+ const attempt = parsed.attemptId ?? currentAttempt;+ if (!attempts.has(attempt)) currentAttempt = attempt;+ const previous = attempts.get(attempt);+ const priced = priceCodexReceipt({ ...parsed, usage: parsed.usage ?? previous?.usage,+ complete: parsed.complete && !(previous?.usage && !parsed.usage) });+ priced.pricingProvenance ??= {+ source: priced.costUsd != null || priced.costUsdExact != null || priced.cacheAdjustedCostUsd != null ? "provider_reported" : "unknown",+ version: "accounting-receipt/v1",+ };+ attempts.set(attempt, priced);+ const parts = [...attempts.values()];+ const latest = attempts.get(currentAttempt)!;+ const receipt: AdapterUsageCheckpoint = { ...latest, complete: latest.complete && !captureFailed, usage: {+ inputTokens: parts.reduce((sum, item) => sum + (item.usage?.inputTokens ?? 0), 0),+ cachedInputTokens: parts.reduce((sum, item) => sum + (item.usage?.cachedInputTokens ?? 0), 0),+ ...(parts.some(item => item.usage?.cacheWriteTokens !== undefined) ? { cacheWriteTokens: parts.reduce((sum, item) => sum + (item.usage?.cacheWriteTokens ?? 0), 0) } : {}),+ outputTokens: parts.reduce((sum, item) => sum + (item.usage?.outputTokens ?? 0), 0),+ } };+ if (parts.length > 1) {+ let total = 0n, priced = true;+ for (const part of parts) {+ const subscription = ["subscription", "subscription_included"].includes(part.billingType ?? "");+ const cost = subscription ? 0 : part.cacheAdjustedCostUsd ?? part.costUsdExact ?? part.costUsd;+ if (cost == null || (!subscription && part.costStatus === "unpriced")) priced = false;+ if (cost != null) total += usdToUnits(cost);+ }+ if (new Set(parts.map(part => part.billingType ?? "unknown")).size > 1) receipt.billingType = "unknown";+ const decimal = `${total / 1_000_000_000n}.${String(total % 1_000_000_000n).padStart(9, "0")}`;+ receipt.costUsdExact = decimal;+ receipt.costUsd = Number(decimal);+ receipt.cacheAdjustedCostUsd = null;+ // A rejected resume can report a complete, explicit zero before the+ // successful retry. It contributes neither spend nor tokens and must+ // not discard the successful attempt's known model attribution.+ const attributed = parts.filter(part => {+ const cost = part.cacheAdjustedCostUsd ?? part.costUsdExact ?? part.costUsd;+ return !part.complete || part.costStatus === "unpriced" || cost == null || usdToUnits(cost) !== 0n+ || Object.values(part.usage ?? {}).some(value => (value ?? 0) !== 0);+ });+ receipt.usageByModel = attributed.length === 1 ? attributed[0].usageByModel : undefined;+ receipt.costStatus = priced && parts.some(part => part.costStatus === "estimated") ? "estimated" : priced ? "reported" : "unpriced";+ receipt.pricingProvenance = { source: receipt.costStatus === "estimated" ? "rate_card" : "unknown", version: "per-attempt/v1", evidence: "Sum of attempted-run receipts; component prices are retained in the immutable receipt journal." };+ // Every attempted provider must supply a final receipt before the total+ // can be considered complete, even if a later attempt succeeded.+ receipt.complete = !captureFailed && parts.every(part => part.complete);+ }+ const envelope: UsageReceiptEnvelope = { schema: "paperclip/accounting-receipt/v1", id: randomUUID(), ...input, sourceId, sequence: ++sequence, receivedAt: new Date().toISOString(), receipt };+ const file = await spoolUsageReceipt(envelope, directory);+ try { await persistUsageReceipt(db, envelope); await fs.rm(file, { force: true }); }+ catch (error) { logger.warn({ err: error, runId: input.runId, receiptId: envelope.id }, "Usage receipt is durable on disk; database replay pending"); }+ return receipt;+ }+ return {+ capture: (receipt: AdapterUsageCheckpoint) => enqueue(() => capture(receipt)),+ // Retry a transient database failure before heartbeat can mark the run+ // terminal. A failed retry must propagate and leave finalization pending.+ persistFailure: async () => { await chain; await persistFailure(); },+ complete: (result: AdapterExecutionResult) => enqueue(async () => {+ const final = checkpointSchema.parse({ ...result, complete: result.usageComplete !== false }) as AdapterUsageCheckpoint;+ const previous = attempts.get(currentAttempt);+ // A bounded stdout tail can lose a terminal record already saved from the+ // full stream. Keep that stronger evidence, but never hide additional+ // usage/charges or certify a snapshot inherited from a replaced recorder.+ if (sequence > 0 && previous?.complete && result.usageComplete === false) {+ const moreTokens = (["inputTokens", "cachedInputTokens", "cacheWriteTokens", "outputTokens"] as const)+ .some(key => (final.usage?.[key] ?? 0) > (previous.usage?.[key] ?? 0));+ const finalPrice = final.cacheAdjustedCostUsd ?? final.costUsdExact ?? final.costUsd;+ const previousPrice = previous.cacheAdjustedCostUsd ?? previous.costUsdExact ?? previous.costUsd;+ const moreCost = finalPrice != null && (previousPrice == null || usdToUnits(finalPrice) > usdToUnits(previousPrice));+ if (!moreTokens && !moreCost) return capture(previous);+ }+ return capture(final);+ }),+ };+}diff --git a/server/vitest.config.ts b/server/vitest.config.tsindex 71e8df328a..0e9d524a1c 100644--- a/server/vitest.config.ts+++ b/server/vitest.config.ts@@ -5,6 +5,12 @@ import { defineConfig } from "vitest/config";export default defineConfig({resolve: {alias: [+ {+ find: /^@paperclipai\/paperclip-runner\/live$/,+ replacement: fileURLToPath(+ new URL("../packages/paperclip-runner/src/live/index.ts", import.meta.url),+ ),+ },{find: /^@paperclipai\/paperclip-runner$/,replacement: fileURLToPath(@@ -37,7 +43,6 @@ export default defineConfig({isolate: true,maxConcurrency: 1,maxWorkers: 1,- minWorkers: 1,pool: "forks",// Server suites share process state and one embedded Postgres instance,// so tests inside a file must run one at a time. Do not setdiff --git a/ui/src/App.activity-routing.test.tsx b/ui/src/App.activity-routing.test.tsxindex b87aec4405..6d97e0d1dc 100644--- a/ui/src/App.activity-routing.test.tsx+++ b/ui/src/App.activity-routing.test.tsx@@ -100,10 +100,10 @@ vi.mock("./pages/audit/CompanyActivity.production", () => ({},}));-vi.mock("./pages/Costs.production", () => ({+vi.mock("./pages/Costs", () => ({Costs: () => {const location = useLocation();- return <div>{`PRODUCTION_COSTS@${location.pathname}${location.search}`}</div>;+ return <div>{`SHARED_COSTS@${location.pathname}${location.search}`}</div>;},}));@@ -267,14 +267,14 @@ describe("App Activity routing (PAP-16302)", () => {flushSync(() => root.unmount());});- it("uses the production Activity and Costs routes when Streamlined UI is disabled", async () => {+ it("uses legacy Activity and the shared standalone Costs page when Streamlined UI is disabled", async () => {streamlinedUiState.enabled = false;const activityRoot = renderAppAt(container, "/PAP/activity");await waitForRoute(container, "PRODUCTION_ACTIVITY@/PAP/activity");flushSync(() => activityRoot.unmount());const costsRoot = renderAppAt(container, "/PAP/costs?range=30d");- await waitForRoute(container, "PRODUCTION_COSTS@/PAP/costs?range=30d");+ await waitForRoute(container, "SHARED_COSTS@/PAP/costs?range=30d");flushSync(() => costsRoot.unmount());});diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex b3894d4971..4d3babdf57 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -53,6 +53,7 @@ import { Approvals } from "./pages/Approvals";import { ApprovalDetail } from "./pages/ApprovalDetail";import { CompanyActivity } from "./pages/audit/CompanyActivity";import { AuditHub } from "./pages/audit/AuditHub";+import { Costs } from "./pages/Costs";import { Inbox } from "./pages/Inbox";import { useCombinedInboxTasksEnabled } from "./hooks/useCombinedInboxTasksEnabled";import { WhatNeedsMe } from "./pages/WhatNeedsMe";@@ -138,9 +139,6 @@ const ProductionCompanySkills = lazy(() =>const ProductionCompanyActivity = lazy(() =>import("./pages/audit/CompanyActivity.production").then((module) => ({ default: module.CompanyActivity })),);-const ProductionCosts = lazy(() =>- import("./pages/Costs.production").then((module) => ({ default: module.Costs })),-);const ProductionOrgChart = lazy(() =>import("./pages/OrgChart.production").then((module) => ({ default: module.OrgChart })),);@@ -424,7 +422,7 @@ function boardRoutes(streamlinedUiEnabled: boolean, combinedInboxTasksEnabled: b</>) : (<>- <Route path="costs" element={<ProductionSurface><ProductionCosts /></ProductionSurface>} />+ <Route path="costs" element={<Costs />} /><Route path="audit" element={<Navigate to="/activity?mode=agents" replace />} /></>)}diff --git a/ui/src/api/costs.ts b/ui/src/api/costs.tsindex 4dda60a77d..637ff175dc 100644--- a/ui/src/api/costs.ts+++ b/ui/src/api/costs.ts@@ -1,6 +1,7 @@import type {CostSummary,CostByAgent,+ CostByUserReport,CostByProviderModel,CostByBiller,CostByAgentModel,@@ -16,6 +17,7 @@ import { api } from "./client";function dateParams(from?: string, to?: string): string {const params = new URLSearchParams();+ if (!from && !to) params.set("period", "all");if (from) params.set("from", from);if (to) params.set("to", to);const qs = params.toString();@@ -25,6 +27,8 @@ function dateParams(from?: string, to?: string): string {export const costsApi = {summary: (companyId: string, from?: string, to?: string) =>api.get<CostSummary>(`/companies/${companyId}/costs/summary${dateParams(from, to)}`),+ byUser: (companyId: string, from?: string, to?: string) =>+ api.get<CostByUserReport>(`/companies/${companyId}/costs/by-user${dateParams(from, to)}`),byAgent: (companyId: string, from?: string, to?: string) =>api.get<CostByAgent[]>(`/companies/${companyId}/costs/by-agent${dateParams(from, to)}`),byAgentModel: (companyId: string, from?: string, to?: string) =>@@ -51,6 +55,7 @@ export const costsApi = {function dateParamsWithLimit(from?: string, to?: string, limit?: number): string {const params = new URLSearchParams();+ if (!from && !to) params.set("period", "all");if (from) params.set("from", from);if (to) params.set("to", to);if (limit) params.set("limit", String(limit));diff --git a/ui/src/components/AccountQuotaPanels.tsx b/ui/src/components/AccountQuotaPanels.tsxnew file mode 100644index 0000000000..6bea5dcd88--- /dev/null+++ b/ui/src/components/AccountQuotaPanels.tsx@@ -0,0 +1,66 @@+import type { ProviderQuotaResult } from "@paperclipai/shared";+import { formatDateTime } from "../lib/utils";+import { QuotaBar } from "./QuotaBar";+import { quotaUnavailableMessage } from "../lib/quota-refresh";++export function AccountQuotaPanels({+ accounts,+ failed,+}: {+ accounts: ProviderQuotaResult[];+ failed?: boolean;+}) {+ return (+ <div className="space-y-4">+ {accounts.map((account) => (+ <section+ className="space-y-2"+ key={account.accountKey ?? account.provider}+ >+ <p className="text-sm font-medium">+ {account.accountLabel ?? "Subscription account"}+ </p>+ {(failed || !account.ok) && (+ <p className="text-sm text-muted-foreground">+ {account.errorFamily === "credentials_unavailable"+ ? "Connect or reconnect a subscription in AI connections to view its quota."+ : quotaUnavailableMessage(account.windows.length > 0)}+ </p>+ )}+ {account.windows.map((window, index) => window.usedPercent == null ? (+ <div key={`${window.label}:${index}`} className="space-y-1 text-sm">+ <div className="flex justify-between gap-3">+ <span>{window.label}</span>+ <span className="font-mono text-muted-foreground">{window.valueLabel ?? "Usage not reported"}</span>+ </div>+ {window.resetsAt && <p className="text-xs font-mono text-muted-foreground">Resets {formatDateTime(window.resetsAt)}</p>}+ </div>+ ) : (+ <QuotaBar+ key={`${window.label}:${index}`}+ className="font-mono"+ label={window.label}+ percentUsed={window.usedPercent}+ leftLabel={+ window.valueLabel ??+ (window.usedPercent === null+ ? "Usage not reported"+ : `${window.usedPercent}% used`)+ }+ rightLabel={+ window.resetsAt+ ? `Resets ${formatDateTime(window.resetsAt)}`+ : undefined+ }+ />+ ))}+ {account.capturedAt && (+ <p className="text-xs font-mono text-muted-foreground">+ Last checked {formatDateTime(account.capturedAt)}+ </p>+ )}+ </section>+ ))}+ </div>+ );+}diff --git a/ui/src/components/BillerSpendCard.tsx b/ui/src/components/BillerSpendCard.tsxindex a2ea2d2eb1..db6aa467c9 100644--- a/ui/src/components/BillerSpendCard.tsx+++ b/ui/src/components/BillerSpendCard.tsx@@ -8,6 +8,8 @@ interface BillerSpendCardProps {row: CostByBiller;weekSpendCents: number;budgetMonthlyCents: number;+ /** Only compare a current-month report with the monthly budget. */+ showBudgetUtilization?: boolean;totalCompanySpendCents: number;providerRows: CostByProviderModel[];}@@ -16,6 +18,7 @@ export function BillerSpendCard({row,weekSpendCents,budgetMonthlyCents,+ showBudgetUtilization = true,totalCompanySpendCents,providerRows,}: BillerSpendCardProps) {@@ -44,10 +47,7 @@ export function BillerSpendCard({return Array.from(map.entries()).sort((a, b) => b[1] - a[1]);}, [providerRows]);- const providerBudgetShare =- budgetMonthlyCents > 0 && totalCompanySpendCents > 0- ? (row.costCents / totalCompanySpendCents) * budgetMonthlyCents- : budgetMonthlyCents;+ const providerBudgetShare = budgetMonthlyCents;const budgetPct =providerBudgetShare > 0? Math.min(100, (row.costCents / providerBudgetShare) * 100)@@ -78,12 +78,12 @@ export function BillerSpendCard({</CardHeader><CardContent className="px-4 pb-4 pt-3 space-y-4">- {budgetMonthlyCents > 0 && (+ {showBudgetUtilization && budgetMonthlyCents > 0 && (<QuotaBarlabel="Period spend"percentUsed={budgetPct}leftLabel={formatCents(row.costCents)}- rightLabel={`${Math.round(budgetPct)}% of allocation`}+ rightLabel={`${Math.round(budgetPct)}% of company budget`}/>)}diff --git a/ui/src/components/BudgetIncidentCard.tsx b/ui/src/components/BudgetIncidentCard.tsxindex 44fa60a7c9..8be14d2542 100644--- a/ui/src/components/BudgetIncidentCard.tsx+++ b/ui/src/components/BudgetIncidentCard.tsx@@ -57,7 +57,9 @@ export function BudgetIncidentCard({</div><CardTitle className="mt-1 text-base text-red-950 dark:text-red-50">{incident.scopeName}</CardTitle><CardDescription className="mt-1 text-red-900/75 dark:text-red-100/70">- Spending reached {formatCents(incident.amountObserved)} against a limit of {formatCents(incident.amountLimit)}.+ {incident.thresholdType === "hard" && incident.amountObserved < incident.amountLimit+ ? `Accounting is incomplete. Known spend is ${formatCents(incident.amountObserved)}; review pending or unpriced usage in the budget policy.`+ : `Spending reached ${formatCents(incident.amountObserved)} against a limit of ${formatCents(incident.amountLimit)}.`}</CardDescription></div><div className="rounded-full border border-red-400/30 bg-red-500/10 p-2 text-red-600 dark:text-red-200">diff --git a/ui/src/components/BudgetPolicyCard.tsx b/ui/src/components/BudgetPolicyCard.tsxindex 2b0624ac19..b79d518cc9 100644--- a/ui/src/components/BudgetPolicyCard.tsx+++ b/ui/src/components/BudgetPolicyCard.tsx@@ -1,4 +1,5 @@-import { useEffect, useState } from "react";+import { centsToUsd, usdToCents } from "@paperclipai/shared";+import { useEffect, useId, useState } from "react";import type { BudgetPolicySummary } from "@paperclipai/shared";import { AlertTriangle, PauseCircle, ShieldAlert, Wallet } from "lucide-react";import { cn, formatCents } from "../lib/utils";@@ -31,12 +32,16 @@ function statusTone(status: BudgetPolicySummary["status"]) {export function BudgetPolicyCard({summary,onSave,+ onUnpricedUsagePolicyChange,+ onReservationChange,isSaving,compact = false,variant = "card",}: {summary: BudgetPolicySummary;onSave?: (amountCents: number) => void;+ onReservationChange?: (cents: string) => void;+ onUnpricedUsagePolicyChange?: (policy: "block" | "allow") => void;isSaving?: boolean;compact?: boolean;variant?: "card" | "plain";@@ -47,6 +52,38 @@ export function BudgetPolicyCard({setDraftBudget(centsInputValue(summary.amount));}, [summary.amount]);+ const [reservation, setReservation] = useState(centsToUsd(summary.reservationCents ?? 0));+ const reservationErrorId = useId();+ useEffect(() => setReservation(centsToUsd(summary.reservationCents ?? 0)), [summary.reservationCents]);+ let reservationCents: string | null = null;+ try { if (!reservation.trim().startsWith("-")) reservationCents = usdToCents(reservation.trim()); } catch { /* Shown as invalid input below. */ }+ const reservationSection = onReservationChange ? <div className="space-y-2">+ <label className="text-sm">Reserve per run (USD)+ <Input aria-label="Reserve per run (USD)" aria-invalid={reservationCents === null} aria-describedby={reservationCents === null ? reservationErrorId : undefined}+ value={reservation} onChange={event => setReservation(event.target.value)} inputMode="decimal" />+ </label>+ {reservationCents === null && <p id={reservationErrorId} role="alert" className="text-xs text-destructive">Enter a valid amount of zero or more.</p>}+ <p className="text-xs text-muted-foreground">An estimate held before each run starts. Zero disables the estimate. Actual provider charges may exceed it.</p>+ <Button variant="outline" disabled={isSaving || reservationCents === null || reservationCents === (summary.reservationCents ?? "0.0000000")}+ onClick={() => { if (reservationCents !== null) onReservationChange(reservationCents); }}>Update reservation</Button>+ </div> : null;++ const advancedSettings = onReservationChange || onUnpricedUsagePolicyChange ? (+ <details className="space-y-3">+ <summary className="cursor-pointer text-sm font-medium">Advanced settings</summary>+ <div className="space-y-4">+ {onUnpricedUsagePolicyChange && (+ <label className="flex items-center gap-2 text-sm">+ <input type="checkbox" checked={summary.unpricedUsagePolicy !== "allow"} disabled={isSaving}+ onChange={(event) => onUnpricedUsagePolicyChange(event.target.checked ? "block" : "allow")} />+ Block new work when usage has no reliable price+ </label>+ )}+ {reservationSection}+ </div>+ </details>+ ) : null;+const parsedDraft = parseDollarInput(draftBudget);const canSave = typeof parsedDraft === "number" && parsedDraft !== summary.amount && Boolean(onSave);const progress = summary.amount > 0 ? Math.min(100, summary.utilizationPercent) : 0;@@ -95,6 +132,10 @@ export function BudgetPolicyCard({const progressSection = (<div className="space-y-2">+ {summary.pendingRunCount > 0 && <p className="text-sm text-destructive">{summary.pendingRunCount} completed runs await accounting.</p>}+ {summary.unpricedEventCount > 0 && (+ <p className="text-sm text-destructive">{summary.unpricedEventCount} usage events are unpriced. Known spend excludes their unknown cost.</p>+ )}<div className="flex items-center justify-between text-xs text-muted-foreground"><span>Remaining</span><span>{summary.amount > 0 ? formatCents(summary.remainingAmount) : "Unlimited"}</span>@@ -125,8 +166,8 @@ export function BudgetPolicyCard({<PauseCircle className="mt-0.5 h-4 w-4 shrink-0" /><div>{summary.scopeType === "project"- ? "Execution is paused for this project until the budget is raised or the incident is dismissed."- : "Heartbeats are paused for this scope until the budget is raised or the incident is dismissed."}+ ? "Execution is paused for this project until the budget block is resolved."+ : "Heartbeats are paused for this scope until the budget block is resolved."}</div></div>) : null;@@ -186,6 +227,7 @@ export function BudgetPolicyCard({{progressSection}{pausedPane}{saveSection}+ {advancedSettings}{parsedDraft === null ? (<p className="text-xs text-destructive">Enter a valid non-negative dollar amount.</p>) : null}@@ -215,6 +257,7 @@ export function BudgetPolicyCard({{progressSection}{pausedPane}{saveSection}+ {advancedSettings}{parsedDraft === null ? (<p className="text-xs text-destructive">Enter a valid non-negative dollar amount.</p>) : null}diff --git a/ui/src/components/CostByUserTable.tsx b/ui/src/components/CostByUserTable.tsxnew file mode 100644index 0000000000..d3561b20a2--- /dev/null+++ b/ui/src/components/CostByUserTable.tsx@@ -0,0 +1,56 @@+import type { CostByUserReport } from "@paperclipai/shared";+import { CostEstimateLabel } from "./CostEstimateLabel";+import { Identity } from "./Identity";+import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";+import { formatCents, formatTokens } from "../lib/utils";++export function CostByUserTable({ report }: { report: CostByUserReport }) {+ return (+ <Card className="gap-3 py-4">+ <CardHeader className="gap-0 px-5">+ <CardTitle className="text-base">By user</CardTitle>+ </CardHeader>+ <CardContent className="px-5">+ <div className="overflow-x-auto">+ <table aria-label="Costs by user" className="w-full text-sm">+ <thead className="text-muted-foreground">+ <tr className="border-b border-border">+ <th scope="col" className="py-2 pr-4 text-left font-medium">User</th>+ <th scope="col" className="px-4 py-2 text-right font-medium">Runs</th>+ <th scope="col" className="px-4 py-2 text-right font-medium">Input</th>+ <th scope="col" className="px-4 py-2 text-right font-medium">Output</th>+ <th scope="col" className="py-2 pl-4 text-right font-medium">Cost</th>+ </tr>+ </thead>+ <tbody>+ {report.rows.length === 0 && (+ <tr><td colSpan={5} className="py-3 text-muted-foreground">No user-attributed costs yet.</td></tr>+ )}+ {report.rows.map(row => (+ <tr key={row.userId ?? "unattributed"} className="border-b border-border last:border-0">+ <th scope="row" className="py-3 pr-4 text-left font-normal">+ {row.userId ? <Identity name={row.userName ?? "Unknown user"} avatarUrl={row.userImage} /> : "Unattributed"}+ </th>+ <td className="px-4 py-3 text-right tabular-nums">{row.runCount.toLocaleString()}</td>+ <td className="px-4 py-3 text-right tabular-nums">+ {formatTokens(row.inputTokens + row.cachedInputTokens)}+ {row.cachedInputTokens > 0 && <div className="whitespace-nowrap text-xs text-muted-foreground">{formatTokens(row.cachedInputTokens)} cached</div>}+ </td>+ <td className="px-4 py-3 text-right tabular-nums">{formatTokens(row.outputTokens)}</td>+ <td className="py-3 pl-4 text-right tabular-nums">+ <div>{row.costCents === 0 && row.eventCount > 0 && row.unpricedEventCount === row.eventCount ? "—" : formatCents(row.costCents)}</div>+ <CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />+ {row.unpricedEventCount > 0 && <div className="whitespace-nowrap text-xs text-muted-foreground">{row.unpricedEventCount} unpriced {row.unpricedEventCount === 1 ? "charge" : "charges"}</div>}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ {report.rows.some(row => row.userId === null) && (+ <p className="mt-3 text-xs text-muted-foreground">Unattributed costs have no recorded user in this organization.</p>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/ui/src/components/CostEstimateLabel.tsx b/ui/src/components/CostEstimateLabel.tsxnew file mode 100644index 0000000000..3f8b38d016--- /dev/null+++ b/ui/src/components/CostEstimateLabel.tsx@@ -0,0 +1,20 @@+import type { CostByAgent } from "@paperclipai/shared";+import { Badge } from "./ui/badge";++/** Use this group's ledger counts, never the page-wide estimate count. */+export function CostEstimateLabel({+ eventCount,+ estimatedEventCount,+}: Partial<Pick<CostByAgent, "eventCount" | "estimatedEventCount">>) {+ if (!estimatedEventCount) return null;+ const allEstimated = estimatedEventCount === eventCount;+ return (+ <Badge+ variant="outline"+ className="font-normal text-muted-foreground"+ title={`${estimatedEventCount} estimated ${estimatedEventCount === 1 ? "charge" : "charges"}. Calculated from token usage and published rates; provider bills may differ.`}+ >+ {allEstimated ? "Estimated" : "Partially estimated"}+ </Badge>+ );+}diff --git a/ui/src/components/FinanceBillerCard.tsx b/ui/src/components/FinanceBillerCard.tsxindex e2673b9f96..00f0705b93 100644--- a/ui/src/components/FinanceBillerCard.tsx+++ b/ui/src/components/FinanceBillerCard.tsx@@ -18,7 +18,7 @@ export function FinanceBillerCard({ row }: FinanceBillerCardProps) {</CardDescription></div><div className="text-right">- <div className="text-lg font-semibold tabular-nums">{formatCents(row.netCents)}</div>+ <div className="text-lg font-semibold tabular-nums">{formatCents(row.netCents, row.currency)}</div><div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">net</div></div></div>@@ -27,15 +27,15 @@ export function FinanceBillerCard({ row }: FinanceBillerCardProps) {<div className="grid gap-2 text-sm sm:grid-cols-3"><div className="border border-border p-3"><div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">debits</div>- <div className="mt-1 font-medium tabular-nums">{formatCents(row.debitCents)}</div>+ <div className="mt-1 font-medium tabular-nums">{formatCents(row.debitCents, row.currency)}</div></div><div className="border border-border p-3"><div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">credits</div>- <div className="mt-1 font-medium tabular-nums">{formatCents(row.creditCents)}</div>+ <div className="mt-1 font-medium tabular-nums">{formatCents(row.creditCents, row.currency)}</div></div><div className="border border-border p-3"><div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">estimated</div>- <div className="mt-1 font-medium tabular-nums">{formatCents(row.estimatedDebitCents)}</div>+ <div className="mt-1 font-medium tabular-nums">{formatCents(row.estimatedDebitCents, row.currency)}</div></div></div></CardContent>diff --git a/ui/src/components/FinanceKindCard.tsx b/ui/src/components/FinanceKindCard.tsxindex 4b800a39ee..83eca1f743 100644--- a/ui/src/components/FinanceKindCard.tsx+++ b/ui/src/components/FinanceKindCard.tsx@@ -19,7 +19,7 @@ export function FinanceKindCard({ rows }: FinanceKindCardProps) {) : (rows.map((row) => (<div- key={row.eventKind}+ key={`${row.eventKind}:${row.currency}`}className="flex items-center justify-between gap-3 border border-border px-3 py-2"><div className="min-w-0">@@ -29,9 +29,9 @@ export function FinanceKindCard({ rows }: FinanceKindCardProps) {</div></div><div className="text-right tabular-nums">- <div className="text-sm font-medium">{formatCents(row.netCents)}</div>+ <div className="text-sm font-medium">{formatCents(row.netCents, row.currency)}</div><div className="text-xs text-muted-foreground">- {formatCents(row.debitCents)} debits+ {formatCents(row.debitCents, row.currency)} debits</div></div></div>diff --git a/ui/src/components/FinanceTimelineCard.tsx b/ui/src/components/FinanceTimelineCard.tsxindex c01ab39c30..7000fdfc14 100644--- a/ui/src/components/FinanceTimelineCard.tsx+++ b/ui/src/components/FinanceTimelineCard.tsx@@ -16,13 +16,13 @@ interface FinanceTimelineCardProps {export function FinanceTimelineCard({rows,- emptyMessage = "No financial events in this period.",+ emptyMessage = "No financial events recorded in this period. Events appear when reported through the API, CLI, or a supported integration.",}: FinanceTimelineCardProps) {return (<Card><CardHeader className="px-4 pt-4 pb-1"><CardTitle className="text-base">Recent financial events</CardTitle>- <CardDescription>Top-ups, fees, credits, commitments, and other non-request charges.</CardDescription>+ <CardDescription>Provider charges, subscriptions, fees, and credits. Reported separately from run-cost estimates.</CardDescription></CardHeader><CardContent className="space-y-3 px-4 pb-4 pt-3">{rows.length === 0 ? (@@ -36,7 +36,7 @@ export function FinanceTimelineCard({<div className="flex items-start justify-between gap-3"><div className="min-w-0 space-y-2"><div className="flex flex-wrap items-center gap-2">- <Badge variant="secondary">{financeEventKindDisplayName(row.eventKind)}</Badge>+ <Badge variant="secondary">{row.metadataJson?.source === "provider_cost_report" ? "Provider cost report" : financeEventKindDisplayName(row.eventKind)}</Badge><Badge variant={row.direction === "credit" ? "outline" : "secondary"}>{financeDirectionDisplayName(row.direction)}</Badge>@@ -57,7 +57,7 @@ export function FinanceTimelineCard({)}</div><div className="text-right tabular-nums">- <div className="text-sm font-semibold">{formatCents(row.amountCents)}</div>+ <div className="text-sm font-semibold">{formatCents(row.amountCents, row.currency)}</div><div className="text-xs text-muted-foreground">{row.currency}</div>{row.estimated ? <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-amber-600">estimated</div> : null}</div>diff --git a/ui/src/components/ProviderQuotaCard.tsx b/ui/src/components/ProviderQuotaCard.tsxindex bd20aedbe5..aa5ee70e3b 100644--- a/ui/src/components/ProviderQuotaCard.tsx+++ b/ui/src/components/ProviderQuotaCard.tsx@@ -1,5 +1,7 @@+import { AccountQuotaPanels } from "./AccountQuotaPanels";+import { quotaUnavailableMessage } from "@/lib/quota-refresh";import { useMemo } from "react";-import type { CostByProviderModel, CostWindowSpendRow, QuotaWindow } from "@paperclipai/shared";+import type { CostByProviderModel, CostWindowSpendRow, QuotaWindow, ProviderQuotaResult } from "@paperclipai/shared";import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";import { QuotaBar } from "./QuotaBar";@@ -21,6 +23,8 @@ interface ProviderQuotaCardProps {rows: CostByProviderModel[];/** company monthly budget in cents (0 means unlimited) */budgetMonthlyCents: number;+ /** Only compare a current-month report with the monthly budget. */+ showBudgetUtilization?: boolean;/** total company spend in this period in cents, all providers */totalCompanySpendCents: number;/** spend in the current calendar week in cents, this provider only */@@ -30,6 +34,8 @@ interface ProviderQuotaCardProps {showDeficitNotch: boolean;/** live subscription quota windows from the provider's own api */quotaWindows?: QuotaWindow[];+ quotaAccounts?: ProviderQuotaResult[];+ quotaRequestFailed?: boolean;quotaError?: string | null;quotaSource?: string | null;quotaLoading?: boolean;@@ -39,10 +45,13 @@ export function ProviderQuotaCard({provider,rows,budgetMonthlyCents,+ showBudgetUtilization = true,totalCompanySpendCents,weekSpendCents,windowRows,showDeficitNotch,+ quotaAccounts,+ quotaRequestFailed,quotaWindows = [],quotaError = null,quotaSource = null,@@ -55,18 +64,18 @@ export function ProviderQuotaCard({let inputTokens = 0, outputTokens = 0, costCents = 0;let apiRunCount = 0, subRunCount = 0, subInputTokens = 0, subOutputTokens = 0;for (const r of rows) {- inputTokens += r.inputTokens;+ inputTokens += r.inputTokens + r.cachedInputTokens;outputTokens += r.outputTokens;costCents += r.costCents;apiRunCount += r.apiRunCount;subRunCount += r.subscriptionRunCount;- subInputTokens += r.subscriptionInputTokens;+ subInputTokens += r.subscriptionInputTokens + r.subscriptionCachedInputTokens;subOutputTokens += r.subscriptionOutputTokens;}const totalTokens = inputTokens + outputTokens;const subTokens = subInputTokens + subOutputTokens;- // denominator: api-billed tokens (from cost_events) + subscription tokens (from heartbeat_runs)- const allTokens = totalTokens + subTokens;+ // Subscription tokens are already included in the ledger totals.+ const allTokens = totalTokens;return {totalInputTokens: inputTokens,totalOutputTokens: outputTokens,@@ -94,13 +103,8 @@ export function ProviderQuotaCard({subSharePct,} = totals;- // budget bars: use this provider's own spend vs its pro-rata share of budget- // pro-rata: if a provider is 40% of total spend, it gets 40% of the budget allocated.- // falls back to raw provider spend vs total budget when totalCompanySpend is 0.- const providerBudgetShare =- budgetMonthlyCents > 0 && totalCompanySpendCents > 0- ? (totalCostCents / totalCompanySpendCents) * budgetMonthlyCents- : budgetMonthlyCents;+ // Each biller contributes to the company budget; there is no per-biller allocation.+ const providerBudgetShare = budgetMonthlyCents;const budgetPct =providerBudgetShare > 0@@ -112,7 +116,7 @@ export function ProviderQuotaCard({const weekPct =weeklyBudgetShare > 0 ? Math.min(100, (weekSpendCents / weeklyBudgetShare) * 100) : 0;- const hasBudget = budgetMonthlyCents > 0;+ const hasBudget = showBudgetUtilization && budgetMonthlyCents > 0;// memoized so the Map and max are not reconstructed on every parent render tickconst windowMap = useMemo(@@ -127,7 +131,7 @@ export function ProviderQuotaCard({const isCodexQuotaPanel = provider === "openai" && quotaSource?.startsWith("codex-");const supportsSubscriptionQuota = provider === "anthropic" || provider === "openai";const showSubscriptionQuotaSection =- supportsSubscriptionQuota && (quotaLoading || quotaWindows.length > 0 || quotaError != null);+ supportsSubscriptionQuota && (quotaLoading || Boolean(quotaAccounts?.length) || quotaWindows.length > 0 || quotaError != null);return (<Card>@@ -165,7 +169,7 @@ export function ProviderQuotaCard({label="Period spend"percentUsed={budgetPct}leftLabel={formatCents(totalCostCents)}- rightLabel={`${Math.round(budgetPct)}% of allocation`}+ rightLabel={`${Math.round(budgetPct)}% of company budget`}showDeficitNotch={showDeficitNotch}/><QuotaBar@@ -192,7 +196,7 @@ export function ProviderQuotaCard({// omit windows with no data rather than showing false $0.00 zerosif (!row) return null;const cents = row.costCents;- const tokens = row.inputTokens + row.outputTokens;+ const tokens = row.inputTokens + row.cachedInputTokens + row.outputTokens;const barPct = maxWindowCents > 0 ? (cents / maxWindowCents) * 100 : 0;return (<div key={w} className="space-y-1">@@ -261,7 +265,7 @@ export function ProviderQuotaCard({<div className="border-t border-border" /><div className="space-y-3">{rows.map((row) => {- const rowTokens = row.inputTokens + row.outputTokens;+ const rowTokens = row.inputTokens + row.cachedInputTokens + row.outputTokens;const tokenPct = totalTokens > 0 ? (rowTokens / totalTokens) * 100 : 0;const costPct = totalCostCents > 0 ? (row.costCents / totalCostCents) * 100 : 0;return (@@ -321,6 +325,8 @@ export function ProviderQuotaCard({</div>{quotaLoading ? (<QuotaPanelSkeleton />+ ) : quotaAccounts?.length ? (+ <AccountQuotaPanels accounts={quotaAccounts} failed={quotaRequestFailed} />) : isClaudeQuotaPanel ? (<ClaudeSubscriptionPanel windows={quotaWindows} source={quotaSource} error={quotaError} />) : isCodexQuotaPanel ? (@@ -328,8 +334,8 @@ export function ProviderQuotaCard({) : (<>{quotaError ? (- <p className="text-xs text-destructive">- {quotaError}+ <p role="status" className="text-xs text-muted-foreground">+ {quotaUnavailableMessage(quotaWindows.length > 0)}</p>) : null}<div className="space-y-2.5">diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsxindex 6727ae1383..0a8118a39c 100644--- a/ui/src/context/LiveUpdatesProvider.tsx+++ b/ui/src/context/LiveUpdatesProvider.tsx@@ -1216,7 +1216,7 @@ function invalidateHeartbeatQueries(queryClient.invalidateQueries({ queryKey: queryKeys.heartbeats(companyId) });queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(companyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.costs(companyId) });+ queryClient.invalidateQueries({ queryKey: ["costs", companyId] });queryClient.invalidateQueries({queryKey: queryKeys.sidebarBadges(companyId),});@@ -1492,10 +1492,11 @@ function invalidateActivityQueries(}if (entityType === "cost_event") {- queryClient.invalidateQueries({ queryKey: queryKeys.costs(companyId) });+ queryClient.invalidateQueries({ queryKey: ["costs", companyId] });queryClient.invalidateQueries({- queryKey: queryKeys.usageByProvider(companyId),+ queryKey: ["usage-by-provider", companyId],});+ queryClient.invalidateQueries({ queryKey: ["usage-by-biller", companyId] });queryClient.invalidateQueries({queryKey: queryKeys.usageWindowSpend(companyId),});diff --git a/ui/src/hooks/useDateRange.ts b/ui/src/hooks/useDateRange.tsindex 2e4a94875f..5fe2740b61 100644--- a/ui/src/hooks/useDateRange.ts+++ b/ui/src/hooks/useDateRange.ts@@ -4,8 +4,8 @@ export type DatePreset = "mtd" | "7d" | "30d" | "ytd" | "all" | "custom";export const PRESET_LABELS: Record<DatePreset, string> = {mtd: "Month to Date",- "7d": "Last 7 Days",- "30d": "Last 30 Days",+ "7d": "7 Days",+ "30d": "30 Days",ytd: "Year to Date",all: "All Time",custom: "Custom",@@ -16,12 +16,12 @@ export const PRESET_KEYS: DatePreset[] = ["mtd", "7d", "30d", "ytd", "all", "cus// note: computeRange is called inside a useMemo that re-evaluates once per minute// (driven by minuteTick). this means sliding windows (7d, 30d) advance their upper// bound at most once per minute — acceptable for a cost dashboard.-function computeRange(preset: DatePreset): { from: string; to: string } {+export function computeRange(preset: DatePreset): { from: string; to: string } {const now = new Date();const to = now.toISOString();switch (preset) {case "mtd": {- const d = new Date(now.getFullYear(), now.getMonth(), 1);+ const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));return { from: d.toISOString(), to };}case "7d": {@@ -33,7 +33,7 @@ function computeRange(preset: DatePreset): { from: string; to: string } {return { from: d.toISOString(), to };}case "ytd": {- const d = new Date(now.getFullYear(), 0, 1);+ const d = new Date(Date.UTC(now.getUTCFullYear(), 0, 1));return { from: d.toISOString(), to };}case "all":diff --git a/ui/src/lib/utils.ts b/ui/src/lib/utils.tsindex 41fb267aa6..43fabc93c3 100644--- a/ui/src/lib/utils.ts+++ b/ui/src/lib/utils.ts@@ -33,8 +33,13 @@ export function asFiniteNumber(value: unknown, fallback: number) {return typeof value === "number" && Number.isFinite(value) ? value : fallback;}-export function formatCents(cents: number): string {- return `$${(cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+export function formatCents(cents: number, currency = "USD"): string {+ // Older finance writes accepted arbitrary three-character codes. Keep those+ // amounts readable without passing an invalid currency to Intl.+ if (!/^[a-z]{3}$/i.test(currency)) {+ return `${currency} ${(cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+ }+ return (cents / 100).toLocaleString("en-US", { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: 2 });}export function formatNumber(n: number, options?: Intl.NumberFormatOptions): string {@@ -170,13 +175,42 @@ function coerceBillingType(value: unknown): BillingType | null {return null;}-function readRunCostUsd(payload: Record<string, unknown> | null): number {- if (!payload) return 0;- for (const key of ["costUsd", "cost_usd", "total_cost_usd"] as const) {+function readRunCostUsd(payload: Record<string, unknown> | null): number | null {+ if (!payload) return null;+ for (const key of ["cacheAdjustedCostUsd", "costUsdExact", "costUsd", "cost_usd", "total_cost_usd"] as const) {const value = payload[key];- if (typeof value === "number" && Number.isFinite(value)) return value;+ if (key === "costUsdExact" && typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value))) return Number(value);+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;}- return 0;+ return null;+}++/** Receipt-backed runs and legacy Claude/Gemini snapshots store uncached input+ * separately. OpenCode/Pi persist their provider-qualified model IDs and also+ * separate cache reads. Older Codex input already includes cached tokens.+ * Unknown legacy formats retain their input-plus-output interpretation. */+export function visibleRunTokenTotal(usage: Record<string, unknown> | null | undefined): number {+ const count = (...keys: string[]) => {+ for (const key of keys) {+ const value = usage?.[key];+ if (typeof value === "number" && Number.isFinite(value)) return Math.max(0, value);+ }+ return 0;+ };+ const input = count("inputTokens", "input_tokens");+ const output = count("outputTokens", "output_tokens");+ const cached = count("cachedInputTokens", "cached_input_tokens", "cache_read_input_tokens");+ const provider = typeof usage?.provider === "string" ? usage.provider : "";+ const model = typeof usage?.model === "string" ? usage.model : "";+ // Use the saved model convention, not the agent's current adapter: an agent+ // can change adapters after a historical run. Codex saves an unqualified ID.+ const qualifiedModel = provider !== "" && provider !== "unknown"+ && model.startsWith(`${provider}/`) && model.length > provider.length + 1;+ const inputExcludesCached = usage?.provider === "anthropic"+ || usage?.provider === "google"+ || qualifiedModel+ || (typeof usage?.accountingReceiptId === "string" && usage.accountingReceiptId.length > 0);+ return input + output + (inputExcludesCached ? cached : 0);}export function visibleRunCostUsd(@@ -185,7 +219,7 @@ export function visibleRunCostUsd(): number {const billingType = coerceBillingType(usage?.billingType) ?? coerceBillingType(result?.billingType);if (billingType === "subscription_included") return 0;- return readRunCostUsd(usage) || readRunCostUsd(result);+ return readRunCostUsd(usage) ?? readRunCostUsd(result) ?? 0;}export function financeEventKindDisplayName(eventKind: FinanceEventKind): string {diff --git a/ui/src/pages/AgentDetail.production.tsx b/ui/src/pages/AgentDetail.production.tsxindex 91efc76433..9082602709 100644--- a/ui/src/pages/AgentDetail.production.tsx+++ b/ui/src/pages/AgentDetail.production.tsx@@ -64,7 +64,7 @@ import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";import { buildSameOriginWebSocketUrl } from "../lib/websocket-url";import { tryCreateWebSocket } from "../lib/websocket";-import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";+import { formatCents, formatDate, relativeTime, formatTokens, visibleRunCostUsd, visibleRunTokenTotal } from "../lib/utils";import { cn } from "../lib/utils";import { describeRunRetryState } from "../lib/runRetryState";import { Button } from "@/components/ui/button";@@ -380,7 +380,7 @@ function runMetrics(run: HeartbeatRun) {output,cached,cost,- totalTokens: input + output,+ totalTokens: visibleRunTokenTotal(usage),provider,model,};@@ -935,6 +935,8 @@ export function AgentDetail() {metric: "billed_cents",windowKind: "calendar_month_utc",amount: budgetMonthlyCents,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: spentMonthlyCents,remainingAmount: Math.max(0, budgetMonthlyCents - spentMonthlyCents),utilizationPercent:diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsxindex 308116e7b3..7d4863bceb 100644--- a/ui/src/pages/AgentDetail.tsx+++ b/ui/src/pages/AgentDetail.tsx@@ -63,7 +63,7 @@ import { SourceResolvedFoldBadge } from "../components/SourceResolvedFoldBadge";import { readSourceResolvedWatchdogFold } from "../lib/source-resolved-watchdog-fold";import { buildSameOriginWebSocketUrl } from "../lib/websocket-url";import { tryCreateWebSocket } from "../lib/websocket";-import { formatDate, relativeTime, formatTokens, visibleRunCostUsd } from "../lib/utils";+import { formatDate, relativeTime, formatTokens, visibleRunCostUsd, visibleRunTokenTotal } from "../lib/utils";import { cn } from "../lib/utils";import { RunRetryDetails } from "../components/RunRetryDetails";import { Button } from "@/components/ui/button";@@ -383,7 +383,7 @@ function runMetrics(run: HeartbeatRun) {output,cached,cost,- totalTokens: input + output,+ totalTokens: visibleRunTokenTotal(usage),provider,model,};diff --git a/ui/src/pages/Costs.production.tsx b/ui/src/pages/Costs.production.tsxdeleted file mode 100644index bbb8b9a804..0000000000--- a/ui/src/pages/Costs.production.tsx+++ /dev/null@@ -1,1104 +0,0 @@-import { AgentIdentity } from "@/components/AgentIdentity";-import { useEffect, useMemo, useRef, useState, type ComponentType } from "react";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import type {- BudgetPolicySummary,- CostByAgentModel,- CostByBiller,- CostByProviderModel,- CostWindowSpendRow,- FinanceEvent,- QuotaWindow,-} from "@paperclipai/shared";-import { ArrowDownLeft, ArrowUpRight, ChevronDown, ChevronRight, Coins, DollarSign, ReceiptText } from "lucide-react";-import { budgetsApi } from "../api/budgets";-import { costsApi } from "../api/costs";-import { BillerSpendCard } from "../components/BillerSpendCard";-import { BudgetIncidentCard } from "../components/BudgetIncidentCard";-import { BudgetPolicyCard } from "../components/BudgetPolicyCard";-import { EmptyState } from "../components/EmptyState";-import { FinanceBillerCard } from "../components/FinanceBillerCard";-import { FinanceKindCard } from "../components/FinanceKindCard";-import { FinanceTimelineCard } from "../components/FinanceTimelineCard";-import { Identity } from "../components/Identity";-import { PageSkeleton } from "../components/PageSkeleton";-import { PageTabBar } from "../components/PageTabBar";-import { ProviderQuotaCard } from "../components/ProviderQuotaCard";-import { StatusBadge } from "../components/StatusBadge";-import { useBreadcrumbs } from "../context/BreadcrumbContext";-import { useCompany } from "../context/CompanyContext";-import { useDateRange, PRESET_KEYS, PRESET_LABELS } from "../hooks/useDateRange";-import { queryKeys } from "../lib/queryKeys";-import { billingTypeDisplayName, cn, formatCents, formatTokens, providerDisplayName } from "../lib/utils";-import { Button } from "@/components/ui/button";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";--const NO_COMPANY = "__none__";--function currentWeekRange(): { from: string; to: string } {- const now = new Date();- const day = now.getDay();- const diffToMon = day === 0 ? -6 : 1 - day;- const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate() + diffToMon, 0, 0, 0, 0);- const sun = new Date(mon.getFullYear(), mon.getMonth(), mon.getDate() + 6, 23, 59, 59, 999);- return { from: mon.toISOString(), to: sun.toISOString() };-}--function ProviderTabLabel({ provider, rows }: { provider: string; rows: CostByProviderModel[] }) {- const totalTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0);- const totalCost = rows.reduce((sum, row) => sum + row.costCents, 0);- return (- <span className="flex items-center gap-1.5">- <span>{providerDisplayName(provider)}</span>- <span className="font-mono text-xs text-muted-foreground">{formatTokens(totalTokens)}</span>- <span className="text-xs text-muted-foreground">{formatCents(totalCost)}</span>- </span>- );-}--function BillerTabLabel({ biller, rows }: { biller: string; rows: CostByBiller[] }) {- const totalTokens = rows.reduce((sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0);- const totalCost = rows.reduce((sum, row) => sum + row.costCents, 0);- return (- <span className="flex items-center gap-1.5">- <span>{providerDisplayName(biller)}</span>- <span className="font-mono text-xs text-muted-foreground">{formatTokens(totalTokens)}</span>- <span className="text-xs text-muted-foreground">{formatCents(totalCost)}</span>- </span>- );-}--function MetricTile({- label,- value,- subtitle,- icon: Icon,-}: {- label: string;- value: string;- subtitle: string;- icon: ComponentType<{ className?: string }>;-}) {- return (- <Card className="block p-4">- <div className="flex items-center justify-between gap-3">- <div className="min-w-0">- <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">{label}</div>- <div className="mt-2 text-2xl font-semibold tabular-nums">{value}</div>- <div className="mt-1 text-xs leading-5 text-muted-foreground">{subtitle}</div>- </div>- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border">- <Icon className="h-4 w-4 text-muted-foreground" />- </div>- </div>- </Card>- );-}--function FinanceSummaryCard({- debitCents,- creditCents,- netCents,- estimatedDebitCents,- eventCount,-}: {- debitCents: number;- creditCents: number;- netCents: number;- estimatedDebitCents: number;- eventCount: number;-}) {- return (- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">Finance ledger</CardTitle>- <CardDescription>- Account-level charges that do not map to a single inference request.- </CardDescription>- </CardHeader>- <CardContent className="grid gap-3 px-5 pb-5 pt-2 sm:grid-cols-2 xl:grid-cols-4">- <MetricTile- label="Debits"- value={formatCents(debitCents)}- subtitle={`${eventCount} total event${eventCount === 1 ? "" : "s"} in range`}- icon={ArrowUpRight}- />- <MetricTile- label="Credits"- value={formatCents(creditCents)}- subtitle="Refunds, offsets, and credit returns"- icon={ArrowDownLeft}- />- <MetricTile- label="Net"- value={formatCents(netCents)}- subtitle="Debit minus credit for the selected period"- icon={ReceiptText}- />- <MetricTile- label="Estimated"- value={formatCents(estimatedDebitCents)}- subtitle="Estimated debits that are not yet invoice-authoritative"- icon={Coins}- />- </CardContent>- </Card>- );-}--export function Costs() {- const { selectedCompanyId } = useCompany();- const { setBreadcrumbs } = useBreadcrumbs();- const queryClient = useQueryClient();-- const [mainTab, setMainTab] = useState<"overview" | "budgets" | "providers" | "billers" | "finance">("overview");- const [activeProvider, setActiveProvider] = useState("all");- const [activeBiller, setActiveBiller] = useState("all");-- const {- preset,- setPreset,- customFrom,- setCustomFrom,- customTo,- setCustomTo,- from,- to,- customReady,- } = useDateRange();-- useEffect(() => {- setBreadcrumbs([{ label: "Costs" }]);- }, [setBreadcrumbs]);-- const [today, setToday] = useState(() => new Date().toDateString());- const todayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- useEffect(() => {- const schedule = () => {- const now = new Date();- const ms = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime() - now.getTime();- todayTimerRef.current = setTimeout(() => {- setToday(new Date().toDateString());- schedule();- }, ms);- };- schedule();- return () => {- if (todayTimerRef.current != null) clearTimeout(todayTimerRef.current);- };- }, []);-- const weekRange = useMemo(() => currentWeekRange(), [today]);- const companyId = selectedCompanyId ?? NO_COMPANY;-- const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({- queryKey: queryKeys.budgets.overview(companyId),- queryFn: () => budgetsApi.overview(companyId),- enabled: !!selectedCompanyId && customReady,- refetchInterval: 30_000,- staleTime: 5_000,- });-- const invalidateBudgetViews = () => {- if (!selectedCompanyId) return;- queryClient.invalidateQueries({ queryKey: queryKeys.budgets.overview(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.dashboard(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.agents.list(selectedCompanyId) });- queryClient.invalidateQueries({ queryKey: queryKeys.projects.all(selectedCompanyId) });- };-- const policyMutation = useMutation({- mutationFn: (input: {- scopeType: BudgetPolicySummary["scopeType"];- scopeId: string;- amount: number;- windowKind: BudgetPolicySummary["windowKind"];- }) =>- budgetsApi.upsertPolicy(companyId, {- scopeType: input.scopeType,- scopeId: input.scopeId,- amount: input.amount,- windowKind: input.windowKind,- }),- onSuccess: invalidateBudgetViews,- });-- const incidentMutation = useMutation({- mutationFn: (input: { incidentId: string; action: "keep_paused" | "raise_budget_and_resume"; amount?: number }) =>- budgetsApi.resolveIncident(companyId, input.incidentId, input),- onSuccess: invalidateBudgetViews,- });-- const { data: spendData, isLoading: spendLoading, error: spendError } = useQuery({- queryKey: queryKeys.costs(companyId, from || undefined, to || undefined),- queryFn: async () => {- const [summary, byAgent, byProject, byAgentModel] = await Promise.all([- costsApi.summary(companyId, from || undefined, to || undefined),- costsApi.byAgent(companyId, from || undefined, to || undefined),- costsApi.byProject(companyId, from || undefined, to || undefined),- costsApi.byAgentModel(companyId, from || undefined, to || undefined),- ]);- return { summary, byAgent, byProject, byAgentModel };- },- enabled: !!selectedCompanyId && customReady,- });-- const { data: financeData, isLoading: financeLoading, error: financeError } = useQuery({- queryKey: [- queryKeys.financeSummary(companyId, from || undefined, to || undefined),- queryKeys.financeByBiller(companyId, from || undefined, to || undefined),- queryKeys.financeByKind(companyId, from || undefined, to || undefined),- queryKeys.financeEvents(companyId, from || undefined, to || undefined, 18),- ],- queryFn: async () => {- const [summary, byBiller, byKind, events] = await Promise.all([- costsApi.financeSummary(companyId, from || undefined, to || undefined),- costsApi.financeByBiller(companyId, from || undefined, to || undefined),- costsApi.financeByKind(companyId, from || undefined, to || undefined),- costsApi.financeEvents(companyId, from || undefined, to || undefined, 18),- ]);- return { summary, byBiller, byKind, events };- },- enabled: !!selectedCompanyId && customReady,- });-- const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());- useEffect(() => {- setExpandedAgents(new Set());- }, [companyId, from, to]);-- function toggleAgent(agentId: string) {- setExpandedAgents((prev) => {- const next = new Set(prev);- if (next.has(agentId)) next.delete(agentId);- else next.add(agentId);- return next;- });- }-- const agentModelRows = useMemo(() => {- const map = new Map<string, CostByAgentModel[]>();- for (const row of spendData?.byAgentModel ?? []) {- const rows = map.get(row.agentId) ?? [];- rows.push(row);- map.set(row.agentId, rows);- }- for (const [agentId, rows] of map) {- map.set(agentId, rows.slice().sort((a, b) => b.costCents - a.costCents));- }- return map;- }, [spendData?.byAgentModel]);-- const { data: providerData } = useQuery({- queryKey: queryKeys.usageByProvider(companyId, from || undefined, to || undefined),- queryFn: () => costsApi.byProvider(companyId, from || undefined, to || undefined),- enabled: !!selectedCompanyId && customReady && (mainTab === "providers" || mainTab === "billers"),- refetchInterval: 30_000,- staleTime: 10_000,- });-- const { data: billerData } = useQuery({- queryKey: queryKeys.usageByBiller(companyId, from || undefined, to || undefined),- queryFn: () => costsApi.byBiller(companyId, from || undefined, to || undefined),- enabled: !!selectedCompanyId && customReady && mainTab === "billers",- refetchInterval: 30_000,- staleTime: 10_000,- });-- const { data: weekData } = useQuery({- queryKey: queryKeys.usageByProvider(companyId, weekRange.from, weekRange.to),- queryFn: () => costsApi.byProvider(companyId, weekRange.from, weekRange.to),- enabled: !!selectedCompanyId && (mainTab === "providers" || mainTab === "billers"),- refetchInterval: 30_000,- staleTime: 10_000,- });-- const { data: weekBillerData } = useQuery({- queryKey: queryKeys.usageByBiller(companyId, weekRange.from, weekRange.to),- queryFn: () => costsApi.byBiller(companyId, weekRange.from, weekRange.to),- enabled: !!selectedCompanyId && mainTab === "billers",- refetchInterval: 30_000,- staleTime: 10_000,- });-- const { data: windowData } = useQuery({- queryKey: queryKeys.usageWindowSpend(companyId),- queryFn: () => costsApi.windowSpend(companyId),- enabled: !!selectedCompanyId && mainTab === "providers",- refetchInterval: 30_000,- staleTime: 10_000,- });-- const { data: quotaData, isLoading: quotaLoading } = useQuery({- queryKey: queryKeys.usageQuotaWindows(companyId),- queryFn: () => costsApi.quotaWindows(companyId),- enabled: !!selectedCompanyId && mainTab === "providers",- refetchInterval: 300_000,- staleTime: 60_000,- });-- const byProvider = useMemo(() => {- const map = new Map<string, CostByProviderModel[]>();- for (const row of providerData ?? []) {- const rows = map.get(row.provider) ?? [];- rows.push(row);- map.set(row.provider, rows);- }- return map;- }, [providerData]);-- const byBiller = useMemo(() => {- const map = new Map<string, CostByBiller[]>();- for (const row of billerData ?? []) {- const rows = map.get(row.biller) ?? [];- rows.push(row);- map.set(row.biller, rows);- }- return map;- }, [billerData]);-- const weekSpendByProvider = useMemo(() => {- const map = new Map<string, number>();- for (const row of weekData ?? []) {- map.set(row.provider, (map.get(row.provider) ?? 0) + row.costCents);- }- return map;- }, [weekData]);-- const weekSpendByBiller = useMemo(() => {- const map = new Map<string, number>();- for (const row of weekBillerData ?? []) {- map.set(row.biller, (map.get(row.biller) ?? 0) + row.costCents);- }- return map;- }, [weekBillerData]);-- const windowSpendByProvider = useMemo(() => {- const map = new Map<string, CostWindowSpendRow[]>();- for (const row of windowData ?? []) {- const rows = map.get(row.provider) ?? [];- rows.push(row);- map.set(row.provider, rows);- }- return map;- }, [windowData]);-- const quotaWindowsByProvider = useMemo(() => {- const map = new Map<string, QuotaWindow[]>();- for (const result of quotaData ?? []) {- if (result.ok && result.windows.length > 0) {- map.set(result.provider, result.windows);- }- }- return map;- }, [quotaData]);-- const quotaErrorsByProvider = useMemo(() => {- const map = new Map<string, string>();- for (const result of quotaData ?? []) {- if (!result.ok && result.error) map.set(result.provider, result.error);- }- return map;- }, [quotaData]);-- const quotaSourcesByProvider = useMemo(() => {- const map = new Map<string, string>();- for (const result of quotaData ?? []) {- if (typeof result.source === "string" && result.source.length > 0) {- map.set(result.provider, result.source);- }- }- return map;- }, [quotaData]);-- const deficitNotchByProvider = useMemo(() => {- const map = new Map<string, boolean>();- if (preset !== "mtd") return map;- const budget = spendData?.summary.budgetCents ?? 0;- if (budget <= 0) return map;- const totalSpend = spendData?.summary.spendCents ?? 0;- const now = new Date();- const daysElapsed = now.getDate();- const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();- for (const [providerKey, rows] of byProvider) {- const providerCostCents = rows.reduce((sum, row) => sum + row.costCents, 0);- const providerShare = totalSpend > 0 ? providerCostCents / totalSpend : 0;- const providerBudget = budget * providerShare;- if (providerBudget <= 0) {- map.set(providerKey, false);- continue;- }- const burnRate = providerCostCents / Math.max(daysElapsed, 1);- map.set(providerKey, providerCostCents + burnRate * (daysInMonth - daysElapsed) > providerBudget);- }- return map;- }, [preset, spendData, byProvider]);-- const providers = useMemo(() => Array.from(byProvider.keys()), [byProvider]);- const billers = useMemo(() => Array.from(byBiller.keys()), [byBiller]);-- const effectiveProvider =- activeProvider === "all" || providers.includes(activeProvider) ? activeProvider : "all";- useEffect(() => {- if (effectiveProvider !== activeProvider) setActiveProvider("all");- }, [effectiveProvider, activeProvider]);-- const effectiveBiller =- activeBiller === "all" || billers.includes(activeBiller) ? activeBiller : "all";- useEffect(() => {- if (effectiveBiller !== activeBiller) setActiveBiller("all");- }, [effectiveBiller, activeBiller]);-- const providerTabItems = useMemo(() => {- const providerKeys = Array.from(byProvider.keys());- const allTokens = providerKeys.reduce(- (sum, provider) => sum + (byProvider.get(provider)?.reduce((acc, row) => acc + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0) ?? 0),- 0,- );- const allCents = providerKeys.reduce(- (sum, provider) => sum + (byProvider.get(provider)?.reduce((acc, row) => acc + row.costCents, 0) ?? 0),- 0,- );- return [- {- value: "all",- label: (- <span className="flex items-center gap-1.5">- <span>All providers</span>- {providerKeys.length > 0 ? (- <>- <span className="font-mono text-xs text-muted-foreground">{formatTokens(allTokens)}</span>- <span className="text-xs text-muted-foreground">{formatCents(allCents)}</span>- </>- ) : null}- </span>- ),- },- ...providerKeys.map((provider) => ({- value: provider,- label: <ProviderTabLabel provider={provider} rows={byProvider.get(provider) ?? []} />,- })),- ];- }, [byProvider]);-- const billerTabItems = useMemo(() => {- const billerKeys = Array.from(byBiller.keys());- const allTokens = billerKeys.reduce(- (sum, biller) => sum + (byBiller.get(biller)?.reduce((acc, row) => acc + row.inputTokens + row.cachedInputTokens + row.outputTokens, 0) ?? 0),- 0,- );- const allCents = billerKeys.reduce(- (sum, biller) => sum + (byBiller.get(biller)?.reduce((acc, row) => acc + row.costCents, 0) ?? 0),- 0,- );- return [- {- value: "all",- label: (- <span className="flex items-center gap-1.5">- <span>All billers</span>- {billerKeys.length > 0 ? (- <>- <span className="font-mono text-xs text-muted-foreground">{formatTokens(allTokens)}</span>- <span className="text-xs text-muted-foreground">{formatCents(allCents)}</span>- </>- ) : null}- </span>- ),- },- ...billerKeys.map((biller) => ({- value: biller,- label: <BillerTabLabel biller={biller} rows={byBiller.get(biller) ?? []} />,- })),- ];- }, [byBiller]);-- const inferenceTokenTotal =- (spendData?.byAgent ?? []).reduce(- (sum, row) => sum + row.inputTokens + row.cachedInputTokens + row.outputTokens,- 0,- );-- const topFinanceEvents = (financeData?.events ?? []) as FinanceEvent[];- const budgetPolicies = budgetData?.policies ?? [];- const activeBudgetIncidents = budgetData?.activeIncidents ?? [];- const budgetPoliciesByScope = useMemo(() => ({- company: budgetPolicies.filter((policy) => policy.scopeType === "company"),- agent: budgetPolicies.filter((policy) => policy.scopeType === "agent"),- project: budgetPolicies.filter((policy) => policy.scopeType === "project"),- }), [budgetPolicies]);-- if (!selectedCompanyId) {- return <EmptyState icon={DollarSign} message="Select a company to view costs." />;- }-- const showCustomPrompt = preset === "custom" && !customReady;- const showOverviewLoading = (spendLoading || financeLoading) && customReady;- const overviewError = spendError ?? financeError;-- return (- <div className="space-y-6">- <div className="space-y-5">- <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">- <div>- <h1 className="text-3xl font-semibold tracking-tight">Costs</h1>- <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">- Inference spend, platform fees, credits, and live quota windows.- </p>- </div>-- <div className="flex flex-wrap items-center gap-2">- {PRESET_KEYS.map((key) => (- <Button- key={key}- variant={preset === key ? "secondary" : "ghost"}- size="sm"- onClick={() => setPreset(key)}- aria-pressed={preset === key}- >- {PRESET_LABELS[key]}- </Button>- ))}- </div>- </div>-- {preset === "custom" ? (- <div className="flex flex-wrap items-center gap-2 border border-border p-3">- <input- type="date"- value={customFrom}- onChange={(event) => setCustomFrom(event.target.value)}- className="h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"- />- <span className="text-sm text-muted-foreground">to</span>- <input- type="date"- value={customTo}- onChange={(event) => setCustomTo(event.target.value)}- className="h-9 rounded-md border border-input bg-background px-3 text-sm text-foreground"- />- </div>- ) : null}-- <div className="grid gap-3 lg:grid-cols-4">- <MetricTile- label="Inference spend"- value={formatCents(spendData?.summary.spendCents ?? 0)}- subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}- icon={DollarSign}- />- <MetricTile- label="Budget"- value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (- spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `${spendData.summary.utilizationPercent}%`- : "Open"- )}- subtitle={- activeBudgetIncidents.length > 0- ? `${budgetData?.pausedAgentCount ?? 0} agents paused · ${budgetData?.pausedProjectCount ?? 0} projects paused`- : spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `${formatCents(spendData.summary.spendCents)} of ${formatCents(spendData.summary.budgetCents)}`- : "No monthly cap configured"- }- icon={Coins}- />- <MetricTile- label="Finance net"- value={formatCents(financeData?.summary.netCents ?? 0)}- subtitle={`${formatCents(financeData?.summary.debitCents ?? 0)} debits · ${formatCents(financeData?.summary.creditCents ?? 0)} credits`}- icon={ReceiptText}- />- <MetricTile- label="Finance events"- value={String(financeData?.summary.eventCount ?? 0)}- subtitle={`${formatCents(financeData?.summary.estimatedDebitCents ?? 0)} estimated in range`}- icon={ArrowUpRight}- />- </div>- </div>-- <Tabs value={mainTab} onValueChange={(value) => setMainTab(value as typeof mainTab)}>- <TabsList variant="line" className="justify-start">- <TabsTrigger value="overview">Overview</TabsTrigger>- <TabsTrigger value="budgets">Budgets</TabsTrigger>- <TabsTrigger value="providers">Providers</TabsTrigger>- <TabsTrigger value="billers">Billers</TabsTrigger>- <TabsTrigger value="finance">Finance</TabsTrigger>- </TabsList>-- <TabsContent value="overview" className="mt-4 space-y-4">- {showCustomPrompt ? (- <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>- ) : showOverviewLoading ? (- <PageSkeleton variant="costs" />- ) : overviewError ? (- <p className="text-sm text-destructive">{(overviewError as Error).message}</p>- ) : (- <>- {activeBudgetIncidents.length > 0 ? (- <div className="grid gap-4 xl:grid-cols-2">- {activeBudgetIncidents.slice(0, 2).map((incident) => (- <BudgetIncidentCard- key={incident.id}- incident={incident}- isMutating={incidentMutation.isPending}- onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}- onRaiseAndResume={(amount) =>- incidentMutation.mutate({- incidentId: incident.id,- action: "raise_budget_and_resume",- amount,- })}- />- ))}- </div>- ) : null}-- <div className="grid gap-4 xl:grid-cols-(--gtc-31)">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">Inference ledger</CardTitle>- <CardDescription>- Request-scoped inference spend for the selected period.- </CardDescription>- </CardHeader>- <CardContent className="space-y-4 px-5 pb-5 pt-2">- <div className="flex flex-wrap items-end justify-between gap-3">- <div>- <div className="text-3xl font-semibold tabular-nums">- {formatCents(spendData?.summary.spendCents ?? 0)}- </div>- <div className="mt-1 text-sm text-muted-foreground">- {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `Budget ${formatCents(spendData.summary.budgetCents)}`- : "Unlimited budget"}- </div>- </div>- <div className="border border-border px-4 py-3 text-right">- <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">usage</div>- <div className="mt-1 text-lg font-medium tabular-nums">- {formatTokens(inferenceTokenTotal)}- </div>- </div>- </div>- {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0 ? (- <div className="space-y-2">- <div className="h-2 overflow-hidden bg-muted">- <div- className={cn(- "h-full transition-(--tp-width-background-color) duration-150",- spendData.summary.utilizationPercent > 90- ? "bg-(--status-task-blocked)"- : spendData.summary.utilizationPercent > 70- ? "bg-(--status-task-todo)"- : "bg-(--status-task-done)",- )}- style={{ width: `${Math.min(100, spendData.summary.utilizationPercent)}%` }}- />- </div>- <div className="text-xs text-muted-foreground">- {spendData.summary.utilizationPercent}% of monthly budget consumed in this range.- </div>- </div>- ) : null}- </CardContent>- </Card>-- <FinanceSummaryCard- debitCents={financeData?.summary.debitCents ?? 0}- creditCents={financeData?.summary.creditCents ?? 0}- netCents={financeData?.summary.netCents ?? 0}- estimatedDebitCents={financeData?.summary.estimatedDebitCents ?? 0}- eventCount={financeData?.summary.eventCount ?? 0}- />- </div>-- <div className="grid gap-4 xl:grid-cols-(--gtc-32)">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">By agent</CardTitle>- <CardDescription>What each agent consumed in the selected period.</CardDescription>- </CardHeader>- <CardContent className="space-y-2 px-5 pb-5 pt-2">- {(spendData?.byAgent.length ?? 0) === 0 ? (- <p className="text-sm text-muted-foreground">No cost events yet.</p>- ) : (- spendData?.byAgent.map((row) => {- const modelRows = agentModelRows.get(row.agentId) ?? [];- const isExpanded = expandedAgents.has(row.agentId);- const hasBreakdown = modelRows.length > 0;- return (- <div key={row.agentId} className="border border-border px-4 py-3">- <div- className={cn("flex items-start justify-between gap-3", hasBreakdown ? "cursor-pointer select-none" : "")}- onClick={() => hasBreakdown && toggleAgent(row.agentId)}- >- <div className="flex min-w-0 items-center gap-2">- {hasBreakdown ? (- isExpanded- ? <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />- : <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />- ) : (- <span className="h-3 w-3 shrink-0" />- )}- <AgentIdentity agent={{ id: row.agentId, name: row.agentName ?? row.agentId, appearance: row.agentAppearance }} size="sm" />- {row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}- </div>- <div className="text-right text-sm tabular-nums">- <div className="font-medium">{formatCents(row.costCents)}</div>- <div className="text-xs text-muted-foreground">- in {formatTokens(row.inputTokens + row.cachedInputTokens)} · out {formatTokens(row.outputTokens)}- </div>- {(row.apiRunCount > 0 || row.subscriptionRunCount > 0) ? (- <div className="text-xs text-muted-foreground">- {row.apiRunCount > 0 ? `${row.apiRunCount} api` : "0 api"}- {" · "}- {row.subscriptionRunCount > 0- ? `${row.subscriptionRunCount} subscription`- : "0 subscription"}- </div>- ) : null}- </div>- </div>-- {isExpanded && modelRows.length > 0 ? (- <div className="mt-3 space-y-2 border-l border-border pl-4">- {modelRows.map((modelRow) => {- const sharePct = row.costCents > 0 ? Math.round((modelRow.costCents / row.costCents) * 100) : 0;- return (- <div- key={`${modelRow.provider}:${modelRow.model}:${modelRow.billingType}`}- className="flex items-start justify-between gap-3 text-xs"- >- <div className="min-w-0">- <div className="truncate font-medium text-foreground">- {providerDisplayName(modelRow.provider)}- <span className="mx-1 text-border">/</span>- <span className="font-mono">{modelRow.model}</span>- </div>- <div className="truncate text-muted-foreground">- {providerDisplayName(modelRow.biller)} · {billingTypeDisplayName(modelRow.billingType)}- </div>- </div>- <div className="text-right tabular-nums">- <div className="font-medium">- {formatCents(modelRow.costCents)}- <span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>- </div>- <div className="text-muted-foreground">- {formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok- </div>- </div>- </div>- );- })}- </div>- ) : null}- </div>- );- })- )}- </CardContent>- </Card>-- <div className="space-y-4">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">By project</CardTitle>- <CardDescription>Run costs attributed through project-linked tasks.</CardDescription>- </CardHeader>- <CardContent className="space-y-2 px-5 pb-5 pt-2">- {(spendData?.byProject.length ?? 0) === 0 ? (- <p className="text-sm text-muted-foreground">No project-attributed run costs yet.</p>- ) : (- spendData?.byProject.map((row, index) => (- <div- key={row.projectId ?? `unattributed-${index}`}- className="flex items-center justify-between gap-3 border border-border px-3 py-2 text-sm"- >- <span className="truncate">{row.projectName ?? row.projectId ?? "Unattributed"}</span>- <span className="font-medium tabular-nums">{formatCents(row.costCents)}</span>- </div>- ))- )}- </CardContent>- </Card>-- <FinanceTimelineCard rows={topFinanceEvents.slice(0, 6)} emptyMessage="No finance events yet. Add account-level charges once biller invoices or credits land." />- </div>- </div>- </>- )}- </TabsContent>-- <TabsContent value="budgets" className="mt-4 space-y-4">- {budgetLoading ? (- <PageSkeleton variant="costs" />- ) : budgetError ? (- <p className="text-sm text-destructive">{(budgetError as Error).message}</p>- ) : (- <>- <Card className="border-border/70 bg-(image:--gradient-extract-2)">- <CardHeader className="px-5 pt-5 pb-3">- <CardTitle className="text-base">Budget control plane</CardTitle>- <CardDescription>- Hard-stop spend limits for agents and projects. Provider subscription quota stays separate and appears under Providers.- </CardDescription>- </CardHeader>- <CardContent className="grid gap-3 px-5 pb-5 pt-0 md:grid-cols-4">- <MetricTile- label="Active incidents"- value={String(activeBudgetIncidents.length)}- subtitle="Open soft or hard threshold crossings"- icon={ReceiptText}- />- <MetricTile- label="Pending approvals"- value={String(budgetData?.pendingApprovalCount ?? 0)}- subtitle="Budget override approvals awaiting board action"- icon={ArrowUpRight}- />- <MetricTile- label="Paused agents"- value={String(budgetData?.pausedAgentCount ?? 0)}- subtitle="Agent heartbeats blocked by budget"- icon={Coins}- />- <MetricTile- label="Paused projects"- value={String(budgetData?.pausedProjectCount ?? 0)}- subtitle="Project execution blocked by budget"- icon={DollarSign}- />- </CardContent>- </Card>-- {activeBudgetIncidents.length > 0 ? (- <div className="space-y-3">- <div>- <h2 className="text-lg font-semibold">Active incidents</h2>- <p className="text-sm text-muted-foreground">- Resolve hard stops here by raising the budget or explicitly keeping the scope paused.- </p>- </div>- <div className="grid gap-4 xl:grid-cols-2">- {activeBudgetIncidents.map((incident) => (- <BudgetIncidentCard- key={incident.id}- incident={incident}- isMutating={incidentMutation.isPending}- onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}- onRaiseAndResume={(amount) =>- incidentMutation.mutate({- incidentId: incident.id,- action: "raise_budget_and_resume",- amount,- })}- />- ))}- </div>- </div>- ) : null}-- <div className="space-y-5">- {(["company", "agent", "project"] as const).map((scopeType) => {- const rows = budgetPoliciesByScope[scopeType];- if (rows.length === 0) return null;- return (- <section key={scopeType} className="space-y-3">- <div>- <h2 className="text-lg font-semibold capitalize">{scopeType} budgets</h2>- <p className="text-sm text-muted-foreground">- {scopeType === "company"- ? "Company-wide monthly policy."- : scopeType === "agent"- ? "Recurring monthly spend policies for individual agents."- : "Lifetime spend policies for execution-bound projects."}- </p>- </div>- <div className="grid gap-4 xl:grid-cols-2">- {rows.map((summary) => (- <BudgetPolicyCard- key={summary.policyId}- summary={summary}- isSaving={policyMutation.isPending}- onSave={(amount) =>- policyMutation.mutate({- scopeType: summary.scopeType,- scopeId: summary.scopeId,- amount,- windowKind: summary.windowKind,- })}- />- ))}- </div>- </section>- );- })}-- {budgetPolicies.length === 0 ? (- <Card>- <CardContent className="px-5 py-8 text-sm text-muted-foreground">- No budget policies yet. Set agent and project budgets from their detail pages, or use the existing company monthly budget control.- </CardContent>- </Card>- ) : null}- </div>- </>- )}- </TabsContent>-- <TabsContent value="providers" className="mt-4 space-y-4">- {showCustomPrompt ? (- <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>- ) : (- <>- <Tabs value={effectiveProvider} onValueChange={setActiveProvider}>- <PageTabBar items={providerTabItems} value={effectiveProvider} />-- <TabsContent value="all" className="mt-4">- {providers.length === 0 ? (- <p className="text-sm text-muted-foreground">No cost events in this period.</p>- ) : (- <div className="grid gap-4 md:grid-cols-2">- {providers.map((provider) => (- <ProviderQuotaCard- key={provider}- provider={provider}- rows={byProvider.get(provider) ?? []}- budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}- totalCompanySpendCents={spendData?.summary.spendCents ?? 0}- weekSpendCents={weekSpendByProvider.get(provider) ?? 0}- windowRows={windowSpendByProvider.get(provider) ?? []}- showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}- quotaWindows={quotaWindowsByProvider.get(provider) ?? []}- quotaError={quotaErrorsByProvider.get(provider) ?? null}- quotaSource={quotaSourcesByProvider.get(provider) ?? null}- quotaLoading={quotaLoading}- />- ))}- </div>- )}- </TabsContent>-- {providers.map((provider) => (- <TabsContent key={provider} value={provider} className="mt-4">- <ProviderQuotaCard- provider={provider}- rows={byProvider.get(provider) ?? []}- budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}- totalCompanySpendCents={spendData?.summary.spendCents ?? 0}- weekSpendCents={weekSpendByProvider.get(provider) ?? 0}- windowRows={windowSpendByProvider.get(provider) ?? []}- showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}- quotaWindows={quotaWindowsByProvider.get(provider) ?? []}- quotaError={quotaErrorsByProvider.get(provider) ?? null}- quotaSource={quotaSourcesByProvider.get(provider) ?? null}- quotaLoading={quotaLoading}- />- </TabsContent>- ))}- </Tabs>- </>- )}- </TabsContent>-- <TabsContent value="billers" className="mt-4 space-y-4">- {showCustomPrompt ? (- <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>- ) : (- <>- <Tabs value={effectiveBiller} onValueChange={setActiveBiller}>- <PageTabBar items={billerTabItems} value={effectiveBiller} />-- <TabsContent value="all" className="mt-4">- {billers.length === 0 ? (- <p className="text-sm text-muted-foreground">No billable events in this period.</p>- ) : (- <div className="grid gap-4 md:grid-cols-2">- {billers.map((biller) => {- const row = (byBiller.get(biller) ?? [])[0];- if (!row) return null;- const providerRows = (providerData ?? []).filter((entry) => entry.biller === biller);- return (- <BillerSpendCard- key={biller}- row={row}- weekSpendCents={weekSpendByBiller.get(biller) ?? 0}- budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}- totalCompanySpendCents={spendData?.summary.spendCents ?? 0}- providerRows={providerRows}- />- );- })}- </div>- )}- </TabsContent>-- {billers.map((biller) => {- const row = (byBiller.get(biller) ?? [])[0];- if (!row) return null;- const providerRows = (providerData ?? []).filter((entry) => entry.biller === biller);- return (- <TabsContent key={biller} value={biller} className="mt-4">- <BillerSpendCard- row={row}- weekSpendCents={weekSpendByBiller.get(biller) ?? 0}- budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}- totalCompanySpendCents={spendData?.summary.spendCents ?? 0}- providerRows={providerRows}- />- </TabsContent>- );- })}- </Tabs>- </>- )}- </TabsContent>-- <TabsContent value="finance" className="mt-4 space-y-4">- {showCustomPrompt ? (- <p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>- ) : financeLoading ? (- <PageSkeleton variant="costs" />- ) : financeError ? (- <p className="text-sm text-destructive">{(financeError as Error).message}</p>- ) : (- <>- <FinanceSummaryCard- debitCents={financeData?.summary.debitCents ?? 0}- creditCents={financeData?.summary.creditCents ?? 0}- netCents={financeData?.summary.netCents ?? 0}- estimatedDebitCents={financeData?.summary.estimatedDebitCents ?? 0}- eventCount={financeData?.summary.eventCount ?? 0}- />-- <div className="grid gap-4 xl:grid-cols-(--gtc-33)">- <div className="space-y-4">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">By biller</CardTitle>- <CardDescription>Account-level financial events grouped by who charged or credited them.</CardDescription>- </CardHeader>- <CardContent className="grid gap-4 px-5 pb-5 pt-2 md:grid-cols-2">- {(financeData?.byBiller.length ?? 0) === 0 ? (- <p className="text-sm text-muted-foreground">No finance events yet.</p>- ) : (- financeData?.byBiller.map((row) => <FinanceBillerCard key={row.biller} row={row} />)- )}- </CardContent>- </Card>- <FinanceTimelineCard rows={topFinanceEvents} />- </div>-- <FinanceKindCard rows={financeData?.byKind ?? []} />- </div>- </>- )}- </TabsContent>- </Tabs>- </div>- );-}diff --git a/ui/src/pages/Costs.test.tsx b/ui/src/pages/Costs.test.tsxindex 04b21bd3c7..d7f21fd8da 100644--- a/ui/src/pages/Costs.test.tsx+++ b/ui/src/pages/Costs.test.tsx@@ -5,12 +5,17 @@ import { createRoot } from "react-dom/client";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Costs } from "./Costs";+import { CostByUserTable } from "../components/CostByUserTable";+import { MemoryRouter } from "react-router-dom";+const resolveIncidentMock = vi.hoisted(() => vi.fn());+const upsertPolicyMock = vi.hoisted(() => vi.fn());const budgetOverviewMock = vi.hoisted(() => vi.fn());const setBreadcrumbsMock = vi.hoisted(() => vi.fn());const costsApiMocks = vi.hoisted(() => ({summary: vi.fn(),byAgent: vi.fn(),+ byUser: vi.fn(),byProject: vi.fn(),byAgentModel: vi.fn(),financeSummary: vi.fn(),@@ -26,8 +31,8 @@ const costsApiMocks = vi.hoisted(() => ({vi.mock("../api/budgets", () => ({budgetsApi: {overview: (...args: unknown[]) => budgetOverviewMock(...args),- upsertPolicy: vi.fn(),- resolveIncident: vi.fn(),+ upsertPolicy: upsertPolicyMock,+ resolveIncident: resolveIncidentMock,},}));@@ -41,14 +46,22 @@ vi.mock("../context/BreadcrumbContext", () => ({useBreadcrumbs: () => ({ setBreadcrumbs: setBreadcrumbsMock }),}));+vi.mock("../context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false }) }));+// eslint-disable-next-line @typescript-eslint/no-explicit-any(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;-describe("Costs embedded Audit surfaces", () => {+const surfaces = [+ ["streamlined", { embedded: true, hideBudgetsTab: true }],+ ["standalone", {}],+] as const;++describe("Shared Costs surfaces", () => {let container: HTMLDivElement;let root: ReturnType<typeof createRoot>;beforeEach(() => {+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });container = document.createElement("div");document.body.appendChild(container);budgetOverviewMock.mockResolvedValue({@@ -66,6 +79,16 @@ describe("Costs embedded Audit surfaces", () => {vi.clearAllMocks();});+ it.each([0, 125])("shows $%s of known user spend while retaining an unpriced warning", async (costCents) => {+ root = createRoot(container);+ await act(async () => root.render(<CostByUserTable report={{ activeUserCount: 1, rows: [{+ userId: null, userName: null, userImage: null, runCount: 1, eventCount: 1, estimatedEventCount: 0, unpricedEventCount: 1,+ costCents, costCentsExact: `${costCents}.0000000`, inputTokens: 10, cachedInputTokens: 0, outputTokens: 2,+ }] }} />));+ expect(container.querySelector("tbody tr td:last-child")?.textContent).toContain(costCents > 0 ? "$1.25" : "—");+ expect(container.textContent).toContain("1 unpriced charge");+ });+it("renders a focused Budgets section without duplicate Costs chrome or spend queries", async () => {const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });root = createRoot(container);@@ -89,4 +112,214 @@ describe("Costs embedded Audit surfaces", () => {expect(setBreadcrumbsMock).not.toHaveBeenCalled();for (const mock of Object.values(costsApiMocks)) expect(mock).not.toHaveBeenCalled();});++ it.each([+ ["reservation", 500, "agent"], ["unknown price", 500, "agent"], ["amount", 500, "agent"],+ ["amount", 0, "company"], ["amount", 0, "agent"], ["amount", 0, "project"],+ ] as const)("preserves other settings when editing %s from %s on a %s budget", async (field, previousAmount, scopeType) => {+ const summary = {+ policyId: "policy", companyId: "company-1", scopeType, scopeId: "agent", scopeName: "Worker", metric: "billed_cents", windowKind: "lifetime",+ amount: previousAmount, warnPercent: 65, hardStopEnabled: false, notifyEnabled: false, isActive: false, unpricedUsagePolicy: "allow", reservationCents: "2.0000000",+ observedAmount: 0, remainingAmount: 500, utilizationPercent: 0, unpricedEventCount: 0, pendingRunCount: 0, status: "ok", paused: false, pauseReason: null,+ };+ budgetOverviewMock.mockResolvedValue({ policies: [summary], activeIncidents: [], pendingApprovalCount: 0, pausedAgentCount: 0, pausedProjectCount: 0 });+ upsertPolicyMock.mockResolvedValue({});+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(container);+ await act(async () => root.render(<QueryClientProvider client={queryClient}><Costs embedded initialTab="budgets" lockTab /></QueryClientProvider>));+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('[aria-label="Reserve per run (USD)"]')).not.toBeNull()); });+ const advanced = container.querySelector("details")!;+ expect(advanced.open).toBe(false);+ if (field !== "amount") await act(async () => advanced.querySelector("summary")!.click());+ if (field === "unknown price") await act(async () => container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());+ else {+ const element = field === "reservation" ? container.querySelector<HTMLInputElement>('[aria-label="Reserve per run (USD)"]')! : container.querySelector<HTMLInputElement>('input:not([type="checkbox"]):not([aria-label])')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(element, "1");+ element.dispatchEvent(new Event("input", { bubbles: true }));+ });+ const label = field === "reservation" ? "Update reservation" : previousAmount === 0 ? "Set budget" : "Update budget";+ await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === label)!.click());+ }+ await act(async () => { await vi.waitFor(() => expect(upsertPolicyMock).toHaveBeenCalled()); });+ expect(upsertPolicyMock).toHaveBeenCalledWith("company-1", {+ scopeType: summary.scopeType, scopeId: summary.scopeId, metric: summary.metric, windowKind: summary.windowKind,+ ...(field === "amount" ? { amount: 100 } : field === "unknown price" ? { unpricedUsagePolicy: "block" } : { reservationCents: "100.0000000" }),+ });+ queryClient.clear();+ });++ it("shows a safe policy-save failure without losing the operator's settings", async () => {+ const policy = {+ policyId: "policy", companyId: "company-1", scopeType: "agent", scopeId: "agent", scopeName: "Worker", metric: "billed_cents", windowKind: "lifetime",+ amount: 500, warnPercent: 65, hardStopEnabled: false, notifyEnabled: false, isActive: false, unpricedUsagePolicy: "allow", reservationCents: "2.0000000",+ observedAmount: 0, remainingAmount: 500, utilizationPercent: 0, unpricedEventCount: 0, pendingRunCount: 0, status: "ok", paused: false, pauseReason: null,+ };+ budgetOverviewMock.mockResolvedValue({ policies: [policy], activeIncidents: [], pausedAgentCount: 0, pausedProjectCount: 0 });+ upsertPolicyMock.mockRejectedValueOnce(new Error("private SQL policy error"));+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ root = createRoot(container);+ await act(async () => root.render(<QueryClientProvider client={queryClient}><Costs embedded initialTab="budgets" lockTab /></QueryClientProvider>));+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('input[type="checkbox"]')).not.toBeNull()); });+ const reservation = container.querySelector<HTMLInputElement>('[aria-label="Reserve per run (USD)"]')!;+ const originalReservation = reservation.value;+ await act(async () => container.querySelector("details summary")!.dispatchEvent(new MouseEvent("click", { bubbles: true })));+ await act(async () => container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click());+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Could not update the budget policy")); });+ expect(container.textContent).toContain("Worker");+ expect(container.textContent).not.toContain("private SQL");+ expect(reservation.value).toBe(originalReservation);+ queryClient.clear();+ });++ it.each(surfaces)("shows failed budget actions on the %s Overview", async (_name, props) => {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 1000, pricingComplete: false });+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });+ budgetOverviewMock.mockResolvedValue({ policies: [], activeIncidents: [{ id: "incident", scopeType: "agent", scopeName: "Codie", status: "open", thresholdType: "hard", amountObserved: 200, amountLimit: 1000 }], pausedAgentCount: 1, pausedProjectCount: 0 });+ resolveIncidentMock.mockRejectedValue(new Error("private database error"));+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });+ root = createRoot(container);+ await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>));+ await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("Raise budget & resume")); });+ await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "Raise budget & resume")!.click());+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Could not update the budget")); });+ expect(resolveIncidentMock).toHaveBeenCalledWith("company-1", "incident", { incidentId: "incident", action: "raise_budget_and_resume", amount: 1200 });+ expect(container.querySelector('[role="tab"][data-state="active"]')?.textContent).toBe("Overview");+ expect(container.textContent).toContain("Check any pending runs or unpriced usage shown on this page");+ expect(container.textContent).not.toContain("private database error");+ queryClient.clear();+ });++ it("compares monthly budgets only with month-to-date spend", async () => {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 200, budgetCents: 1000, utilizationPercent: 20, pricingComplete: true });+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(container);+ await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs /></QueryClientProvider></MemoryRouter>));+ const budgetCard = () => [...container.querySelectorAll("div")].find(node => node.textContent === "Budget")?.closest('[data-slot="card"]');+ await act(async () => { await vi.waitFor(() => expect(budgetCard()?.textContent).toContain("20%")); });+ expect(budgetCard()?.textContent).toContain("$2.00 of $10.00 this month");+ costsApiMocks.summary.mockResolvedValue({ spendCents: 12000, budgetCents: 1000, utilizationPercent: 1200, pricingComplete: true });+ await act(async () => [...container.querySelectorAll("button")].find(b => b.textContent === "All Time")!.click());+ await act(async () => { await vi.waitFor(() => expect(container.textContent).toContain("$120.00")); });+ expect(budgetCard()?.textContent).toContain("$10.00");+ expect(budgetCard()?.textContent).toContain("Monthly limit");+ expect(container.textContent).not.toContain("1200%");+ expect(container.textContent).not.toContain("of monthly budget consumed");+ expect(costsApiMocks.summary).toHaveBeenLastCalledWith("company-1", undefined, undefined);+ queryClient.clear();+ });++ it.each(surfaces)("uses the displayed company cap for provider warnings on the %s page", async (_name, props) => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-10-16T00:30:00Z"));+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ try {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 800, budgetCents: 1000, pricingComplete: true });+ const row = { model: "test", billingType: "metered_api", inputTokens: 0, cachedInputTokens: 0, outputTokens: 0,+ apiRunCount: 1, subscriptionRunCount: 0, subscriptionInputTokens: 0, subscriptionCachedInputTokens: 0, subscriptionOutputTokens: 0 };+ costsApiMocks.byProvider.mockResolvedValue([+ { ...row, provider: "openai", biller: "openai", costCents: 100 },+ { ...row, provider: "google", biller: "google", costCents: 700 },+ ]);+ root = createRoot(container);+ await act(async () => root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} initialTab="providers" /></QueryClientProvider></MemoryRouter>));+ await act(async () => { await vi.waitFor(() => expect(container.querySelectorAll('[aria-label^="Period spend:"]')).toHaveLength(2)); });+ const bar = (percent: number) => container.querySelector(`[aria-label="Period spend: ${percent}%"]`)!.parentElement!;+ expect(bar(10).querySelector(".bg-destructive")).toBeNull();+ expect(bar(70).querySelector(".bg-destructive")).not.toBeNull();+ expect(container.textContent).toContain("10% of company budget");+ expect(container.textContent).toContain("70% of company budget");+ await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "All Time")!.click());+ await act(async () => { await vi.waitFor(() => expect(container.querySelector('[aria-label^="Period spend:"]')).toBeNull()); });+ } finally { queryClient.clear(); vi.useRealTimers(); }+ });++ it.each(surfaces)("shows incomplete accounting and currency boundaries on the %s page", async (_name, props) => {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 12.4, budgetCents: 0, pricingComplete: false, unpricedEventCount: 2, pendingRunCount: 1 });+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 1,+ currencies: [{ currency: "EUR", netCents: 100 }],+ });+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(container);+ await act(async () => {+ root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>);+ });+ await act(async () => {+ await vi.waitFor(() => expect(container.textContent).toContain("Spend is incomplete: 2 usage events have no reliable price; 1 runs await accounting."));+ });+ expect(container.textContent).toContain("Finance headline totals are USD only");+ });++ it.each(surfaces)("labels each agent and expanded model independently on the %s page", async (_name, props) => {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 600, budgetCents: 0, pricingComplete: true, estimatedEventCount: 3 });+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });+ const base = { costCents: 200, inputTokens: 10, cachedInputTokens: 5, outputTokens: 2, apiRunCount: 2, subscriptionRunCount: 0, eventCount: 2 };+ costsApiMocks.byAgent.mockResolvedValue([+ { ...base, agentId: "codie", agentName: "Codie", estimatedEventCount: 2 },+ { ...base, agentId: "mixed", agentName: "Mixed", estimatedEventCount: 1 },+ { ...base, agentId: "reported", agentName: "Reported", estimatedEventCount: 0 },+ { ...base, agentId: "legacy", agentName: "Legacy", eventCount: undefined },+ ]);+ costsApiMocks.byAgentModel.mockResolvedValue([+ { ...base, agentId: "mixed", provider: "openai", biller: "openai", billingType: "metered_api", model: "gpt-6-astra", eventCount: 1, estimatedEventCount: 1 },+ { ...base, agentId: "mixed", provider: "openai", biller: "openai", billingType: "metered_api", model: "gpt-6-sol", eventCount: 1, estimatedEventCount: 0 },+ ]);+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(container);+ await act(async () => {+ root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>);+ });+ await act(async () => {+ await vi.waitFor(() => expect(container.querySelector('[aria-label="Codie costs"]')).not.toBeNull());+ });+ const card = (name: string) => container.querySelector<HTMLElement>(`[aria-label="${name} costs"]`)!;+ expect(card("Codie").textContent).toContain("Estimated");+ expect(card("Codie").textContent).not.toContain("Partially estimated");+ expect(card("Mixed").textContent).toContain("Partially estimated");+ expect(card("Reported").textContent).not.toMatch(/Estimated|Partially estimated/);+ expect(card("Legacy").textContent).not.toMatch(/Estimated|Partially estimated/);+ await act(async () => card("Mixed").querySelector<HTMLElement>(".cursor-pointer")!.click());+ const breakdown = card("Mixed").querySelector(".border-l")!;+ expect(breakdown.textContent).toContain("gpt-6-astra");+ expect(breakdown.querySelectorAll('[data-slot="badge"]')).toHaveLength(1);+ expect(breakdown.querySelector('[data-slot="badge"]')!.textContent).toBe("Estimated");+ // The count is for charges, not runs; it must not use apiRunCount or the+ // page-wide estimated count when determining whether a row is mixed.+ expect(breakdown.querySelector('[data-slot="badge"]')!.getAttribute("title")).toContain("1 estimated charge.");+ });++ it.each(surfaces)("preserves the %s heading, breadcrumbs and tab navigation", async (name, props) => {+ for (const mock of Object.values(costsApiMocks)) mock.mockResolvedValue([]);+ costsApiMocks.byUser.mockResolvedValue({ activeUserCount: 1, rows: [] });+ costsApiMocks.summary.mockResolvedValue({ spendCents: 0, budgetCents: 0, pricingComplete: true });+ costsApiMocks.financeSummary.mockResolvedValue({ netCents: 0, debitCents: 0, creditCents: 0, estimatedDebitCents: 0, eventCount: 0 });+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(container);+ await act(async () => {+ root.render(<MemoryRouter><QueryClientProvider client={queryClient}><Costs {...props} /></QueryClientProvider></MemoryRouter>);+ });+ const streamlined = name === "streamlined";+ expect(container.querySelector(streamlined ? "h2" : "h1")?.textContent).toBe("Costs");+ if (streamlined) {+ expect(container.querySelector("h1")).toBeNull();+ expect(setBreadcrumbsMock).not.toHaveBeenCalled();+ } else {+ expect(setBreadcrumbsMock).toHaveBeenCalledWith([{ label: "Costs" }]);+ }+ expect([...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent)).toEqual(+ streamlined ? ["Overview", "Providers", "Billers", "Finance"] : ["Overview", "Budgets", "Providers", "Billers", "Finance"],+ );+ });+});diff --git a/ui/src/pages/Costs.tsx b/ui/src/pages/Costs.tsxindex e28cf08dd9..3f951d0d2d 100644--- a/ui/src/pages/Costs.tsx+++ b/ui/src/pages/Costs.tsx@@ -1,5 +1,7 @@+import { CostEstimateLabel } from "../components/CostEstimateLabel";+import { CostByUserTable } from "../components/CostByUserTable";import { AgentIdentity } from "@/components/AgentIdentity";-import { useEffect, useMemo, useRef, useState, type ComponentType } from "react";+import { useEffect, useMemo, useRef, useState, type ComponentType, type ReactNode } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import type {BudgetPolicySummary,@@ -9,6 +11,7 @@ import type {CostWindowSpendRow,FinanceEvent,QuotaWindow,+ ProviderQuotaResult,} from "@paperclipai/shared";import { ArrowDownLeft, ArrowUpRight, ChevronDown, ChevronRight, Coins, DollarSign, ReceiptText } from "lucide-react";import { budgetsApi } from "../api/budgets";@@ -28,6 +31,7 @@ import { StatusBadge } from "../components/StatusBadge";import { useBreadcrumbs } from "../context/BreadcrumbContext";import { useCompany } from "../context/CompanyContext";import { useDateRange, PRESET_KEYS, PRESET_LABELS } from "../hooks/useDateRange";+import { retainQuotaWindows } from "../lib/quota-refresh";import { queryKeys } from "../lib/queryKeys";import { billingTypeDisplayName, cn, formatCents, formatTokens, providerDisplayName } from "../lib/utils";import { Button } from "@/components/ui/button";@@ -88,7 +92,7 @@ function MetricTile({}: {label: string;value: string;- subtitle: string;+ subtitle: ReactNode;icon: ComponentType<{ className?: string }>;}) {return (@@ -212,6 +216,13 @@ export function Costs({const weekRange = useMemo(() => currentWeekRange(), [today]);const companyId = selectedCompanyId ?? NO_COMPANY;+ // The clock advances the request bounds, not the identity of the report.+ // Keep successful data visible during polling; a different company or selected+ // period still gets its own cache entry and initial loading state.+ // Month/year-to-date become a different reporting period at their UTC+ // boundary. Rolling windows retain identity as their lower bound advances.+ const reportQueryFrom = ["custom", "mtd", "ytd"].includes(preset) ? from || undefined : undefined;+ const reportQueryTo = preset === "custom" ? to || undefined : preset;const { data: budgetData, isLoading: budgetLoading, error: budgetError } = useQuery({queryKey: queryKeys.budgets.overview(companyId),@@ -230,18 +241,16 @@ export function Costs({};const policyMutation = useMutation({- mutationFn: (input: {- scopeType: BudgetPolicySummary["scopeType"];- scopeId: string;- amount: number;- windowKind: BudgetPolicySummary["windowKind"];- }) =>- budgetsApi.upsertPolicy(companyId, {- scopeType: input.scopeType,- scopeId: input.scopeId,- amount: input.amount,- windowKind: input.windowKind,- }),+ mutationFn: ({ summary, changes }: {+ summary: BudgetPolicySummary;+ changes: Partial<Pick<BudgetPolicySummary, "amount" | "reservationCents" | "unpricedUsagePolicy">>;+ }) => budgetsApi.upsertPolicy(companyId, {+ scopeType: summary.scopeType,+ scopeId: summary.scopeId,+ metric: summary.metric,+ windowKind: summary.windowKind,+ ...changes,+ }),onSuccess: invalidateBudgetViews,});@@ -252,7 +261,7 @@ export function Costs({});const { data: spendData, isLoading: spendLoading, error: spendError } = useQuery({- queryKey: queryKeys.costs(companyId, from || undefined, to || undefined),+ queryKey: queryKeys.costs(companyId, reportQueryFrom, reportQueryTo),queryFn: async () => {const [summary, byAgent, byProject, byAgentModel] = await Promise.all([costsApi.summary(companyId, from || undefined, to || undefined),@@ -263,14 +272,22 @@ export function Costs({return { summary, byAgent, byProject, byAgentModel };},enabled: !!selectedCompanyId && customReady && showSummaryChrome,+ refetchInterval: 30_000,+ });++ const { data: userSpendData, error: userSpendError } = useQuery({+ queryKey: [...queryKeys.costs(companyId, reportQueryFrom, reportQueryTo), "by-user"],+ queryFn: () => costsApi.byUser(companyId, from || undefined, to || undefined),+ enabled: !!selectedCompanyId && customReady && showSummaryChrome && mainTab === "overview",+ refetchInterval: 30_000,});const { data: financeData, isLoading: financeLoading, error: financeError } = useQuery({queryKey: [- queryKeys.financeSummary(companyId, from || undefined, to || undefined),- queryKeys.financeByBiller(companyId, from || undefined, to || undefined),- queryKeys.financeByKind(companyId, from || undefined, to || undefined),- queryKeys.financeEvents(companyId, from || undefined, to || undefined, 18),+ queryKeys.financeSummary(companyId, reportQueryFrom, reportQueryTo),+ queryKeys.financeByBiller(companyId, reportQueryFrom, reportQueryTo),+ queryKeys.financeByKind(companyId, reportQueryFrom, reportQueryTo),+ queryKeys.financeEvents(companyId, reportQueryFrom, reportQueryTo, 18),],queryFn: async () => {const [summary, byBiller, byKind, events] = await Promise.all([@@ -282,12 +299,13 @@ export function Costs({return { summary, byBiller, byKind, events };},enabled: !!selectedCompanyId && customReady && showSummaryChrome,+ refetchInterval: 30_000,});const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());useEffect(() => {setExpandedAgents(new Set());- }, [companyId, from, to]);+ }, [companyId, preset, customFrom, customTo]);function toggleAgent(agentId: string) {setExpandedAgents((prev) => {@@ -311,23 +329,23 @@ export function Costs({return map;}, [spendData?.byAgentModel]);- const { data: providerData } = useQuery({- queryKey: queryKeys.usageByProvider(companyId, from || undefined, to || undefined),+ const { data: providerData, error: providerError } = useQuery({+ queryKey: queryKeys.usageByProvider(companyId, reportQueryFrom, reportQueryTo),queryFn: () => costsApi.byProvider(companyId, from || undefined, to || undefined),enabled: !!selectedCompanyId && customReady && (mainTab === "providers" || mainTab === "billers"),refetchInterval: 30_000,staleTime: 10_000,});- const { data: billerData } = useQuery({- queryKey: queryKeys.usageByBiller(companyId, from || undefined, to || undefined),+ const { data: billerData, error: billerError } = useQuery({+ queryKey: queryKeys.usageByBiller(companyId, reportQueryFrom, reportQueryTo),queryFn: () => costsApi.byBiller(companyId, from || undefined, to || undefined),enabled: !!selectedCompanyId && customReady && mainTab === "billers",refetchInterval: 30_000,staleTime: 10_000,});- const { data: weekData } = useQuery({+ const { data: weekData, error: weekError } = useQuery({queryKey: queryKeys.usageByProvider(companyId, weekRange.from, weekRange.to),queryFn: () => costsApi.byProvider(companyId, weekRange.from, weekRange.to),enabled: !!selectedCompanyId && (mainTab === "providers" || mainTab === "billers"),@@ -335,7 +353,7 @@ export function Costs({staleTime: 10_000,});- const { data: weekBillerData } = useQuery({+ const { data: weekBillerData, error: weekBillerError } = useQuery({queryKey: queryKeys.usageByBiller(companyId, weekRange.from, weekRange.to),queryFn: () => costsApi.byBiller(companyId, weekRange.from, weekRange.to),enabled: !!selectedCompanyId && mainTab === "billers",@@ -343,7 +361,7 @@ export function Costs({staleTime: 10_000,});- const { data: windowData } = useQuery({+ const { data: windowData, error: windowError } = useQuery({queryKey: queryKeys.usageWindowSpend(companyId),queryFn: () => costsApi.windowSpend(companyId),enabled: !!selectedCompanyId && mainTab === "providers",@@ -351,9 +369,13 @@ export function Costs({staleTime: 10_000,});- const { data: quotaData, isLoading: quotaLoading } = useQuery({+ const { data: quotaData, isLoading: quotaLoading, error: quotaFetchError } = useQuery({queryKey: queryKeys.usageQuotaWindows(companyId),queryFn: () => costsApi.quotaWindows(companyId),+ structuralSharing: (previous, incoming) => retainQuotaWindows(+ previous as ProviderQuotaResult[] | undefined,+ incoming as ProviderQuotaResult[],+ ),enabled: !!selectedCompanyId && mainTab === "providers",refetchInterval: 300_000,staleTime: 60_000,@@ -408,7 +430,7 @@ export function Costs({const quotaWindowsByProvider = useMemo(() => {const map = new Map<string, QuotaWindow[]>();for (const result of quotaData ?? []) {- if (result.ok && result.windows.length > 0) {+ if (result.windows.length > 0) {map.set(result.provider, result.windows);}}@@ -418,10 +440,14 @@ export function Costs({const quotaErrorsByProvider = useMemo(() => {const map = new Map<string, string>();for (const result of quotaData ?? []) {- if (!result.ok && result.error) map.set(result.provider, result.error);+ if (!result.ok) map.set(result.provider, "unavailable");+ }+ if (quotaFetchError) {+ map.set("anthropic", "unavailable");+ map.set("openai", "unavailable");}return map;- }, [quotaData]);+ }, [quotaData, quotaFetchError]);const quotaSourcesByProvider = useMemo(() => {const map = new Map<string, string>();@@ -438,20 +464,13 @@ export function Costs({if (preset !== "mtd") return map;const budget = spendData?.summary.budgetCents ?? 0;if (budget <= 0) return map;- const totalSpend = spendData?.summary.spendCents ?? 0;const now = new Date();- const daysElapsed = now.getDate();- const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();+ const daysElapsed = now.getUTCDate();+ const daysInMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();for (const [providerKey, rows] of byProvider) {const providerCostCents = rows.reduce((sum, row) => sum + row.costCents, 0);- const providerShare = totalSpend > 0 ? providerCostCents / totalSpend : 0;- const providerBudget = budget * providerShare;- if (providerBudget <= 0) {- map.set(providerKey, false);- continue;- }const burnRate = providerCostCents / Math.max(daysElapsed, 1);- map.set(providerKey, providerCostCents + burnRate * (daysInMonth - daysElapsed) > providerBudget);+ map.set(providerKey, providerCostCents + burnRate * (daysInMonth - daysElapsed) > budget);}return map;}, [preset, spendData, byProvider]);@@ -555,8 +574,8 @@ export function Costs({}const showCustomPrompt = preset === "custom" && !customReady;- const showOverviewLoading = (spendLoading || financeLoading) && customReady;- const overviewError = spendError ?? financeError;+ const showOverviewLoading = spendLoading && customReady;+ const overviewError = !spendData && spendError;return (<div className="space-y-6">{showSummaryChrome ? (@@ -568,9 +587,6 @@ export function Costs({) : (<h1 className="text-3xl font-semibold tracking-tight">Costs</h1>)}- <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">- Inference spend, platform fees, credits, and live quota windows.- </p></div><div className="flex flex-wrap items-center gap-2">@@ -606,10 +622,20 @@ export function Costs({</div>) : null}+ {spendData?.summary.pricingComplete === false && (+ <p role="status" className="text-sm text-destructive">+ Spend is incomplete: {spendData.summary.unpricedEventCount} usage events have no reliable price; {spendData.summary.pendingRunCount} runs await accounting. Known spend is shown below.+ </p>+ )}+ {financeData?.summary.currencies?.some((row) => row.currency !== "USD") && (+ <p role="status" className="text-sm text-muted-foreground">+ Finance headline totals are USD only. Other currencies are listed separately; no exchange-rate conversion is applied.+ </p>+ )}<div className="grid gap-3 lg:grid-cols-4"><MetricTilelabel="Inference spend"- value={formatCents(spendData?.summary.spendCents ?? 0)}+ value={spendData ? formatCents(spendData.summary.spendCents) : "—"}subtitle={`${formatTokens(inferenceTokenTotal)} tokens across request-scoped events`}icon={DollarSign}/>@@ -617,34 +643,52 @@ export function Costs({label="Budget"value={activeBudgetIncidents.length > 0 ? String(activeBudgetIncidents.length) : (spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `${spendData.summary.utilizationPercent}%`+ ? preset === "mtd" ? `${spendData.summary.utilizationPercent}%` : formatCents(spendData.summary.budgetCents): "Open")}subtitle={activeBudgetIncidents.length > 0? `${budgetData?.pausedAgentCount ?? 0} agents paused · ${budgetData?.pausedProjectCount ?? 0} projects paused`: spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `${formatCents(spendData.summary.spendCents)} of ${formatCents(spendData.summary.budgetCents)}`+ ? preset === "mtd" ? `${formatCents(spendData.summary.spendCents)} of ${formatCents(spendData.summary.budgetCents)} this month` : "Monthly limit": "No monthly cap configured"}icon={Coins}/><MetricTile- label="Finance net"- value={formatCents(financeData?.summary.netCents ?? 0)}- subtitle={`${formatCents(financeData?.summary.debitCents ?? 0)} debits · ${formatCents(financeData?.summary.creditCents ?? 0)} credits`}+ label="Recorded charges"+ value={financeData ? formatCents(financeData.summary.netCents) : "—"}+ subtitle={financeData ? (+ <>+ <span className="block whitespace-nowrap">{formatCents(financeData.summary.debitCents)} debits</span>+ <span className="block whitespace-nowrap">{formatCents(financeData.summary.creditCents)} credits</span>+ </>+ ) : "Financial data unavailable"}icon={ReceiptText}/><MetricTilelabel="Finance events"- value={String(financeData?.summary.eventCount ?? 0)}- subtitle={`${formatCents(financeData?.summary.estimatedDebitCents ?? 0)} estimated in range`}+ value={financeData ? String(financeData.summary.eventCount) : "—"}+ subtitle={financeData ? `${formatCents(financeData.summary.estimatedDebitCents)} estimated in range` : "Financial data unavailable"}icon={ArrowUpRight}/></div></div>) : null}+ {budgetError && !budgetData ? (+ <p role="status" className="text-sm text-muted-foreground">+ Budget data could not be loaded. Please try again shortly.+ </p>+ ) : null}+ {((spendData && spendError) || (financeData && financeError) || (budgetData && budgetError) || providerError || billerError || weekError || weekBillerError || windowError) ? (+ <p role="status" className="text-sm text-muted-foreground">+ Showing the last loaded data. Updates will resume automatically.+ </p>+ ) : null}++ {!!spendData?.summary.estimatedEventCount && <p role="status" className="text-sm text-muted-foreground">Includes {spendData.summary.estimatedEventCount} estimated run charges. Token estimates use published rates and recorded assumptions; provider bills may differ.</p>}+ {incidentMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget. Check any pending runs or unpriced usage shown on this page, then try again.</p>}<Tabs value={mainTab} onValueChange={(value) => setMainTab(value as typeof mainTab)}>{!lockTab ? (<TabsList variant="line" className="justify-start">@@ -662,182 +706,117 @@ export function Costs({) : showOverviewLoading ? (<PageSkeleton variant="costs" />) : overviewError ? (- <p className="text-sm text-destructive">{(overviewError as Error).message}</p>+ <p className="text-sm text-destructive">Cost data could not be loaded. Please try again shortly.</p>) : (<>- {activeBudgetIncidents.length > 0 ? (- <div className="grid gap-4 xl:grid-cols-2">- {activeBudgetIncidents.slice(0, 2).map((incident) => (- <BudgetIncidentCard- key={incident.id}- incident={incident}- isMutating={incidentMutation.isPending}- onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}- onRaiseAndResume={(amount) =>- incidentMutation.mutate({- incidentId: incident.id,- action: "raise_budget_and_resume",- amount,- })}- />- ))}- </div>- ) : null}-- <div className="grid gap-4 xl:grid-cols-(--gtc-31)">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">Inference ledger</CardTitle>- <CardDescription>- Request-scoped inference spend for the selected period.- </CardDescription>- </CardHeader>- <CardContent className="space-y-4 px-5 pb-5 pt-2">- <div className="flex flex-wrap items-end justify-between gap-3">- <div>- <div className="text-3xl font-semibold tabular-nums">- {formatCents(spendData?.summary.spendCents ?? 0)}- </div>- <div className="mt-1 text-sm text-muted-foreground">- {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0- ? `Budget ${formatCents(spendData.summary.budgetCents)}`- : "Unlimited budget"}- </div>- </div>- <div className="border border-border px-4 py-3 text-right">- <div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">usage</div>- <div className="mt-1 text-lg font-medium tabular-nums">- {formatTokens(inferenceTokenTotal)}- </div>- </div>- </div>- {spendData?.summary.budgetCents && spendData.summary.budgetCents > 0 ? (- <div className="space-y-2">- <div className="h-2 overflow-hidden bg-muted">- <div- className={cn(- "h-full transition-(--tp-width-background-color) duration-150",- spendData.summary.utilizationPercent > 90- ? "bg-(--status-task-blocked)"- : spendData.summary.utilizationPercent > 70- ? "bg-(--status-task-todo)"- : "bg-(--status-task-done)",- )}- style={{ width: `${Math.min(100, spendData.summary.utilizationPercent)}%` }}- />- </div>- <div className="text-xs text-muted-foreground">- {spendData.summary.utilizationPercent}% of monthly budget consumed in this range.- </div>- </div>- ) : null}- </CardContent>- </Card>-- <FinanceSummaryCard- debitCents={financeData?.summary.debitCents ?? 0}- creditCents={financeData?.summary.creditCents ?? 0}- netCents={financeData?.summary.netCents ?? 0}- estimatedDebitCents={financeData?.summary.estimatedDebitCents ?? 0}- eventCount={financeData?.summary.eventCount ?? 0}- />- </div>-<div className="grid gap-4 xl:grid-cols-(--gtc-32)">- <Card>- <CardHeader className="px-5 pt-5 pb-2">- <CardTitle className="text-base">By agent</CardTitle>- <CardDescription>What each agent consumed in the selected period.</CardDescription>- </CardHeader>- <CardContent className="space-y-2 px-5 pb-5 pt-2">- {(spendData?.byAgent.length ?? 0) === 0 ? (- <p className="text-sm text-muted-foreground">No cost events yet.</p>- ) : (- spendData?.byAgent.map((row) => {- const modelRows = agentModelRows.get(row.agentId) ?? [];- const isExpanded = expandedAgents.has(row.agentId);- const hasBreakdown = modelRows.length > 0;- return (- <div key={row.agentId} className="border border-border px-4 py-3">- <div- className={cn("flex items-start justify-between gap-3", hasBreakdown ? "cursor-pointer select-none" : "")}- onClick={() => hasBreakdown && toggleAgent(row.agentId)}- >- <div className="flex min-w-0 items-center gap-2">- {hasBreakdown ? (- isExpanded- ? <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />- : <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />- ) : (- <span className="h-3 w-3 shrink-0" />- )}- <AgentIdentity agent={{ id: row.agentId, name: row.agentName ?? row.agentId, appearance: row.agentAppearance }} size="sm" />- {row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}- </div>- <div className="text-right text-sm tabular-nums">- <div className="font-medium">{formatCents(row.costCents)}</div>- <div className="text-xs text-muted-foreground">- in {formatTokens(row.inputTokens + row.cachedInputTokens)} · out {formatTokens(row.outputTokens)}+ <div className="min-w-0 space-y-4">+ <Card className="gap-3 py-4">+ <CardHeader className="gap-0 px-5">+ <CardTitle className="text-base">By agent</CardTitle>+ </CardHeader>+ <CardContent className="space-y-2 px-5">+ {(spendData?.byAgent.length ?? 0) === 0 ? (+ <p className="text-sm text-muted-foreground">No cost events yet.</p>+ ) : (+ spendData?.byAgent.map((row) => {+ const modelRows = agentModelRows.get(row.agentId) ?? [];+ const isExpanded = expandedAgents.has(row.agentId);+ const hasBreakdown = modelRows.length > 0;+ return (+ <div key={row.agentId} role="group" aria-label={`${row.agentName ?? row.agentId} costs`} className="border border-border px-4 py-3">+ <div+ className={cn("flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", hasBreakdown ? "cursor-pointer select-none" : "")}+ onClick={() => hasBreakdown && toggleAgent(row.agentId)}+ >+ <div className="flex min-w-0 items-center gap-2">+ {hasBreakdown ? (+ isExpanded+ ? <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />+ : <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />+ ) : (+ <span className="h-3 w-3 shrink-0" />+ )}+ <AgentIdentity agent={{ id: row.agentId, name: row.agentName ?? row.agentId, appearance: row.agentAppearance }} size="sm" />+ {row.agentStatus === "terminated" ? <StatusBadge status="terminated" /> : null}</div>- {(row.apiRunCount > 0 || row.subscriptionRunCount > 0) ? (+ <div className="text-right text-sm tabular-nums">+ <div className="flex flex-wrap items-center justify-end gap-2 font-medium">+ <span>{formatCents(row.costCents)}</span>+ <CostEstimateLabel eventCount={row.eventCount} estimatedEventCount={row.estimatedEventCount} />+ </div><div className="text-xs text-muted-foreground">- {row.apiRunCount > 0 ? `${row.apiRunCount} api` : "0 api"}- {" · "}- {row.subscriptionRunCount > 0- ? `${row.subscriptionRunCount} subscription`- : "0 subscription"}+ in {formatTokens(row.inputTokens + row.cachedInputTokens)} ({formatTokens(row.cachedInputTokens)} cached) · out {formatTokens(row.outputTokens)}</div>- ) : null}+ {(row.apiRunCount > 0 || row.subscriptionRunCount > 0) ? (+ <div className="text-xs text-muted-foreground">+ {"runs: "}+ {row.apiRunCount > 0 ? `${row.apiRunCount} api` : "0 api"}+ {" · "}+ {row.subscriptionRunCount > 0+ ? `${row.subscriptionRunCount} sub`+ : "0 sub"}+ </div>+ ) : null}+ </div></div>- </div>- {isExpanded && modelRows.length > 0 ? (- <div className="mt-3 space-y-2 border-l border-border pl-4">- {modelRows.map((modelRow) => {- const sharePct = row.costCents > 0 ? Math.round((modelRow.costCents / row.costCents) * 100) : 0;- return (- <div- key={`${modelRow.provider}:${modelRow.model}:${modelRow.billingType}`}- className="flex items-start justify-between gap-3 text-xs"- >- <div className="min-w-0">- <div className="truncate font-medium text-foreground">- {providerDisplayName(modelRow.provider)}- <span className="mx-1 text-border">/</span>- <span className="font-mono">{modelRow.model}</span>- </div>- <div className="truncate text-muted-foreground">- {providerDisplayName(modelRow.biller)} · {billingTypeDisplayName(modelRow.billingType)}- </div>- </div>- <div className="text-right tabular-nums">- <div className="font-medium">- {formatCents(modelRow.costCents)}- <span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>+ {isExpanded && modelRows.length > 0 ? (+ <div className="mt-3 space-y-2 border-l border-border pl-4">+ {modelRows.map((modelRow) => {+ const sharePct = row.costCents > 0 ? Math.round((modelRow.costCents / row.costCents) * 100) : 0;+ return (+ <div+ key={`${modelRow.provider}:${modelRow.model}:${modelRow.billingType}`}+ className="flex flex-col gap-2 text-xs sm:flex-row sm:items-start sm:justify-between sm:gap-3"+ >+ <div className="min-w-0">+ <div className="truncate font-medium text-foreground">+ {providerDisplayName(modelRow.provider)}+ <span className="mx-1 text-border">/</span>+ <span className="font-mono">{modelRow.model}</span>+ </div>+ <div className="truncate text-muted-foreground">+ {providerDisplayName(modelRow.biller)} · {billingTypeDisplayName(modelRow.billingType)}+ </div></div>- <div className="text-muted-foreground">- {formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok+ <div className="text-right tabular-nums">+ <div className="flex flex-wrap items-center justify-end gap-2 font-medium">+ <span>+ {formatCents(modelRow.costCents)}+ <span className="ml-1 font-normal text-muted-foreground">({sharePct}%)</span>+ </span>+ <CostEstimateLabel eventCount={modelRow.eventCount} estimatedEventCount={modelRow.estimatedEventCount} />+ </div>+ <div className="text-muted-foreground">+ {formatTokens(modelRow.inputTokens + modelRow.cachedInputTokens + modelRow.outputTokens)} tok+ </div></div></div>- </div>- );- })}- </div>- ) : null}- </div>- );- })- )}- </CardContent>- </Card>+ );+ })}+ </div>+ ) : null}+ </div>+ );+ })+ )}+ </CardContent>+ </Card>+ {userSpendError && (+ <p role="status" className="text-sm text-muted-foreground">+ {userSpendData ? "User costs could not be refreshed. Showing the last loaded data." : "User costs could not be loaded. Please try again shortly."}+ </p>+ )}+ {userSpendData && <CostByUserTable report={userSpendData} />}+ </div><div className="space-y-4">- <Card>- <CardHeader className="px-5 pt-5 pb-2">+ <Card className="gap-3 py-4">+ <CardHeader className="gap-0 px-5"><CardTitle className="text-base">By project</CardTitle>- <CardDescription>Run costs attributed through project-linked tasks.</CardDescription></CardHeader>- <CardContent className="space-y-2 px-5 pb-5 pt-2">+ <CardContent className="space-y-2 px-5">{(spendData?.byProject.length ?? 0) === 0 ? (<p className="text-sm text-muted-foreground">No project-attributed run costs yet.</p>) : (@@ -854,19 +833,50 @@ export function Costs({</CardContent></Card>- <FinanceTimelineCard rows={topFinanceEvents.slice(0, 6)} emptyMessage="No finance events yet. Add account-level charges once biller invoices or credits land." /></div></div>++ {activeBudgetIncidents.length > 0 ? (+ <div className="grid gap-4 xl:grid-cols-2">+ {activeBudgetIncidents.slice(0, 2).map((incident) => (+ <BudgetIncidentCard+ key={incident.id}+ incident={incident}+ isMutating={incidentMutation.isPending}+ onKeepPaused={() => incidentMutation.mutate({ incidentId: incident.id, action: "keep_paused" })}+ onRaiseAndResume={(amount) =>+ incidentMutation.mutate({+ incidentId: incident.id,+ action: "raise_budget_and_resume",+ amount,+ })}+ />+ ))}+ </div>+ ) : null}++ {financeData ? (+ <FinanceSummaryCard+ debitCents={financeData.summary.debitCents}+ creditCents={financeData.summary.creditCents}+ netCents={financeData.summary.netCents}+ estimatedDebitCents={financeData.summary.estimatedDebitCents}+ eventCount={financeData.summary.eventCount}+ />+ ) : (+ <p role="status" className="text-sm text-muted-foreground">+ {financeLoading ? "Loading financial events…" : "Financial events could not be loaded. Please try again shortly."}+ </p>+ )}</>)}</TabsContent><TabsContent value="budgets" className="mt-4 space-y-4">+ {policyMutation.error && <p role="alert" className="text-sm text-destructive">Could not update the budget policy. Review your settings and try again.</p>}{budgetLoading ? (<PageSkeleton variant="costs" />- ) : budgetError ? (- <p className="text-sm text-destructive">{(budgetError as Error).message}</p>- ) : (+ ) : budgetError && !budgetData ? null : (<><Card className="border-border/70 bg-(image:--gradient-extract-2)"><CardHeader className="px-5 pt-5 pb-3">@@ -951,14 +961,11 @@ export function Costs({<BudgetPolicyCardkey={summary.policyId}summary={summary}+ onReservationChange={(reservationCents) => policyMutation.mutate({ summary, changes: { reservationCents } })}+ onUnpricedUsagePolicyChange={(unpricedUsagePolicy) => policyMutation.mutate({ summary, changes: { unpricedUsagePolicy } })}isSaving={policyMutation.isPending}onSave={(amount) =>- policyMutation.mutate({- scopeType: summary.scopeType,- scopeId: summary.scopeId,- amount,- windowKind: summary.windowKind,- })}+ policyMutation.mutate({ summary, changes: { amount } })}/>))}</div>@@ -997,11 +1004,14 @@ export function Costs({provider={provider}rows={byProvider.get(provider) ?? []}budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}+ showBudgetUtilization={preset === "mtd"}totalCompanySpendCents={spendData?.summary.spendCents ?? 0}weekSpendCents={weekSpendByProvider.get(provider) ?? 0}windowRows={windowSpendByProvider.get(provider) ?? []}showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}- quotaWindows={quotaWindowsByProvider.get(provider) ?? []}+ quotaAccounts={quotaData?.filter(account => account.provider === provider)}+ quotaRequestFailed={Boolean(quotaFetchError)}+ quotaWindows={quotaWindowsByProvider.get(provider) ?? []}quotaError={quotaErrorsByProvider.get(provider) ?? null}quotaSource={quotaSourcesByProvider.get(provider) ?? null}quotaLoading={quotaLoading}@@ -1017,10 +1027,13 @@ export function Costs({provider={provider}rows={byProvider.get(provider) ?? []}budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}+ showBudgetUtilization={preset === "mtd"}totalCompanySpendCents={spendData?.summary.spendCents ?? 0}weekSpendCents={weekSpendByProvider.get(provider) ?? 0}windowRows={windowSpendByProvider.get(provider) ?? []}showDeficitNotch={deficitNotchByProvider.get(provider) ?? false}+ quotaAccounts={quotaData?.filter(account => account.provider === provider)}+ quotaRequestFailed={Boolean(quotaFetchError)}quotaWindows={quotaWindowsByProvider.get(provider) ?? []}quotaError={quotaErrorsByProvider.get(provider) ?? null}quotaSource={quotaSourcesByProvider.get(provider) ?? null}@@ -1056,6 +1069,7 @@ export function Costs({row={row}weekSpendCents={weekSpendByBiller.get(biller) ?? 0}budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}+ showBudgetUtilization={preset === "mtd"}totalCompanySpendCents={spendData?.summary.spendCents ?? 0}providerRows={providerRows}/>@@ -1075,6 +1089,7 @@ export function Costs({row={row}weekSpendCents={weekSpendByBiller.get(biller) ?? 0}budgetMonthlyCents={spendData?.summary.budgetCents ?? 0}+ showBudgetUtilization={preset === "mtd"}totalCompanySpendCents={spendData?.summary.spendCents ?? 0}providerRows={providerRows}/>@@ -1087,12 +1102,14 @@ export function Costs({</TabsContent><TabsContent value="finance" className="mt-4 space-y-4">+ {financeData?.summary.providerReportedCentsExact !== undefined && <p className="text-sm text-muted-foreground">Provider API cost reports: {formatCents(financeData.summary.providerReportedCents ?? 0)}. Report totals overlap invoices and run estimates and are shown separately from recorded charges.</p>}+{showCustomPrompt ? (<p className="text-sm text-muted-foreground">Select a start and end date to load data.</p>) : financeLoading ? (<PageSkeleton variant="costs" />- ) : financeError ? (- <p className="text-sm text-destructive">{(financeError as Error).message}</p>+ ) : financeError && !financeData ? (+ <p className="text-sm text-destructive">Financial events could not be loaded. Please try again shortly.</p>) : (<><FinanceSummaryCard@@ -1114,7 +1131,7 @@ export function Costs({{(financeData?.byBiller.length ?? 0) === 0 ? (<p className="text-sm text-muted-foreground">No finance events yet.</p>) : (- financeData?.byBiller.map((row) => <FinanceBillerCard key={row.biller} row={row} />)+ financeData?.byBiller.map((row) => <FinanceBillerCard key={`${row.biller}:${row.currency}`} row={row} />))}</CardContent></Card>diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsxindex c740003a6b..31e4b70dc0 100644--- a/ui/src/pages/IssueDetail.tsx+++ b/ui/src/pages/IssueDetail.tsx@@ -175,6 +175,7 @@ import {formatDurationMs,formatTokens,visibleRunCostUsd,+ visibleRunTokenTotal,} from "../lib/utils";import { liveBlueBadge } from "../lib/status-colors";import { ApprovalCard } from "../components/ApprovalCard";@@ -2693,6 +2694,7 @@ function IssueDetailActivityTab({let input = 0;let output = 0;let cached = 0;+ let totalTokens = 0;let cost = 0;let runtimeMs = 0;let runCount = 0;@@ -2717,6 +2719,7 @@ function IssueDetailActivityTab({input += runInput;output += runOutput;cached += runCached;+ totalTokens += visibleRunTokenTotal(usage);cost += runCost;if (run.startedAt) {@@ -2740,7 +2743,7 @@ function IssueDetailActivityTab({output,cached,cost,- totalTokens: input + output,+ totalTokens,hasCost,hasTokens,runtimeMs,@@ -2750,6 +2753,7 @@ function IssueDetailActivityTab({}, [linkedRuns]);const issueTreeCostTokens =(issueTreeCostSummary?.inputTokens ?? 0) ++ (issueTreeCostSummary?.cachedInputTokens ?? 0) +(issueTreeCostSummary?.outputTokens ?? 0);const hasIssueTreeCost =!!issueTreeCostSummary &&diff --git a/ui/src/pages/ProjectDetail.tsx b/ui/src/pages/ProjectDetail.tsxindex 8588bdec6f..8c8943411d 100644--- a/ui/src/pages/ProjectDetail.tsx+++ b/ui/src/pages/ProjectDetail.tsx@@ -605,6 +605,8 @@ export function ProjectDetail() {metric: "billed_cents",windowKind: "lifetime",amount: 0,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: 0,remainingAmount: 0,utilizationPercent: 0,diff --git a/ui/src/pages/audit/AuditHub.tsx b/ui/src/pages/audit/AuditHub.tsxindex bbd242df66..9369ad8c54 100644--- a/ui/src/pages/audit/AuditHub.tsx+++ b/ui/src/pages/audit/AuditHub.tsx@@ -85,10 +85,6 @@ export function AuditHub({ section }: { section: AuditSection }) {<div className="space-y-6"><div><h1 className="text-3xl font-semibold tracking-tight text-foreground">Audit</h1>- <p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">- Review what happened, inspect agent runs, and understand the costs and budget controls- behind your organization.- </p></div><Tabsdiff --git a/ui/storybook/fixtures/paperclipData.ts b/ui/storybook/fixtures/paperclipData.tsindex ea3b9054f5..23a2d8db9c 100644--- a/ui/storybook/fixtures/paperclipData.ts+++ b/ui/storybook/fixtures/paperclipData.ts@@ -1118,6 +1118,8 @@ export const storybookApprovals: Approval[] = [windowKind: "calendar_month_utc",metric: "billed_cents",budgetAmount: 120_000,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: 131_400,guidance: "Raise the project budget only after current release smoke checks are green.",},@@ -1162,6 +1164,8 @@ export const storybookBudgetSummaries: BudgetPolicySummary[] = [metric: "billed_cents",windowKind: "calendar_month_utc",amount: 250_000,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: 67_500,remainingAmount: 182_500,utilizationPercent: 27,@@ -1184,6 +1188,8 @@ export const storybookBudgetSummaries: BudgetPolicySummary[] = [metric: "billed_cents",windowKind: "calendar_month_utc",amount: 120_000,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: 103_100,remainingAmount: 16_900,utilizationPercent: 86,@@ -1206,6 +1212,8 @@ export const storybookBudgetSummaries: BudgetPolicySummary[] = [metric: "billed_cents",windowKind: "calendar_month_utc",amount: 40_000,+ unpricedEventCount: 0, pendingRunCount: 0,+ unpricedUsagePolicy: "block",observedAmount: 43_200,remainingAmount: 0,utilizationPercent: 108,diff --git a/ui/storybook/stories/budget-finance.stories.tsx b/ui/storybook/stories/budget-finance.stories.tsxindex f47ff68aa1..21cbe1df0c 100644--- a/ui/storybook/stories/budget-finance.stories.tsx+++ b/ui/storybook/stories/budget-finance.stories.tsx@@ -346,6 +346,7 @@ const billerSpendRows: Array<{const financeBillerRows: FinanceByBiller[] = [{biller: "openai",+ currency: "USD",debitCents: 74_200,creditCents: 12_000,netCents: 62_200,@@ -355,6 +356,7 @@ const financeBillerRows: FinanceByBiller[] = [},{biller: "aws_bedrock",+ currency: "USD",debitCents: 45_880,creditCents: 0,netCents: 45_880,@@ -367,6 +369,7 @@ const financeBillerRows: FinanceByBiller[] = [const financeKindRows: FinanceByKind[] = [{eventKind: "inference_charge",+ currency: "USD",debitCents: 49_820,creditCents: 0,netCents: 49_820,@@ -376,6 +379,7 @@ const financeKindRows: FinanceByKind[] = [},{eventKind: "log_storage_charge",+ currency: "USD",debitCents: 8_760,creditCents: 0,netCents: 8_760,@@ -385,6 +389,7 @@ const financeKindRows: FinanceByKind[] = [},{eventKind: "provisioned_capacity_charge",+ currency: "USD",debitCents: 42_900,creditCents: 0,netCents: 42_900,@@ -394,6 +399,7 @@ const financeKindRows: FinanceByKind[] = [},{eventKind: "credit_refund",+ currency: "USD",debitCents: 0,creditCents: 12_000,netCents: -12_000,@@ -428,6 +434,7 @@ const financeTimelineRows: FinanceEvent[] = [amountCents: 40_000,currency: "USD",estimated: false,+ idempotencyKey: null,externalInvoiceId: "INV-2026-04-OPENAI-1184",metadataJson: { paymentMethod: "corporate-card" },occurredAt: at(1_260),@@ -457,6 +464,7 @@ const financeTimelineRows: FinanceEvent[] = [amountCents: 42_900,currency: "USD",estimated: true,+ idempotencyKey: null,externalInvoiceId: "AWS-EST-7713",metadataJson: { purchaseOrder: "PO-STORYBOOK-APR" },occurredAt: at(420),@@ -486,6 +494,7 @@ const financeTimelineRows: FinanceEvent[] = [amountCents: 8_760,currency: "USD",estimated: true,+ idempotencyKey: null,externalInvoiceId: "CF-APR-2026-0091",metadataJson: null,occurredAt: at(210),@@ -515,6 +524,7 @@ const financeTimelineRows: FinanceEvent[] = [amountCents: 12_000,currency: "USD",estimated: false,+ idempotencyKey: null,externalInvoiceId: "CR-2026-04-OPENAI-041",metadataJson: null,occurredAt: at(64),