From 8c029e3e76045312199fffef5d7596aea1264337 Mon Sep 17 00:00:00 2001 From: Rietie Date: Thu, 20 Aug 2026 10:38:26 +0200 Subject: [PATCH] chore(referrals): retire the KiloClaw referral program Fresh KiloClaw provisioning is closed, so no account can make a first paid KiloClaw subscription payment and no KiloClaw referral can ever be earned. Remove the KiloClaw Advocate referral program and keep Kilo Pass as the only live referral program. - Stop creating KiloClaw referral touches, participants, conversions, reward decisions, and rewards; KiloClaw Advocate config no longer resolves and the Advocate token endpoint rejects `product=kiloclaw`. - Split the shared referral machinery out of `kiloclaw-referrals.ts` into `referral-attribution.ts` and `referral-delivery.ts` for Kilo Pass. - Report KiloClaw affiliate SALEs directly for renewals of existing subscriptions instead of routing them through referral attribution, in both the web Stripe/credit paths and the billing lifecycle worker. - Drop the KiloClaw refer page, sidebar entry, and referral reward UI; rename the admin investigation surface to Impact referrals with KiloClaw retained read-only for support history. - Migration 0221 cancels unapplied KiloClaw rewards and terminates their queued Advocate redemptions. Applied free months and historical records stand. --- .specs/impact-referrals.md | 52 +- CONTRIBUTING.md | 1 - ENVIRONMENT.md | 5 +- apps/storybook/stories/Sidebar.stories.tsx | 7 - .../billing/ReferralRewardStatusCard.test.ts | 130 - .../billing/ReferralRewardStatusCard.tsx | 330 - .../billing/ReferralRewardsSummary.test.ts | 67 - .../billing/ReferralRewardsSummary.tsx | 110 - .../components/billing/SubscriptionCard.tsx | 9 - .../components/billing/billing-types.test.ts | 4 - .../claw/components/billing/billing-types.ts | 10 - apps/web/src/app/(app)/claw/refer/page.tsx | 48 - .../(app)/components/PersonalAppSidebar.tsx | 8 - .../subscriptions/kilo-pass/refer/page.tsx | 2 +- .../route.test.ts | 234 - .../kiloclaw-referral-eligibility/route.ts | 98 - .../src/app/admin/components/AppSidebar.tsx | 4 +- ...s => ImpactReferralsInvestigation.test.ts} | 6 +- ...n.tsx => ImpactReferralsInvestigation.tsx} | 16 +- .../src/app/admin/impact-referrals/page.tsx | 5 + .../src/app/admin/kiloclaw-referrals/page.tsx | 5 - .../dispatch-affiliate-events/route.test.ts | 24 +- .../cron/dispatch-affiliate-events/route.ts | 6 +- .../app/api/impact-advocate/token/route.ts | 5 +- .../billing-side-effects/route.test.ts | 115 +- .../kiloclaw/billing-side-effects/route.ts | 72 - .../ImpactAdvocateReferralCard.test.ts | 14 +- .../referrals/ImpactAdvocateReferralCard.tsx | 37 +- .../ImpactAdvocateReferralCard.utils.ts | 8 +- .../subscriptions/kiloclaw/KiloClawDetail.tsx | 3 - apps/web/src/lib/config.server.ts | 4 - apps/web/src/lib/impact/advocate.test.ts | 96 +- apps/web/src/lib/impact/advocate.ts | 59 +- .../lib/impact/kilo-pass-referrals.test.ts | 2 +- .../web/src/lib/impact/kilo-pass-referrals.ts | 44 +- .../src/lib/impact/kiloclaw-referrals.test.ts | 2236 - apps/web/src/lib/impact/kiloclaw-referrals.ts | 2553 - .../src/lib/impact/referral-attribution.ts | 118 + apps/web/src/lib/impact/referral-delivery.ts | 809 + .../web/src/lib/impact/referral-utils.test.ts | 23 +- apps/web/src/lib/impact/referral-utils.ts | 43 +- apps/web/src/lib/impact/referral.test.ts | 18 +- apps/web/src/lib/impact/referral.ts | 8 +- apps/web/src/lib/kiloclaw/credit-billing.ts | 19 - apps/web/src/lib/kiloclaw/stripe-handlers.ts | 39 +- apps/web/src/lib/stripe/index.ts | 28 +- apps/web/src/routers/admin-router.ts | 4 +- ...est.ts => impact-referrals-router.test.ts} | 11 +- ...s-router.ts => impact-referrals-router.ts} | 4 +- apps/web/src/routers/kiloclaw-router.test.ts | 455 - apps/web/src/routers/kiloclaw-router.ts | 280 - dev/seed/AGENTS.md | 4 +- dev/seed/kiloclaw/referrals-cap-boundary.ts | 278 - dev/seed/kiloclaw/referrals-happy-path.ts | 318 - .../kiloclaw/referrals-pending-referrer.ts | 282 - .../kiloclaw/referrals-support-override.ts | 173 - dev/seed/lib/kiloclaw-referrals.ts | 364 - .../0221_retire_kiloclaw_referral_rewards.sql | 30 + .../db/src/migrations/meta/0221_snapshot.json | 39128 ++++++++++++++++ packages/db/src/migrations/meta/_journal.json | 7 + .../kiloclaw-billing/src/lifecycle.test.ts | 199 +- services/kiloclaw-billing/src/lifecycle.ts | 61 +- 62 files changed, 40408 insertions(+), 8724 deletions(-) delete mode 100644 apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.test.ts delete mode 100644 apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.tsx delete mode 100644 apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.test.ts delete mode 100644 apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.tsx delete mode 100644 apps/web/src/app/(app)/claw/refer/page.tsx delete mode 100644 apps/web/src/app/admin/api/users/[id]/kiloclaw-referral-eligibility/route.test.ts delete mode 100644 apps/web/src/app/admin/api/users/[id]/kiloclaw-referral-eligibility/route.ts rename apps/web/src/app/admin/components/{KiloclawReferralsInvestigation.test.ts => ImpactReferralsInvestigation.test.ts} (96%) rename apps/web/src/app/admin/components/{KiloclawReferralsInvestigation.tsx => ImpactReferralsInvestigation.tsx} (96%) create mode 100644 apps/web/src/app/admin/impact-referrals/page.tsx delete mode 100644 apps/web/src/app/admin/kiloclaw-referrals/page.tsx delete mode 100644 apps/web/src/lib/impact/kiloclaw-referrals.test.ts delete mode 100644 apps/web/src/lib/impact/kiloclaw-referrals.ts create mode 100644 apps/web/src/lib/impact/referral-attribution.ts create mode 100644 apps/web/src/lib/impact/referral-delivery.ts rename apps/web/src/routers/admin/{kiloclaw-referrals-router.test.ts => impact-referrals-router.test.ts} (97%) rename apps/web/src/routers/admin/{kiloclaw-referrals-router.ts => impact-referrals-router.ts} (99%) delete mode 100644 dev/seed/kiloclaw/referrals-cap-boundary.ts delete mode 100644 dev/seed/kiloclaw/referrals-happy-path.ts delete mode 100644 dev/seed/kiloclaw/referrals-pending-referrer.ts delete mode 100644 dev/seed/kiloclaw/referrals-support-override.ts delete mode 100644 dev/seed/lib/kiloclaw-referrals.ts create mode 100644 packages/db/src/migrations/0221_retire_kiloclaw_referral_rewards.sql create mode 100644 packages/db/src/migrations/meta/0221_snapshot.json diff --git a/.specs/impact-referrals.md b/.specs/impact-referrals.md index 0b7833fd13..a30c81072b 100644 --- a/.specs/impact-referrals.md +++ b/.specs/impact-referrals.md @@ -22,6 +22,8 @@ Updated 2026-05-29 -- name the Impact-facing Kilo Pass reward unit `Kilo Pass Bo Updated 2026-06-05 -- final Commit term reward-extension behavior. Updated 2026-06-12 -- clarify subscription-independent Kilo Pass referral sharing and automatic pending reward application. +Updated 2026-08-19 -- retire the KiloClaw Advocate referral program. Kilo Pass is the only live referral program; the +KiloClaw rules below are retained as history for referral data that still exists. ## Conventions @@ -81,7 +83,7 @@ BCP 14 [RFC 2119] [RFC 8174] keywords apply only when they appear in all capital `.specs/stripe-early-fraud-warnings.md` after a new Stripe Early Fraud Warning; it is an adverse payment even when no later chargeback is created. -### KiloClaw Definitions +### KiloClaw Definitions (Retired) - **KiloClaw Advocate Program**: Impact Advocate referral program for KiloClaw. Existing ProgramId is `51699`. - **KiloClaw Advocate widget**: Existing Verified Access widget `p/51699/w/referrerWidget`. @@ -132,8 +134,10 @@ referral cookies, participant registration, and provider-facing referral reporti eligibility, affiliate/referral attribution conflict resolution, first-paid-conversion detection, reward grant idempotency, reward caps, reward expiry, adverse-payment handling, and local billing/credit fulfillment. -KiloClaw referrals reward both sides with one free KiloClaw month, fulfilled by delaying an eligible KiloClaw renewal by -one calendar month. KiloClaw remains scoped to personal KiloClaw subscriptions and preserves existing behavior. +KiloClaw referrals are retired. They rewarded both sides with one free KiloClaw month, fulfilled by delaying an +eligible KiloClaw renewal by one calendar month. Because fresh KiloClaw instance provisioning is closed, no account can +make a first paid KiloClaw subscription payment, so no KiloClaw referral can be earned. See +`### KiloClaw Referral Program Retirement`. Kilo Pass referrals reward both sides with a one-time 50% Kilo Pass bonus based on the referee's eligible monthly tier, fulfilled as a future monthly `referral_bonus` issuance item after the reward is earned. Pending Kilo Pass rewards stack @@ -153,12 +157,9 @@ application, and Kilo Pass redeems after local referral bonus allocation. 1. The system MUST support product-scoped Advocate program configuration for `kiloclaw` and `kilo_pass`. -2. KiloClaw MUST keep compatibility with the existing configuration constants: - - Impact Account: `7138521` - - Impact Performance CampaignId: `50754` - - Impact Advocate ProgramId: `51699` - - UTT UUID: `A7138521-9724-4b8f-95f4-1db2fbae81141` - - Advocate widget ID: `p/51699/w/referrerWidget` +2. The retired KiloClaw Advocate program used these constants. Advocate ProgramId `51699` and widget + `p/51699/w/referrerWidget` MUST NOT be reused by any live Advocate program. The shared Impact Account `7138521`, + Impact Performance CampaignId `50754`, and UTT UUID `A7138521-9724-4b8f-95f4-1db2fbae81141` remain in use. 3. Impact Advocate account SID, auth token, and tenant alias MAY be shared across Advocate programs. KiloClaw and Kilo Pass MUST each require explicit product-scoped Advocate program ID and widget ID configuration. Products MUST NOT @@ -379,7 +380,31 @@ application, and Kilo Pass redeems after local referral bonus allocation. 69. Fraudulent, test, admin-created, or manually adjusted subscriptions/payments MUST NOT qualify for referral rewards unless an authorized operator explicitly marks the conversion as eligible under a documented support process. -### KiloClaw Product Rules +### KiloClaw Referral Program Retirement + +69a. The KiloClaw Advocate referral program is retired. The system MUST NOT create new KiloClaw referral touches, + KiloClaw Advocate participants, KiloClaw referral conversions, KiloClaw reward decisions, or KiloClaw referral + rewards. + +69b. The system MUST NOT resolve Impact Advocate configuration for the KiloClaw program key, and MUST NOT issue KiloClaw + Advocate Verified Access tokens. + +69c. KiloClaw referral rewards that were pending or earned but never applied MUST be canceled. Already-applied KiloClaw + free months MUST NOT be reversed, and the renewal boundaries they moved MUST stand. + +69d. Historical KiloClaw referral records MUST be retained for accounting and support history, and MUST remain readable + through admin investigation surfaces. Retention does not make them eligible for any reward. + +69e. Queued Impact Advocate reward redemptions for KiloClaw rewards MUST terminate rather than retry indefinitely. + +69f. Retiring KiloClaw referrals MUST NOT change Impact Performance affiliate tracking for KiloClaw. Affiliate SALE + reporting for renewals of existing KiloClaw subscriptions MUST continue under + `.specs/impact-affiliate-tracking.md`, and MUST no longer be suppressed by referral attribution. + +69g. The KiloClaw rules in this spec are retained as history for the records described in 69d. They MUST NOT be + implemented for new conversions. + +### KiloClaw Product Rules (Retired) 70. KiloClaw referrals apply only to personal KiloClaw subscriptions. Organization-scoped KiloClaw instances, team plans, admin interventions, and non-KiloClaw purchases are out of scope. @@ -788,6 +813,13 @@ application, and Kilo Pass redeems after local referral bonus allocation. ## Changelog +### 2026-08-19 -- Retire the KiloClaw referral program + +Removed the KiloClaw Advocate referral program. New KiloClaw referral touches, participants, conversions, decisions, and +rewards are no longer created; KiloClaw Advocate configuration no longer resolves; unapplied KiloClaw rewards are +canceled while applied free months stand; historical records are retained for support and accounting; and KiloClaw +affiliate SALE reporting is no longer suppressed by referral attribution. Kilo Pass is the only live referral program. + ### 2026-06-05 -- Extend guarded final Commit terms Allowed KiloClaw free-month rewards to extend final Commit terms guarded for retirement while preserving ordinary user-cancellation ineligibility, non-renewal, authorized final boundary, and scheduled Standard timing. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 239680c020..30a41e79d5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -131,7 +131,6 @@ The repo includes a seed runner for creating local fixtures via `pnpm dev:seed`. - `pnpm dev:seed kiloclaw:fake-instance [options]` — creates a fake personal KiloClaw instance + subscription in the database only (no real container or Worker). Before creating, it retires any prior fake personal instances for that user. Supports `--plan=trial|standard|commit` and `--days=`. For paid plans, it also grants enough credits to cover the plan cost and then deducts the subscription cost. - `pnpm dev:seed kiloclaw:fake-org-instance [options]` — same as above, but creates an instance belonging to an organization rather than a personal account. -- `pnpm dev:seed kiloclaw:referrals-` — seeds KiloClaw referral fixtures. Topics include `referrals-happy-path`, `referrals-pending-referrer`, `referrals-cap-boundary`, and `referrals-support-override`. - `pnpm dev:seed kiloclaw-billing:inactive-trials` — seeds inactive-trial billing fixtures. One user is provisioned through the real KiloClaw worker endpoint (`/api/platform/provision`), while others are DB-only rows representing users in recently-started, support-marked, or eligible inactive-trial states. ## Common Development Commands diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md index 44282d2d87..147e7ec156 100644 --- a/ENVIRONMENT.md +++ b/ENVIRONMENT.md @@ -302,9 +302,10 @@ When `VERCEL_TARGET_ENV` is absent in local development or a script process, tra - `IMPACT_AUTH_TOKEN` - Impact.com API auth token for affiliate/click events. `[SECRET]` - `IMPACT_ADVOCATE_ACCOUNT_SID` - Impact.com account SID for Advocate (referral) API. `[SECRET]` - `IMPACT_ADVOCATE_AUTH_TOKEN` - Impact.com Advocate API auth token. `[SECRET]` -- `IMPACT_ADVOCATE_PROGRAM_ID` - Impact.com Advocate program ID. [SERVER] +- `IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID` - Impact.com Advocate program ID for the Kilo Pass referral program. [SERVER] +- `IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID` - Impact.com Advocate widget ID for the Kilo Pass referral program. [SERVER] - `IMPACT_ADVOCATE_TENANT_ALIAS` - Impact.com Advocate tenant alias. [SERVER] -- `IMPACT_ADVOCATE_WIDGET_ID` - Impact.com Advocate widget ID. [SERVER] +- `IMPACT_ADVOCATE_API_BASE_URL` - Impact.com Advocate API base URL. Defaults to `https://app.referralsaasquatch.com`. [SERVER] - `IMPACT_CAMPAIGN_ID` - Impact.com campaign ID for event tracking. [SERVER] ### Cloudflare Analytics diff --git a/apps/storybook/stories/Sidebar.stories.tsx b/apps/storybook/stories/Sidebar.stories.tsx index 47c7502045..4e5e14fc59 100644 --- a/apps/storybook/stories/Sidebar.stories.tsx +++ b/apps/storybook/stories/Sidebar.stories.tsx @@ -141,13 +141,6 @@ const kiloClawItems: SidebarStoryItem[] = [ icon: Sparkles, url: '/claw/changelog', }, - { - title: 'Refer & Earn', - subtitle: 'Get 1 Month Free', - badge: 'NEW', - icon: Gift, - url: '/claw/refer', - }, ]; const cloudItems: SidebarStoryItem[] = [ diff --git a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.test.ts b/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.test.ts deleted file mode 100644 index 20d2229baa..0000000000 --- a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import React from 'react'; -import { renderToStaticMarkup } from 'react-dom/server'; -import { describe, expect, it } from '@jest/globals'; - -import { ReferralRewardStatusCard } from './ReferralRewardStatusCard'; - -const emptySummary = { - totals: { - totalRewards: 0, - pendingRewards: 0, - totalAppliedMonths: 0, - }, - pendingRewardAction: { - showStartReactivateCta: false, - pendingRewardCount: 0, - }, - referredPeople: [], - rewards: [], -}; - -describe('ReferralRewardStatusCard', () => { - it('renders the empty state with a referral-share CTA and no warning state', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardStatusCard, { summary: emptySummary }) - ); - - expect(html).toContain('No referral rewards yet.'); - expect(html).toContain('href="#referral-share"'); - expect(html).not.toContain('data-testid="summary-indicator-warning"'); - expect(html).not.toContain('credits'); - expect(html).not.toContain('awards'); - }); - - it('renders the Impact share widget slot when provided', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardStatusCard, { - summary: emptySummary, - shareWidget: React.createElement('div', { 'data-testid': 'share-widget' }, 'widget body'), - }) - ); - - expect(html).toContain('id="referral-share"'); - expect(html).toContain('data-testid="share-widget"'); - expect(html).toContain('widget body'); - }); - - it('surfaces on-hold rewards, applied renewal dates, and customer-safe referee status', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardStatusCard, { - summary: { - totals: { - totalRewards: 2, - pendingRewards: 1, - totalAppliedMonths: 1, - }, - pendingRewardAction: { - showStartReactivateCta: true, - pendingRewardCount: 1, - }, - referredPeople: [ - { - maskedEmail: 'q***@example.com', - state: 'reward_granted', - rewardGranted: true, - }, - { - maskedEmail: 's***@example.com', - state: 'waiting_for_paid_conversion', - rewardGranted: false, - }, - ], - rewards: [ - { - role: 'referrer', - status: 'applied', - monthsGranted: 1, - earnedAt: '2026-04-10T00:00:00.000Z', - appliedAt: '2026-04-10T00:05:00.000Z', - expiresAt: null, - reviewReason: null, - application: { - appliedAt: '2026-04-10T00:05:00.000Z', - subscriptionId: '11111111-1111-4111-8111-111111111111', - previousRenewalBoundary: '2026-05-01T12:00:00.000Z', - newRenewalBoundary: '2026-06-01T12:00:00.000Z', - }, - }, - { - role: 'referee', - status: 'pending', - monthsGranted: 1, - earnedAt: '2026-04-11T00:00:00.000Z', - appliedAt: null, - expiresAt: null, - reviewReason: null, - application: null, - }, - ], - }, - }) - ); - - expect(html).toContain('1 reward on hold'); - expect(html).toContain('Start or reactivate KiloClaw'); - expect(html).toContain('data-testid="summary-indicator-warning"'); - expect(html).toContain('Applied'); - expect(html).toContain('May 1, 2026'); - expect(html).toContain('June 1, 2026'); - expect(html).toContain('Waiting for an eligible KiloClaw subscription'); - expect(html).toContain('q***@example.com'); - expect(html).toContain('Reward granted'); - expect(html).toContain('s***@example.com'); - expect(html).toContain('Signed up, waiting for paid KiloClaw conversion'); - }); - - it('pluralizes the reactivate banner copy when more than one reward is pending', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardStatusCard, { - summary: { - ...emptySummary, - totals: { totalRewards: 2, pendingRewards: 2, totalAppliedMonths: 0 }, - pendingRewardAction: { showStartReactivateCta: true, pendingRewardCount: 2 }, - }, - }) - ); - - expect(html).toContain('2 rewards on hold'); - expect(html).toContain('to apply them'); - }); -}); diff --git a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.tsx b/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.tsx deleted file mode 100644 index a7bb2c9771..0000000000 --- a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardStatusCard.tsx +++ /dev/null @@ -1,330 +0,0 @@ -import React from 'react'; -import Link from 'next/link'; -import { CalendarDays, Gift, Info, Sparkles } from 'lucide-react'; - -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; -import { formatBillingDate } from './billing-types'; - -const SHARE_WIDGET_ANCHOR_ID = 'referral-share'; - -type ReferralRewardStatus = - | 'pending' - | 'earned' - | 'applied' - | 'expired' - | 'canceled' - | 'reversed' - | 'review_required'; - -type ReferralRewardSummary = { - totals: { - totalRewards: number; - pendingRewards: number; - totalAppliedMonths: number; - }; - pendingRewardAction: { - showStartReactivateCta: boolean; - pendingRewardCount: number; - }; - referredPeople: Array<{ - maskedEmail: string | null; - state: 'reward_granted' | 'waiting_for_paid_conversion'; - rewardGranted: boolean; - }>; - rewards: Array<{ - role: 'referrer' | 'referee'; - status: ReferralRewardStatus; - monthsGranted: number; - earnedAt: string; - appliedAt: string | null; - expiresAt: string | null; - reviewReason: string | null; - application: { - appliedAt: string; - subscriptionId: string | null; - previousRenewalBoundary: string; - newRenewalBoundary: string; - } | null; - }>; -}; - -type ReferralRewardStatusCardProps = { - summary: ReferralRewardSummary; - shareWidget?: React.ReactNode; -}; - -type StatusPresentation = { - label: string; - className: string; -}; - -function rewardStatusPresentation(status: ReferralRewardStatus): StatusPresentation { - switch (status) { - case 'applied': - return { - label: 'Applied', - className: 'bg-emerald-500/20 text-emerald-400 ring-emerald-500/20', - }; - case 'earned': - return { - label: 'Waiting for renewal extension', - className: 'bg-blue-500/20 text-blue-400 ring-blue-500/20', - }; - case 'pending': - return { - label: 'Waiting for an eligible KiloClaw subscription', - className: 'bg-yellow-500/20 text-yellow-400 ring-yellow-500/20', - }; - case 'expired': - return { - label: 'Expired', - className: 'bg-zinc-500/20 text-zinc-400 ring-zinc-500/20', - }; - case 'canceled': - return { - label: 'Canceled', - className: 'bg-zinc-500/20 text-zinc-400 ring-zinc-500/20', - }; - case 'reversed': - return { - label: 'Reversed', - className: 'bg-red-500/20 text-red-400 ring-red-500/20', - }; - case 'review_required': - return { - label: 'Needs review', - className: 'bg-orange-500/20 text-orange-400 ring-orange-500/20', - }; - } -} - -function roleLabel(role: 'referrer' | 'referee'): string { - return role === 'referrer' ? 'Referral you shared' : 'Referral you used'; -} - -function monthLabel(months: number): string { - return `${months} ${months === 1 ? 'free month' : 'free months'}`; -} - -export function ReferralRewardStatusCard({ summary, shareWidget }: ReferralRewardStatusCardProps) { - const showReactivateCta = summary.pendingRewardAction.showStartReactivateCta; - - return ( - - - - - - Share KiloClaw with someone else and when they sign up for a paid subscription, you both - get 1 free month of KiloClaw hosting. - - - - {shareWidget ?
{shareWidget}
: null} - - {showReactivateCta ? ( -
-
- You have {summary.pendingRewardAction.pendingRewardCount}{' '} - {summary.pendingRewardAction.pendingRewardCount === 1 ? 'reward' : 'rewards'} on hold. - Start or reactivate KiloClaw to apply{' '} - {summary.pendingRewardAction.pendingRewardCount === 1 ? 'it' : 'them'}. -
- -
- ) : null} - -
- - 0 ? 'warning' : undefined} - /> - -
- -
-

- Earned rewards -

- - {summary.rewards.length === 0 ? ( -
- No referral rewards yet.{' '} - - Share your referral link - {' '} - to earn a free month. -
- ) : ( -
- {summary.rewards.map((reward, index) => ( - - ))} -
- )} -
- -
-

- Your referees -

- - {summary.referredPeople.length === 0 ? ( -
- No referred people yet. -
- ) : ( -
- {summary.referredPeople.map((person, index) => ( -
-
-
- {person.maskedEmail ?? 'Unknown referee'} -
-
Masked referee identity
-
- - {person.state === 'reward_granted' - ? 'Reward granted' - : 'Signed up, waiting for paid KiloClaw conversion'} - -
- ))} -
- )} -
-
-
- ); -} - -type IndicatorTone = 'warning'; - -function SummaryTile({ - label, - value, - info, - indicator, -}: { - label: string; - value: string; - info?: string; - indicator?: IndicatorTone; -}) { - return ( -
-
- {indicator === 'warning' ? ( -
-
- {value} -
-
- ); -} - -function RewardRow({ reward }: { reward: ReferralRewardSummary['rewards'][number] }) { - const status = rewardStatusPresentation(reward.status); - return ( -
-
-
{roleLabel(reward.role)}
-
-
-
-
- - {status.label} - - - {monthLabel(reward.monthsGranted)} -
-
- {reward.application ? ( - <> -
-
-
- Renewal moved{' '} - - {formatBillingDate(reward.application.previousRenewalBoundary)} - {' '} - to{' '} - - {formatBillingDate(reward.application.newRenewalBoundary)} - -
- - ) : reward.expiresAt ? ( -
- Expires{' '} - {formatBillingDate(reward.expiresAt)} -
- ) : ( -
Reward application details appear after the free month is applied.
- )} -
-
- ); -} diff --git a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.test.ts b/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.test.ts deleted file mode 100644 index 21938983d8..0000000000 --- a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react'; -import { renderToStaticMarkup } from 'react-dom/server'; -import { describe, expect, it } from '@jest/globals'; - -import { ReferralRewardsSummary } from './ReferralRewardsSummary'; -import type { ClawBillingStatus } from './billing-types'; - -const emptyRewards: NonNullable['referralRewards'] = { - totalAppliedMonths: 0, - applications: [], -}; - -describe('ReferralRewardsSummary', () => { - it('renders the empty state with a primary refer-a-friend CTA', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardsSummary, { rewards: emptyRewards }) - ); - - expect(html).toContain('No rewards yet. Refer a friend to earn a free month.'); - expect(html).toContain('href="/claw/refer"'); - }); - - it('renders applied referrer and referee rewards with renewal boundaries', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardsSummary, { - rewards: { - totalAppliedMonths: 2, - applications: [ - { - role: 'referrer', - appliedAt: '2026-04-10T00:05:00.000Z', - monthsGranted: 1, - previousRenewalBoundary: '2026-05-01T12:00:00.000Z', - newRenewalBoundary: '2026-06-01T12:00:00.000Z', - }, - { - role: 'referee', - appliedAt: '2026-04-11T00:05:00.000Z', - monthsGranted: 1, - previousRenewalBoundary: '2026-06-01T12:00:00.000Z', - newRenewalBoundary: '2026-07-01T12:00:00.000Z', - }, - ], - }, - }) - ); - - expect(html).toContain('2 free months applied'); - expect(html).toContain('Reward for referring'); - expect(html).toContain('Welcome reward'); - expect(html).toContain('May 1, 2026'); - expect(html).toContain('July 1, 2026'); - }); - - it('drops its own border when rendered as a section variant', () => { - const html = renderToStaticMarkup( - React.createElement(ReferralRewardsSummary, { - rewards: emptyRewards, - variant: 'section', - }) - ); - - // The card variant has bg-background/40; the section variant must not. - expect(html).not.toContain('bg-background/40'); - expect(html).toContain('border-t'); - }); -}); diff --git a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.tsx b/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.tsx deleted file mode 100644 index d17fa21e78..0000000000 --- a/apps/web/src/app/(app)/claw/components/billing/ReferralRewardsSummary.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import React from 'react'; -import Link from 'next/link'; -import { ArrowRight, CalendarDays, Gift } from 'lucide-react'; - -import { Badge } from '@/components/ui/badge'; -import { Button } from '@/components/ui/button'; -import { cn } from '@/lib/utils'; -import type { ClawBillingStatus } from './billing-types'; -import { formatBillingDate } from './billing-types'; - -type ReferralRewards = NonNullable['referralRewards']; - -type ReferralRewardsSummaryProps = { - rewards: ReferralRewards; - /** - * `card` (default) renders inside its own bordered container. Use this when - * the summary stands alone as a sibling card on a detail page. - * `section` renders as a flat block separated by a top divider — use it when - * embedding inside another `` to avoid the nested-card anti-pattern. - */ - variant?: 'card' | 'section'; -}; - -function roleLabel(role: ReferralRewards['applications'][number]['role']): string { - // Address the user, not the system. "Referee" is internal jargon. - return role === 'referrer' ? 'Reward for referring' : 'Welcome reward'; -} - -function monthsLabel(months: number): string { - return `${months} ${months === 1 ? 'free month' : 'free months'}`; -} - -export function ReferralRewardsSummary({ rewards, variant = 'card' }: ReferralRewardsSummaryProps) { - const isCard = variant === 'card'; - - return ( -
-
-
-
-
-
-

- Referral rewards -

-

- Free months push your renewal date out. -

-
-
- {rewards.totalAppliedMonths > 0 ? ( - - {monthsLabel(rewards.totalAppliedMonths)} applied - - ) : null} -
- - {rewards.applications.length === 0 ? ( -
-

No rewards yet. Refer a friend to earn a free month.

- -
- ) : ( -
    - {rewards.applications.map(application => ( -
  • -
    -
    {roleLabel(application.role)}
    -
    - {monthsLabel(application.monthsGranted)} -
    -
    -
    - - - - Renewal: - - {formatBillingDate(application.previousRenewalBoundary)} - - -
    -
  • - ))} -
- )} -
- ); -} diff --git a/apps/web/src/app/(app)/claw/components/billing/SubscriptionCard.tsx b/apps/web/src/app/(app)/claw/components/billing/SubscriptionCard.tsx index 847bca4fba..a9150f8986 100644 --- a/apps/web/src/app/(app)/claw/components/billing/SubscriptionCard.tsx +++ b/apps/web/src/app/(app)/claw/components/billing/SubscriptionCard.tsx @@ -37,7 +37,6 @@ import { planLabel, type ClawBillingStatus, } from './billing-types'; -import { ReferralRewardsSummary } from './ReferralRewardsSummary'; type SubscriptionCardProps = { billing: ClawBillingStatus; @@ -345,8 +344,6 @@ function ActiveSubscriptionCard({ ) : null} - -
{retirement.needsSupportReview ? null : retirement.isFinalCommitTerm ? ( retirement.standardContinuationScheduled ? ( @@ -473,8 +470,6 @@ function ConvertingSubscriptionCard({ - -
)} - - Billing history diff --git a/apps/web/src/lib/config.server.ts b/apps/web/src/lib/config.server.ts index 5522488c55..f83042d237 100644 --- a/apps/web/src/lib/config.server.ts +++ b/apps/web/src/lib/config.server.ts @@ -71,10 +71,6 @@ export const IMPACT_CAMPAIGN_ID = getEnvVariable('IMPACT_CAMPAIGN_ID') || ''; export const IMPACT_ADVOCATE_TENANT_ALIAS = getEnvVariable('IMPACT_ADVOCATE_TENANT_ALIAS') || ''; export const IMPACT_ADVOCATE_ACCOUNT_SID = getEnvVariable('IMPACT_ADVOCATE_ACCOUNT_SID') || ''; export const IMPACT_ADVOCATE_AUTH_TOKEN = getEnvVariable('IMPACT_ADVOCATE_AUTH_TOKEN') || ''; -export const IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = - getEnvVariable('IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID') || ''; -export const IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = - getEnvVariable('IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID') || ''; export const IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = getEnvVariable('IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID') || ''; export const IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = diff --git a/apps/web/src/lib/impact/advocate.test.ts b/apps/web/src/lib/impact/advocate.test.ts index b690f7da96..b0de483b2f 100644 --- a/apps/web/src/lib/impact/advocate.test.ts +++ b/apps/web/src/lib/impact/advocate.test.ts @@ -9,8 +9,6 @@ describe('impact advocate', () => { IMPACT_ADVOCATE_PROGRAM_ID: process.env.IMPACT_ADVOCATE_PROGRAM_ID, IMPACT_ADVOCATE_TENANT_ALIAS: process.env.IMPACT_ADVOCATE_TENANT_ALIAS, IMPACT_ADVOCATE_WIDGET_ID: process.env.IMPACT_ADVOCATE_WIDGET_ID, - IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID: process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID, - IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID: process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID, IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID: process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID, IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID: process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID, IMPACT_ACCOUNT_SID: process.env.IMPACT_ACCOUNT_SID, @@ -24,9 +22,6 @@ describe('impact advocate', () => { process.env.IMPACT_ADVOCATE_PROGRAM_ID = originalEnv.IMPACT_ADVOCATE_PROGRAM_ID; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = originalEnv.IMPACT_ADVOCATE_TENANT_ALIAS; process.env.IMPACT_ADVOCATE_WIDGET_ID = originalEnv.IMPACT_ADVOCATE_WIDGET_ID; - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = - originalEnv.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = originalEnv.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID; process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = originalEnv.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID; process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = @@ -36,7 +31,7 @@ describe('impact advocate', () => { }); it('builds register participant payloads with exact cookie attribution', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'kilo'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'account-sid'; @@ -62,44 +57,18 @@ describe('impact advocate', () => { }); it('normalizes bare widget IDs to the full Impact embed widget path', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-account-sid'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = '52766'; const { getImpactAdvocateWidgetId } = await import('@/lib/impact/advocate'); - expect(getImpactAdvocateWidgetId()).toBe('p/51699/w/referrerWidget'); + expect(getImpactAdvocateWidgetId()).toBe('p/52766/w/referrerWidget'); }); - it('uses KiloClaw-scoped Advocate config for widget and token issuance', async () => { - process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'kiloclaw-account'; - process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'kiloclaw-secret'; - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699-scoped'; - process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'kiloclaw-tenant'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = '51699-scoped'; - - const { - getImpactAdvocateProgramId, - getImpactAdvocateWidgetId, - issueImpactAdvocateVerifiedAccessToken, - } = await import('@/lib/impact/advocate'); - - expect(getImpactAdvocateProgramId()).toBe('51699-scoped'); - expect(getImpactAdvocateWidgetId()).toBe('p/51699-scoped/w/referrerWidget'); - - const token = issueImpactAdvocateVerifiedAccessToken( - { id: 'user_123', google_user_email: 'referrer@example.com' }, - new Date('2026-04-23T12:00:00.000Z') - ); - const decoded = jwt.decode(token ?? '', { complete: true }); - expect(decoded && typeof decoded === 'object' ? decoded.header.kid : null).toBe( - 'kiloclaw-account' - ); - }); - - it('does not configure KiloClaw from legacy unscoped program/widget config', async () => { + it('does not configure any Advocate program from legacy unscoped program/widget config', async () => { process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'legacy-account'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'legacy-secret'; process.env.IMPACT_ADVOCATE_PROGRAM_ID = '51699'; @@ -124,12 +93,12 @@ describe('impact advocate', () => { ).toBeNull(); }); - it('does not use KiloClaw config for Kilo Pass', async () => { - process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'fallback-account'; - process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'fallback-secret'; - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; - process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'fallback-tenant'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; + it('never configures the retired KiloClaw Advocate program', async () => { + process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'shared-account'; + process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'shared-secret'; + process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'shared-tenant'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; const { getImpactAdvocateWidgetId, @@ -137,16 +106,17 @@ describe('impact advocate', () => { issueImpactAdvocateVerifiedAccessToken, } = await import('@/lib/impact/advocate'); - const scope = { product: 'kilo_pass' as const }; - expect(isImpactAdvocateConfigured(scope)).toBe(false); - expect(getImpactAdvocateWidgetId(scope)).toBeNull(); - expect( - issueImpactAdvocateVerifiedAccessToken( - { id: 'user_123', google_user_email: 'referrer@example.com' }, - new Date('2026-04-23T12:00:00.000Z'), - scope - ) - ).toBeNull(); + for (const scope of [{ product: 'kiloclaw' as const }, { programKey: 'kiloclaw' as const }]) { + expect(isImpactAdvocateConfigured(scope)).toBe(false); + expect(getImpactAdvocateWidgetId(scope)).toBeNull(); + expect( + issueImpactAdvocateVerifiedAccessToken( + { id: 'user_123', google_user_email: 'referrer@example.com' }, + new Date('2026-04-23T12:00:00.000Z'), + scope + ) + ).toBeNull(); + } }); it('uses Kilo Pass-scoped program and widget config for token issuance', async () => { @@ -177,12 +147,10 @@ describe('impact advocate', () => { ); }); - it('rejects Kilo Pass Advocate config that reuses KiloClaw program or widget IDs', async () => { + it('rejects Kilo Pass Advocate config that reuses the retired KiloClaw program or widget IDs', async () => { process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'shared-account'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'shared-secret'; - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'shared-tenant'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; const scope = { product: 'kilo_pass' as const }; @@ -204,11 +172,11 @@ describe('impact advocate', () => { }); it('logs debug data without tokens, credentials, authorization headers, cookie values, or email identities', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-account-sid'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; process.env.IMPACT_ADVOCATE_DEBUG_LOGGING = 'true'; const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined); @@ -240,11 +208,11 @@ describe('impact advocate', () => { }); it('issues verified access JWTs with the account sid in the kid header', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-account-sid'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; const { getImpactAdvocateWidgetId, issueImpactAdvocateVerifiedAccessToken } = await import('@/lib/impact/advocate'); @@ -255,7 +223,7 @@ describe('impact advocate', () => { ); expect(token).toBeTruthy(); - expect(getImpactAdvocateWidgetId()).toBe('p/51699/w/referrerWidget'); + expect(getImpactAdvocateWidgetId()).toBe('p/52766/w/referrerWidget'); const decoded = jwt.decode(token ?? '', { complete: true }); if (!decoded || typeof decoded !== 'object') { @@ -275,11 +243,11 @@ describe('impact advocate', () => { }); it('looks up account rewards with account and user filters', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-account-sid'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; process.env.IMPACT_ADVOCATE_DEBUG_LOGGING = 'true'; const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined); const fetchMock = jest.fn().mockResolvedValue( @@ -320,11 +288,11 @@ describe('impact advocate', () => { }); it('redeems a credit reward with amount and unit', async () => { - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'secret'; process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-account-sid'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; const fetchMock = jest .fn() .mockResolvedValue(new Response('{"ok":true}', { status: 200 })); diff --git a/apps/web/src/lib/impact/advocate.ts b/apps/web/src/lib/impact/advocate.ts index 055a9e57b1..35eed99034 100644 --- a/apps/web/src/lib/impact/advocate.ts +++ b/apps/web/src/lib/impact/advocate.ts @@ -7,8 +7,6 @@ import { IMPACT_ADVOCATE_ACCOUNT_SID, IMPACT_ADVOCATE_API_BASE_URL, IMPACT_ADVOCATE_AUTH_TOKEN, - IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID, - IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID, IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID, IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID, IMPACT_ADVOCATE_TENANT_ALIAS, @@ -57,7 +55,7 @@ function resolveImpactAdvocateProgramKey( ): ImpactAdvocateProgramKey { if (scope?.programKey) return scope.programKey; if (scope?.product) return getImpactAdvocateProgramKeyForProduct(scope.product); - return ImpactAdvocateProgramKey.KiloClaw; + return ImpactAdvocateProgramKey.KiloPass; } export type ImpactAdvocateIdentityPayload = { @@ -221,49 +219,35 @@ function getImpactAdvocateWidgetPath(widgetId: string, programId: string): strin return `p/${trimmedWidgetId}/w/${IMPACT_ADVOCATE_WIDGET_NAME}`; } -function getKiloClawAdvocateIdentifiersForComparison(): { - programIds: Set; - widgetIds: Set; -} { - const programId = configuredValue(IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID); - const rawWidgetId = configuredValue(IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID); - const programIds = new Set(); - const widgetIds = new Set(); - - if (programId) { - programIds.add(programId); - } - if (programId && rawWidgetId) { - widgetIds.add(getImpactAdvocateWidgetPath(rawWidgetId, programId)); - } - - return { programIds, widgetIds }; -} +/** + * The KiloClaw Advocate program is retired. Its identifiers stay recorded here so + * a misconfigured Kilo Pass program can never be pointed at the dead program and + * silently register participants or redeem rewards against it. + */ +const RETIRED_KILOCLAW_ADVOCATE_PROGRAM_ID = '51699'; -function kiloPassAdvocateConfigReusesKiloClawIdentifiers(params: { +function reusesRetiredKiloClawIdentifiers(params: { programId: string; widgetId: string; }): boolean { - const kiloClawIdentifiers = getKiloClawAdvocateIdentifiersForComparison(); return ( - kiloClawIdentifiers.programIds.has(params.programId) || - kiloClawIdentifiers.widgetIds.has(params.widgetId) + params.programId === RETIRED_KILOCLAW_ADVOCATE_PROGRAM_ID || + params.widgetId === getImpactAdvocateWidgetPath('', RETIRED_KILOCLAW_ADVOCATE_PROGRAM_ID) ); } function getImpactAdvocateConfig(scope?: ImpactAdvocateConfigScope): ImpactAdvocateConfig | null { const programKey = resolveImpactAdvocateProgramKey(scope); - const scopedValues = - programKey === ImpactAdvocateProgramKey.KiloPass - ? { - programId: configuredValue(IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID), - widgetId: configuredValue(IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID), - } - : { - programId: configuredValue(IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID), - widgetId: configuredValue(IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID), - }; + // Kilo Pass is the only live Advocate program; KiloClaw referrals are retired. + if (programKey !== ImpactAdvocateProgramKey.KiloPass) { + return null; + } + + const scopedValues = { + programId: configuredValue(IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID), + widgetId: configuredValue(IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID), + }; const accountSid = configuredValue(IMPACT_ADVOCATE_ACCOUNT_SID); const authToken = configuredValue(IMPACT_ADVOCATE_AUTH_TOKEN); @@ -281,10 +265,7 @@ function getImpactAdvocateConfig(scope?: ImpactAdvocateConfigScope): ImpactAdvoc return null; } - if ( - programKey === ImpactAdvocateProgramKey.KiloPass && - kiloPassAdvocateConfigReusesKiloClawIdentifiers({ programId, widgetId }) - ) { + if (reusesRetiredKiloClawIdentifiers({ programId, widgetId })) { return null; } diff --git a/apps/web/src/lib/impact/kilo-pass-referrals.test.ts b/apps/web/src/lib/impact/kilo-pass-referrals.test.ts index f83c794a3f..89191882b5 100644 --- a/apps/web/src/lib/impact/kilo-pass-referrals.test.ts +++ b/apps/web/src/lib/impact/kilo-pass-referrals.test.ts @@ -57,7 +57,7 @@ import { markPersonalKiloPassReferralPaymentAdverse, processPersonalKiloPassStripePaidConversion, } from '@/lib/impact/kilo-pass-referrals'; -import { dispatchQueuedImpactAdvocateRewardRedemptions } from '@/lib/impact/kiloclaw-referrals'; +import { dispatchQueuedImpactAdvocateRewardRedemptions } from '@/lib/impact/referral-delivery'; import { insertTestUser } from '@/tests/helpers/user.helper'; import { deleted_user_email_tombstones, diff --git a/apps/web/src/lib/impact/kilo-pass-referrals.ts b/apps/web/src/lib/impact/kilo-pass-referrals.ts index d9b0118e13..d2b8753fc8 100644 --- a/apps/web/src/lib/impact/kilo-pass-referrals.ts +++ b/apps/web/src/lib/impact/kilo-pass-referrals.ts @@ -4,19 +4,15 @@ import { addMonths } from 'date-fns'; import { and, asc, count, eq, inArray, isNull, lte, ne, sql } from 'drizzle-orm'; import { db, type DrizzleTransaction } from '@/lib/drizzle'; -import { - IMPACT_ACTION_TRACKER_IDS, - buildSalePayload, - hashEmailForImpact, - isImpactConfigured, -} from '@/lib/impact'; -import { isImpactAdvocateConfigured } from '@/lib/impact/advocate'; +import { IMPACT_ACTION_TRACKER_IDS, buildSalePayload, hashEmailForImpact } from '@/lib/impact'; +import { resolveWinningAttributionTouch } from '@/lib/impact/referral-attribution'; import { dispatchImpactConversionReportById, + getRewardBearingReferralConfigurationState, + logRewardBearingReferralConfigurationFailure, queueImpactAdvocateRewardRedemption, - resolveWinningAttributionTouch, type AdverseReferralPaymentReason, -} from '@/lib/impact/kiloclaw-referrals'; +} from '@/lib/impact/referral-delivery'; import { hashNormalizedEmailForDeletionTombstone } from '@/lib/impact/referral'; import { logImpactReferralDebug } from '@/lib/impact/debug'; import { KILO_PASS_TIER_CONFIG } from '@/lib/kilo-pass/constants'; @@ -82,32 +78,6 @@ function getAdversePaymentReason(reason: AdverseReferralPaymentReason): string { return `referral_payment_${reason}`; } -function getKiloPassReferralConfigurationState() { - const impactPerformanceConfigured = isImpactConfigured(); - const impactAdvocateConfigured = isImpactAdvocateConfigured({ - product: ImpactReferralProduct.KiloPass, - }); - - return { - impactPerformanceConfigured, - impactAdvocateConfigured, - isConfigured: impactPerformanceConfigured && impactAdvocateConfigured, - }; -} - -function logKiloPassReferralConfigurationFailure(params: { - sourcePaymentId?: string; - conversionId?: string; - userId?: string; -}): void { - const configurationState = getKiloPassReferralConfigurationState(); - console.error('[kilo-pass-referrals] reward-bearing referral configuration is incomplete', { - ...params, - impactPerformanceConfigured: configurationState.impactPerformanceConfigured, - impactAdvocateConfigured: configurationState.impactAdvocateConfigured, - }); -} - function buildImpactReferralId(touch: ImpactAttributionTouch): string | null { return touch.rs_code?.trim() || touch.opaque_tracking_value?.trim() || null; } @@ -717,9 +687,9 @@ export async function processPersonalKiloPassStripePaidConversion(params: { throw new Error('Kilo Pass referral referrer unexpectedly missing after eligibility checks'); } - if (!getKiloPassReferralConfigurationState().isConfigured) { + if (!getRewardBearingReferralConfigurationState().isConfigured) { const missingConfigReason = referralDisqualificationReason('missing_configuration'); - logKiloPassReferralConfigurationFailure({ + logRewardBearingReferralConfigurationFailure({ sourcePaymentId: params.sourcePaymentId, userId: params.userId, }); diff --git a/apps/web/src/lib/impact/kiloclaw-referrals.test.ts b/apps/web/src/lib/impact/kiloclaw-referrals.test.ts deleted file mode 100644 index dabf3d4412..0000000000 --- a/apps/web/src/lib/impact/kiloclaw-referrals.test.ts +++ /dev/null @@ -1,2236 +0,0 @@ -import { randomUUID } from 'crypto'; -import { eq, sql } from 'drizzle-orm'; - -jest.mock('@/lib/impact', () => { - const actual = jest.requireActual('@/lib/impact'); - return { - ...actual, - isImpactConfigured: jest.fn(() => true), - sendImpactConversionPayload: jest.fn(async () => ({ ok: true, delivery: 'accepted' })), - reverseImpactAction: jest.fn(async () => ({ ok: true, delivery: 'accepted' })), - }; -}); - -jest.mock('@/lib/impact/advocate', () => { - const actual = jest.requireActual('@/lib/impact/advocate'); - return { - ...actual, - isImpactAdvocateConfigured: jest.fn(() => true), - sendImpactAdvocateRewardLookupPayload: jest.fn(async () => ({ - ok: true, - statusCode: 200, - responseBody: JSON.stringify({ rewards: [{ id: 'impact-reward-123', type: 'CREDIT' }] }), - rewards: [{ id: 'impact-reward-123', type: 'CREDIT' }], - })), - sendImpactAdvocateRewardRedemptionPayload: jest.fn(async () => ({ - ok: true, - statusCode: 200, - responseBody: '{}', - })), - }; -}); - -jest.mock('@/lib/kiloclaw/stripe-price-ids.server', () => ({ - getClawPlanForStripePriceId: jest.fn((priceId: string | null | undefined) => { - if (priceId === 'price_commit') return 'commit'; - if (priceId === 'price_standard') return 'standard'; - return null; - }), -})); - -jest.mock('@/lib/stripe-client', () => ({ - client: { - subscriptions: { - retrieve: jest.fn(async (id: string) => ({ - id, - schedule: null, - cancel_at_period_end: true, - })), - update: jest.fn(async () => ({})), - }, - subscriptionSchedules: { - retrieve: jest.fn(async () => ({})), - update: jest.fn(async () => ({})), - release: jest.fn(async () => ({})), - }, - }, -})); - -import { db } from '@/lib/drizzle'; -import { - credit_transactions, - impact_advocate_participants, - impact_advocate_reward_redemptions, - impact_conversion_reports, - impact_attribution_touches, - kiloclaw_instances, - impact_referral_conversions, - impact_referral_reward_applications, - impact_referral_reward_decisions, - impact_referral_rewards, - kiloclaw_subscription_change_log, - kiloclaw_subscriptions, - kilocode_users, - referral_codes, - user_affiliate_attributions, - type ImpactAttributionTouch, -} from '@kilocode/db/schema'; -import { insertTestUser } from '@/tests/helpers/user.helper'; -import { - dispatchQueuedImpactAdvocateRewardRedemptions, - markPersonalKiloClawReferralPaymentAdverse, - processPersonalKiloClawPaidConversion, - processQueuedKiloClawReferralRewards, - resolveWinningAttributionTouch, -} from '@/lib/impact/kiloclaw-referrals'; -import { isImpactConfigured, reverseImpactAction, sendImpactConversionPayload } from '@/lib/impact'; -import { - isImpactAdvocateConfigured, - sendImpactAdvocateRewardLookupPayload, - sendImpactAdvocateRewardRedemptionPayload, -} from '@/lib/impact/advocate'; -import { client as stripeClient } from '@/lib/stripe-client'; -import { ImpactReferralPaymentProvider } from '@kilocode/db/schema-types'; - -const mockIsImpactConfigured = jest.mocked(isImpactConfigured); -const mockIsImpactAdvocateConfigured = jest.mocked(isImpactAdvocateConfigured); -const mockSendImpactConversionPayload = jest.mocked(sendImpactConversionPayload); -const mockSendImpactAdvocateRewardLookupPayload = jest.mocked( - sendImpactAdvocateRewardLookupPayload -); -const mockSendImpactAdvocateRewardRedemptionPayload = jest.mocked( - sendImpactAdvocateRewardRedemptionPayload -); -const mockReverseImpactAction = jest.mocked(reverseImpactAction); -const mockStripeSubscriptionRetrieve = jest.mocked(stripeClient.subscriptions.retrieve); -const mockStripeSubscriptionUpdate = jest.mocked(stripeClient.subscriptions.update); -const mockStripeScheduleRetrieve = jest.mocked(stripeClient.subscriptionSchedules.retrieve); -const mockStripeScheduleUpdate = jest.mocked(stripeClient.subscriptionSchedules.update); -const mockStripeScheduleRelease = jest.mocked(stripeClient.subscriptionSchedules.release); - -function makeTouch( - overrides: Partial & Pick -): ImpactAttributionTouch { - const touchedAt = overrides.touched_at ?? '2026-04-01T00:00:00.000Z'; - return { - id: overrides.id ?? randomUUID(), - product: overrides.product ?? 'kiloclaw', - program_key: overrides.program_key ?? 'kiloclaw', - dedupe_key: overrides.dedupe_key ?? randomUUID(), - anonymous_id: overrides.anonymous_id ?? null, - user_id: overrides.user_id ?? 'user_123', - touch_type: overrides.touch_type, - provider: - overrides.provider ?? - (overrides.touch_type === 'referral' ? 'impact_advocate' : 'impact_performance'), - opaque_tracking_value: overrides.opaque_tracking_value ?? 'opaque-value', - tracking_value_length: overrides.tracking_value_length ?? 12, - is_tracking_value_accepted: overrides.is_tracking_value_accepted ?? true, - rs_code: overrides.rs_code ?? null, - rs_share_medium: overrides.rs_share_medium ?? null, - rs_engagement_medium: overrides.rs_engagement_medium ?? null, - im_ref: overrides.im_ref ?? null, - landing_path: overrides.landing_path ?? null, - utm_source: overrides.utm_source ?? null, - utm_medium: overrides.utm_medium ?? null, - utm_campaign: overrides.utm_campaign ?? null, - utm_term: overrides.utm_term ?? null, - utm_content: overrides.utm_content ?? null, - touched_at: touchedAt, - expires_at: overrides.expires_at ?? '2026-05-01T00:00:00.000Z', - sale_attributed_at: overrides.sale_attributed_at ?? null, - created_at: overrides.created_at ?? touchedAt, - }; -} - -async function insertActivePersonalSubscription( - userId: string, - overrides?: Partial & { - organizationId?: string | null; - } -): Promise<{ subscriptionId: string; instanceId: string }> { - const [instance] = await db - .insert(kiloclaw_instances) - .values({ - user_id: userId, - sandbox_id: `sandbox-${userId}`, - organization_id: overrides?.organizationId ?? null, - }) - .returning({ id: kiloclaw_instances.id }); - - const [subscription] = await db - .insert(kiloclaw_subscriptions) - .values({ - user_id: userId, - instance_id: instance.id, - payment_source: 'credits', - plan: 'standard', - status: 'active', - current_period_start: '2026-04-01T00:00:00.000Z', - current_period_end: '2026-05-01T12:00:00.000Z', - credit_renewal_at: '2026-05-01T12:00:00.000Z', - cancel_at_period_end: false, - ...overrides, - }) - .returning({ id: kiloclaw_subscriptions.id }); - - return { - subscriptionId: subscription.id, - instanceId: instance.id, - }; -} - -async function insertImpactAdvocateParticipant(userId: string, opaqueReferralIdentifier?: string) { - const identifier = opaqueReferralIdentifier ?? randomUUID(); - await db.insert(impact_advocate_participants).values({ - user_id: userId, - advocate_id: userId, - advocate_account_id: userId, - opaque_referral_identifier: identifier, - contact_email: `${userId}@example.com`, - registration_state: 'registered', - registered_at: '2026-03-01T00:00:00.000Z', - }); - return identifier; -} - -async function insertEarnedReferralRewardForUser(userId: string): Promise { - const [conversion] = await db - .insert(impact_referral_conversions) - .values({ - referee_user_id: userId, - referrer_user_id: null, - winning_touch_type: 'none', - source_payment_id: `reward-application-test:${randomUUID()}`, - qualified: true, - converted_at: '2026-04-10T00:00:00.000Z', - }) - .returning({ id: impact_referral_conversions.id }); - if (!conversion) throw new Error('Failed to insert referral conversion'); - - const [decision] = await db - .insert(impact_referral_reward_decisions) - .values({ - conversion_id: conversion.id, - beneficiary_user_id: userId, - beneficiary_role: 'referee', - outcome: 'granted', - months_granted: 1, - }) - .returning({ id: impact_referral_reward_decisions.id }); - if (!decision) throw new Error('Failed to insert referral reward decision'); - - const [reward] = await db - .insert(impact_referral_rewards) - .values({ - conversion_id: conversion.id, - decision_id: decision.id, - beneficiary_user_id: userId, - beneficiary_role: 'referee', - months_granted: 1, - status: 'earned', - earned_at: '2026-04-10T00:00:00.000Z', - }) - .returning({ id: impact_referral_rewards.id }); - if (!reward) throw new Error('Failed to insert referral reward'); - - return reward.id; -} - -async function insertAppliedReferralRewardForUser(userId: string): Promise { - const [conversion] = await db - .insert(impact_referral_conversions) - .values({ - referee_user_id: userId, - referrer_user_id: null, - winning_touch_type: 'none', - source_payment_id: `reward-redemption-test:${randomUUID()}`, - qualified: true, - converted_at: '2026-04-10T00:00:00.000Z', - }) - .returning({ id: impact_referral_conversions.id }); - - if (!conversion) throw new Error('Failed to insert referral conversion'); - - const [decision] = await db - .insert(impact_referral_reward_decisions) - .values({ - conversion_id: conversion.id, - beneficiary_user_id: userId, - beneficiary_role: 'referee', - outcome: 'granted', - months_granted: 1, - }) - .returning({ id: impact_referral_reward_decisions.id }); - - if (!decision) throw new Error('Failed to insert referral reward decision'); - - const [reward] = await db - .insert(impact_referral_rewards) - .values({ - conversion_id: conversion.id, - decision_id: decision.id, - beneficiary_user_id: userId, - beneficiary_role: 'referee', - months_granted: 1, - status: 'applied', - earned_at: '2026-04-10T00:00:00.000Z', - applied_at: '2026-04-10T00:05:00.000Z', - }) - .returning({ id: impact_referral_rewards.id }); - - if (!reward) throw new Error('Failed to insert referral reward'); - - return reward.id; -} - -describe('kiloclaw referrals', () => { - afterEach(async () => { - jest.clearAllMocks(); - mockIsImpactConfigured.mockReturnValue(true); - mockIsImpactAdvocateConfigured.mockReturnValue(true); - mockSendImpactAdvocateRewardLookupPayload.mockResolvedValue({ - ok: true, - statusCode: 200, - responseBody: JSON.stringify({ rewards: [{ id: 'impact-reward-123', type: 'CREDIT' }] }), - rewards: [{ id: 'impact-reward-123', type: 'CREDIT' }], - }); - mockSendImpactAdvocateRewardRedemptionPayload.mockResolvedValue({ - ok: true, - statusCode: 200, - responseBody: '{}', - }); - await db.delete(impact_conversion_reports).where(sql`true`); - await db.delete(impact_advocate_reward_redemptions).where(sql`true`); - await db.delete(impact_referral_reward_applications).where(sql`true`); - await db.delete(impact_referral_rewards).where(sql`true`); - await db.delete(impact_referral_reward_decisions).where(sql`true`); - await db.delete(impact_referral_conversions).where(sql`true`); - await db.delete(user_affiliate_attributions).where(sql`true`); - await db.delete(impact_attribution_touches).where(sql`true`); - await db.delete(credit_transactions).where(sql`true`); - await db.delete(kiloclaw_subscription_change_log).where(sql`true`); - await db.delete(kiloclaw_subscriptions).where(sql`true`); - await db.delete(kiloclaw_instances).where(sql`true`); - await db.delete(impact_advocate_participants).where(sql`true`); - await db.delete(referral_codes).where(sql`true`); - await db.delete(kilocode_users).where(sql`true`); - }); - - describe('processQueuedKiloClawReferralRewards retirement behavior', () => { - it('extends a retirement-guarded final Commit term and keeps ordinary user cancellation pending', async () => { - const guardedUser = await insertTestUser({ - google_user_email: 'guarded-final-commit@example.com', - normalized_email: 'guarded-final-commit@example.com', - }); - const userCanceledUser = await insertTestUser({ - google_user_email: 'user-canceled-commit@example.com', - normalized_email: 'user-canceled-commit@example.com', - }); - const { subscriptionId: guardedSubscriptionId } = await insertActivePersonalSubscription( - guardedUser.id, - { - plan: 'commit', - cancel_at_period_end: true, - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: '2026-12-01T12:00:00.000Z', - commit_ends_at: '2026-12-01T12:00:00.000Z', - } - ); - const { subscriptionId: userCanceledSubscriptionId } = await insertActivePersonalSubscription( - userCanceledUser.id, - { - plan: 'commit', - cancel_at_period_end: true, - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: '2026-12-01T12:00:00.000Z', - commit_ends_at: '2026-12-01T12:00:00.000Z', - } - ); - await db.insert(kiloclaw_subscription_change_log).values([ - { - subscription_id: guardedSubscriptionId, - actor_type: 'system', - actor_id: 'commit-retirement', - action: 'schedule_changed', - reason: 'commit_retirement_guarded', - }, - { - subscription_id: userCanceledSubscriptionId, - actor_type: 'user', - actor_id: userCanceledUser.id, - action: 'canceled', - reason: 'user_requested_cancellation', - }, - ]); - await insertEarnedReferralRewardForUser(guardedUser.id); - await insertEarnedReferralRewardForUser(userCanceledUser.id); - - const summary = await processQueuedKiloClawReferralRewards({ - beneficiaryUserIds: [guardedUser.id, userCanceledUser.id], - }); - - expect(summary).toEqual({ claimed: 2, applied: 1, expired: 0, pending: 1, failed: 0 }); - const subscriptions = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.plan, 'commit')); - expect(subscriptions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - user_id: guardedUser.id, - current_period_end: '2027-01-01 12:00:00+00', - credit_renewal_at: '2027-01-01 12:00:00+00', - commit_ends_at: '2027-01-01 12:00:00+00', - cancel_at_period_end: true, - }), - expect.objectContaining({ - user_id: userCanceledUser.id, - current_period_end: '2026-12-01 12:00:00+00', - }), - ]) - ); - }); - - it('extends a pending Stripe-to-credits final Commit conversion without reopening Commit renewal', async () => { - const user = await insertTestUser({ - google_user_email: 'pending-conversion-final-commit@example.com', - normalized_email: 'pending-conversion-final-commit@example.com', - }); - await insertActivePersonalSubscription(user.id, { - payment_source: 'credits', - stripe_subscription_id: 'sub_pending_conversion_final_commit', - stripe_schedule_id: null, - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - pending_conversion: true, - cancel_at_period_end: true, - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: '2026-12-01T12:00:00.000Z', - commit_ends_at: '2026-12-01T12:00:00.000Z', - }); - await insertEarnedReferralRewardForUser(user.id); - const newBoundary = Math.floor(new Date('2027-01-01T12:00:00.000Z').getTime() / 1000); - - const summary = await processQueuedKiloClawReferralRewards({ beneficiaryUserIds: [user.id] }); - - expect(summary).toEqual({ claimed: 1, applied: 1, expired: 0, pending: 0, failed: 0 }); - expect(mockStripeSubscriptionUpdate).toHaveBeenCalledWith( - 'sub_pending_conversion_final_commit', - { - trial_end: newBoundary, - proration_behavior: 'none', - }, - { idempotencyKey: expect.any(String) } - ); - expect(mockStripeScheduleRetrieve).not.toHaveBeenCalled(); - expect(mockStripeScheduleUpdate).not.toHaveBeenCalled(); - const [subscription] = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.user_id, user.id)); - expect(subscription).toEqual( - expect.objectContaining({ - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - stripe_schedule_id: null, - pending_conversion: true, - cancel_at_period_end: true, - current_period_end: '2027-01-01 12:00:00+00', - credit_renewal_at: '2027-01-01 12:00:00+00', - commit_ends_at: '2027-01-01 12:00:00+00', - }) - ); - }); - - it('moves a scheduled Standard transition when extending a Stripe final term', async () => { - const user = await insertTestUser({ - google_user_email: 'scheduled-standard-final-commit@example.com', - normalized_email: 'scheduled-standard-final-commit@example.com', - }); - await insertActivePersonalSubscription(user.id, { - payment_source: 'stripe', - stripe_subscription_id: 'sub_final_commit', - stripe_schedule_id: 'sched_final_commit', - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: null, - commit_ends_at: '2026-12-01T12:00:00.000Z', - }); - await insertEarnedReferralRewardForUser(user.id); - const previousBoundary = Math.floor(new Date('2026-12-01T12:00:00.000Z').getTime() / 1000); - const newBoundary = Math.floor(new Date('2027-01-01T12:00:00.000Z').getTime() / 1000); - const boundaryExtension = newBoundary - previousBoundary; - const previousStandardEnd = previousBoundary + 2_592_000; - mockStripeScheduleRetrieve.mockResolvedValueOnce({ - id: 'sched_final_commit', - status: 'active', - phases: [ - { - start_date: previousBoundary - 15_552_000, - end_date: previousBoundary, - items: [{ price: 'price_commit' }], - }, - { - start_date: previousBoundary, - end_date: previousStandardEnd, - items: [{ price: 'price_standard' }], - }, - ], - } as never); - - const summary = await processQueuedKiloClawReferralRewards({ beneficiaryUserIds: [user.id] }); - - expect(summary).toEqual({ claimed: 1, applied: 1, expired: 0, pending: 0, failed: 0 }); - expect(mockStripeScheduleUpdate).toHaveBeenCalledWith('sched_final_commit', { - phases: [ - { - items: [{ price: 'price_commit' }], - start_date: previousBoundary - 15_552_000, - end_date: newBoundary, - }, - { - items: [{ price: 'price_standard' }], - start_date: newBoundary, - end_date: previousStandardEnd + boundaryExtension, - }, - ], - }); - expect(mockStripeSubscriptionUpdate).not.toHaveBeenCalled(); - const [subscription] = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.user_id, user.id)); - expect(subscription).toEqual( - expect.objectContaining({ - current_period_end: '2027-01-01 12:00:00+00', - commit_ends_at: '2027-01-01 12:00:00+00', - }) - ); - }); - - it('completes local reward application when the Stripe schedule was already extended', async () => { - const user = await insertTestUser({ - google_user_email: 'already-extended-final-commit@example.com', - normalized_email: 'already-extended-final-commit@example.com', - }); - await insertActivePersonalSubscription(user.id, { - payment_source: 'stripe', - stripe_subscription_id: 'sub_already_extended_final_commit', - stripe_schedule_id: 'sched_already_extended_final_commit', - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: null, - commit_ends_at: '2026-12-01T12:00:00.000Z', - }); - await insertEarnedReferralRewardForUser(user.id); - const previousBoundary = Math.floor(new Date('2026-12-01T12:00:00.000Z').getTime() / 1000); - const newBoundary = Math.floor(new Date('2027-01-01T12:00:00.000Z').getTime() / 1000); - mockStripeScheduleRetrieve.mockResolvedValueOnce({ - id: 'sched_already_extended_final_commit', - status: 'active', - phases: [ - { - start_date: previousBoundary - 15_552_000, - end_date: newBoundary, - items: [{ price: 'price_commit' }], - }, - { - start_date: newBoundary, - items: [{ price: 'price_standard' }], - }, - ], - } as never); - - const summary = await processQueuedKiloClawReferralRewards({ beneficiaryUserIds: [user.id] }); - - expect(summary).toEqual({ claimed: 1, applied: 1, expired: 0, pending: 0, failed: 0 }); - expect(mockStripeScheduleUpdate).not.toHaveBeenCalled(); - const [subscription] = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.user_id, user.id)); - expect(subscription).toEqual( - expect.objectContaining({ - current_period_end: '2027-01-01 12:00:00+00', - commit_ends_at: '2027-01-01 12:00:00+00', - }) - ); - }); - - it('preserves an indefinite Standard phase when moving its retirement transition', async () => { - const user = await insertTestUser({ - google_user_email: 'indefinite-standard-final-commit@example.com', - normalized_email: 'indefinite-standard-final-commit@example.com', - }); - await insertActivePersonalSubscription(user.id, { - payment_source: 'stripe', - stripe_subscription_id: 'sub_indefinite_final_commit', - stripe_schedule_id: 'sched_indefinite_final_commit', - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: null, - commit_ends_at: '2026-12-01T12:00:00.000Z', - }); - await insertEarnedReferralRewardForUser(user.id); - const previousBoundary = Math.floor(new Date('2026-12-01T12:00:00.000Z').getTime() / 1000); - const newBoundary = Math.floor(new Date('2027-01-01T12:00:00.000Z').getTime() / 1000); - mockStripeScheduleRetrieve.mockResolvedValueOnce({ - id: 'sched_indefinite_final_commit', - status: 'active', - phases: [ - { - start_date: previousBoundary - 15_552_000, - end_date: previousBoundary, - items: [{ price: 'price_commit' }], - }, - { - start_date: previousBoundary, - items: [{ price: 'price_standard' }], - }, - ], - } as never); - - const summary = await processQueuedKiloClawReferralRewards({ beneficiaryUserIds: [user.id] }); - - expect(summary).toEqual({ claimed: 1, applied: 1, expired: 0, pending: 0, failed: 0 }); - expect(mockStripeScheduleUpdate).toHaveBeenCalledWith('sched_indefinite_final_commit', { - phases: [ - { - items: [{ price: 'price_commit' }], - start_date: previousBoundary - 15_552_000, - end_date: newBoundary, - }, - { - items: [{ price: 'price_standard' }], - start_date: newBoundary, - }, - ], - }); - }); - - it('contains ambiguous retirement schedules without reopening Commit or applying reward', async () => { - const user = await insertTestUser({ - google_user_email: 'ambiguous-scheduled-standard@example.com', - normalized_email: 'ambiguous-scheduled-standard@example.com', - }); - await insertActivePersonalSubscription(user.id, { - payment_source: 'stripe', - stripe_subscription_id: 'sub_ambiguous_final_commit', - stripe_schedule_id: 'sched_ambiguous_final_commit', - plan: 'commit', - scheduled_plan: 'standard', - scheduled_by: 'user', - current_period_end: '2026-12-01T12:00:00.000Z', - credit_renewal_at: null, - commit_ends_at: '2026-12-01T12:00:00.000Z', - }); - await insertEarnedReferralRewardForUser(user.id); - mockStripeScheduleRetrieve.mockResolvedValueOnce({ - id: 'sched_ambiguous_final_commit', - status: 'active', - phases: [], - } as never); - - const summary = await processQueuedKiloClawReferralRewards({ beneficiaryUserIds: [user.id] }); - - expect(summary).toEqual({ claimed: 1, applied: 0, expired: 0, pending: 1, failed: 0 }); - expect(mockStripeScheduleUpdate).not.toHaveBeenCalled(); - expect(mockStripeSubscriptionRetrieve).not.toHaveBeenCalled(); - expect(mockStripeScheduleRelease).not.toHaveBeenCalled(); - expect(mockStripeSubscriptionUpdate).not.toHaveBeenCalled(); - const [subscription] = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.user_id, user.id)); - expect(subscription).toEqual( - expect.objectContaining({ - current_period_end: '2026-12-01 12:00:00+00', - commit_ends_at: '2026-12-01 12:00:00+00', - scheduled_plan: 'standard', - plan: 'commit', - }) - ); - const [reward] = await db - .select() - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.beneficiary_user_id, user.id)); - expect(reward).toEqual( - expect.objectContaining({ - status: 'review_required', - review_reason: 'referral_reward_ambiguous_standard_schedule', - applies_to_subscription_id: null, - applied_at: null, - }) - ); - const applications = await db - .select() - .from(impact_referral_reward_applications) - .where(eq(impact_referral_reward_applications.reward_id, reward.id)); - expect(applications).toHaveLength(0); - const redemptions = await db - .select() - .from(impact_advocate_reward_redemptions) - .where(eq(impact_advocate_reward_redemptions.reward_id, reward.id)); - expect(redemptions).toHaveLength(0); - }); - }); - - describe('dispatchQueuedImpactAdvocateRewardRedemptions', () => { - it('does not treat already-redeemed Impact responses as success before this row has selected the reward', async () => { - const user = await insertTestUser({ - google_user_email: 'first-already-redeemed@example.com', - normalized_email: 'first-already-redeemed@example.com', - }); - const rewardId = await insertAppliedReferralRewardForUser(user.id); - await db.insert(impact_advocate_reward_redemptions).values({ - reward_id: rewardId, - dedupe_key: `first-already-redeemed:${rewardId}`, - beneficiary_user_id: user.id, - state: 'queued', - request_payload: { - lookup: { - accountId: user.google_user_email, - userId: user.google_user_email, - rewardTypeFilter: 'CREDIT', - }, - redemption: { amount: 1, unit: 'MONTH' }, - }, - }); - mockSendImpactAdvocateRewardRedemptionPayload.mockResolvedValueOnce({ - ok: false, - failureKind: 'http_4xx', - statusCode: 400, - responseBody: 'Reward already redeemed', - }); - - const summary = await dispatchQueuedImpactAdvocateRewardRedemptions(); - - expect(summary).toEqual({ claimed: 1, redeemed: 0, retried: 0, failed: 1 }); - const [redemption] = await db.select().from(impact_advocate_reward_redemptions); - expect(redemption).toEqual( - expect.objectContaining({ - state: 'failed', - impact_reward_id: 'impact-reward-123', - response_status_code: 400, - }) - ); - }); - - it('treats already-redeemed Impact responses as idempotent success for a previously selected reward', async () => { - const user = await insertTestUser({ - google_user_email: 'retry-already-redeemed@example.com', - normalized_email: 'retry-already-redeemed@example.com', - }); - const rewardId = await insertAppliedReferralRewardForUser(user.id); - await db.insert(impact_advocate_reward_redemptions).values({ - reward_id: rewardId, - dedupe_key: `retry-already-redeemed:${rewardId}`, - beneficiary_user_id: user.id, - state: 'queued', - impact_reward_id: 'impact-reward-123', - request_payload: { - lookup: { - accountId: user.google_user_email, - userId: user.google_user_email, - rewardTypeFilter: 'CREDIT', - }, - redemption: { amount: 1, unit: 'MONTH' }, - }, - }); - mockSendImpactAdvocateRewardRedemptionPayload.mockResolvedValueOnce({ - ok: false, - failureKind: 'http_4xx', - statusCode: 400, - responseBody: 'Reward already redeemed', - }); - - const summary = await dispatchQueuedImpactAdvocateRewardRedemptions(); - - expect(summary).toEqual({ claimed: 1, redeemed: 1, retried: 0, failed: 0 }); - const [redemption] = await db.select().from(impact_advocate_reward_redemptions); - expect(redemption).toEqual( - expect.objectContaining({ - state: 'redeemed', - impact_reward_id: 'impact-reward-123', - response_status_code: 400, - redeem_response_payload: expect.objectContaining({ alreadyRedeemed: true }), - }) - ); - }); - - it('redeems month credits returned by Impact', async () => { - const user = await insertTestUser({ - google_user_email: 'month-credit@example.com', - normalized_email: 'month-credit@example.com', - }); - const rewardId = await insertAppliedReferralRewardForUser(user.id); - await db.insert(impact_advocate_reward_redemptions).values({ - reward_id: rewardId, - dedupe_key: `month-credit:${rewardId}`, - beneficiary_user_id: user.id, - state: 'queued', - request_payload: { - lookup: { - accountId: user.google_user_email, - userId: user.google_user_email, - rewardTypeFilter: 'CREDIT', - }, - redemption: { amount: 1, unit: 'MONTH' }, - }, - }); - mockSendImpactAdvocateRewardLookupPayload.mockResolvedValueOnce({ - ok: true, - statusCode: 200, - responseBody: JSON.stringify([ - { - id: 'impact-month-reward', - type: 'CREDIT', - unit: 'MONTH', - assignedCredit: 1, - redeemedCredit: 0, - }, - ]), - rewards: [ - { - id: 'impact-month-reward', - type: 'CREDIT', - unit: 'MONTH', - assignedCredit: 1, - redeemedCredit: 0, - }, - ], - }); - - const summary = await dispatchQueuedImpactAdvocateRewardRedemptions(); - - expect(summary).toEqual({ claimed: 1, redeemed: 1, retried: 0, failed: 0 }); - expect(mockSendImpactAdvocateRewardRedemptionPayload).toHaveBeenCalledWith({ - rewardId: 'impact-month-reward', - amount: 1, - unit: 'MONTH', - }); - const [redemption] = await db.select().from(impact_advocate_reward_redemptions); - expect(redemption).toEqual( - expect.objectContaining({ - state: 'redeemed', - impact_reward_id: 'impact-month-reward', - }) - ); - }); - }); - - describe('resolveWinningAttributionTouch', () => { - const convertedAt = new Date('2026-04-10T00:00:00.000Z'); - - it('prefers referral over an unsold affiliate touch', () => { - const affiliateTouch = makeTouch({ - id: 'affiliate-touch', - touch_type: 'affiliate', - touched_at: '2026-04-01T00:00:00.000Z', - im_ref: 'im-ref', - }); - const referralTouch = makeTouch({ - id: 'referral-touch', - touch_type: 'referral', - touched_at: '2026-04-02T00:00:00.000Z', - rs_code: 'ref-code', - }); - - expect( - resolveWinningAttributionTouch({ touches: [affiliateTouch, referralTouch], convertedAt }) - ).toMatchObject({ winner: 'referral', referralTouch: { id: 'referral-touch' } }); - }); - - it('preserves affiliate when it had already been sale-attributed before the referral touch', () => { - const affiliateTouch = makeTouch({ - id: 'affiliate-touch', - touch_type: 'affiliate', - touched_at: '2026-04-01T00:00:00.000Z', - sale_attributed_at: '2026-04-01T12:00:00.000Z', - im_ref: 'im-ref', - }); - const referralTouch = makeTouch({ - id: 'referral-touch', - touch_type: 'referral', - touched_at: '2026-04-02T00:00:00.000Z', - rs_code: 'ref-code', - }); - - expect( - resolveWinningAttributionTouch({ touches: [affiliateTouch, referralTouch], convertedAt }) - ).toMatchObject({ winner: 'affiliate', affiliateTouch: { id: 'affiliate-touch' } }); - }); - - it('keeps referral priority when the referral touch happened first', () => { - const referralTouch = makeTouch({ - id: 'referral-touch', - touch_type: 'referral', - touched_at: '2026-04-01T00:00:00.000Z', - rs_code: 'ref-code', - }); - const affiliateTouch = makeTouch({ - id: 'affiliate-touch', - touch_type: 'affiliate', - touched_at: '2026-04-02T00:00:00.000Z', - im_ref: 'im-ref', - }); - - expect( - resolveWinningAttributionTouch({ touches: [affiliateTouch, referralTouch], convertedAt }) - ).toMatchObject({ winner: 'referral', referralTouch: { id: 'referral-touch' } }); - }); - - it('falls back to affiliate when no valid referral exists', () => { - const affiliateTouch = makeTouch({ - id: 'affiliate-touch', - touch_type: 'affiliate', - im_ref: 'im-ref', - }); - - expect( - resolveWinningAttributionTouch({ touches: [affiliateTouch], convertedAt }) - ).toMatchObject({ winner: 'affiliate', affiliateTouch: { id: 'affiliate-touch' } }); - }); - - it('falls back to referral when no affiliate exists', () => { - const referralTouch = makeTouch({ - id: 'referral-touch', - touch_type: 'referral', - rs_code: 'ref-code', - }); - - expect( - resolveWinningAttributionTouch({ touches: [referralTouch], convertedAt }) - ).toMatchObject({ winner: 'referral', referralTouch: { id: 'referral-touch' } }); - }); - - it('returns none when all touches are expired or invalid', () => { - const expiredAffiliateTouch = makeTouch({ - id: 'affiliate-touch', - touch_type: 'affiliate', - im_ref: 'im-ref', - touched_at: '2026-03-01T00:00:00.000Z', - expires_at: '2026-03-31T00:00:00.000Z', - }); - const invalidReferralTouch = makeTouch({ - id: 'referral-touch', - touch_type: 'referral', - rs_code: 'ref-code', - opaque_tracking_value: null, - is_tracking_value_accepted: false, - }); - - expect( - resolveWinningAttributionTouch({ - touches: [expiredAffiliateTouch, invalidReferralTouch], - convertedAt, - }) - ).toEqual({ - winner: 'none', - affiliateTouch: null, - referralTouch: null, - }); - }); - - it('filters touches by product for mirrored Kilo Pass attribution', () => { - const kiloClawReferralTouch = makeTouch({ - id: 'kiloclaw-referral-touch', - product: 'kiloclaw', - touch_type: 'referral', - touched_at: '2026-04-01T00:00:00.000Z', - rs_code: 'claw-ref-code', - }); - const kiloPassAffiliateTouch = makeTouch({ - id: 'kilo-pass-affiliate-touch', - product: 'kilo_pass', - program_key: null, - touch_type: 'affiliate', - touched_at: '2026-04-02T00:00:00.000Z', - im_ref: 'pass-im-ref', - }); - - expect( - resolveWinningAttributionTouch({ - product: 'kilo_pass', - touches: [kiloClawReferralTouch, kiloPassAffiliateTouch], - convertedAt, - }) - ).toMatchObject({ - winner: 'affiliate', - affiliateTouch: { id: 'kilo-pass-affiliate-touch' }, - referralTouch: null, - }); - }); - - it('uses the exact 30-day UTC expiration boundary', () => { - const referralTouch = makeTouch({ - id: 'boundary-referral-touch', - touch_type: 'referral', - touched_at: '2026-04-01T00:00:00.000Z', - expires_at: '2026-06-01T00:00:00.000Z', - rs_code: 'ref-code', - }); - - expect( - resolveWinningAttributionTouch({ - touches: [referralTouch], - convertedAt: new Date('2026-04-30T23:59:59.999Z'), - }) - ).toMatchObject({ winner: 'referral' }); - expect( - resolveWinningAttributionTouch({ - touches: [referralTouch], - convertedAt: new Date('2026-05-01T00:00:00.000Z'), - }) - ).toEqual({ - winner: 'none', - affiliateTouch: null, - referralTouch: null, - }); - }); - }); - - describe('processPersonalKiloClawPaidConversion', () => { - it('records affiliate-winning first paid conversions and marks the touch as sale-attributed', async () => { - const user = await insertTestUser({ - google_user_email: 'affiliate-winner@example.com', - normalized_email: 'affiliate-winner@example.com', - }); - const sourcePaymentId = 'kiloclaw-subscription:instance-a:2026-04'; - - await insertActivePersonalSubscription(user.id); - await db.insert(credit_transactions).values({ - kilo_user_id: user.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - const affiliateTouchId = '11111111-1111-4111-8111-111111111111'; - await db.insert(impact_attribution_touches).values({ - id: affiliateTouchId, - dedupe_key: 'affiliate-touch', - user_id: user.id, - touch_type: 'affiliate', - provider: 'impact_performance', - opaque_tracking_value: 'im-ref-123', - tracking_value_length: 10, - is_tracking_value_accepted: true, - im_ref: 'im-ref-123', - touched_at: '2026-04-01T00:00:00.000Z', - expires_at: '2026-05-01T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: user.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: true, - winningTouchType: 'affiliate', - conversionId: expect.any(String), - disqualificationReason: 'referral_affiliate_won', - }); - - const [touch] = await db - .select() - .from(impact_attribution_touches) - .where(eq(impact_attribution_touches.id, affiliateTouchId)); - expect(touch.sale_attributed_at).toBeTruthy(); - expect(mockSendImpactConversionPayload).not.toHaveBeenCalled(); - }); - - it('records referral-winning first paid conversions, grants both sides, and queues impact reporting', async () => { - const referrer = await insertTestUser({ - google_user_email: 'referrer@example.com', - normalized_email: 'referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'referee@example.com', - normalized_email: 'referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-b:2026-04'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '22222222-2222-4222-8222-222222222222', - dedupe_key: 'referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition.shouldEnqueueAffiliateSale).toBe(false); - expect(disposition.winningTouchType).toBe('referral'); - expect(disposition.disqualificationReason).toBeNull(); - - const decisions = await db - .select() - .from(impact_referral_reward_decisions) - .where(eq(impact_referral_reward_decisions.conversion_id, disposition.conversionId ?? '')); - expect(decisions).toHaveLength(2); - expect(decisions.map(decision => decision.outcome).sort()).toEqual(['granted', 'granted']); - - const rewards = await db - .select() - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.conversion_id, disposition.conversionId ?? '')); - expect(rewards).toHaveLength(2); - expect(rewards.map(reward => reward.status).sort()).toEqual(['applied', 'applied']); - - const applications = await db.select().from(impact_referral_reward_applications); - expect(applications).toHaveLength(2); - expect( - applications.map(application => String(application.new_renewal_boundary)).sort() - ).toEqual(['2026-06-01 12:00:00+00', '2026-06-01 12:00:00+00']); - - const subscriptions = await db - .select({ - userId: kiloclaw_subscriptions.user_id, - currentPeriodEnd: kiloclaw_subscriptions.current_period_end, - creditRenewalAt: kiloclaw_subscriptions.credit_renewal_at, - }) - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.plan, 'standard')); - expect(subscriptions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - userId: referrer.id, - currentPeriodEnd: '2026-06-01 12:00:00+00', - creditRenewalAt: '2026-06-01 12:00:00+00', - }), - expect.objectContaining({ - userId: referee.id, - currentPeriodEnd: '2026-06-01 12:00:00+00', - creditRenewalAt: '2026-06-01 12:00:00+00', - }), - ]) - ); - - const reports = await db.select().from(impact_conversion_reports); - expect(reports).toHaveLength(1); - expect(reports[0].state).toBe('delivered'); - expect(mockSendImpactConversionPayload).toHaveBeenCalledTimes(1); - }); - - it('scopes conversion identity and report dedupe by payment provider', async () => { - const referrer = await insertTestUser({ - google_user_email: 'provider-scope-referrer@example.com', - normalized_email: 'provider-scope-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'provider-scope-referee@example.com', - normalized_email: 'provider-scope-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'shared-source-payment-id'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(impact_attribution_touches).values({ - id: '33333333-3333-4333-8333-333333333333', - dedupe_key: 'provider-scope-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const creditsDisposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - paymentProvider: ImpactReferralPaymentProvider.Credits, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - const stripeDisposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - paymentProvider: ImpactReferralPaymentProvider.Stripe, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - const repeatCreditsDisposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - paymentProvider: ImpactReferralPaymentProvider.Credits, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(creditsDisposition.conversionId).toEqual(expect.any(String)); - expect(stripeDisposition.conversionId).toEqual(expect.any(String)); - expect(stripeDisposition.conversionId).not.toBe(creditsDisposition.conversionId); - expect(repeatCreditsDisposition.conversionId).toBe(creditsDisposition.conversionId); - - const conversions = await db - .select({ - id: impact_referral_conversions.id, - paymentProvider: impact_referral_conversions.payment_provider, - }) - .from(impact_referral_conversions) - .where(eq(impact_referral_conversions.source_payment_id, sourcePaymentId)); - expect(conversions).toHaveLength(2); - expect(conversions.map(conversion => conversion.paymentProvider).sort()).toEqual([ - ImpactReferralPaymentProvider.Credits, - ImpactReferralPaymentProvider.Stripe, - ]); - - const reports = await db - .select({ dedupeKey: impact_conversion_reports.dedupe_key }) - .from(impact_conversion_reports); - expect(reports.map(report => report.dedupeKey).sort()).toEqual([ - `impact-referral-sale:kiloclaw:${ImpactReferralPaymentProvider.Credits}:${sourcePaymentId}`, - `impact-referral-sale:kiloclaw:${ImpactReferralPaymentProvider.Stripe}:${sourcePaymentId}`, - ]); - }); - - it('resolves referrers through referral_codes when no participant mapping exists', async () => { - const referrer = await insertTestUser({ - google_user_email: 'referral-code-referrer@example.com', - normalized_email: 'referral-code-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'referral-code-referee@example.com', - normalized_email: 'referral-code-referee@example.com', - }); - const impactReferralId = 'REFERRER5616'; - const sourcePaymentId = 'kiloclaw-subscription:instance-referral-code:2026-04'; - - await db.insert(referral_codes).values({ - kilo_user_id: referrer.id, - code: impactReferralId, - }); - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: 'abababab-abab-4bab-8bab-abababababab', - dedupe_key: 'referral-code-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: impactReferralId, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toMatchObject({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'referral', - disqualificationReason: null, - }); - - const [conversion] = await db.select().from(impact_referral_conversions); - expect(conversion.referrer_user_id).toBe(referrer.id); - expect(conversion.qualified).toBe(true); - }); - - it('allows signup referral touches captured shortly after user creation', async () => { - const referrer = await insertTestUser({ - google_user_email: 'signup-race-referrer@example.com', - normalized_email: 'signup-race-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'signup-race-referee@example.com', - normalized_email: 'signup-race-referee@example.com', - created_at: '2026-04-01T00:00:00.000Z', - updated_at: '2026-04-01T00:00:00.000Z', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-signup-race:2026-04'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: 'cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd', - dedupe_key: 'signup-race-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - landing_path: '/users/after-sign-in?signup=true&callbackPath=%2Fclaw%2Fnew', - touched_at: '2026-04-01T00:00:02.000Z', - expires_at: '2026-05-01T00:00:02.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toMatchObject({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'referral', - disqualificationReason: null, - }); - }); - - it('logs terminal 4xx Impact conversion report failures and stops retrying unchanged payloads', async () => { - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); - mockSendImpactConversionPayload.mockResolvedValueOnce({ - ok: false, - failureKind: 'http_4xx', - statusCode: 400, - responseBody: 'bad request', - }); - - const referrer = await insertTestUser({ - google_user_email: 'terminal-report-referrer@example.com', - normalized_email: 'terminal-report-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'terminal-report-referee@example.com', - normalized_email: 'terminal-report-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-terminal-report:2026-04'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '12121212-1212-4212-8212-121212121212', - dedupe_key: 'terminal-report-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'referral', - conversionId: expect.any(String), - disqualificationReason: null, - }); - - const [report] = await db.select().from(impact_conversion_reports); - expect(report.state).toBe('failed'); - expect(report.next_retry_at).toBeNull(); - expect(consoleErrorSpy).toHaveBeenCalledWith( - '[kiloclaw-referrals] Impact conversion report failed permanently', - expect.objectContaining({ - reportId: report.id, - conversionId: disposition.conversionId, - statusCode: 400, - failureKind: 'http_4xx', - }) - ); - }); - - it('fails closed when reward-bearing referral configuration is missing', async () => { - mockIsImpactConfigured.mockReturnValue(false); - const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); - - try { - const referrer = await insertTestUser({ - google_user_email: 'config-referrer@example.com', - normalized_email: 'config-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'config-referee@example.com', - normalized_email: 'config-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-config:2026-04'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '77777777-7777-4777-8777-777777777777', - dedupe_key: 'missing-config-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'referral', - conversionId: expect.any(String), - disqualificationReason: 'referral_missing_configuration', - }); - - const decisions = await db - .select({ - beneficiaryRole: impact_referral_reward_decisions.beneficiary_role, - outcome: impact_referral_reward_decisions.outcome, - reason: impact_referral_reward_decisions.reason, - }) - .from(impact_referral_reward_decisions) - .where( - eq(impact_referral_reward_decisions.conversion_id, disposition.conversionId ?? '') - ); - expect(decisions).toHaveLength(2); - expect(decisions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - beneficiaryRole: 'referee', - outcome: 'disqualified', - reason: 'referral_missing_configuration', - }), - expect.objectContaining({ - beneficiaryRole: 'referrer', - outcome: 'disqualified', - reason: 'referral_missing_configuration', - }), - ]) - ); - - const rewards = await db.select().from(impact_referral_rewards); - expect(rewards).toHaveLength(0); - - const reports = await db.select().from(impact_conversion_reports); - expect(reports).toHaveLength(1); - expect(reports[0].state).toBe('failed'); - expect(reports[0].response_payload).toMatchObject({ - error: 'missing_reward_bearing_referral_configuration', - }); - expect(mockSendImpactConversionPayload).not.toHaveBeenCalled(); - expect(consoleErrorSpy).toHaveBeenCalledWith( - '[kiloclaw-referrals] reward-bearing referral configuration is incomplete', - expect.objectContaining({ - sourcePaymentId, - userId: referee.id, - impactPerformanceConfigured: false, - impactAdvocateConfigured: true, - }) - ); - } finally { - consoleErrorSpy.mockRestore(); - } - }); - - it('disqualifies referral touches captured after the user already existed', async () => { - const referrer = await insertTestUser({ - google_user_email: 'old-referrer@example.com', - normalized_email: 'old-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'existing-referee@example.com', - normalized_email: 'existing-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-c:2026-04'; - - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '33333333-3333-4333-8333-333333333333', - dedupe_key: 'late-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2030-01-01T00:00:00.000Z', - expires_at: '2030-02-01T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2030-01-05T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'referral', - conversionId: expect.any(String), - disqualificationReason: 'referral_existing_user_before_touch', - }); - - const rewards = await db.select().from(impact_referral_rewards); - expect(rewards).toHaveLength(0); - expect(mockSendImpactConversionPayload).not.toHaveBeenCalled(); - }); - - it('does not preserve affiliate renewals when no affiliate touch has previously won a sale', async () => { - const referee = await insertTestUser({ - google_user_email: 'renewal-no-sale-touch@example.com', - normalized_email: 'renewal-no-sale-touch@example.com', - }); - - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values([ - { - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: 'kiloclaw-subscription:instance-renewal:2026-03', - }, - { - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard renewal', - credit_category: 'kiloclaw-subscription:instance-renewal:2026-04', - }, - ]); - await db.insert(user_affiliate_attributions).values({ - user_id: referee.id, - provider: 'impact', - tracking_id: 'impact-click-123', - }); - await db.insert(impact_attribution_touches).values({ - id: '88888888-8888-4888-8888-888888888888', - dedupe_key: 'affiliate-touch-without-sale', - user_id: referee.id, - touch_type: 'affiliate', - provider: 'impact_performance', - opaque_tracking_value: 'impact-click-123', - tracking_value_length: 16, - is_tracking_value_accepted: true, - im_ref: 'impact-click-123', - touched_at: '2026-03-01T00:00:00.000Z', - expires_at: '2026-03-31T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-renewal:2026-04', - orderId: 'kiloclaw-subscription:instance-renewal:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'none', - conversionId: null, - disqualificationReason: 'not_first_paid_period', - }); - }); - - it('preserves affiliate renewals when a prior affiliate touch already won the sale', async () => { - const referee = await insertTestUser({ - google_user_email: 'renewal-sale-touch@example.com', - normalized_email: 'renewal-sale-touch@example.com', - }); - - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values([ - { - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: 'kiloclaw-subscription:instance-renewal-sale:2026-03', - }, - { - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard renewal', - credit_category: 'kiloclaw-subscription:instance-renewal-sale:2026-04', - }, - ]); - await db.insert(user_affiliate_attributions).values({ - user_id: referee.id, - provider: 'impact', - tracking_id: 'impact-click-456', - }); - await db.insert(impact_attribution_touches).values({ - id: '99999999-9999-4999-8999-999999999999', - dedupe_key: 'affiliate-touch-with-sale', - user_id: referee.id, - touch_type: 'affiliate', - provider: 'impact_performance', - opaque_tracking_value: 'impact-click-456', - tracking_value_length: 16, - is_tracking_value_accepted: true, - im_ref: 'impact-click-456', - touched_at: '2026-03-01T00:00:00.000Z', - expires_at: '2026-03-31T00:00:00.000Z', - sale_attributed_at: '2026-03-05T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-renewal-sale:2026-04', - orderId: 'kiloclaw-subscription:instance-renewal-sale:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: 'not_first_paid_period', - }); - }); - - it('disqualifies conversions when the user has no current personal KiloClaw subscription', async () => { - const referee = await insertTestUser({ - google_user_email: 'no-personal-sub@example.com', - normalized_email: 'no-personal-sub@example.com', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-missing:2026-04', - orderId: 'kiloclaw-subscription:instance-missing:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'none', - conversionId: null, - disqualificationReason: 'referral_non_personal_subscription', - }); - }); - - it('disqualifies admin-adjusted subscriptions unless explicitly overridden', async () => { - const referee = await insertTestUser({ - google_user_email: 'admin-adjusted@example.com', - normalized_email: 'admin-adjusted@example.com', - }); - const { subscriptionId } = await insertActivePersonalSubscription(referee.id); - await db.insert(kiloclaw_subscription_change_log).values({ - subscription_id: subscriptionId, - actor_type: 'system', - actor_id: 'admin-test', - action: 'admin_override', - reason: 'manual adjustment', - before_state: null, - after_state: null, - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-admin-adjusted:2026-04', - orderId: 'kiloclaw-subscription:instance-admin-adjusted:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'none', - conversionId: null, - disqualificationReason: 'referral_admin_adjusted_subscription', - }); - }); - - it('disqualifies explicitly flagged test conversions unless an override marks them eligible', async () => { - const referee = await insertTestUser({ - google_user_email: 'test-flagged@example.com', - normalized_email: 'test-flagged@example.com', - }); - await insertActivePersonalSubscription(referee.id); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-test-flagged:2026-04', - orderId: 'kiloclaw-subscription:instance-test-flagged:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - qualificationContext: { - sourceType: 'test', - }, - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: false, - winningTouchType: 'none', - conversionId: null, - disqualificationReason: 'referral_test_subscription', - }); - }); - - it('allows explicitly overridden manual conversions to continue through normal qualification', async () => { - const referee = await insertTestUser({ - google_user_email: 'override-eligible@example.com', - normalized_email: 'override-eligible@example.com', - }); - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: 'kiloclaw-subscription:instance-override-eligible:2026-04', - }); - await db.insert(impact_attribution_touches).values({ - id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - dedupe_key: 'override-eligible-affiliate-touch', - user_id: referee.id, - touch_type: 'affiliate', - provider: 'impact_performance', - opaque_tracking_value: 'impact-click-override', - tracking_value_length: 21, - is_tracking_value_accepted: true, - im_ref: 'impact-click-override', - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId: 'kiloclaw-subscription:instance-override-eligible:2026-04', - orderId: 'kiloclaw-subscription:instance-override-eligible:2026-04', - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - qualificationContext: { - sourceType: 'manual_adjustment', - overrideEligible: true, - }, - }); - - expect(disposition).toEqual({ - shouldEnqueueAffiliateSale: true, - winningTouchType: 'affiliate', - conversionId: expect.any(String), - disqualificationReason: 'referral_affiliate_won', - }); - }); - - it('applies pending referrer rewards after the referrer later starts an eligible subscription', async () => { - const referrer = await insertTestUser({ - google_user_email: 'pending-referrer@example.com', - normalized_email: 'pending-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'pending-referee@example.com', - normalized_email: 'pending-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-d:2026-04'; - - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '44444444-4444-4444-8444-444444444444', - dedupe_key: 'pending-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - const disposition = await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - const rewardsBefore = await db - .select({ - beneficiaryUserId: impact_referral_rewards.beneficiary_user_id, - status: impact_referral_rewards.status, - }) - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.conversion_id, disposition.conversionId ?? '')); - expect(rewardsBefore).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - beneficiaryUserId: referee.id, - status: 'applied', - }), - expect.objectContaining({ - beneficiaryUserId: referrer.id, - status: 'pending', - }), - ]) - ); - - await insertActivePersonalSubscription(referrer.id); - - const summary = await processQueuedKiloClawReferralRewards({ - beneficiaryUserIds: [referrer.id], - }); - expect(summary).toEqual({ - claimed: 1, - applied: 1, - expired: 0, - pending: 0, - failed: 0, - }); - - const [referrerReward] = await db - .select() - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.beneficiary_user_id, referrer.id)); - expect(referrerReward.status).toBe('applied'); - - const queuedRedemptions = await db.select().from(impact_advocate_reward_redemptions); - expect(queuedRedemptions).toHaveLength(2); - expect(queuedRedemptions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ beneficiary_user_id: referee.id, state: 'queued' }), - expect.objectContaining({ beneficiary_user_id: referrer.id, state: 'queued' }), - ]) - ); - - const redemptionSummary = await dispatchQueuedImpactAdvocateRewardRedemptions(); - expect(redemptionSummary).toEqual({ claimed: 2, redeemed: 2, retried: 0, failed: 0 }); - expect(mockSendImpactAdvocateRewardLookupPayload).toHaveBeenCalledTimes(2); - expect(mockSendImpactAdvocateRewardLookupPayload).toHaveBeenCalledWith({ - accountId: 'pending-referee@example.com', - userId: 'pending-referee@example.com', - rewardTypeFilter: 'CREDIT', - }); - expect(mockSendImpactAdvocateRewardLookupPayload).toHaveBeenCalledWith({ - accountId: 'pending-referrer@example.com', - userId: 'pending-referrer@example.com', - rewardTypeFilter: 'CREDIT', - }); - expect(mockSendImpactAdvocateRewardRedemptionPayload).toHaveBeenCalledTimes(2); - expect(mockSendImpactAdvocateRewardRedemptionPayload).toHaveBeenCalledWith({ - rewardId: 'impact-reward-123', - amount: 1, - unit: 'MONTH', - }); - - const redeemedRedemptions = await db.select().from(impact_advocate_reward_redemptions); - expect(redeemedRedemptions).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - beneficiary_user_id: referee.id, - state: 'redeemed', - impact_reward_id: 'impact-reward-123', - }), - expect.objectContaining({ - beneficiary_user_id: referrer.id, - state: 'redeemed', - impact_reward_id: 'impact-reward-123', - }), - ]) - ); - }); - - it('leaves local reward state unchanged when Stripe reward application fails', async () => { - const referrer = await insertTestUser({ - google_user_email: 'stripe-failure-referrer@example.com', - normalized_email: 'stripe-failure-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'stripe-failure-referee@example.com', - normalized_email: 'stripe-failure-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-stripe-failure:2026-04'; - - mockStripeSubscriptionUpdate.mockRejectedValueOnce(new Error('stripe exploded')); - - await insertActivePersonalSubscription(referee.id, { - stripe_subscription_id: 'sub_referee_failure_123', - }); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '54545454-5454-4545-8545-545454545454', - dedupe_key: 'stripe-failure-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - const [subscription] = await db - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.user_id, referee.id)); - expect(subscription.current_period_end).toBe('2026-05-01 12:00:00+00'); - - const refereeRewards = await db - .select({ - status: impact_referral_rewards.status, - appliedAt: impact_referral_rewards.applied_at, - }) - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.beneficiary_user_id, referee.id)); - expect(refereeRewards).toEqual([ - { - status: 'earned', - appliedAt: null, - }, - ]); - - const applications = await db.select().from(impact_referral_reward_applications); - expect(applications).toHaveLength(0); - }); - - it('keeps stripe-funded reward application in sync with Stripe trial-end billing delays', async () => { - const referrer = await insertTestUser({ - google_user_email: 'stripe-referrer@example.com', - normalized_email: 'stripe-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'stripe-referee@example.com', - normalized_email: 'stripe-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-e:2026-04'; - - await insertActivePersonalSubscription(referrer.id); - await insertActivePersonalSubscription(referee.id, { - stripe_subscription_id: 'sub_referee_123', - }); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '55555555-5555-4555-8555-555555555555', - dedupe_key: 'stripe-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - expect(mockStripeSubscriptionUpdate).toHaveBeenCalledWith( - 'sub_referee_123', - expect.objectContaining({ - proration_behavior: 'none', - trial_end: Math.floor(new Date('2026-06-01T12:00:00.000Z').getTime() / 1000), - }), - expect.objectContaining({ - idempotencyKey: expect.stringContaining('stripe-apply'), - }) - ); - }); - - it('cancels unapplied rewards and marks applied rewards for review when the qualifying payment is charged back', async () => { - const referrer = await insertTestUser({ - google_user_email: 'reversal-referrer@example.com', - normalized_email: 'reversal-referrer@example.com', - }); - const referee = await insertTestUser({ - google_user_email: 'reversal-referee@example.com', - normalized_email: 'reversal-referee@example.com', - }); - const opaqueReferralIdentifier = await insertImpactAdvocateParticipant(referrer.id); - const sourcePaymentId = 'kiloclaw-subscription:instance-f:2026-04'; - - mockSendImpactConversionPayload.mockResolvedValueOnce({ - ok: true, - delivery: 'immediate', - actionId: '1000.2000.3000', - responseBody: '{}', - }); - - await insertActivePersonalSubscription(referee.id); - await db.insert(credit_transactions).values({ - kilo_user_id: referee.id, - amount_microdollars: -9_000_000, - is_free: false, - description: 'KiloClaw standard enrollment', - credit_category: sourcePaymentId, - }); - await db.insert(impact_attribution_touches).values({ - id: '66666666-6666-4666-8666-666666666666', - dedupe_key: 'reversal-referral-touch', - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'sq-cookie', - tracking_value_length: 9, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - touched_at: '2026-03-31T00:00:00.000Z', - expires_at: '2026-04-30T00:00:00.000Z', - }); - - await processPersonalKiloClawPaidConversion({ - userId: referee.id, - sourcePaymentId, - orderId: sourcePaymentId, - amount: 9, - currencyCode: 'usd', - itemCategory: 'kiloclaw-standard', - itemName: 'KiloClaw Standard Plan', - itemSku: 'price_standard', - convertedAt: new Date('2026-04-09T00:00:00.000Z'), - }); - - const summary = await markPersonalKiloClawReferralPaymentAdverse({ - sourcePaymentId, - reason: 'chargeback', - occurredAt: new Date('2026-04-15T00:00:00.000Z'), - }); - expect(summary).toEqual({ - conversionId: expect.any(String), - canceledRewards: 1, - reviewRequiredRewards: 1, - impactActionReversed: true, - }); - - const rewards = await db - .select({ - beneficiaryUserId: impact_referral_rewards.beneficiary_user_id, - status: impact_referral_rewards.status, - reviewReason: impact_referral_rewards.review_reason, - }) - .from(impact_referral_rewards); - expect(rewards).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - beneficiaryUserId: referee.id, - status: 'review_required', - reviewReason: 'referral_payment_chargeback', - }), - expect.objectContaining({ - beneficiaryUserId: referrer.id, - status: 'canceled', - reviewReason: 'referral_payment_chargeback', - }), - ]) - ); - expect(mockReverseImpactAction).toHaveBeenCalledWith({ actionId: '1000.2000.3000' }); - }); - }); -}); diff --git a/apps/web/src/lib/impact/kiloclaw-referrals.ts b/apps/web/src/lib/impact/kiloclaw-referrals.ts deleted file mode 100644 index 29882e146d..0000000000 --- a/apps/web/src/lib/impact/kiloclaw-referrals.ts +++ /dev/null @@ -1,2553 +0,0 @@ -import 'server-only'; - -import type Stripe from 'stripe'; -import { addMonths } from 'date-fns'; -import { and, asc, count, eq, inArray, like, lt, lte, or, sql } from 'drizzle-orm'; - -import { db, type DrizzleTransaction } from '@/lib/drizzle'; -import { - IMPACT_ACTION_TRACKER_IDS, - buildSalePayload, - hashEmailForImpact, - isImpactConfigured, - reverseImpactAction, - sendImpactConversionPayload, - type ImpactConversionPayload, - type ImpactDispatchResult, -} from '@/lib/impact'; -import { - isImpactAdvocateConfigured, - sendImpactAdvocateRewardLookupPayload, - sendImpactAdvocateRewardRedemptionPayload, - type ImpactAdvocateDispatchResult, -} from '@/lib/impact/advocate'; -import { logImpactReferralDebug } from '@/lib/impact/debug'; -import { hashNormalizedEmailForDeletionTombstone } from '@/lib/impact/referral'; -import { IMPACT_REFERRAL_TOUCH_VALIDITY_MS } from '@/lib/impact/referral-utils'; -import { resolveCurrentPersonalSubscriptionRow } from '@/lib/kiloclaw/current-personal-subscription'; -import { getClawPlanForStripePriceId } from '@/lib/kiloclaw/stripe-price-ids.server'; -import { client as stripe } from '@/lib/stripe-client'; -import { insertKiloClawSubscriptionChangeLog } from '@kilocode/db'; -import { - credit_transactions, - deleted_user_email_tombstones, - impact_advocate_participants, - impact_advocate_reward_redemptions, - impact_conversion_reports, - impact_attribution_touches, - impact_referral_conversions, - impact_referral_reward_applications, - impact_referral_reward_decisions, - impact_referral_rewards, - impact_referrals, - kiloclaw_subscription_change_log, - kiloclaw_subscriptions, - kilocode_users, - referral_codes, - type ImpactAttributionTouch, - type KiloClawSubscription, -} from '@kilocode/db/schema'; -import { - ImpactAdvocateProgramKey, - ImpactAdvocateRewardRedemptionState, - ImpactConversionReportState, - ImpactReferralPaymentProvider, - ImpactReferralProduct, - ImpactReferralRewardKind, - ImpactReferralRewardStatus, - ImpactAttributionTouchType, - KiloClawReferralBeneficiaryRole, - KiloClawReferralDecisionOutcome, - KiloClawReferralRewardStatus, - KiloClawReferralWinningTouchType, -} from '@kilocode/db/schema-types'; - -type DatabaseClient = typeof db | DrizzleTransaction; - -type WinningAttributionResolution = - | { - winner: 'referral'; - referralTouch: ImpactAttributionTouch; - affiliateTouch: ImpactAttributionTouch | null; - } - | { - winner: 'affiliate'; - affiliateTouch: ImpactAttributionTouch; - referralTouch: ImpactAttributionTouch | null; - } - | { - winner: 'none'; - affiliateTouch: ImpactAttributionTouch | null; - referralTouch: ImpactAttributionTouch | null; - }; - -export type KiloClawPaidConversionDisposition = { - shouldEnqueueAffiliateSale: boolean; - winningTouchType: 'referral' | 'affiliate' | 'none'; - conversionId: string | null; - disqualificationReason: string | null; -}; - -export type ImpactConversionReportDispatchSummary = { - claimed: number; - delivered: number; - retried: number; - failed: number; -}; - -export type ReferralRewardProcessingSummary = { - claimed: number; - applied: number; - expired: number; - pending: number; - failed: number; -}; - -export type ImpactAdvocateRewardRedemptionDispatchSummary = { - claimed: number; - redeemed: number; - retried: number; - failed: number; -}; - -export type AdverseReferralPaymentReason = 'chargeback' | 'refund' | 'fraud'; - -export type PaidConversionQualificationContext = { - sourceType?: 'normal' | 'test' | 'fraudulent' | 'admin_created' | 'manual_adjustment'; - overrideEligible?: boolean; -}; - -export type AdverseReferralPaymentSummary = { - conversionId: string | null; - canceledRewards: number; - reviewRequiredRewards: number; - impactActionReversed: boolean; -}; - -const REFERRAL_REWARD_ACTOR = { - actorType: 'system', - actorId: 'kiloclaw-referrals', -} as const; - -const SIGNUP_REFERRAL_TOUCH_CAPTURE_GRACE_MS = 10 * 60 * 1000; -const IMPACT_ADVOCATE_KILOCLAW_REWARD_UNIT = 'MONTH'; -const IMPACT_ADVOCATE_KILO_PASS_REWARD_UNIT = 'Kilo Pass Bonus Credits'; - -function getDatabaseClient(database?: DatabaseClient): DatabaseClient { - return database ?? db; -} - -function reportBackoffDelayMs(attemptCount: number): number { - const maxDelayMs = 60 * 60 * 1000; - const initialDelayMs = 60 * 1000; - return Math.min(initialDelayMs * 2 ** Math.max(attemptCount, 0), maxDelayMs); -} - -function nextReportRetryAt(attemptCount: number): string { - return new Date(Date.now() + reportBackoffDelayMs(attemptCount)).toISOString(); -} - -function nextReportClaimExpiresAt(): string { - return new Date(Date.now() + 15 * 60 * 1000).toISOString(); -} - -function referralDisqualificationReason(reason: string): string { - return `referral_${reason}`; -} - -function hasAcceptedTrackingValue(touch: ImpactAttributionTouch): boolean { - return touch.is_tracking_value_accepted && Boolean(touch.opaque_tracking_value?.trim()); -} - -function isTouchValidAtConversion(touch: ImpactAttributionTouch, convertedAt: Date): boolean { - const touchedAt = new Date(touch.touched_at).getTime(); - const convertedAtMs = convertedAt.getTime(); - // Qualification intentionally ignores the denormalized expires_at column: the referral - // spec defines validity as touched_at + 30 * 24h using server UTC timestamps. - const exactExpiration = touchedAt + IMPACT_REFERRAL_TOUCH_VALIDITY_MS; - return ( - hasAcceptedTrackingValue(touch) && touchedAt <= convertedAtMs && convertedAtMs < exactExpiration - ); -} - -export function resolveWinningAttributionTouch(params: { - product?: ImpactReferralProduct | null; - touches: ImpactAttributionTouch[]; - convertedAt: Date; -}): WinningAttributionResolution { - const scopedTouches = params.product - ? params.touches.filter(touch => touch.product === params.product) - : params.touches; - const validReferralTouches = scopedTouches - .filter( - touch => - touch.touch_type === ImpactAttributionTouchType.Referral && - isTouchValidAtConversion(touch, params.convertedAt) - ) - .sort((a, b) => new Date(a.touched_at).getTime() - new Date(b.touched_at).getTime()); - const validAffiliateTouches = scopedTouches - .filter( - touch => - touch.touch_type === ImpactAttributionTouchType.Affiliate && - isTouchValidAtConversion(touch, params.convertedAt) - ) - .sort((a, b) => new Date(a.touched_at).getTime() - new Date(b.touched_at).getTime()); - - const oldestReferralTouch = validReferralTouches[0] ?? null; - const oldestAffiliateTouch = validAffiliateTouches[0] ?? null; - - if (!oldestReferralTouch && !oldestAffiliateTouch) { - return { - winner: 'none', - affiliateTouch: null, - referralTouch: null, - }; - } - - if (!oldestReferralTouch && oldestAffiliateTouch) { - return { - winner: 'affiliate', - affiliateTouch: oldestAffiliateTouch, - referralTouch: null, - }; - } - - if (!oldestAffiliateTouch && oldestReferralTouch) { - return { - winner: 'referral', - affiliateTouch: null, - referralTouch: oldestReferralTouch, - }; - } - - const preservedAffiliateTouch = validAffiliateTouches.find(touch => { - if (!touch.sale_attributed_at) return false; - return ( - new Date(touch.sale_attributed_at).getTime() < - new Date(oldestReferralTouch.touched_at).getTime() - ); - }); - - if (preservedAffiliateTouch) { - return { - winner: 'affiliate', - affiliateTouch: preservedAffiliateTouch, - referralTouch: oldestReferralTouch, - }; - } - - return { - winner: 'referral', - affiliateTouch: oldestAffiliateTouch, - referralTouch: oldestReferralTouch, - }; -} - -async function countMonetizedKiloClawPaymentPeriods( - userId: string, - database: DatabaseClient -): Promise { - const [result] = await database - .select({ count: count() }) - .from(credit_transactions) - .where( - and( - eq(credit_transactions.kilo_user_id, userId), - eq(credit_transactions.is_free, false), - lt(credit_transactions.amount_microdollars, 0), - or( - like(credit_transactions.credit_category, 'kiloclaw-subscription:%'), - like(credit_transactions.credit_category, 'kiloclaw-subscription-commit:%'), - like(credit_transactions.credit_category, 'kiloclaw-settlement:%') - ) - ) - ); - - return result?.count ?? 0; -} - -async function findAcceptedUserTouches(params: { - userId: string; - convertedAt: Date; - database: DatabaseClient; -}): Promise { - return await params.database - .select() - .from(impact_attribution_touches) - .where( - and( - eq(impact_attribution_touches.product, ImpactReferralProduct.KiloClaw), - eq(impact_attribution_touches.user_id, params.userId), - lte(impact_attribution_touches.touched_at, params.convertedAt.toISOString()) - ) - ) - .orderBy( - asc(impact_attribution_touches.touched_at), - asc(impact_attribution_touches.created_at) - ); -} - -function buildOpaqueReferralIdentifierFromTouch(touch: ImpactAttributionTouch): string | null { - const referralIdentifier = buildImpactReferralId(touch)?.trim(); - return referralIdentifier ? referralIdentifier : null; -} - -async function resolveReferrerUserIdFromReferralTouch(params: { - referralTouch: ImpactAttributionTouch; - database: DatabaseClient; -}): Promise { - const opaqueReferralIdentifier = buildOpaqueReferralIdentifierFromTouch(params.referralTouch); - if (!opaqueReferralIdentifier) { - return null; - } - - const [participant] = await params.database - .select({ userId: impact_advocate_participants.user_id }) - .from(impact_advocate_participants) - .where( - and( - eq(impact_advocate_participants.program_key, ImpactAdvocateProgramKey.KiloClaw), - eq(impact_advocate_participants.opaque_referral_identifier, opaqueReferralIdentifier) - ) - ) - .limit(1); - - if (participant) { - return participant.userId; - } - - const [referralCode] = await params.database - .select({ userId: referral_codes.kilo_user_id }) - .from(referral_codes) - .where(eq(referral_codes.code, opaqueReferralIdentifier)) - .limit(1); - - return referralCode?.userId ?? null; -} - -function wasReferralTouchCapturedDuringSignup(params: { - userCreatedAt: string; - referralTouch: ImpactAttributionTouch; -}): boolean { - if (!params.referralTouch.landing_path) { - return false; - } - - const touchTime = new Date(params.referralTouch.touched_at).getTime(); - const userCreatedTime = new Date(params.userCreatedAt).getTime(); - if (touchTime < userCreatedTime) { - return false; - } - - if (touchTime - userCreatedTime > SIGNUP_REFERRAL_TOUCH_CAPTURE_GRACE_MS) { - return false; - } - - try { - const landingUrl = new URL(params.referralTouch.landing_path, 'http://localhost'); - return landingUrl.searchParams.get('signup') === 'true'; - } catch { - return false; - } -} - -async function hasDeletedUserEmailTombstone(params: { - normalizedEmail: string | null; - database: DatabaseClient; -}): Promise { - if (!params.normalizedEmail) { - return false; - } - - const [row] = await params.database - .select({ hash: deleted_user_email_tombstones.normalized_email_hash }) - .from(deleted_user_email_tombstones) - .where( - eq( - deleted_user_email_tombstones.normalized_email_hash, - hashNormalizedEmailForDeletionTombstone(params.normalizedEmail) - ) - ) - .limit(1); - - return Boolean(row); -} - -function hasUserScheduledStandardContinuation(subscription: KiloClawSubscription): boolean { - return subscription.scheduled_plan === 'standard' && subscription.scheduled_by === 'user'; -} - -async function isEligibleFinalCommitCancellation( - subscription: KiloClawSubscription, - database: DatabaseClient -): Promise { - if ( - subscription.plan !== 'commit' || - subscription.commit_ends_at === null || - subscription.current_period_end !== subscription.commit_ends_at || - !subscription.cancel_at_period_end || - (!hasUserScheduledStandardContinuation(subscription) && subscription.scheduled_plan !== null) - ) { - return false; - } - - if (hasUserScheduledStandardContinuation(subscription)) { - return true; - } - - const [latestCancellationChange] = await database - .select({ reason: kiloclaw_subscription_change_log.reason }) - .from(kiloclaw_subscription_change_log) - .where( - and( - eq(kiloclaw_subscription_change_log.subscription_id, subscription.id), - inArray(kiloclaw_subscription_change_log.reason, [ - 'commit_retirement_guarded', - 'user_requested_cancellation', - ]) - ) - ) - .orderBy( - sql`${kiloclaw_subscription_change_log.created_at} DESC`, - sql`${kiloclaw_subscription_change_log.id} DESC` - ) - .limit(1); - - return latestCancellationChange?.reason === 'commit_retirement_guarded'; -} - -async function hasActiveEligibleSubscriptionRow( - subscription: KiloClawSubscription, - database: DatabaseClient -): Promise { - if ( - subscription.plan === 'trial' || - subscription.status !== 'active' || - subscription.suspended_at !== null || - subscription.past_due_since !== null - ) { - return false; - } - - return ( - !subscription.cancel_at_period_end || - (await isEligibleFinalCommitCancellation(subscription, database)) - ); -} - -async function hasActiveEligiblePersonalSubscription( - userId: string, - database: DatabaseClient -): Promise { - const row = await resolveCurrentPersonalSubscriptionRow({ userId, dbOrTx: database }); - return row ? hasActiveEligibleSubscriptionRow(row.subscription, database) : false; -} - -async function markAffiliateTouchSaleAttributed(params: { - database: DatabaseClient; - affiliateTouchId: string; - convertedAt: Date; -}): Promise { - await params.database - .update(impact_attribution_touches) - .set({ - sale_attributed_at: sql`COALESCE(${impact_attribution_touches.sale_attributed_at}, ${params.convertedAt.toISOString()}::timestamptz)`, - }) - .where(eq(impact_attribution_touches.id, params.affiliateTouchId)); -} - -async function lockReferrerRewardCapacity( - referrerUserId: string, - database: DatabaseClient -): Promise { - await database.execute( - sql`SELECT ${kilocode_users.id} FROM ${kilocode_users} WHERE ${kilocode_users.id} = ${referrerUserId} FOR UPDATE` - ); -} - -async function getGrantedReferrerMonths( - referrerUserId: string, - database: DatabaseClient -): Promise { - const [result] = await database - .select({ - totalMonths: sql`COALESCE(SUM(${impact_referral_reward_decisions.months_granted}), 0)`, - }) - .from(impact_referral_reward_decisions) - .where( - and( - eq(impact_referral_reward_decisions.product, ImpactReferralProduct.KiloClaw), - eq( - impact_referral_reward_decisions.reward_kind, - ImpactReferralRewardKind.KiloClawFreeMonth - ), - eq(impact_referral_reward_decisions.beneficiary_user_id, referrerUserId), - eq( - impact_referral_reward_decisions.beneficiary_role, - KiloClawReferralBeneficiaryRole.Referrer - ), - eq(impact_referral_reward_decisions.outcome, KiloClawReferralDecisionOutcome.Granted) - ) - ); - - return Number(result?.totalMonths ?? 0); -} - -async function hasSaleAttributedAffiliateTouch(params: { - userId: string; - database: DatabaseClient; -}): Promise { - const [touch] = await params.database - .select({ id: impact_attribution_touches.id }) - .from(impact_attribution_touches) - .where( - and( - eq(impact_attribution_touches.product, ImpactReferralProduct.KiloClaw), - eq(impact_attribution_touches.user_id, params.userId), - eq(impact_attribution_touches.touch_type, ImpactAttributionTouchType.Affiliate), - sql`${impact_attribution_touches.sale_attributed_at} IS NOT NULL` - ) - ) - .limit(1); - - return Boolean(touch); -} - -async function hasAdminOverrideHistory(params: { - subscriptionId: string; - database: DatabaseClient; -}): Promise { - const [row] = await params.database - .select({ id: kiloclaw_subscription_change_log.id }) - .from(kiloclaw_subscription_change_log) - .where( - and( - eq(kiloclaw_subscription_change_log.subscription_id, params.subscriptionId), - eq(kiloclaw_subscription_change_log.action, 'admin_override') - ) - ) - .limit(1); - - return Boolean(row); -} - -async function getHeuristicSourcePaymentDisqualificationReason(params: { - sourcePaymentId: string; - database: DatabaseClient; -}): Promise { - const [transaction] = await params.database - .select({ - description: credit_transactions.description, - isFree: credit_transactions.is_free, - }) - .from(credit_transactions) - .where(eq(credit_transactions.credit_category, params.sourcePaymentId)) - .limit(1); - - if (!transaction) { - return null; - } - - if (transaction.isFree) { - return referralDisqualificationReason('fully_comped_period'); - } - - const description = transaction.description?.trim().toLowerCase() ?? ''; - if (description.includes('fraud')) { - return referralDisqualificationReason('fraudulent_subscription'); - } - if (description.includes('manual')) { - return referralDisqualificationReason('manual_adjustment_subscription'); - } - if (description.includes('admin')) { - return referralDisqualificationReason('admin_created_subscription'); - } - if (description.includes('test')) { - return referralDisqualificationReason('test_subscription'); - } - - return null; -} - -function getObjectProperty(record: unknown, key: string): unknown { - if (typeof record !== 'object' || record === null) { - return undefined; - } - - if (!Object.prototype.hasOwnProperty.call(record, key)) { - return undefined; - } - - return Reflect.get(record, key); -} - -function getCaseInsensitiveObjectProperty(record: unknown, key: string): unknown { - if (typeof record !== 'object' || record === null) { - return undefined; - } - - const keys = Object.keys(record); - const matchedKey = keys.find(candidate => candidate.toLowerCase() === key.toLowerCase()); - return matchedKey ? Reflect.get(record, matchedKey) : undefined; -} - -function getStringProperty(record: unknown, keys: string[]): string | null { - for (const key of keys) { - const value = getCaseInsensitiveObjectProperty(record, key); - if (typeof value === 'string' && value.trim()) return value.trim(); - } - return null; -} - -function getNumberProperty(record: unknown, keys: string[]): number | null { - for (const key of keys) { - const value = getCaseInsensitiveObjectProperty(record, key); - if (typeof value === 'number' && Number.isFinite(value)) return value; - if (typeof value === 'string' && value.trim()) { - const parsed = Number(value); - if (Number.isFinite(parsed)) return parsed; - } - } - return null; -} - -function rewardHasUnit(reward: unknown, unit: string): boolean { - const unitValue = - getStringProperty(reward, ['unit', 'Unit', 'currency']) ?? - getStringProperty(getCaseInsensitiveObjectProperty(reward, 'credit'), ['unit', 'Unit']) ?? - getStringProperty(getCaseInsensitiveObjectProperty(reward, 'value'), ['unit', 'Unit']); - return !unitValue || unitValue.toLowerCase() === unit.toLowerCase(); -} - -function rewardHasAmount(reward: unknown, amount: number): boolean { - const amountValue = - getNumberProperty(reward, ['amount', 'Amount', 'remainingAmount', 'RemainingAmount']) ?? - getNumberProperty(getCaseInsensitiveObjectProperty(reward, 'credit'), ['amount', 'Amount']) ?? - getNumberProperty(getCaseInsensitiveObjectProperty(reward, 'value'), ['amount', 'Amount']); - return amountValue === null || amountValue >= amount; -} - -function rewardIsCredit(reward: unknown): boolean { - const type = getStringProperty(reward, ['type', 'Type', 'rewardType', 'RewardType']); - return !type || type.toUpperCase() === 'CREDIT'; -} - -function rewardIsRedeemable(reward: unknown): boolean { - const status = getStringProperty(reward, ['status', 'Status', 'state', 'State']); - if (status) { - const normalizedStatus = status.toUpperCase().replaceAll(' ', '_'); - if ( - normalizedStatus === 'REDEEMED' || - normalizedStatus === 'CANCELLED' || - normalizedStatus === 'CANCELED' - ) { - return false; - } - } - - const redeemed = getCaseInsensitiveObjectProperty(reward, 'redeemed'); - if (redeemed === true) return false; - - const terminalTimestamps = [ - 'redeemedAt', - 'dateRedeemed', - 'cancelledAt', - 'canceledAt', - 'dateCancelled', - 'dateCanceled', - ]; - return !terminalTimestamps.some(key => Boolean(getCaseInsensitiveObjectProperty(reward, key))); -} - -function getImpactAdvocateRewardId(reward: unknown): string | null { - return getStringProperty(reward, ['id', 'Id', 'ID', 'rewardId', 'RewardId']); -} - -function selectImpactAdvocateRewardId(params: { - rewards: unknown[]; - amount: number; - unit: string; -}): string | null { - for (const reward of params.rewards) { - const rewardId = getImpactAdvocateRewardId(reward); - if ( - rewardId && - rewardIsCredit(reward) && - rewardHasUnit(reward, params.unit) && - rewardHasAmount(reward, params.amount) && - rewardIsRedeemable(reward) - ) { - return rewardId; - } - } - - return null; -} - -function isAlreadyRedeemedResponse(responseBody: string | null | undefined): boolean { - const normalized = responseBody?.toLowerCase() ?? ''; - return normalized.includes('already') && normalized.includes('redeem'); -} - -function getImpactActionIdFromResponsePayload(payload: unknown): string | null { - const value = getObjectProperty(payload, 'actionId'); - return typeof value === 'string' && value.trim() ? value : null; -} - -function getRewardApplicationReason(reason: string): string { - return `referral_reward_${reason}`; -} - -function getAdversePaymentReason(reason: AdverseReferralPaymentReason): string { - return `referral_payment_${reason}`; -} - -function getQualificationDisqualificationReason( - sourceType: Exclude -): string { - switch (sourceType) { - case 'test': - return referralDisqualificationReason('test_subscription'); - case 'fraudulent': - return referralDisqualificationReason('fraudulent_subscription'); - case 'admin_created': - return referralDisqualificationReason('admin_created_subscription'); - case 'manual_adjustment': - return referralDisqualificationReason('manual_adjustment_subscription'); - } -} - -function getRewardBearingReferralConfigurationState() { - const impactPerformanceConfigured = isImpactConfigured(); - const impactAdvocateConfigured = isImpactAdvocateConfigured(); - - return { - impactPerformanceConfigured, - impactAdvocateConfigured, - isConfigured: impactPerformanceConfigured && impactAdvocateConfigured, - }; -} - -function logRewardBearingReferralConfigurationFailure(params: { - sourcePaymentId?: string; - conversionId?: string; - rewardId?: string; - userId?: string; -}): void { - const configurationState = getRewardBearingReferralConfigurationState(); - console.error('[kiloclaw-referrals] reward-bearing referral configuration is incomplete', { - ...params, - impactPerformanceConfigured: configurationState.impactPerformanceConfigured, - impactAdvocateConfigured: configurationState.impactAdvocateConfigured, - }); -} - -function getNextRenewalBoundary(subscription: KiloClawSubscription): string | null { - if (subscription.plan === 'commit') { - return subscription.commit_ends_at; - } - return subscription.credit_renewal_at ?? subscription.current_period_end; -} - -function hasScheduledStandardTransition(subscription: KiloClawSubscription): boolean { - return ( - subscription.plan === 'commit' && - hasUserScheduledStandardContinuation(subscription) && - subscription.stripe_schedule_id !== null - ); -} - -function requiresDeferredStripeRewardApplication(subscription: KiloClawSubscription): boolean { - if (hasUserScheduledStandardContinuation(subscription)) { - return false; - } - return Boolean(subscription.stripe_schedule_id || subscription.scheduled_plan); -} - -function toStripeTimestamp(value: string): number { - return Math.floor(new Date(value).getTime() / 1000); -} - -function resolveSchedulePhasePrice(phase: Stripe.SubscriptionSchedule.Phase): string | null { - const price = phase.items[0]?.price; - if (!price) return null; - return typeof price === 'string' ? price : (price.id ?? null); -} - -function isExtendedRetirementScheduleAlreadyApplied(params: { - schedule: Stripe.SubscriptionSchedule; - newBoundary: string; -}): boolean { - const newBoundary = toStripeTimestamp(params.newBoundary); - if (!Number.isFinite(newBoundary)) return false; - - const commitPhaseIndex = params.schedule.phases.findIndex( - phase => - phase.end_date === newBoundary && phase.start_date < newBoundary && phase.items.length === 1 - ); - const commitPhase = params.schedule.phases[commitPhaseIndex]; - const standardPhase = params.schedule.phases[commitPhaseIndex + 1]; - const commitPrice = commitPhase ? resolveSchedulePhasePrice(commitPhase) : null; - const standardPrice = standardPhase ? resolveSchedulePhasePrice(standardPhase) : null; - - return ( - (params.schedule.status === 'active' || params.schedule.status === 'not_started') && - commitPhaseIndex >= 0 && - Boolean(commitPhase) && - Boolean(standardPhase) && - params.schedule.phases.length === commitPhaseIndex + 2 && - standardPhase?.start_date === newBoundary && - standardPhase.items.length === 1 && - commitPrice !== null && - standardPrice !== null && - getClawPlanForStripePriceId(commitPrice) === 'commit' && - getClawPlanForStripePriceId(standardPrice) === 'standard' - ); -} - -function buildExtendedRetirementSchedulePhases(params: { - schedule: Stripe.SubscriptionSchedule; - previousBoundary: string; - newBoundary: string; -}): Stripe.SubscriptionScheduleUpdateParams.Phase[] | null { - if (params.schedule.status !== 'active' && params.schedule.status !== 'not_started') { - return null; - } - - const previousBoundary = toStripeTimestamp(params.previousBoundary); - const newBoundary = toStripeTimestamp(params.newBoundary); - if (!Number.isFinite(previousBoundary) || !Number.isFinite(newBoundary)) { - return null; - } - - const currentPhaseIndex = params.schedule.phases.findIndex( - phase => - phase.end_date === previousBoundary && - phase.start_date < previousBoundary && - phase.items.length === 1 - ); - const currentPhase = params.schedule.phases[currentPhaseIndex]; - const standardPhase = params.schedule.phases[currentPhaseIndex + 1]; - const currentPrice = currentPhase ? resolveSchedulePhasePrice(currentPhase) : null; - const standardPrice = standardPhase ? resolveSchedulePhasePrice(standardPhase) : null; - if ( - currentPhaseIndex < 0 || - !currentPhase || - !standardPhase || - params.schedule.phases.length !== currentPhaseIndex + 2 || - standardPhase.items.length !== 1 || - standardPhase.start_date !== previousBoundary || - !currentPrice || - !standardPrice || - getClawPlanForStripePriceId(currentPrice) !== 'commit' || - getClawPlanForStripePriceId(standardPrice) !== 'standard' - ) { - return null; - } - - if (newBoundary <= previousBoundary) { - return null; - } - - const standardEndDate = standardPhase.end_date - ? standardPhase.end_date + (newBoundary - previousBoundary) - : null; - if (standardEndDate !== null && standardEndDate <= newBoundary) { - return null; - } - - return [ - { - items: [{ price: currentPrice }], - start_date: currentPhase.start_date, - end_date: newBoundary, - }, - { - items: [{ price: standardPrice }], - start_date: newBoundary, - ...(standardEndDate !== null ? { end_date: standardEndDate } : {}), - }, - ]; -} - -async function applyReferralRewardById( - rewardId: string, - options?: { stripeAlreadyApplied?: boolean } -): Promise<'applied' | 'expired' | 'pending' | 'noop'> { - const result = await db.transaction(async tx => { - const [reward] = await tx - .select() - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.id, rewardId)) - .limit(1); - - if (!reward) { - return 'noop'; - } - - if ( - reward.product !== ImpactReferralProduct.KiloClaw || - reward.reward_kind !== ImpactReferralRewardKind.KiloClawFreeMonth - ) { - return 'noop'; - } - - if ( - reward.status === KiloClawReferralRewardStatus.Applied || - reward.status === KiloClawReferralRewardStatus.Canceled || - reward.status === KiloClawReferralRewardStatus.Expired || - reward.status === KiloClawReferralRewardStatus.Reversed || - reward.status === KiloClawReferralRewardStatus.ReviewRequired - ) { - return 'noop'; - } - - const now = new Date(); - if ( - reward.status === KiloClawReferralRewardStatus.Pending && - reward.expires_at && - now.getTime() >= new Date(reward.expires_at).getTime() - ) { - await tx - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.Expired, - review_reason: getRewardApplicationReason('inactive_referrer_expired'), - }) - .where(eq(impact_referral_rewards.id, reward.id)); - return 'expired'; - } - - if (!getRewardBearingReferralConfigurationState().isConfigured) { - logRewardBearingReferralConfigurationFailure({ - rewardId: reward.id, - userId: reward.beneficiary_user_id, - }); - return 'pending'; - } - - await lockReferrerRewardCapacity(reward.beneficiary_user_id, tx); - const currentSubscription = await resolveCurrentPersonalSubscriptionRow({ - userId: reward.beneficiary_user_id, - dbOrTx: tx, - }); - const subscription = currentSubscription?.subscription ?? null; - - if (!subscription || !(await hasActiveEligibleSubscriptionRow(subscription, tx))) { - if (reward.status === KiloClawReferralRewardStatus.Earned) { - // Mirror the conversion-time invariant: a Referrer reward that lands - // in Pending because the referrer is no longer on an eligible paid - // personal subscription MUST carry the 12-month expiry from earned_at - // (see .specs/impact-referrals.md KiloClaw product rules). Without this back-fill, - // a reward earned during a brief eligible window and then orphaned - // when the referrer churns would have expires_at = NULL forever. - const shouldBackfillExpiresAt = - reward.beneficiary_role === KiloClawReferralBeneficiaryRole.Referrer && - reward.expires_at === null; - await tx - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.Pending, - ...(shouldBackfillExpiresAt - ? { - expires_at: addMonths(new Date(reward.earned_at), 12).toISOString(), - } - : {}), - }) - .where(eq(impact_referral_rewards.id, reward.id)); - } - return 'pending'; - } - - const previousBoundary = getNextRenewalBoundary(subscription); - if (!previousBoundary) { - console.warn( - '[kiloclaw-referrals] reward application left pending due to ambiguous renewal boundary', - { - rewardId: reward.id, - userId: reward.beneficiary_user_id, - subscriptionId: subscription.id, - } - ); - if (reward.status === KiloClawReferralRewardStatus.Pending) { - await tx - .update(impact_referral_rewards) - .set({ status: KiloClawReferralRewardStatus.Earned }) - .where(eq(impact_referral_rewards.id, reward.id)); - } - return 'pending'; - } - - if ( - subscription.stripe_subscription_id !== null && - requiresDeferredStripeRewardApplication(subscription) - ) { - console.warn( - '[kiloclaw-referrals] reward application deferred due to scheduled Stripe changes', - { - rewardId: reward.id, - userId: reward.beneficiary_user_id, - subscriptionId: subscription.id, - stripeScheduleId: subscription.stripe_schedule_id, - scheduledPlan: subscription.scheduled_plan, - } - ); - if (reward.status === KiloClawReferralRewardStatus.Pending) { - await tx - .update(impact_referral_rewards) - .set({ status: KiloClawReferralRewardStatus.Earned }) - .where(eq(impact_referral_rewards.id, reward.id)); - } - return 'pending'; - } - - const appliedAt = now.toISOString(); - const newBoundary = addMonths(new Date(previousBoundary), reward.months_granted).toISOString(); - const localOperationId = `kiloclaw-referral-reward:${reward.id}:apply`; - const stripeIdempotencyKey = `kiloclaw-referral-reward:${reward.id}:stripe-apply`; - - if (subscription.stripe_subscription_id && !options?.stripeAlreadyApplied) { - if (hasScheduledStandardTransition(subscription)) { - const scheduleId = subscription.stripe_schedule_id; - if (!scheduleId) { - return 'pending'; - } - return { - outcome: 'retirement_schedule_pending' as const, - subscriptionId: subscription.id, - stripeSubscriptionId: subscription.stripe_subscription_id, - scheduleId, - previousBoundary, - newBoundary, - }; - } - - return { - outcome: 'stripe_pending' as const, - stripeSubscriptionId: subscription.stripe_subscription_id, - trialEnd: toStripeTimestamp(newBoundary), - idempotencyKey: stripeIdempotencyKey, - }; - } - - const [beforeSubscription] = await tx - .select() - .from(kiloclaw_subscriptions) - .where(eq(kiloclaw_subscriptions.id, subscription.id)) - .limit(1); - const [afterSubscription] = await tx - .update(kiloclaw_subscriptions) - .set({ - current_period_end: newBoundary, - credit_renewal_at: - subscription.payment_source === 'credits' ? newBoundary : subscription.credit_renewal_at, - commit_ends_at: subscription.plan === 'commit' ? newBoundary : subscription.commit_ends_at, - }) - .where(eq(kiloclaw_subscriptions.id, subscription.id)) - .returning(); - - if (!afterSubscription) { - return 'noop'; - } - - const [appliedReward] = await tx - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.Applied, - applies_to_subscription_id: subscription.id, - applied_at: appliedAt, - review_reason: null, - }) - .where( - and( - eq(impact_referral_rewards.id, reward.id), - or( - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Earned), - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Pending) - ), - sql`${impact_referral_rewards.applied_at} IS NULL` - ) - ) - .returning({ id: impact_referral_rewards.id }); - - if (!appliedReward) { - return 'noop'; - } - - await insertKiloClawSubscriptionChangeLog(tx, { - subscriptionId: subscription.id, - actor: REFERRAL_REWARD_ACTOR, - action: 'period_advanced', - reason: getRewardApplicationReason('applied'), - before: beforeSubscription ?? null, - after: afterSubscription, - }); - - const [existingApplication] = await tx - .select({ id: impact_referral_reward_applications.id }) - .from(impact_referral_reward_applications) - .where(eq(impact_referral_reward_applications.reward_id, reward.id)) - .limit(1); - - if (!existingApplication) { - await tx.insert(impact_referral_reward_applications).values({ - reward_id: reward.id, - beneficiary_user_id: reward.beneficiary_user_id, - subscription_id: subscription.id, - previous_renewal_boundary: previousBoundary, - new_renewal_boundary: newBoundary, - local_operation_id: localOperationId, - stripe_operation_id: subscription.stripe_subscription_id, - stripe_idempotency_key: subscription.stripe_subscription_id ? stripeIdempotencyKey : null, - applied_at: appliedAt, - }); - } - - await queueImpactAdvocateRewardRedemption({ rewardId: reward.id, database: tx }); - - return 'applied'; - }); - - if (typeof result === 'string') { - return result; - } - - if (result.outcome === 'stripe_pending') { - await stripe.subscriptions.update( - result.stripeSubscriptionId, - { - trial_end: result.trialEnd, - proration_behavior: 'none', - }, - { idempotencyKey: result.idempotencyKey } - ); - return applyReferralRewardById(rewardId, { stripeAlreadyApplied: true }); - } - - try { - const schedule = await stripe.subscriptionSchedules.retrieve(result.scheduleId); - const phases = buildExtendedRetirementSchedulePhases({ - schedule, - previousBoundary: result.previousBoundary, - newBoundary: result.newBoundary, - }); - if (phases) { - await stripe.subscriptionSchedules.update(result.scheduleId, { phases }); - } else if ( - !isExtendedRetirementScheduleAlreadyApplied({ - schedule, - newBoundary: result.newBoundary, - }) - ) { - throw new Error('Ambiguous retirement schedule phases'); - } - } catch (error) { - console.error( - '[kiloclaw-referrals] reward application requires review due to ambiguous retirement schedule', - { - rewardId, - subscriptionId: result.subscriptionId, - stripeSubscriptionId: result.stripeSubscriptionId, - scheduleId: result.scheduleId, - error, - } - ); - await db - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.ReviewRequired, - review_reason: getRewardApplicationReason('ambiguous_standard_schedule'), - }) - .where( - and( - eq(impact_referral_rewards.id, rewardId), - or( - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Earned), - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Pending) - ) - ) - ); - return 'pending'; - } - - return applyReferralRewardById(rewardId, { stripeAlreadyApplied: true }); -} - -export async function processQueuedKiloClawReferralRewards(params?: { - limit?: number; - beneficiaryUserIds?: string[]; -}): Promise { - const limit = params?.limit ?? 100; - const pendingRows = await db - .select({ id: impact_referral_rewards.id }) - .from(impact_referral_rewards) - .where( - and( - eq(impact_referral_rewards.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloClawFreeMonth), - or( - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Pending), - eq(impact_referral_rewards.status, KiloClawReferralRewardStatus.Earned) - ), - params?.beneficiaryUserIds?.length - ? inArray(impact_referral_rewards.beneficiary_user_id, params.beneficiaryUserIds) - : undefined - ) - ) - .orderBy(asc(impact_referral_rewards.earned_at), asc(impact_referral_rewards.created_at)) - .limit(limit); - - const summary: ReferralRewardProcessingSummary = { - claimed: pendingRows.length, - applied: 0, - expired: 0, - pending: 0, - failed: 0, - }; - - for (const row of pendingRows) { - try { - const outcome = await applyReferralRewardById(row.id); - if (outcome === 'applied') { - summary.applied++; - } else if (outcome === 'expired') { - summary.expired++; - } else if (outcome === 'pending') { - summary.pending++; - } - } catch { - summary.failed++; - } - } - - return summary; -} - -export async function queueImpactAdvocateRewardRedemption(params: { - rewardId: string; - database: DatabaseClient; -}): Promise { - const [reward] = await params.database - .select({ - id: impact_referral_rewards.id, - beneficiaryUserId: impact_referral_rewards.beneficiary_user_id, - monthsGranted: impact_referral_rewards.months_granted, - rewardAmountUsd: impact_referral_rewards.reward_amount_usd, - status: impact_referral_rewards.status, - product: impact_referral_rewards.product, - rewardKind: impact_referral_rewards.reward_kind, - email: kilocode_users.google_user_email, - }) - .from(impact_referral_rewards) - .innerJoin(kilocode_users, eq(kilocode_users.id, impact_referral_rewards.beneficiary_user_id)) - .where(eq(impact_referral_rewards.id, params.rewardId)) - .limit(1); - - if (!reward) { - return; - } - - let programKey: ImpactAdvocateProgramKey | null = null; - let amount: number | null = null; - let unit: string | null = null; - - if ( - reward.status === KiloClawReferralRewardStatus.Applied && - reward.product === ImpactReferralProduct.KiloClaw && - reward.rewardKind === ImpactReferralRewardKind.KiloClawFreeMonth - ) { - amount = reward.monthsGranted; - unit = IMPACT_ADVOCATE_KILOCLAW_REWARD_UNIT; - } else if ( - reward.product === ImpactReferralProduct.KiloPass && - reward.rewardKind === ImpactReferralRewardKind.KiloPassBonus && - (reward.status === ImpactReferralRewardStatus.Pending || - reward.status === ImpactReferralRewardStatus.Earned || - reward.status === ImpactReferralRewardStatus.Applied) && - reward.rewardAmountUsd !== null && - reward.rewardAmountUsd > 0 - ) { - programKey = ImpactAdvocateProgramKey.KiloPass; - amount = reward.rewardAmountUsd; - unit = IMPACT_ADVOCATE_KILO_PASS_REWARD_UNIT; - } else { - return; - } - - const accountId = reward.email.trim(); - if (!accountId) { - console.error('[impact-referrals] missing beneficiary email for Impact reward redemption', { - rewardId: params.rewardId, - beneficiaryUserId: reward.beneficiaryUserId, - }); - return; - } - - await params.database - .insert(impact_advocate_reward_redemptions) - .values({ - reward_id: reward.id, - dedupe_key: `impact-advocate-reward-redemption:${reward.id}`, - beneficiary_user_id: reward.beneficiaryUserId, - state: ImpactAdvocateRewardRedemptionState.Queued, - request_payload: { - ...(programKey ? { programKey } : {}), - lookup: { - accountId, - userId: accountId, - rewardTypeFilter: 'CREDIT', - }, - redemption: { - amount, - unit, - }, - } satisfies Record, - }) - .onConflictDoNothing({ target: [impact_advocate_reward_redemptions.reward_id] }); -} - -type ImpactAdvocateRewardRedemptionRequestPayload = { - programKey?: ImpactAdvocateProgramKey; - lookup: { - accountId: string; - userId: string; - rewardTypeFilter: 'CREDIT'; - }; - redemption: { - amount: number; - unit: string; - }; -}; - -function isImpactConversionPayload(payload: unknown): payload is ImpactConversionPayload { - return ( - typeof payload === 'object' && - payload !== null && - typeof getObjectProperty(payload, 'CampaignId') === 'string' && - typeof getObjectProperty(payload, 'ActionTrackerId') === 'number' && - typeof getObjectProperty(payload, 'EventDate') === 'string' && - typeof getObjectProperty(payload, 'OrderId') === 'string' - ); -} - -function isRewardRedemptionRequestPayload( - payload: unknown -): payload is ImpactAdvocateRewardRedemptionRequestPayload { - const lookup = getObjectProperty(payload, 'lookup'); - const redemption = getObjectProperty(payload, 'redemption'); - const programKey = getObjectProperty(payload, 'programKey'); - return ( - typeof lookup === 'object' && - lookup !== null && - typeof redemption === 'object' && - redemption !== null && - (programKey === undefined || - programKey === ImpactAdvocateProgramKey.KiloClaw || - programKey === ImpactAdvocateProgramKey.KiloPass) && - typeof getObjectProperty(lookup, 'accountId') === 'string' && - typeof getObjectProperty(lookup, 'userId') === 'string' && - getObjectProperty(lookup, 'rewardTypeFilter') === 'CREDIT' && - typeof getObjectProperty(redemption, 'amount') === 'number' && - typeof getObjectProperty(redemption, 'unit') === 'string' - ); -} - -function getRewardRedemptionProgramKey( - payload: ImpactAdvocateRewardRedemptionRequestPayload -): ImpactAdvocateProgramKey { - return payload.programKey ?? ImpactAdvocateProgramKey.KiloClaw; -} - -function buildFailurePayload(result: ImpactAdvocateDispatchResult): Record { - return { - failureKind: result.ok ? null : result.failureKind, - responseBody: result.responseBody ?? null, - error: result.ok ? null : (result.error ?? null), - }; -} - -async function persistRewardRedemptionFailure(params: { - redemptionId: string; - attemptCount: number; - result: ImpactAdvocateDispatchResult; - stage: 'lookup' | 'redeem'; - terminal?: boolean; -}): Promise<'retried' | 'failed'> { - const terminal = - params.terminal ?? (!params.result.ok && params.result.failureKind === 'http_4xx'); - const responsePayload = buildFailurePayload(params.result); - await db - .update(impact_advocate_reward_redemptions) - .set({ - state: terminal - ? ImpactAdvocateRewardRedemptionState.Failed - : ImpactAdvocateRewardRedemptionState.Retrying, - attempt_count: params.attemptCount, - next_retry_at: terminal ? null : nextReportRetryAt(params.attemptCount), - response_status_code: params.result.ok ? null : (params.result.statusCode ?? null), - ...(params.stage === 'lookup' - ? { lookup_response_payload: responsePayload } - : { redeem_response_payload: responsePayload }), - }) - .where(eq(impact_advocate_reward_redemptions.id, params.redemptionId)); - - if (terminal) { - console.error('[kiloclaw-referrals] Impact Advocate reward redemption failed permanently', { - redemptionId: params.redemptionId, - stage: params.stage, - statusCode: params.result.ok ? null : (params.result.statusCode ?? null), - failureKind: params.result.ok ? null : params.result.failureKind, - }); - return 'failed'; - } - - return 'retried'; -} - -async function dispatchImpactAdvocateRewardRedemptionById( - redemptionId: string -): Promise<'redeemed' | 'retried' | 'failed'> { - const redemption = await db.query.impact_advocate_reward_redemptions.findFirst({ - where: eq(impact_advocate_reward_redemptions.id, redemptionId), - }); - if (!redemption) return 'failed'; - if (redemption.state === ImpactAdvocateRewardRedemptionState.Redeemed) return 'redeemed'; - if (redemption.state === ImpactAdvocateRewardRedemptionState.Failed) return 'failed'; - - const attemptCount = redemption.attempt_count + 1; - if (!isRewardRedemptionRequestPayload(redemption.request_payload)) { - await db - .update(impact_advocate_reward_redemptions) - .set({ - state: ImpactAdvocateRewardRedemptionState.Failed, - attempt_count: attemptCount, - redeem_response_payload: { error: 'missing_request_payload' } satisfies Record< - string, - unknown - >, - }) - .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); - return 'failed'; - } - - const programKey = getRewardRedemptionProgramKey(redemption.request_payload); - const advocateScope = - programKey === ImpactAdvocateProgramKey.KiloClaw ? undefined : { programKey }; - - const lookupResult = advocateScope - ? await sendImpactAdvocateRewardLookupPayload(redemption.request_payload.lookup, advocateScope) - : await sendImpactAdvocateRewardLookupPayload(redemption.request_payload.lookup); - if (!lookupResult.ok) { - return await persistRewardRedemptionFailure({ - redemptionId: redemption.id, - attemptCount, - result: lookupResult, - stage: 'lookup', - }); - } - - const persistedImpactRewardId = redemption.impact_reward_id?.trim() || null; - const impactRewardId = - persistedImpactRewardId ?? - selectImpactAdvocateRewardId({ - rewards: lookupResult.rewards ?? [], - amount: redemption.request_payload.redemption.amount, - unit: redemption.request_payload.redemption.unit, - }); - if (!impactRewardId) { - await db - .update(impact_advocate_reward_redemptions) - .set({ - state: ImpactAdvocateRewardRedemptionState.Retrying, - attempt_count: attemptCount, - next_retry_at: nextReportRetryAt(attemptCount), - response_status_code: lookupResult.statusCode ?? null, - lookup_response_payload: { - error: 'impact_reward_not_found', - responseBody: lookupResult.responseBody ?? null, - } satisfies Record, - }) - .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); - return 'retried'; - } - - if (!persistedImpactRewardId) { - await db - .update(impact_advocate_reward_redemptions) - .set({ - impact_reward_id: impactRewardId, - lookup_response_payload: { - selectedRewardId: impactRewardId, - responseBody: lookupResult.responseBody ?? null, - } satisfies Record, - }) - .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); - } - - const redemptionPayload = { - rewardId: impactRewardId, - ...redemption.request_payload.redemption, - }; - const redeemResult = advocateScope - ? await sendImpactAdvocateRewardRedemptionPayload(redemptionPayload, advocateScope) - : await sendImpactAdvocateRewardRedemptionPayload(redemptionPayload); - const isIdempotentAlreadyRedeemed = - !redeemResult.ok && - persistedImpactRewardId === impactRewardId && - isAlreadyRedeemedResponse(redeemResult.responseBody); - if (!redeemResult.ok && !isIdempotentAlreadyRedeemed) { - return await persistRewardRedemptionFailure({ - redemptionId: redemption.id, - attemptCount, - result: redeemResult, - stage: 'redeem', - }); - } - - await db - .update(impact_advocate_reward_redemptions) - .set({ - state: ImpactAdvocateRewardRedemptionState.Redeemed, - impact_reward_id: impactRewardId, - attempt_count: attemptCount, - next_retry_at: null, - redeemed_at: new Date().toISOString(), - response_status_code: redeemResult.statusCode ?? null, - lookup_response_payload: { - selectedRewardId: impactRewardId, - responseBody: lookupResult.responseBody ?? null, - } satisfies Record, - redeem_response_payload: redeemResult.ok - ? ({ responseBody: redeemResult.responseBody ?? null } satisfies Record) - : ({ - alreadyRedeemed: true, - responseBody: redeemResult.responseBody ?? null, - } satisfies Record), - }) - .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); - - return 'redeemed'; -} - -async function queueMissingImpactAdvocateRewardRedemptions(limit: number): Promise { - const rows = await db - .select({ id: impact_referral_rewards.id }) - .from(impact_referral_rewards) - .where( - and( - or( - and( - eq(impact_referral_rewards.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloClawFreeMonth), - eq(impact_referral_rewards.status, ImpactReferralRewardStatus.Applied) - ), - and( - eq(impact_referral_rewards.product, ImpactReferralProduct.KiloPass), - eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloPassBonus), - inArray(impact_referral_rewards.status, [ - ImpactReferralRewardStatus.Pending, - ImpactReferralRewardStatus.Earned, - ImpactReferralRewardStatus.Applied, - ]), - sql`${impact_referral_rewards.reward_amount_usd} > 0` - ) - ), - sql`NOT EXISTS ( - SELECT 1 - FROM ${impact_advocate_reward_redemptions} - WHERE ${impact_advocate_reward_redemptions.reward_id} = ${impact_referral_rewards.id} - )` - ) - ) - .orderBy(asc(impact_referral_rewards.earned_at), asc(impact_referral_rewards.created_at)) - .limit(limit); - - for (const row of rows) { - await queueImpactAdvocateRewardRedemption({ rewardId: row.id, database: db }); - } -} - -export async function dispatchQueuedImpactAdvocateRewardRedemptions(params?: { - limit?: number; -}): Promise { - const limit = params?.limit ?? 100; - await queueMissingImpactAdvocateRewardRedemptions(limit); - const nowIso = new Date().toISOString(); - const rows = await db - .update(impact_advocate_reward_redemptions) - .set({ - state: ImpactAdvocateRewardRedemptionState.Retrying, - next_retry_at: nextReportClaimExpiresAt(), - }) - .where( - and( - or( - eq(impact_advocate_reward_redemptions.state, ImpactAdvocateRewardRedemptionState.Queued), - eq(impact_advocate_reward_redemptions.state, ImpactAdvocateRewardRedemptionState.Retrying) - ), - or( - sql`${impact_advocate_reward_redemptions.next_retry_at} IS NULL`, - lte(impact_advocate_reward_redemptions.next_retry_at, nowIso) - ), - sql`${impact_advocate_reward_redemptions.id} IN ( - SELECT ${impact_advocate_reward_redemptions.id} - FROM ${impact_advocate_reward_redemptions} - WHERE ${or( - eq( - impact_advocate_reward_redemptions.state, - ImpactAdvocateRewardRedemptionState.Queued - ), - eq( - impact_advocate_reward_redemptions.state, - ImpactAdvocateRewardRedemptionState.Retrying - ) - )} - AND ${or( - sql`${impact_advocate_reward_redemptions.next_retry_at} IS NULL`, - lte(impact_advocate_reward_redemptions.next_retry_at, nowIso) - )} - ORDER BY ${impact_advocate_reward_redemptions.created_at}, ${impact_advocate_reward_redemptions.id} - LIMIT ${limit} - )` - ) - ) - .returning({ id: impact_advocate_reward_redemptions.id }); - - const summary: ImpactAdvocateRewardRedemptionDispatchSummary = { - claimed: rows.length, - redeemed: 0, - retried: 0, - failed: 0, - }; - - for (const row of rows) { - const outcome = await dispatchImpactAdvocateRewardRedemptionById(row.id); - if (outcome === 'redeemed') { - summary.redeemed++; - } else if (outcome === 'retried') { - summary.retried++; - } else { - summary.failed++; - } - } - - return summary; -} - -async function persistImpactReportReversal(params: { - reportId: string; - reason: AdverseReferralPaymentReason; - occurredAt: Date; -}): Promise { - const existing = await getImpactConversionReportById(params.reportId, db); - if (!existing) { - return false; - } - - const existingPayload = existing.response_payload ?? {}; - if (getObjectProperty(existingPayload, 'referralReversal')) { - return false; - } - - const actionId = getImpactActionIdFromResponsePayload(existingPayload); - if (!actionId) { - await db - .update(impact_conversion_reports) - .set({ - response_payload: { - ...existingPayload, - referralReversal: { - reason: params.reason, - occurredAt: params.occurredAt.toISOString(), - status: 'missing_action_id', - }, - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, params.reportId)); - return false; - } - - const result = await reverseImpactAction({ actionId }); - await db - .update(impact_conversion_reports) - .set({ - response_payload: { - ...existingPayload, - referralReversal: { - reason: params.reason, - occurredAt: params.occurredAt.toISOString(), - ok: result.ok, - failureKind: result.ok ? null : result.failureKind, - statusCode: result.ok ? null : (result.statusCode ?? null), - responseBody: result.responseBody ?? null, - }, - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, params.reportId)); - - return result.ok; -} - -export async function markPersonalKiloClawReferralPaymentAdverse(params: { - sourcePaymentId: string; - reason: AdverseReferralPaymentReason; - occurredAt: Date; - paymentProvider?: ImpactReferralPaymentProvider; -}): Promise { - const paymentProvider = params.paymentProvider ?? ImpactReferralPaymentProvider.Credits; - let impactReportId: string | null = null; - - const summary = await db.transaction(async tx => { - const conversion = await tx.query.impact_referral_conversions.findFirst({ - where: and( - eq(impact_referral_conversions.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_conversions.payment_provider, paymentProvider), - eq(impact_referral_conversions.source_payment_id, params.sourcePaymentId) - ), - }); - - if (!conversion) { - return { - conversionId: null, - canceledRewards: 0, - reviewRequiredRewards: 0, - }; - } - - const rewards = await tx - .select() - .from(impact_referral_rewards) - .where(eq(impact_referral_rewards.conversion_id, conversion.id)); - - let canceledRewards = 0; - let reviewRequiredRewards = 0; - for (const reward of rewards) { - if ( - reward.status === KiloClawReferralRewardStatus.Pending || - reward.status === KiloClawReferralRewardStatus.Earned - ) { - await tx - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.Canceled, - review_reason: getAdversePaymentReason(params.reason), - }) - .where(eq(impact_referral_rewards.id, reward.id)); - canceledRewards++; - continue; - } - - if (reward.status === KiloClawReferralRewardStatus.Applied) { - await tx - .update(impact_referral_rewards) - .set({ - status: KiloClawReferralRewardStatus.ReviewRequired, - review_reason: getAdversePaymentReason(params.reason), - }) - .where(eq(impact_referral_rewards.id, reward.id)); - reviewRequiredRewards++; - } - } - - const report = await tx.query.impact_conversion_reports.findFirst({ - where: eq(impact_conversion_reports.conversion_id, conversion.id), - columns: { id: true }, - }); - impactReportId = report?.id ?? null; - - return { - conversionId: conversion.id, - canceledRewards, - reviewRequiredRewards, - }; - }); - - const impactActionReversed = impactReportId - ? await persistImpactReportReversal({ - reportId: impactReportId, - reason: params.reason, - occurredAt: params.occurredAt, - }) - : false; - - return { - ...summary, - impactActionReversed, - }; -} - -async function upsertReferralRelationship(params: { - refereeUserId: string; - referrerUserId: string | null; - sourceTouchId: string; - impactReferralId: string | null; - database: DatabaseClient; -}): Promise { - await params.database - .insert(impact_referrals) - .values({ - product: ImpactReferralProduct.KiloClaw, - referee_user_id: params.refereeUserId, - referrer_user_id: params.referrerUserId, - source_touch_id: params.sourceTouchId, - impact_referral_id: params.impactReferralId, - }) - .onConflictDoUpdate({ - target: [impact_referrals.product, impact_referrals.referee_user_id], - set: { - referrer_user_id: params.referrerUserId, - source_touch_id: params.sourceTouchId, - impact_referral_id: params.impactReferralId, - }, - }); -} - -function buildImpactReferralId(touch: ImpactAttributionTouch): string | null { - return touch.rs_code?.trim() || touch.opaque_tracking_value?.trim() || null; -} - -async function getImpactConversionReportById( - reportId: string, - database: DatabaseClient -): Promise { - const report = await database.query.impact_conversion_reports.findFirst({ - where: eq(impact_conversion_reports.id, reportId), - }); - return report ?? null; -} - -async function persistImpactConversionReportResult(params: { - reportId: string; - result: ImpactDispatchResult; - database?: DatabaseClient; -}): Promise { - const database = getDatabaseClient(params.database); - const existing = await getImpactConversionReportById(params.reportId, database); - if (!existing) return; - - const attemptCount = existing.attempt_count + 1; - if (params.result.ok) { - if ('skipped' in params.result) { - logRewardBearingReferralConfigurationFailure({ - conversionId: existing.conversion_id ?? undefined, - }); - await database - .update(impact_conversion_reports) - .set({ - state: ImpactConversionReportState.Failed, - attempt_count: attemptCount, - next_retry_at: null, - delivered_at: null, - response_status_code: null, - response_payload: { - error: 'missing_reward_bearing_referral_configuration', - delivery: params.result.skipped, - responseBody: params.result.responseBody ?? null, - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, params.reportId)); - return; - } - - await database - .update(impact_conversion_reports) - .set({ - state: ImpactConversionReportState.Delivered, - attempt_count: attemptCount, - next_retry_at: null, - delivered_at: new Date().toISOString(), - response_status_code: null, - response_payload: { - delivery: params.result.delivery ?? null, - responseBody: params.result.responseBody ?? null, - ...('actionId' in params.result ? { actionId: params.result.actionId } : {}), - ...('submissionUri' in params.result - ? { submissionUri: params.result.submissionUri } - : {}), - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, params.reportId)); - return; - } - - const isTerminalFailure = params.result.failureKind === 'http_4xx'; - if (isTerminalFailure) { - console.error('[kiloclaw-referrals] Impact conversion report failed permanently', { - reportId: params.reportId, - conversionId: existing.conversion_id, - statusCode: params.result.statusCode ?? null, - failureKind: params.result.failureKind, - }); - } - - await database - .update(impact_conversion_reports) - .set({ - state: isTerminalFailure - ? ImpactConversionReportState.Failed - : ImpactConversionReportState.Retrying, - attempt_count: attemptCount, - next_retry_at: isTerminalFailure ? null : nextReportRetryAt(attemptCount), - response_status_code: params.result.statusCode ?? null, - response_payload: { - failureKind: params.result.failureKind, - responseBody: params.result.responseBody ?? null, - error: params.result.error ?? null, - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, params.reportId)); -} - -export async function dispatchImpactConversionReportById( - reportId: string -): Promise<'delivered' | 'retried' | 'failed'> { - logImpactReferralDebug('Dispatching Impact referral conversion report', { - reportId, - }); - - const report = await getImpactConversionReportById(reportId, db); - if (!report) { - logImpactReferralDebug('Impact referral conversion report missing before dispatch', { - reportId, - }); - return 'failed'; - } - - if (!isImpactConversionPayload(report.request_payload)) { - await db - .update(impact_conversion_reports) - .set({ - state: ImpactConversionReportState.Failed, - response_payload: { - error: - report.request_payload === null ? 'missing_request_payload' : 'invalid_request_payload', - } satisfies Record, - }) - .where(eq(impact_conversion_reports.id, report.id)); - return 'failed'; - } - const payload = report.request_payload; - - const result = await sendImpactConversionPayload(payload); - await persistImpactConversionReportResult({ reportId: report.id, result }); - const outcome = result.ok - ? 'delivered' - : result.failureKind === 'http_4xx' - ? 'failed' - : 'retried'; - logImpactReferralDebug('Impact referral conversion report dispatch result', { - reportId: report.id, - conversionId: report.conversion_id, - outcome, - ok: result.ok, - failureKind: result.ok ? null : result.failureKind, - statusCode: result.ok ? null : (result.statusCode ?? null), - }); - return outcome; -} - -export async function dispatchQueuedImpactConversionReports(params?: { - limit?: number; -}): Promise { - const limit = params?.limit ?? 100; - const nowIso = new Date().toISOString(); - const rows = await db - .update(impact_conversion_reports) - .set({ - state: ImpactConversionReportState.Retrying, - next_retry_at: nextReportClaimExpiresAt(), - }) - .where( - sql`${impact_conversion_reports.id} IN ( - SELECT ${impact_conversion_reports.id} - FROM ${impact_conversion_reports} - WHERE ${or( - eq(impact_conversion_reports.state, ImpactConversionReportState.Queued), - eq(impact_conversion_reports.state, ImpactConversionReportState.Retrying) - )} - AND ${or( - sql`${impact_conversion_reports.next_retry_at} IS NULL`, - lte(impact_conversion_reports.next_retry_at, nowIso) - )} - ORDER BY ${impact_conversion_reports.created_at}, ${impact_conversion_reports.id} - LIMIT ${limit} - )` - ) - .returning({ id: impact_conversion_reports.id }); - - const summary: ImpactConversionReportDispatchSummary = { - claimed: rows.length, - delivered: 0, - retried: 0, - failed: 0, - }; - - for (const row of rows) { - const outcome = await dispatchImpactConversionReportById(row.id); - if (outcome === 'delivered') { - summary.delivered++; - } else if (outcome === 'retried') { - summary.retried++; - } else { - summary.failed++; - } - } - - return summary; -} - -export async function processPersonalKiloClawPaidConversion(params: { - userId: string; - sourcePaymentId: string; - orderId: string; - paymentProvider?: ImpactReferralPaymentProvider; - amount: number; - currencyCode: string; - itemCategory: string; - itemName: string; - itemSku?: string; - convertedAt: Date; - qualificationContext?: PaidConversionQualificationContext; -}): Promise { - const paymentProvider = params.paymentProvider ?? ImpactReferralPaymentProvider.Credits; - const referralSaleDedupeKey = `impact-referral-sale:${ImpactReferralProduct.KiloClaw}:${paymentProvider}:${params.sourcePaymentId}`; - - logImpactReferralDebug( - 'Processing personal KiloClaw paid conversion for Impact referral attribution', - { - userId: params.userId, - sourcePaymentId: params.sourcePaymentId, - paymentProvider, - orderId: params.orderId, - amount: params.amount, - currencyCode: params.currencyCode, - itemCategory: params.itemCategory, - qualificationSourceType: params.qualificationContext?.sourceType ?? null, - qualificationOverrideEligible: params.qualificationContext?.overrideEligible ?? null, - } - ); - - let impactReportId: string | null = null; - const rewardBeneficiaryUserIds = new Set(); - const disposition = await db.transaction(async tx => { - const existingConversion = await tx.query.impact_referral_conversions.findFirst({ - where: and( - eq(impact_referral_conversions.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_conversions.payment_provider, paymentProvider), - eq(impact_referral_conversions.source_payment_id, params.sourcePaymentId) - ), - }); - - if (existingConversion) { - const overrideDisqualificationReason = - params.qualificationContext?.sourceType && - params.qualificationContext.sourceType !== 'normal' - ? getQualificationDisqualificationReason(params.qualificationContext.sourceType) - : null; - const canReprocessWithAdminOverride = - params.qualificationContext?.overrideEligible === true && - existingConversion.qualified === false && - existingConversion.disqualification_reason === overrideDisqualificationReason; - - if (canReprocessWithAdminOverride) { - await tx - .delete(impact_referral_conversions) - .where(eq(impact_referral_conversions.id, existingConversion.id)); - } else { - return { - shouldEnqueueAffiliateSale: - existingConversion.winning_touch_type === KiloClawReferralWinningTouchType.Affiliate, - winningTouchType: existingConversion.winning_touch_type, - conversionId: existingConversion.id, - disqualificationReason: existingConversion.disqualification_reason, - } satisfies KiloClawPaidConversionDisposition; - } - } - - const [user] = await tx - .select({ - id: kilocode_users.id, - createdAt: kilocode_users.created_at, - email: kilocode_users.google_user_email, - normalizedEmail: kilocode_users.normalized_email, - }) - .from(kilocode_users) - .where(eq(kilocode_users.id, params.userId)) - .limit(1); - - if (!user) { - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: 'user_missing', - } satisfies KiloClawPaidConversionDisposition; - } - - const explicitDisqualificationReason = - params.qualificationContext?.sourceType && - params.qualificationContext.sourceType !== 'normal' && - !params.qualificationContext.overrideEligible - ? getQualificationDisqualificationReason(params.qualificationContext.sourceType) - : null; - if (explicitDisqualificationReason) { - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: explicitDisqualificationReason, - } satisfies KiloClawPaidConversionDisposition; - } - - const heuristicDisqualificationReason = await getHeuristicSourcePaymentDisqualificationReason({ - sourcePaymentId: params.sourcePaymentId, - database: tx, - }); - if (heuristicDisqualificationReason && !params.qualificationContext?.overrideEligible) { - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: heuristicDisqualificationReason, - } satisfies KiloClawPaidConversionDisposition; - } - - const currentPersonalSubscription = await resolveCurrentPersonalSubscriptionRow({ - userId: params.userId, - dbOrTx: tx, - }); - if (!currentPersonalSubscription) { - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: referralDisqualificationReason('non_personal_subscription'), - } satisfies KiloClawPaidConversionDisposition; - } - - const hasAdminAdjustedSubscription = await hasAdminOverrideHistory({ - subscriptionId: currentPersonalSubscription.subscription.id, - database: tx, - }); - if (hasAdminAdjustedSubscription && !params.qualificationContext?.overrideEligible) { - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: referralDisqualificationReason('admin_adjusted_subscription'), - } satisfies KiloClawPaidConversionDisposition; - } - - const monetizedPeriods = await countMonetizedKiloClawPaymentPeriods(params.userId, tx); - if (monetizedPeriods > 1) { - const hasPreservedAffiliateSale = await hasSaleAttributedAffiliateTouch({ - userId: params.userId, - database: tx, - }); - - return { - shouldEnqueueAffiliateSale: hasPreservedAffiliateSale, - winningTouchType: hasPreservedAffiliateSale - ? KiloClawReferralWinningTouchType.Affiliate - : KiloClawReferralWinningTouchType.None, - conversionId: null, - disqualificationReason: 'not_first_paid_period', - } satisfies KiloClawPaidConversionDisposition; - } - - const touches = await findAcceptedUserTouches({ - userId: params.userId, - convertedAt: params.convertedAt, - database: tx, - }); - const resolution = resolveWinningAttributionTouch({ - product: ImpactReferralProduct.KiloClaw, - touches, - convertedAt: params.convertedAt, - }); - - logImpactReferralDebug('Resolved KiloClaw Impact attribution touches for paid conversion', { - userId: params.userId, - sourcePaymentId: params.sourcePaymentId, - touchCount: touches.length, - affiliateTouchCount: touches.filter( - touch => touch.touch_type === ImpactAttributionTouchType.Affiliate - ).length, - referralTouchCount: touches.filter( - touch => touch.touch_type === ImpactAttributionTouchType.Referral - ).length, - winner: resolution.winner, - affiliateTouchId: resolution.affiliateTouch?.id ?? null, - referralTouchId: resolution.referralTouch?.id ?? null, - }); - - if (resolution.winner === 'none') { - const [conversion] = await tx - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.userId, - referrer_user_id: null, - source_touch_id: null, - winning_touch_type: KiloClawReferralWinningTouchType.None, - source_payment_id: params.sourcePaymentId, - payment_provider: paymentProvider, - qualified: false, - disqualification_reason: referralDisqualificationReason('no_valid_attribution'), - converted_at: params.convertedAt.toISOString(), - }) - .returning({ id: impact_referral_conversions.id }); - - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.None, - conversionId: conversion?.id ?? null, - disqualificationReason: referralDisqualificationReason('no_valid_attribution'), - } satisfies KiloClawPaidConversionDisposition; - } - - if (resolution.winner === 'affiliate') { - await markAffiliateTouchSaleAttributed({ - database: tx, - affiliateTouchId: resolution.affiliateTouch.id, - convertedAt: params.convertedAt, - }); - - const [conversion] = await tx - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.userId, - referrer_user_id: null, - source_touch_id: resolution.affiliateTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Affiliate, - source_payment_id: params.sourcePaymentId, - payment_provider: paymentProvider, - qualified: false, - disqualification_reason: referralDisqualificationReason('affiliate_won'), - converted_at: params.convertedAt.toISOString(), - }) - .returning({ id: impact_referral_conversions.id }); - - return { - shouldEnqueueAffiliateSale: true, - winningTouchType: KiloClawReferralWinningTouchType.Affiliate, - conversionId: conversion?.id ?? null, - disqualificationReason: referralDisqualificationReason('affiliate_won'), - } satisfies KiloClawPaidConversionDisposition; - } - - const referrerUserId = await resolveReferrerUserIdFromReferralTouch({ - referralTouch: resolution.referralTouch, - database: tx, - }); - await upsertReferralRelationship({ - refereeUserId: params.userId, - referrerUserId, - sourceTouchId: resolution.referralTouch.id, - impactReferralId: buildImpactReferralId(resolution.referralTouch), - database: tx, - }); - logImpactReferralDebug('Upserted KiloClaw Impact referral relationship', { - refereeUserId: params.userId, - referrerUserId, - sourceTouchId: resolution.referralTouch.id, - impactReferralIdPresent: Boolean(buildImpactReferralId(resolution.referralTouch)?.trim()), - }); - - const deletedUser = await hasDeletedUserEmailTombstone({ - normalizedEmail: user.normalizedEmail, - database: tx, - }); - const userExistedBeforeReferral = - new Date(user.createdAt).getTime() < - new Date(resolution.referralTouch.touched_at).getTime() && - !wasReferralTouchCapturedDuringSignup({ - userCreatedAt: user.createdAt, - referralTouch: resolution.referralTouch, - }); - const isSelfReferral = referrerUserId !== null && referrerUserId === params.userId; - - if (deletedUser || userExistedBeforeReferral || !referrerUserId || isSelfReferral) { - const disqualificationReason = deletedUser - ? referralDisqualificationReason('deleted_user_tombstone') - : userExistedBeforeReferral - ? referralDisqualificationReason('existing_user_before_touch') - : !referrerUserId - ? referralDisqualificationReason('referrer_unresolved') - : referralDisqualificationReason('self_referral'); - - const [conversion] = await tx - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.userId, - referrer_user_id: referrerUserId, - source_touch_id: resolution.referralTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: params.sourcePaymentId, - payment_provider: paymentProvider, - qualified: false, - disqualification_reason: disqualificationReason, - converted_at: params.convertedAt.toISOString(), - }) - .returning({ id: impact_referral_conversions.id }); - - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.Referral, - conversionId: conversion?.id ?? null, - disqualificationReason, - } satisfies KiloClawPaidConversionDisposition; - } - - if (!getRewardBearingReferralConfigurationState().isConfigured) { - const disqualificationReason = referralDisqualificationReason('missing_configuration'); - logRewardBearingReferralConfigurationFailure({ - sourcePaymentId: params.sourcePaymentId, - userId: params.userId, - }); - - const [conversion] = await tx - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.userId, - referrer_user_id: referrerUserId, - source_touch_id: resolution.referralTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: params.sourcePaymentId, - payment_provider: paymentProvider, - qualified: false, - disqualification_reason: disqualificationReason, - converted_at: params.convertedAt.toISOString(), - }) - .returning({ id: impact_referral_conversions.id }); - - if (!conversion) { - throw new Error( - `Failed to create referral conversion for payment ${params.sourcePaymentId}` - ); - } - - await tx.insert(impact_referral_reward_decisions).values([ - { - conversion_id: conversion.id, - beneficiary_user_id: params.userId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Disqualified, - reason: disqualificationReason, - months_granted: 0, - }, - { - conversion_id: conversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: KiloClawReferralDecisionOutcome.Disqualified, - reason: disqualificationReason, - months_granted: 0, - }, - ]); - - const payload = buildSalePayload({ - customerId: params.userId, - customerEmailHash: hashEmailForImpact(user.email), - eventDate: params.convertedAt, - orderId: params.orderId, - amount: params.amount, - currencyCode: params.currencyCode, - itemCategory: params.itemCategory, - itemName: params.itemName, - itemSku: params.itemSku, - trackingId: null, - }); - - await tx - .insert(impact_conversion_reports) - .values({ - conversion_id: conversion.id, - dedupe_key: referralSaleDedupeKey, - action_tracker_id: IMPACT_ACTION_TRACKER_IDS.sale, - order_id: params.orderId, - state: ImpactConversionReportState.Failed, - request_payload: payload satisfies Record, - response_payload: { - error: 'missing_reward_bearing_referral_configuration', - } satisfies Record, - }) - .onConflictDoNothing({ target: [impact_conversion_reports.dedupe_key] }); - - impactReportId = null; - - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.Referral, - conversionId: conversion.id, - disqualificationReason, - } satisfies KiloClawPaidConversionDisposition; - } - - await lockReferrerRewardCapacity(referrerUserId, tx); - const referrerGrantedMonths = await getGrantedReferrerMonths(referrerUserId, tx); - const referrerAtCap = referrerGrantedMonths >= 12; - - const [conversion] = await tx - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.userId, - referrer_user_id: referrerUserId, - source_touch_id: resolution.referralTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: params.sourcePaymentId, - payment_provider: paymentProvider, - qualified: true, - disqualification_reason: null, - converted_at: params.convertedAt.toISOString(), - }) - .returning({ id: impact_referral_conversions.id }); - - if (!conversion) { - throw new Error(`Failed to create referral conversion for payment ${params.sourcePaymentId}`); - } - - const refereeHasEligibleSubscription = await hasActiveEligiblePersonalSubscription( - params.userId, - tx - ); - const referrerHasEligibleSubscription = await hasActiveEligiblePersonalSubscription( - referrerUserId, - tx - ); - - const [refereeDecision, referrerDecision] = await tx - .insert(impact_referral_reward_decisions) - .values([ - { - conversion_id: conversion.id, - beneficiary_user_id: params.userId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Granted, - reason: null, - months_granted: 1, - }, - { - conversion_id: conversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: referrerAtCap - ? KiloClawReferralDecisionOutcome.CapLimited - : KiloClawReferralDecisionOutcome.Granted, - reason: referrerAtCap ? referralDisqualificationReason('referrer_cap_reached') : null, - months_granted: referrerAtCap ? 0 : 1, - }, - ]) - .returning({ - id: impact_referral_reward_decisions.id, - beneficiary_user_id: impact_referral_reward_decisions.beneficiary_user_id, - beneficiary_role: impact_referral_reward_decisions.beneficiary_role, - outcome: impact_referral_reward_decisions.outcome, - }); - - await tx.insert(impact_referral_rewards).values( - [refereeDecision, referrerDecision] - .filter(decision => decision.outcome === KiloClawReferralDecisionOutcome.Granted) - .map(decision => ({ - conversion_id: conversion.id, - decision_id: decision.id, - beneficiary_user_id: decision.beneficiary_user_id, - beneficiary_role: decision.beneficiary_role, - months_granted: 1, - status: - decision.beneficiary_role === KiloClawReferralBeneficiaryRole.Referee - ? refereeHasEligibleSubscription - ? KiloClawReferralRewardStatus.Earned - : KiloClawReferralRewardStatus.Pending - : referrerHasEligibleSubscription - ? KiloClawReferralRewardStatus.Earned - : KiloClawReferralRewardStatus.Pending, - earned_at: params.convertedAt.toISOString(), - expires_at: - decision.beneficiary_role === KiloClawReferralBeneficiaryRole.Referrer && - !referrerHasEligibleSubscription - ? addMonths(params.convertedAt, 12).toISOString() - : null, - })) - ); - - const payload = buildSalePayload({ - customerId: params.userId, - customerEmailHash: hashEmailForImpact(user.email), - eventDate: params.convertedAt, - orderId: params.orderId, - amount: params.amount, - currencyCode: params.currencyCode, - itemCategory: params.itemCategory, - itemName: params.itemName, - itemSku: params.itemSku, - trackingId: null, - }); - - const [report] = await tx - .insert(impact_conversion_reports) - .values({ - conversion_id: conversion.id, - dedupe_key: referralSaleDedupeKey, - action_tracker_id: IMPACT_ACTION_TRACKER_IDS.sale, - order_id: params.orderId, - state: ImpactConversionReportState.Queued, - request_payload: payload satisfies Record, - }) - .onConflictDoNothing({ target: [impact_conversion_reports.dedupe_key] }) - .returning({ id: impact_conversion_reports.id }); - - const existingReport = - report ?? - (await tx.query.impact_conversion_reports.findFirst({ - where: eq(impact_conversion_reports.dedupe_key, referralSaleDedupeKey), - columns: { id: true }, - })); - impactReportId = existingReport?.id ?? null; - rewardBeneficiaryUserIds.add(params.userId); - rewardBeneficiaryUserIds.add(referrerUserId); - - return { - shouldEnqueueAffiliateSale: false, - winningTouchType: KiloClawReferralWinningTouchType.Referral, - conversionId: conversion.id, - disqualificationReason: null, - } satisfies KiloClawPaidConversionDisposition; - }); - - logImpactReferralDebug( - 'Processed personal KiloClaw paid conversion for Impact referral attribution', - { - userId: params.userId, - sourcePaymentId: params.sourcePaymentId, - shouldEnqueueAffiliateSale: disposition.shouldEnqueueAffiliateSale, - winningTouchType: disposition.winningTouchType, - conversionId: disposition.conversionId, - disqualificationReason: disposition.disqualificationReason, - impactReportId, - rewardBeneficiaryCount: rewardBeneficiaryUserIds.size, - } - ); - - if (impactReportId) { - await dispatchImpactConversionReportById(impactReportId); - } - - if (rewardBeneficiaryUserIds.size > 0) { - try { - logImpactReferralDebug('Processing queued KiloClaw Impact referral rewards', { - sourcePaymentId: params.sourcePaymentId, - beneficiaryCount: rewardBeneficiaryUserIds.size, - }); - await processQueuedKiloClawReferralRewards({ - beneficiaryUserIds: Array.from(rewardBeneficiaryUserIds), - }); - } catch (error) { - console.error('[kiloclaw-referrals] failed to apply queued referral rewards', { - sourcePaymentId: params.sourcePaymentId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - return disposition; -} diff --git a/apps/web/src/lib/impact/referral-attribution.ts b/apps/web/src/lib/impact/referral-attribution.ts new file mode 100644 index 0000000000..52c8afcc8c --- /dev/null +++ b/apps/web/src/lib/impact/referral-attribution.ts @@ -0,0 +1,118 @@ +import 'server-only'; + +import { IMPACT_REFERRAL_TOUCH_VALIDITY_MS } from '@/lib/impact/referral-utils'; +import { type ImpactAttributionTouch } from '@kilocode/db/schema'; +import { ImpactAttributionTouchType, type ImpactReferralProduct } from '@kilocode/db/schema-types'; + +/** + * Conversion-time attribution shared by every Impact referral product. + * + * Referral-priority attribution: a valid referral touch beats a valid affiliate + * touch unless that affiliate touch was already sale-attributed before the + * referral touch happened, which preserves affiliate credit for the initial + * sale and its renewals. + */ +export type WinningAttributionResolution = + | { + winner: 'referral'; + referralTouch: ImpactAttributionTouch; + affiliateTouch: ImpactAttributionTouch | null; + } + | { + winner: 'affiliate'; + affiliateTouch: ImpactAttributionTouch; + referralTouch: ImpactAttributionTouch | null; + } + | { + winner: 'none'; + affiliateTouch: ImpactAttributionTouch | null; + referralTouch: ImpactAttributionTouch | null; + }; + +function hasAcceptedTrackingValue(touch: ImpactAttributionTouch): boolean { + return touch.is_tracking_value_accepted && Boolean(touch.opaque_tracking_value?.trim()); +} + +function isTouchValidAtConversion(touch: ImpactAttributionTouch, convertedAt: Date): boolean { + const touchedAt = new Date(touch.touched_at).getTime(); + const convertedAtMs = convertedAt.getTime(); + // Qualification intentionally ignores the denormalized expires_at column: the referral + // spec defines validity as touched_at + 30 * 24h using server UTC timestamps. + const exactExpiration = touchedAt + IMPACT_REFERRAL_TOUCH_VALIDITY_MS; + return ( + hasAcceptedTrackingValue(touch) && touchedAt <= convertedAtMs && convertedAtMs < exactExpiration + ); +} + +export function resolveWinningAttributionTouch(params: { + product?: ImpactReferralProduct | null; + touches: ImpactAttributionTouch[]; + convertedAt: Date; +}): WinningAttributionResolution { + const scopedTouches = params.product + ? params.touches.filter(touch => touch.product === params.product) + : params.touches; + const validReferralTouches = scopedTouches + .filter( + touch => + touch.touch_type === ImpactAttributionTouchType.Referral && + isTouchValidAtConversion(touch, params.convertedAt) + ) + .sort((a, b) => new Date(a.touched_at).getTime() - new Date(b.touched_at).getTime()); + const validAffiliateTouches = scopedTouches + .filter( + touch => + touch.touch_type === ImpactAttributionTouchType.Affiliate && + isTouchValidAtConversion(touch, params.convertedAt) + ) + .sort((a, b) => new Date(a.touched_at).getTime() - new Date(b.touched_at).getTime()); + + const oldestReferralTouch = validReferralTouches[0] ?? null; + const oldestAffiliateTouch = validAffiliateTouches[0] ?? null; + + if (!oldestReferralTouch && !oldestAffiliateTouch) { + return { + winner: 'none', + affiliateTouch: null, + referralTouch: null, + }; + } + + if (!oldestReferralTouch && oldestAffiliateTouch) { + return { + winner: 'affiliate', + affiliateTouch: oldestAffiliateTouch, + referralTouch: null, + }; + } + + if (!oldestAffiliateTouch && oldestReferralTouch) { + return { + winner: 'referral', + affiliateTouch: null, + referralTouch: oldestReferralTouch, + }; + } + + const preservedAffiliateTouch = validAffiliateTouches.find(touch => { + if (!touch.sale_attributed_at) return false; + return ( + new Date(touch.sale_attributed_at).getTime() < + new Date(oldestReferralTouch.touched_at).getTime() + ); + }); + + if (preservedAffiliateTouch) { + return { + winner: 'affiliate', + affiliateTouch: preservedAffiliateTouch, + referralTouch: oldestReferralTouch, + }; + } + + return { + winner: 'referral', + affiliateTouch: oldestAffiliateTouch, + referralTouch: oldestReferralTouch, + }; +} diff --git a/apps/web/src/lib/impact/referral-delivery.ts b/apps/web/src/lib/impact/referral-delivery.ts new file mode 100644 index 0000000000..04ae213ddb --- /dev/null +++ b/apps/web/src/lib/impact/referral-delivery.ts @@ -0,0 +1,809 @@ +import 'server-only'; + +import { and, asc, eq, inArray, lte, or, sql } from 'drizzle-orm'; + +import { db, type DrizzleTransaction } from '@/lib/drizzle'; +import { + isImpactConfigured, + sendImpactConversionPayload, + type ImpactConversionPayload, + type ImpactDispatchResult, +} from '@/lib/impact'; +import { + isImpactAdvocateConfigured, + sendImpactAdvocateRewardLookupPayload, + sendImpactAdvocateRewardRedemptionPayload, + type ImpactAdvocateDispatchResult, +} from '@/lib/impact/advocate'; +import { logImpactReferralDebug } from '@/lib/impact/debug'; +import { + impact_advocate_reward_redemptions, + impact_conversion_reports, + impact_referral_rewards, + kilocode_users, +} from '@kilocode/db/schema'; +import { + ImpactAdvocateProgramKey, + ImpactAdvocateRewardRedemptionState, + ImpactConversionReportState, + ImpactReferralProduct, + ImpactReferralRewardKind, + ImpactReferralRewardStatus, +} from '@kilocode/db/schema-types'; + +/** + * Delivery of queued Impact referral work: Impact Performance conversion + * reports and Impact Advocate reward redemptions. Both are database-backed + * outboxes drained by the affiliate-events cron, and both are shared by every + * referral product, so eligibility and reward decisions deliberately live in + * the product modules rather than here. + */ + +type DatabaseClient = typeof db | DrizzleTransaction; + +const IMPACT_ADVOCATE_KILO_PASS_REWARD_UNIT = 'Kilo Pass Bonus Credits'; + +export type ImpactConversionReportDispatchSummary = { + claimed: number; + delivered: number; + retried: number; + failed: number; +}; + +export type ImpactAdvocateRewardRedemptionDispatchSummary = { + claimed: number; + redeemed: number; + retried: number; + failed: number; +}; + +export type AdverseReferralPaymentReason = 'chargeback' | 'refund' | 'fraud'; + +function getDatabaseClient(database?: DatabaseClient): DatabaseClient { + return database ?? db; +} + +function outboxBackoffDelayMs(attemptCount: number): number { + const maxDelayMs = 60 * 60 * 1000; + const initialDelayMs = 60 * 1000; + return Math.min(initialDelayMs * 2 ** Math.max(attemptCount, 0), maxDelayMs); +} + +function nextOutboxRetryAt(attemptCount: number): string { + return new Date(Date.now() + outboxBackoffDelayMs(attemptCount)).toISOString(); +} + +function nextOutboxClaimExpiresAt(): string { + return new Date(Date.now() + 15 * 60 * 1000).toISOString(); +} + +export function getRewardBearingReferralConfigurationState() { + const impactPerformanceConfigured = isImpactConfigured(); + const impactAdvocateConfigured = isImpactAdvocateConfigured({ + product: ImpactReferralProduct.KiloPass, + }); + + return { + impactPerformanceConfigured, + impactAdvocateConfigured, + isConfigured: impactPerformanceConfigured && impactAdvocateConfigured, + }; +} + +export function logRewardBearingReferralConfigurationFailure(params: { + sourcePaymentId?: string; + conversionId?: string; + rewardId?: string; + userId?: string; +}): void { + const configurationState = getRewardBearingReferralConfigurationState(); + console.error('[impact-referrals] reward-bearing referral configuration is incomplete', { + ...params, + impactPerformanceConfigured: configurationState.impactPerformanceConfigured, + impactAdvocateConfigured: configurationState.impactAdvocateConfigured, + }); +} + +function getObjectProperty(record: unknown, key: string): unknown { + if (typeof record !== 'object' || record === null) { + return undefined; + } + + if (!Object.prototype.hasOwnProperty.call(record, key)) { + return undefined; + } + + return Reflect.get(record, key); +} + +function getCaseInsensitiveObjectProperty(record: unknown, key: string): unknown { + if (typeof record !== 'object' || record === null) { + return undefined; + } + + const keys = Object.keys(record); + const matchedKey = keys.find(candidate => candidate.toLowerCase() === key.toLowerCase()); + return matchedKey ? Reflect.get(record, matchedKey) : undefined; +} + +function getStringProperty(record: unknown, keys: string[]): string | null { + for (const key of keys) { + const value = getCaseInsensitiveObjectProperty(record, key); + if (typeof value === 'string' && value.trim()) return value.trim(); + } + return null; +} + +function getNumberProperty(record: unknown, keys: string[]): number | null { + for (const key of keys) { + const value = getCaseInsensitiveObjectProperty(record, key); + if (typeof value === 'number' && Number.isFinite(value)) return value; + if (typeof value === 'string' && value.trim()) { + const parsed = Number(value); + if (Number.isFinite(parsed)) return parsed; + } + } + return null; +} + +function rewardHasUnit(reward: unknown, unit: string): boolean { + const unitValue = + getStringProperty(reward, ['unit', 'Unit', 'currency']) ?? + getStringProperty(getCaseInsensitiveObjectProperty(reward, 'credit'), ['unit', 'Unit']) ?? + getStringProperty(getCaseInsensitiveObjectProperty(reward, 'value'), ['unit', 'Unit']); + return !unitValue || unitValue.toLowerCase() === unit.toLowerCase(); +} + +function rewardHasAmount(reward: unknown, amount: number): boolean { + const amountValue = + getNumberProperty(reward, ['amount', 'Amount', 'remainingAmount', 'RemainingAmount']) ?? + getNumberProperty(getCaseInsensitiveObjectProperty(reward, 'credit'), ['amount', 'Amount']) ?? + getNumberProperty(getCaseInsensitiveObjectProperty(reward, 'value'), ['amount', 'Amount']); + return amountValue === null || amountValue >= amount; +} + +function rewardIsCredit(reward: unknown): boolean { + const type = getStringProperty(reward, ['type', 'Type', 'rewardType', 'RewardType']); + return !type || type.toUpperCase() === 'CREDIT'; +} + +function rewardIsRedeemable(reward: unknown): boolean { + const status = getStringProperty(reward, ['status', 'Status', 'state', 'State']); + if (status) { + const normalizedStatus = status.toUpperCase().replaceAll(' ', '_'); + if ( + normalizedStatus === 'REDEEMED' || + normalizedStatus === 'CANCELLED' || + normalizedStatus === 'CANCELED' + ) { + return false; + } + } + + const redeemed = getCaseInsensitiveObjectProperty(reward, 'redeemed'); + if (redeemed === true) return false; + + const terminalTimestamps = [ + 'redeemedAt', + 'dateRedeemed', + 'cancelledAt', + 'canceledAt', + 'dateCancelled', + 'dateCanceled', + ]; + return !terminalTimestamps.some(key => Boolean(getCaseInsensitiveObjectProperty(reward, key))); +} + +function getImpactAdvocateRewardId(reward: unknown): string | null { + return getStringProperty(reward, ['id', 'Id', 'ID', 'rewardId', 'RewardId']); +} + +function selectImpactAdvocateRewardId(params: { + rewards: unknown[]; + amount: number; + unit: string; +}): string | null { + for (const reward of params.rewards) { + const rewardId = getImpactAdvocateRewardId(reward); + if ( + rewardId && + rewardIsCredit(reward) && + rewardHasUnit(reward, params.unit) && + rewardHasAmount(reward, params.amount) && + rewardIsRedeemable(reward) + ) { + return rewardId; + } + } + + return null; +} + +function isAlreadyRedeemedResponse(responseBody: string | null | undefined): boolean { + const normalized = responseBody?.toLowerCase() ?? ''; + return normalized.includes('already') && normalized.includes('redeem'); +} + +/** + * Queue Impact Advocate reward redemption so Impact reporting matches local + * allocation state. Redemption is reporting-only: it never gates local reward + * eligibility, application, cancellation, or reversal. + */ +export async function queueImpactAdvocateRewardRedemption(params: { + rewardId: string; + database: DatabaseClient; +}): Promise { + const [reward] = await params.database + .select({ + id: impact_referral_rewards.id, + beneficiaryUserId: impact_referral_rewards.beneficiary_user_id, + rewardAmountUsd: impact_referral_rewards.reward_amount_usd, + status: impact_referral_rewards.status, + product: impact_referral_rewards.product, + rewardKind: impact_referral_rewards.reward_kind, + email: kilocode_users.google_user_email, + }) + .from(impact_referral_rewards) + .innerJoin(kilocode_users, eq(kilocode_users.id, impact_referral_rewards.beneficiary_user_id)) + .where(eq(impact_referral_rewards.id, params.rewardId)) + .limit(1); + + if (!reward) { + return; + } + + const isRedeemableKiloPassReward = + reward.product === ImpactReferralProduct.KiloPass && + reward.rewardKind === ImpactReferralRewardKind.KiloPassBonus && + (reward.status === ImpactReferralRewardStatus.Pending || + reward.status === ImpactReferralRewardStatus.Earned || + reward.status === ImpactReferralRewardStatus.Applied) && + reward.rewardAmountUsd !== null && + reward.rewardAmountUsd > 0; + + if (!isRedeemableKiloPassReward) { + return; + } + + const accountId = reward.email.trim(); + if (!accountId) { + console.error('[impact-referrals] missing beneficiary email for Impact reward redemption', { + rewardId: params.rewardId, + beneficiaryUserId: reward.beneficiaryUserId, + }); + return; + } + + await params.database + .insert(impact_advocate_reward_redemptions) + .values({ + reward_id: reward.id, + dedupe_key: `impact-advocate-reward-redemption:${reward.id}`, + beneficiary_user_id: reward.beneficiaryUserId, + state: ImpactAdvocateRewardRedemptionState.Queued, + request_payload: { + programKey: ImpactAdvocateProgramKey.KiloPass, + lookup: { + accountId, + userId: accountId, + rewardTypeFilter: 'CREDIT', + }, + redemption: { + amount: reward.rewardAmountUsd, + unit: IMPACT_ADVOCATE_KILO_PASS_REWARD_UNIT, + }, + } satisfies Record, + }) + .onConflictDoNothing({ target: [impact_advocate_reward_redemptions.reward_id] }); +} + +type ImpactAdvocateRewardRedemptionRequestPayload = { + programKey: typeof ImpactAdvocateProgramKey.KiloPass; + lookup: { + accountId: string; + userId: string; + rewardTypeFilter: 'CREDIT'; + }; + redemption: { + amount: number; + unit: string; + }; +}; + +function isImpactConversionPayload(payload: unknown): payload is ImpactConversionPayload { + return ( + typeof payload === 'object' && + payload !== null && + typeof getObjectProperty(payload, 'CampaignId') === 'string' && + typeof getObjectProperty(payload, 'ActionTrackerId') === 'number' && + typeof getObjectProperty(payload, 'EventDate') === 'string' && + typeof getObjectProperty(payload, 'OrderId') === 'string' + ); +} + +function isRewardRedemptionRequestPayload( + payload: unknown +): payload is ImpactAdvocateRewardRedemptionRequestPayload { + const lookup = getObjectProperty(payload, 'lookup'); + const redemption = getObjectProperty(payload, 'redemption'); + return ( + typeof lookup === 'object' && + lookup !== null && + typeof redemption === 'object' && + redemption !== null && + getObjectProperty(payload, 'programKey') === ImpactAdvocateProgramKey.KiloPass && + typeof getObjectProperty(lookup, 'accountId') === 'string' && + typeof getObjectProperty(lookup, 'userId') === 'string' && + getObjectProperty(lookup, 'rewardTypeFilter') === 'CREDIT' && + typeof getObjectProperty(redemption, 'amount') === 'number' && + typeof getObjectProperty(redemption, 'unit') === 'string' + ); +} + +/** + * Rows queued before the KiloClaw referral program was retired carry either no + * program key or the KiloClaw one. They must never be redeemed against another + * program, so they terminate instead of being retried forever. + */ +function targetsRetiredAdvocateProgram(payload: unknown): boolean { + const programKey = getObjectProperty(payload, 'programKey'); + return programKey === undefined || programKey === ImpactAdvocateProgramKey.KiloClaw; +} + +function buildFailurePayload(result: ImpactAdvocateDispatchResult): Record { + return { + failureKind: result.ok ? null : result.failureKind, + responseBody: result.responseBody ?? null, + error: result.ok ? null : (result.error ?? null), + }; +} + +async function persistRewardRedemptionFailure(params: { + redemptionId: string; + attemptCount: number; + result: ImpactAdvocateDispatchResult; + stage: 'lookup' | 'redeem'; + terminal?: boolean; +}): Promise<'retried' | 'failed'> { + const terminal = + params.terminal ?? (!params.result.ok && params.result.failureKind === 'http_4xx'); + const responsePayload = buildFailurePayload(params.result); + await db + .update(impact_advocate_reward_redemptions) + .set({ + state: terminal + ? ImpactAdvocateRewardRedemptionState.Failed + : ImpactAdvocateRewardRedemptionState.Retrying, + attempt_count: params.attemptCount, + next_retry_at: terminal ? null : nextOutboxRetryAt(params.attemptCount), + response_status_code: params.result.ok ? null : (params.result.statusCode ?? null), + ...(params.stage === 'lookup' + ? { lookup_response_payload: responsePayload } + : { redeem_response_payload: responsePayload }), + }) + .where(eq(impact_advocate_reward_redemptions.id, params.redemptionId)); + + if (terminal) { + console.error('[impact-referrals] Impact Advocate reward redemption failed permanently', { + redemptionId: params.redemptionId, + stage: params.stage, + statusCode: params.result.ok ? null : (params.result.statusCode ?? null), + failureKind: params.result.ok ? null : params.result.failureKind, + }); + return 'failed'; + } + + return 'retried'; +} + +async function dispatchImpactAdvocateRewardRedemptionById( + redemptionId: string +): Promise<'redeemed' | 'retried' | 'failed'> { + const redemption = await db.query.impact_advocate_reward_redemptions.findFirst({ + where: eq(impact_advocate_reward_redemptions.id, redemptionId), + }); + if (!redemption) return 'failed'; + if (redemption.state === ImpactAdvocateRewardRedemptionState.Redeemed) return 'redeemed'; + if (redemption.state === ImpactAdvocateRewardRedemptionState.Failed) return 'failed'; + + const attemptCount = redemption.attempt_count + 1; + if (!isRewardRedemptionRequestPayload(redemption.request_payload)) { + const error = targetsRetiredAdvocateProgram(redemption.request_payload) + ? 'retired_advocate_program' + : redemption.request_payload === null + ? 'missing_request_payload' + : 'invalid_request_payload'; + await db + .update(impact_advocate_reward_redemptions) + .set({ + state: ImpactAdvocateRewardRedemptionState.Failed, + attempt_count: attemptCount, + redeem_response_payload: { error } satisfies Record, + }) + .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); + return 'failed'; + } + + const advocateScope = { programKey: redemption.request_payload.programKey }; + + const lookupResult = await sendImpactAdvocateRewardLookupPayload( + redemption.request_payload.lookup, + advocateScope + ); + if (!lookupResult.ok) { + return await persistRewardRedemptionFailure({ + redemptionId: redemption.id, + attemptCount, + result: lookupResult, + stage: 'lookup', + }); + } + + const persistedImpactRewardId = redemption.impact_reward_id?.trim() || null; + const impactRewardId = + persistedImpactRewardId ?? + selectImpactAdvocateRewardId({ + rewards: lookupResult.rewards ?? [], + amount: redemption.request_payload.redemption.amount, + unit: redemption.request_payload.redemption.unit, + }); + if (!impactRewardId) { + await db + .update(impact_advocate_reward_redemptions) + .set({ + state: ImpactAdvocateRewardRedemptionState.Retrying, + attempt_count: attemptCount, + next_retry_at: nextOutboxRetryAt(attemptCount), + response_status_code: lookupResult.statusCode ?? null, + lookup_response_payload: { + error: 'impact_reward_not_found', + responseBody: lookupResult.responseBody ?? null, + } satisfies Record, + }) + .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); + return 'retried'; + } + + if (!persistedImpactRewardId) { + await db + .update(impact_advocate_reward_redemptions) + .set({ + impact_reward_id: impactRewardId, + lookup_response_payload: { + selectedRewardId: impactRewardId, + responseBody: lookupResult.responseBody ?? null, + } satisfies Record, + }) + .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); + } + + const redeemResult = await sendImpactAdvocateRewardRedemptionPayload( + { + rewardId: impactRewardId, + ...redemption.request_payload.redemption, + }, + advocateScope + ); + const isIdempotentAlreadyRedeemed = + !redeemResult.ok && + persistedImpactRewardId === impactRewardId && + isAlreadyRedeemedResponse(redeemResult.responseBody); + if (!redeemResult.ok && !isIdempotentAlreadyRedeemed) { + return await persistRewardRedemptionFailure({ + redemptionId: redemption.id, + attemptCount, + result: redeemResult, + stage: 'redeem', + }); + } + + await db + .update(impact_advocate_reward_redemptions) + .set({ + state: ImpactAdvocateRewardRedemptionState.Redeemed, + impact_reward_id: impactRewardId, + attempt_count: attemptCount, + next_retry_at: null, + redeemed_at: new Date().toISOString(), + response_status_code: redeemResult.statusCode ?? null, + lookup_response_payload: { + selectedRewardId: impactRewardId, + responseBody: lookupResult.responseBody ?? null, + } satisfies Record, + redeem_response_payload: redeemResult.ok + ? ({ responseBody: redeemResult.responseBody ?? null } satisfies Record) + : ({ + alreadyRedeemed: true, + responseBody: redeemResult.responseBody ?? null, + } satisfies Record), + }) + .where(eq(impact_advocate_reward_redemptions.id, redemption.id)); + + return 'redeemed'; +} + +async function queueMissingImpactAdvocateRewardRedemptions(limit: number): Promise { + const rows = await db + .select({ id: impact_referral_rewards.id }) + .from(impact_referral_rewards) + .where( + and( + eq(impact_referral_rewards.product, ImpactReferralProduct.KiloPass), + eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloPassBonus), + inArray(impact_referral_rewards.status, [ + ImpactReferralRewardStatus.Pending, + ImpactReferralRewardStatus.Earned, + ImpactReferralRewardStatus.Applied, + ]), + sql`${impact_referral_rewards.reward_amount_usd} > 0`, + sql`NOT EXISTS ( + SELECT 1 + FROM ${impact_advocate_reward_redemptions} + WHERE ${impact_advocate_reward_redemptions.reward_id} = ${impact_referral_rewards.id} + )` + ) + ) + .orderBy(asc(impact_referral_rewards.earned_at), asc(impact_referral_rewards.created_at)) + .limit(limit); + + for (const row of rows) { + await queueImpactAdvocateRewardRedemption({ rewardId: row.id, database: db }); + } +} + +export async function dispatchQueuedImpactAdvocateRewardRedemptions(params?: { + limit?: number; +}): Promise { + const limit = params?.limit ?? 100; + await queueMissingImpactAdvocateRewardRedemptions(limit); + const nowIso = new Date().toISOString(); + const rows = await db + .update(impact_advocate_reward_redemptions) + .set({ + state: ImpactAdvocateRewardRedemptionState.Retrying, + next_retry_at: nextOutboxClaimExpiresAt(), + }) + .where( + and( + or( + eq(impact_advocate_reward_redemptions.state, ImpactAdvocateRewardRedemptionState.Queued), + eq(impact_advocate_reward_redemptions.state, ImpactAdvocateRewardRedemptionState.Retrying) + ), + or( + sql`${impact_advocate_reward_redemptions.next_retry_at} IS NULL`, + lte(impact_advocate_reward_redemptions.next_retry_at, nowIso) + ), + sql`${impact_advocate_reward_redemptions.id} IN ( + SELECT ${impact_advocate_reward_redemptions.id} + FROM ${impact_advocate_reward_redemptions} + WHERE ${or( + eq( + impact_advocate_reward_redemptions.state, + ImpactAdvocateRewardRedemptionState.Queued + ), + eq( + impact_advocate_reward_redemptions.state, + ImpactAdvocateRewardRedemptionState.Retrying + ) + )} + AND ${or( + sql`${impact_advocate_reward_redemptions.next_retry_at} IS NULL`, + lte(impact_advocate_reward_redemptions.next_retry_at, nowIso) + )} + ORDER BY ${impact_advocate_reward_redemptions.created_at}, ${impact_advocate_reward_redemptions.id} + LIMIT ${limit} + )` + ) + ) + .returning({ id: impact_advocate_reward_redemptions.id }); + + const summary: ImpactAdvocateRewardRedemptionDispatchSummary = { + claimed: rows.length, + redeemed: 0, + retried: 0, + failed: 0, + }; + + for (const row of rows) { + const outcome = await dispatchImpactAdvocateRewardRedemptionById(row.id); + if (outcome === 'redeemed') { + summary.redeemed++; + } else if (outcome === 'retried') { + summary.retried++; + } else { + summary.failed++; + } + } + + return summary; +} + +async function getImpactConversionReportById( + reportId: string, + database: DatabaseClient +): Promise { + const report = await database.query.impact_conversion_reports.findFirst({ + where: eq(impact_conversion_reports.id, reportId), + }); + return report ?? null; +} + +async function persistImpactConversionReportResult(params: { + reportId: string; + result: ImpactDispatchResult; + database?: DatabaseClient; +}): Promise { + const database = getDatabaseClient(params.database); + const existing = await getImpactConversionReportById(params.reportId, database); + if (!existing) return; + + const attemptCount = existing.attempt_count + 1; + if (params.result.ok) { + if ('skipped' in params.result) { + logRewardBearingReferralConfigurationFailure({ + conversionId: existing.conversion_id ?? undefined, + }); + await database + .update(impact_conversion_reports) + .set({ + state: ImpactConversionReportState.Failed, + attempt_count: attemptCount, + next_retry_at: null, + delivered_at: null, + response_status_code: null, + response_payload: { + error: 'missing_reward_bearing_referral_configuration', + delivery: params.result.skipped, + responseBody: params.result.responseBody ?? null, + } satisfies Record, + }) + .where(eq(impact_conversion_reports.id, params.reportId)); + return; + } + + await database + .update(impact_conversion_reports) + .set({ + state: ImpactConversionReportState.Delivered, + attempt_count: attemptCount, + next_retry_at: null, + delivered_at: new Date().toISOString(), + response_status_code: null, + response_payload: { + delivery: params.result.delivery ?? null, + responseBody: params.result.responseBody ?? null, + ...('actionId' in params.result ? { actionId: params.result.actionId } : {}), + ...('submissionUri' in params.result + ? { submissionUri: params.result.submissionUri } + : {}), + } satisfies Record, + }) + .where(eq(impact_conversion_reports.id, params.reportId)); + return; + } + + const isTerminalFailure = params.result.failureKind === 'http_4xx'; + if (isTerminalFailure) { + console.error('[impact-referrals] Impact conversion report failed permanently', { + reportId: params.reportId, + conversionId: existing.conversion_id, + statusCode: params.result.statusCode ?? null, + failureKind: params.result.failureKind, + }); + } + + await database + .update(impact_conversion_reports) + .set({ + state: isTerminalFailure + ? ImpactConversionReportState.Failed + : ImpactConversionReportState.Retrying, + attempt_count: attemptCount, + next_retry_at: isTerminalFailure ? null : nextOutboxRetryAt(attemptCount), + response_status_code: params.result.statusCode ?? null, + response_payload: { + failureKind: params.result.failureKind, + responseBody: params.result.responseBody ?? null, + error: params.result.error ?? null, + } satisfies Record, + }) + .where(eq(impact_conversion_reports.id, params.reportId)); +} + +export async function dispatchImpactConversionReportById( + reportId: string +): Promise<'delivered' | 'retried' | 'failed'> { + logImpactReferralDebug('Dispatching Impact referral conversion report', { + reportId, + }); + + const report = await getImpactConversionReportById(reportId, db); + if (!report) { + logImpactReferralDebug('Impact referral conversion report missing before dispatch', { + reportId, + }); + return 'failed'; + } + + if (!isImpactConversionPayload(report.request_payload)) { + await db + .update(impact_conversion_reports) + .set({ + state: ImpactConversionReportState.Failed, + response_payload: { + error: + report.request_payload === null ? 'missing_request_payload' : 'invalid_request_payload', + } satisfies Record, + }) + .where(eq(impact_conversion_reports.id, report.id)); + return 'failed'; + } + const payload = report.request_payload; + + const result = await sendImpactConversionPayload(payload); + await persistImpactConversionReportResult({ reportId: report.id, result }); + const outcome = result.ok + ? 'delivered' + : result.failureKind === 'http_4xx' + ? 'failed' + : 'retried'; + logImpactReferralDebug('Impact referral conversion report dispatch result', { + reportId: report.id, + conversionId: report.conversion_id, + outcome, + ok: result.ok, + failureKind: result.ok ? null : result.failureKind, + statusCode: result.ok ? null : (result.statusCode ?? null), + }); + return outcome; +} + +export async function dispatchQueuedImpactConversionReports(params?: { + limit?: number; +}): Promise { + const limit = params?.limit ?? 100; + const nowIso = new Date().toISOString(); + const rows = await db + .update(impact_conversion_reports) + .set({ + state: ImpactConversionReportState.Retrying, + next_retry_at: nextOutboxClaimExpiresAt(), + }) + .where( + sql`${impact_conversion_reports.id} IN ( + SELECT ${impact_conversion_reports.id} + FROM ${impact_conversion_reports} + WHERE ${or( + eq(impact_conversion_reports.state, ImpactConversionReportState.Queued), + eq(impact_conversion_reports.state, ImpactConversionReportState.Retrying) + )} + AND ${or( + sql`${impact_conversion_reports.next_retry_at} IS NULL`, + lte(impact_conversion_reports.next_retry_at, nowIso) + )} + ORDER BY ${impact_conversion_reports.created_at}, ${impact_conversion_reports.id} + LIMIT ${limit} + )` + ) + .returning({ id: impact_conversion_reports.id }); + + const summary: ImpactConversionReportDispatchSummary = { + claimed: rows.length, + delivered: 0, + retried: 0, + failed: 0, + }; + + for (const row of rows) { + const outcome = await dispatchImpactConversionReportById(row.id); + if (outcome === 'delivered') { + summary.delivered++; + } else if (outcome === 'retried') { + summary.retried++; + } else { + summary.failed++; + } + } + + return summary; +} diff --git a/apps/web/src/lib/impact/referral-utils.test.ts b/apps/web/src/lib/impact/referral-utils.test.ts index 9cebefaa28..3275f43b44 100644 --- a/apps/web/src/lib/impact/referral-utils.test.ts +++ b/apps/web/src/lib/impact/referral-utils.test.ts @@ -44,13 +44,13 @@ describe('impact referral utils', () => { it('parses referral touches and applies a 30 day expiry window', () => { const now = new Date('2026-04-23T10:00:00.000Z'); const touch = parseImpactReferralTouchFromUrl( - 'https://kilo.ai/get-started?_saasquatch=sq-cookie&rsCode=abc&rsShareMedium=email&rsEngagementMedium=link&utm_source=impact', + 'https://kilo.ai/subscriptions/kilo-pass/refer?_saasquatch=sq-cookie&rsCode=abc&rsShareMedium=email&rsEngagementMedium=link&utm_source=impact', now ); expect(touch).toEqual({ - product: 'kiloclaw', - programKey: 'kiloclaw', + product: 'kilo_pass', + programKey: 'kilo_pass', opaqueTrackingValue: 'sq-cookie', trackingValueLength: 9, isTrackingValueAccepted: true, @@ -58,7 +58,7 @@ describe('impact referral utils', () => { rsShareMedium: 'email', rsEngagementMedium: 'link', landingPath: - '/get-started?_saasquatch=sq-cookie&rsCode=abc&rsShareMedium=email&rsEngagementMedium=link&utm_source=impact', + '/subscriptions/kilo-pass/refer?_saasquatch=sq-cookie&rsCode=abc&rsShareMedium=email&rsEngagementMedium=link&utm_source=impact', utmSource: 'impact', utmMedium: null, utmCampaign: null, @@ -69,6 +69,17 @@ describe('impact referral utils', () => { }); }); + it('does not record referral touches that target no live referral program', () => { + expect( + parseImpactReferralTouchFromUrl('https://kilo.ai/get-started?_saasquatch=sq-cookie') + ).toBeNull(); + expect( + parseImpactReferralTouchFromUrl( + 'https://kilo.ai/users/after-sign-in?callbackPath=%2Fclaw%2Fnew&_saasquatch=sq-cookie' + ) + ).toBeNull(); + }); + it('marks Kilo Pass callback paths as Kilo Pass referral touches', () => { const touch = parseImpactReferralTouchFromUrl( 'https://kilo.ai/users/after-sign-in?callbackPath=%2Fsubscriptions%2Fkilo-pass&_saasquatch=pass-cookie' @@ -81,7 +92,7 @@ describe('impact referral utils', () => { it('keeps referral metadata for diagnostics when _saasquatch is missing', () => { const touch = parseImpactReferralTouchFromUrl( - 'https://kilo.ai/get-started?rsCode=abc&rsShareMedium=email' + 'https://kilo.ai/subscriptions/kilo-pass/refer?rsCode=abc&rsShareMedium=email' ); expect(touch?.opaqueTrackingValue).toBeNull(); @@ -93,7 +104,7 @@ describe('impact referral utils', () => { it('ignores over-limit referral values for attribution and metadata', () => { const tooLongValue = 'x'.repeat(IMPACT_OPAQUE_TRACKING_VALUE_MAX_LENGTH + 1); const touch = parseImpactReferralTouchFromUrl( - `https://kilo.ai/get-started?_saasquatch=${tooLongValue}&rsCode=${tooLongValue}&rsShareMedium=email` + `https://kilo.ai/subscriptions/kilo-pass/refer?_saasquatch=${tooLongValue}&rsCode=${tooLongValue}&rsShareMedium=email` ); expect(touch?.opaqueTrackingValue).toBeNull(); diff --git a/apps/web/src/lib/impact/referral-utils.ts b/apps/web/src/lib/impact/referral-utils.ts index c44c770b74..36dedd90cf 100644 --- a/apps/web/src/lib/impact/referral-utils.ts +++ b/apps/web/src/lib/impact/referral-utils.ts @@ -76,24 +76,33 @@ function getCallbackPath(url: URL): string | null { return callbackPath; } -function resolveImpactTouchScope(url: URL): { +function urlTargetsKiloPass(url: URL): boolean { + return pathTargetsKiloPass(url.pathname) || pathTargetsKiloPass(getCallbackPath(url)); +} + +/** + * Kilo Pass is the only live Advocate referral program, so a referral touch that + * does not target it has no program to attribute to and is not recorded. + */ +function resolveImpactReferralTouchScope(url: URL): { product: ImpactReferralProduct; programKey: ImpactAdvocateProgramKey; -} { - const callbackPath = getCallbackPath(url); - if (pathTargetsKiloPass(url.pathname) || pathTargetsKiloPass(callbackPath)) { - return { - product: ImpactReferralProduct.KiloPass, - programKey: ImpactAdvocateProgramKey.KiloPass, - }; - } - +} | null { + if (!urlTargetsKiloPass(url)) return null; return { - product: ImpactReferralProduct.KiloClaw, - programKey: ImpactAdvocateProgramKey.KiloClaw, + product: ImpactReferralProduct.KiloPass, + programKey: ImpactAdvocateProgramKey.KiloPass, }; } +/** + * Affiliate tracking still covers KiloClaw, whose existing subscriptions keep + * renewing, so affiliate touches retain the KiloClaw product scope. + */ +function resolveImpactAffiliateTouchProduct(url: URL): ImpactReferralProduct { + return urlTargetsKiloPass(url) ? ImpactReferralProduct.KiloPass : ImpactReferralProduct.KiloClaw; +} + export function sanitizeOpaqueTrackingValue( value: string | null | undefined ): SanitizedOpaqueTrackingValue { @@ -168,7 +177,11 @@ export function parseImpactReferralTouchFromUrl( } const trackingValue = sanitizeOpaqueTrackingValue(searchParams.get('_saasquatch')); - const scope = resolveImpactTouchScope(url); + const scope = resolveImpactReferralTouchScope(url); + + if (!scope) { + return null; + } return { ...scope, @@ -205,10 +218,8 @@ export function parseImpactAffiliateTouchFromUrl( return null; } - const scope = resolveImpactTouchScope(url); - return { - product: scope.product, + product: resolveImpactAffiliateTouchProduct(url), trackingId: trackingValue.acceptedValue, trackingValueLength: trackingValue.originalLength, isTrackingValueAccepted: trackingValue.isAccepted, diff --git a/apps/web/src/lib/impact/referral.test.ts b/apps/web/src/lib/impact/referral.test.ts index f0c90751ae..a8bf498e5b 100644 --- a/apps/web/src/lib/impact/referral.test.ts +++ b/apps/web/src/lib/impact/referral.test.ts @@ -21,10 +21,8 @@ describe('impact referral participant registration dispatch', () => { process.env.IMPACT_ADVOCATE_ACCOUNT_SID = 'impact-advocate-account-sid'; process.env.IMPACT_ADVOCATE_AUTH_TOKEN = 'impact-advocate-auth-token'; process.env.IMPACT_ADVOCATE_TENANT_ALIAS = 'tenant-alias'; - process.env.IMPACT_ADVOCATE_KILOCLAW_PROGRAM_ID = '51699'; - process.env.IMPACT_ADVOCATE_KILOCLAW_WIDGET_ID = 'p/51699/w/referrerWidget'; - delete process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID; - delete process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID; + process.env.IMPACT_ADVOCATE_KILO_PASS_PROGRAM_ID = '52766'; + process.env.IMPACT_ADVOCATE_KILO_PASS_WIDGET_ID = 'p/52766/w/referrerWidget'; }); afterEach(async () => { @@ -46,7 +44,7 @@ describe('impact referral participant registration dispatch', () => { id: 'sq-hash-id', accountId: 'sq-hash-id', email: 'participant@example.com', - referralCodes: { '51699': 'PARTICIPANT9001' }, + referralCodes: { '52766': 'PARTICIPANT9001' }, referable: true, }), { status: 200 } @@ -99,7 +97,7 @@ describe('impact referral participant registration dispatch', () => { expect(participant.registered_at).toBeTruthy(); expect(participant.last_error_code).toBeNull(); // The advocate's program-scoped SaaSquatch code is now persisted so the - // attribution lookup in kiloclaw-referrals.ts can resolve referrerUserId. + // attribution lookup in kilo-pass-referrals.ts can resolve referrerUserId. expect(participant.opaque_referral_identifier).toBe('PARTICIPANT9001'); const [attempt] = await db.select().from(impact_advocate_registration_attempts); @@ -568,6 +566,7 @@ describe('impact referral participant registration dispatch', () => { normalized_email: 'incumbent@example.com', }); await db.insert(impact_advocate_participants).values({ + program_key: 'kilo_pass', user_id: incumbent.id, advocate_id: incumbent.google_user_email, advocate_account_id: incumbent.google_user_email, @@ -580,7 +579,7 @@ describe('impact referral participant registration dispatch', () => { JSON.stringify({ id: 'sq-hash-id-other', email: 'other@example.com', - referralCodes: { '51699': 'COLLIDING_CODE' }, + referralCodes: { '52766': 'COLLIDING_CODE' }, referable: true, }), { status: 200 } @@ -650,7 +649,7 @@ describe('impact referral participant registration dispatch', () => { JSON.stringify({ id: 'sq-self-id', email: 'advocate@example.com', - referralCodes: { '51699': 'ADVOCATE7777' }, + referralCodes: { '52766': 'ADVOCATE7777' }, referable: true, }), { status: 200 } @@ -709,7 +708,7 @@ describe('impact referral participant registration dispatch', () => { JSON.stringify({ id: 'sq-id', email: 'advocate@example.com', - referralCodes: { '51699': 'ADVOCATE7777' }, + referralCodes: { '52766': 'ADVOCATE7777' }, referable: true, }), { status: 200 } @@ -742,6 +741,7 @@ describe('impact referral participant registration dispatch', () => { }); // Pretend SaaSquatch has already registered them and we have the code. await db.insert(impact_advocate_participants).values({ + program_key: 'kilo_pass', user_id: user.id, advocate_id: user.google_user_email, advocate_account_id: user.google_user_email, diff --git a/apps/web/src/lib/impact/referral.ts b/apps/web/src/lib/impact/referral.ts index af8f715be5..e308b89a23 100644 --- a/apps/web/src/lib/impact/referral.ts +++ b/apps/web/src/lib/impact/referral.ts @@ -59,13 +59,15 @@ function productForProgramKey(programKey: ImpactAdvocateProgramKey): ImpactRefer : ImpactReferralProduct.KiloClaw; } +// Kilo Pass is the only live Advocate program, so it is the fallback when a +// caller supplies neither a product nor a program key. function resolveReferralProgramKey(params: { product?: ImpactReferralProduct | null; programKey?: ImpactAdvocateProgramKey | null; }): ImpactAdvocateProgramKey { if (params.programKey) return params.programKey; - if (params.product === ImpactReferralProduct.KiloPass) return ImpactAdvocateProgramKey.KiloPass; - return ImpactAdvocateProgramKey.KiloClaw; + if (params.product === ImpactReferralProduct.KiloClaw) return ImpactAdvocateProgramKey.KiloClaw; + return ImpactAdvocateProgramKey.KiloPass; } function resolveReferralProduct(params: { @@ -256,7 +258,7 @@ export async function ensureImpactAdvocateParticipantProfile(params: { opaqueReferralIdentifier?: string | null; }): Promise<{ id: string }> { const database = getDatabaseClient(params.database); - const programKey = params.programKey ?? ImpactAdvocateProgramKey.KiloClaw; + const programKey = params.programKey ?? ImpactAdvocateProgramKey.KiloPass; const isConfigured = isImpactAdvocateConfigured({ programKey }); diff --git a/apps/web/src/lib/kiloclaw/credit-billing.ts b/apps/web/src/lib/kiloclaw/credit-billing.ts index 10de967bc1..eae65ac5e5 100644 --- a/apps/web/src/lib/kiloclaw/credit-billing.ts +++ b/apps/web/src/lib/kiloclaw/credit-billing.ts @@ -33,8 +33,6 @@ import { buildAffiliateEventDedupeKey, enqueueAffiliateEventForUser, } from '@/lib/impact/affiliate-events'; -import { processPersonalKiloClawPaidConversion } from '@/lib/impact/kiloclaw-referrals'; -import { ImpactReferralPaymentProvider } from '@kilocode/db/schema-types'; import { maybeIssueKiloPassBonusFromUsageThreshold } from '@/lib/kilo-pass/usage-triggered-bonus'; import { getKiloPassStateForUser, type KiloPassSubscriptionState } from '@/lib/kilo-pass/state'; import { @@ -342,23 +340,6 @@ async function enqueueCreditEnrollmentAffiliateEvents(params: { priceVersion: params.priceVersion, }); - const conversionDisposition = await processPersonalKiloClawPaidConversion({ - userId: params.userId, - sourcePaymentId: params.saleOrderId, - orderId: params.saleOrderId, - paymentProvider: ImpactReferralPaymentProvider.Credits, - amount: params.saleAmountMicrodollars / 1_000_000, - currencyCode: 'usd', - itemCategory, - itemName: getKiloClawAffiliateItemName(params.plan), - itemSku: params.saleItemSku, - convertedAt: params.eventDate, - }); - - if (!conversionDisposition.shouldEnqueueAffiliateSale) { - return; - } - await enqueueAffiliateEventForUser({ userId: params.userId, provider: 'impact', diff --git a/apps/web/src/lib/kiloclaw/stripe-handlers.ts b/apps/web/src/lib/kiloclaw/stripe-handlers.ts index a98bda4caa..7b53091cea 100644 --- a/apps/web/src/lib/kiloclaw/stripe-handlers.ts +++ b/apps/web/src/lib/kiloclaw/stripe-handlers.ts @@ -11,10 +11,7 @@ import { type KiloClawSubscription, } from '@kilocode/db'; import { kiloclaw_subscriptions, kiloclaw_instances, kilocode_users } from '@kilocode/db/schema'; -import { - ImpactReferralPaymentProvider, - type KiloClawSubscriptionStatus, -} from '@kilocode/db/schema-types'; +import { type KiloClawSubscriptionStatus } from '@kilocode/db/schema-types'; import { getClawPlanForStripePriceId, getStripePriceIdForClawPlan, @@ -37,7 +34,6 @@ import { buildAffiliateEventDedupeKey, enqueueAffiliateEventForUser, } from '@/lib/impact/affiliate-events'; -import { processPersonalKiloClawPaidConversion } from '@/lib/impact/kiloclaw-referrals'; import { IMPACT_ORDER_ID_MACRO } from '@/lib/impact'; import { CurrentPersonalSubscriptionResolutionError, @@ -1859,35 +1855,22 @@ export async function handleKiloClawInvoicePaid(params: { invoice.status_transitions?.paid_at != null ? new Date(invoice.status_transitions.paid_at * 1000) : new Date(); - const conversionDisposition = await processPersonalKiloClawPaidConversion({ + await enqueueAffiliateEventForUser({ userId: metadata.kiloUserId, - sourcePaymentId: invoice.id, + provider: 'impact', + eventType: 'sale', + dedupeKey: buildAffiliateEventDedupeKey({ + provider: 'impact', + eventType: 'sale', + entityId: invoice.id, + }), orderId: invoice.id, - paymentProvider: ImpactReferralPaymentProvider.Stripe, amount: invoice.amount_paid / 100, currencyCode: invoice.currency ?? 'usd', - convertedAt: eventDate, + eventDate, ...reportingFields, + stripeChargeId: chargeId ?? undefined, }); - - if (conversionDisposition.shouldEnqueueAffiliateSale) { - await enqueueAffiliateEventForUser({ - userId: metadata.kiloUserId, - provider: 'impact', - eventType: 'sale', - dedupeKey: buildAffiliateEventDedupeKey({ - provider: 'impact', - eventType: 'sale', - entityId: invoice.id, - }), - orderId: invoice.id, - amount: invoice.amount_paid / 100, - currencyCode: invoice.currency ?? 'usd', - eventDate, - ...reportingFields, - stripeChargeId: chargeId ?? undefined, - }); - } } catch (error) { logWarning('Affiliate sale enqueue failed', { stripe_event_id: eventId, diff --git a/apps/web/src/lib/stripe/index.ts b/apps/web/src/lib/stripe/index.ts index 817dd6dcfa..15dffb87a9 100644 --- a/apps/web/src/lib/stripe/index.ts +++ b/apps/web/src/lib/stripe/index.ts @@ -66,7 +66,6 @@ import { handleKiloClawInvoicePaid, } from '@/lib/kiloclaw/stripe-handlers'; import { enqueueImpactSaleReversalForCharge } from '@/lib/impact/affiliate-events'; -import { markPersonalKiloClawReferralPaymentAdverse } from '@/lib/impact/kiloclaw-referrals'; import { markPersonalKiloPassReferralPaymentAdverse } from '@/lib/impact/kilo-pass-referrals'; import { ImpactReferralPaymentProvider } from '@kilocode/db/schema-types'; import { invoiceLooksLikeKiloClawByPriceId } from '@/lib/kiloclaw/stripe-invoice-classifier.server'; @@ -1047,14 +1046,7 @@ export async function processStripePaymentEventHook(event: Stripe.Event) { } ); } - if (affiliateDisputeCharge.saleKind === 'kiloclaw') { - await markPersonalKiloClawReferralPaymentAdverse({ - sourcePaymentId: affiliateDisputeCharge.invoiceId, - paymentProvider: ImpactReferralPaymentProvider.Stripe, - reason: 'chargeback', - occurredAt: new Date(dispute.created * 1000), - }); - } else { + if (affiliateDisputeCharge.saleKind === 'kilo-pass') { await markPersonalKiloPassReferralPaymentAdverse({ sourcePaymentId: affiliateDisputeCharge.invoiceId, paymentProvider: ImpactReferralPaymentProvider.Stripe, @@ -1088,14 +1080,7 @@ export async function processStripePaymentEventHook(event: Stripe.Event) { break; } - if (referralAdverseCharge.saleKind === 'kiloclaw') { - await markPersonalKiloClawReferralPaymentAdverse({ - sourcePaymentId: referralAdverseCharge.invoiceId, - paymentProvider: ImpactReferralPaymentProvider.Stripe, - reason: 'refund', - occurredAt: new Date(charge.created * 1000), - }); - } else { + if (referralAdverseCharge.saleKind === 'kilo-pass') { await markPersonalKiloPassReferralPaymentAdverse({ sourcePaymentId: referralAdverseCharge.invoiceId, paymentProvider: ImpactReferralPaymentProvider.Stripe, @@ -1121,14 +1106,7 @@ export async function processStripePaymentEventHook(event: Stripe.Event) { break; } - if (referralAdverseCharge.saleKind === 'kiloclaw') { - await markPersonalKiloClawReferralPaymentAdverse({ - sourcePaymentId: referralAdverseCharge.invoiceId, - paymentProvider: ImpactReferralPaymentProvider.Stripe, - reason: 'fraud', - occurredAt: new Date(charge.created * 1000), - }); - } else { + if (referralAdverseCharge.saleKind === 'kilo-pass') { await markPersonalKiloPassReferralPaymentAdverse({ sourcePaymentId: referralAdverseCharge.invoiceId, paymentProvider: ImpactReferralPaymentProvider.Stripe, diff --git a/apps/web/src/routers/admin-router.ts b/apps/web/src/routers/admin-router.ts index d553e6ca79..b67808ea5e 100644 --- a/apps/web/src/routers/admin-router.ts +++ b/apps/web/src/routers/admin-router.ts @@ -66,7 +66,7 @@ import { adminBlacklistDomainsRouter } from '@/routers/admin/blacklist-domains-r import { adminRequestLoggingOptInsRouter } from '@/routers/admin/request-logging-opt-ins-router'; import { adminBulkBlockRouter } from '@/routers/admin/bulk-block-router'; import { adminKiloPassRouter } from '@/routers/admin/kilo-pass-router'; -import { adminKiloclawReferralsRouter } from '@/routers/admin/kiloclaw-referrals-router'; +import { adminImpactReferralsRouter } from '@/routers/admin/impact-referrals-router'; import { adminStripeDisputesRouter } from '@/routers/admin/stripe-disputes-router'; import { adminStripeEarlyFraudWarningsRouter } from '@/routers/admin/stripe-early-fraud-warnings-router'; import { adminShellSecurityContentRouter } from '@/routers/admin/shell-security-content-router'; @@ -490,7 +490,7 @@ export const adminRouter = createTRPCRouter({ canManageCredits: userCanManageCredits(currentUser), }; }), - kiloclawReferrals: adminKiloclawReferralsRouter, + impactReferrals: adminImpactReferralsRouter, webhookTriggers: adminWebhookTriggersRouter, github: createTRPCRouter({ getKilocodeOpenPullRequestCounts: adminProcedure.query(async () => { diff --git a/apps/web/src/routers/admin/kiloclaw-referrals-router.test.ts b/apps/web/src/routers/admin/impact-referrals-router.test.ts similarity index 97% rename from apps/web/src/routers/admin/kiloclaw-referrals-router.test.ts rename to apps/web/src/routers/admin/impact-referrals-router.test.ts index bfc0d0d8f6..bd76cd5a13 100644 --- a/apps/web/src/routers/admin/kiloclaw-referrals-router.test.ts +++ b/apps/web/src/routers/admin/impact-referrals-router.test.ts @@ -198,16 +198,16 @@ async function insertReferralInvestigationRow(params: { return referee; } -describe('admin kiloclaw referrals investigation', () => { +describe('admin impact referrals investigation', () => { it('rejects non-admin users', async () => { const caller = await createCallerForUser(nonAdmin.id); await expect( - caller.admin.kiloclawReferrals.investigateReferrer({ search: referrer.id }) + caller.admin.impactReferrals.investigateReferrer({ search: referrer.id }) ).rejects.toMatchObject({ code: 'FORBIDDEN' }); }); - it('searches by referrer email and returns qualified and disqualified referee diagnostics', async () => { + it('searches retired KiloClaw referrals by referrer email and returns referee diagnostics', async () => { const qualifiedReferee = await insertReferralInvestigationRow({ refereeEmail: `qualified-referee-${Math.random()}@example.com`, sourcePaymentId: 'qualified-payment', @@ -224,8 +224,9 @@ describe('admin kiloclaw referrals investigation', () => { }); const caller = await createCallerForUser(admin.id); - const result = await caller.admin.kiloclawReferrals.investigateReferrer({ + const result = await caller.admin.impactReferrals.investigateReferrer({ search: referrer.google_user_email, + product: 'kiloclaw', }); expect(result.product).toBe('kiloclaw'); @@ -324,7 +325,7 @@ describe('admin kiloclaw referrals investigation', () => { }); const caller = await createCallerForUser(admin.id); - const result = await caller.admin.kiloclawReferrals.investigateReferrer({ + const result = await caller.admin.impactReferrals.investigateReferrer({ search: referrer.id, product: 'kilo_pass', }); diff --git a/apps/web/src/routers/admin/kiloclaw-referrals-router.ts b/apps/web/src/routers/admin/impact-referrals-router.ts similarity index 99% rename from apps/web/src/routers/admin/kiloclaw-referrals-router.ts rename to apps/web/src/routers/admin/impact-referrals-router.ts index 3c994e12c7..4fd061a4de 100644 --- a/apps/web/src/routers/admin/kiloclaw-referrals-router.ts +++ b/apps/web/src/routers/admin/impact-referrals-router.ts @@ -26,7 +26,7 @@ const ReferralProductSchema = z.enum([ const ReferralInvestigationInputSchema = z.object({ search: z.string().trim().min(1), - product: ReferralProductSchema.default(ImpactReferralProduct.KiloClaw), + product: ReferralProductSchema.default(ImpactReferralProduct.KiloPass), }); const NullableString = z.string().nullable(); @@ -616,7 +616,7 @@ async function investigateReferrer( }; } -export const adminKiloclawReferralsRouter = createTRPCRouter({ +export const adminImpactReferralsRouter = createTRPCRouter({ investigateReferrer: adminProcedure .input(ReferralInvestigationInputSchema) .output(ReferralInvestigationOutputSchema) diff --git a/apps/web/src/routers/kiloclaw-router.test.ts b/apps/web/src/routers/kiloclaw-router.test.ts index 81e190e17a..0fe67299eb 100644 --- a/apps/web/src/routers/kiloclaw-router.test.ts +++ b/apps/web/src/routers/kiloclaw-router.test.ts @@ -19,12 +19,6 @@ import { kiloclaw_inbound_email_aliases, kiloclaw_inbound_email_reserved_aliases, kiloclaw_instances, - impact_attribution_touches, - impact_referrals, - impact_referral_conversions, - impact_referral_reward_applications, - impact_referral_reward_decisions, - impact_referral_rewards, kiloclaw_subscription_change_log, kiloclaw_subscriptions, } from '@kilocode/db/schema'; @@ -176,59 +170,6 @@ let createCaller: (ctx: { user: Awaited> }) => startedAt: number | null; }>; destroy: () => Promise<{ ok: true }>; - getActivePersonalBillingStatus: () => Promise<{ - subscription: { - referralRewards: { - totalAppliedMonths: number; - applications: Array<{ - role: string; - appliedAt: string; - monthsGranted: number; - previousRenewalBoundary: string; - newRenewalBoundary: string; - }>; - }; - } | null; - }>; - getSubscriptionDetail: (input: { instanceId: string }) => Promise<{ - referralRewards: { - totalAppliedMonths: number; - applications: Array<{ - role: string; - appliedAt: string; - monthsGranted: number; - previousRenewalBoundary: string; - newRenewalBoundary: string; - }>; - }; - }>; - getReferralRewardSummary: () => Promise<{ - rewards: Array<{ - role: string; - status: string; - monthsGranted: number; - earnedAt: string; - appliedAt: string | null; - application: { - previousRenewalBoundary: string; - newRenewalBoundary: string; - } | null; - }>; - totals: { - totalRewards: number; - pendingRewards: number; - totalAppliedMonths: number; - }; - referredPeople: Array<{ - maskedEmail: string | null; - state: string; - rewardGranted: boolean; - }>; - pendingRewardAction: { - showStartReactivateCta: boolean; - pendingRewardCount: number; - }; - }>; // Method syntax (bivariant params) so the real caller's narrower // `source: 'byte'` input stays assignable while tests can pass an arbitrary // string for the input-validation case. @@ -836,402 +777,6 @@ describe('kiloclawRouter start', () => { }); }); -describe('kiloclawRouter getActivePersonalBillingStatus referral rewards', () => { - beforeEach(async () => { - await cleanupDbForTest(); - }); - - async function insertActivePersonalSubscription(userId: string) { - const instanceId = crypto.randomUUID(); - await db.insert(kiloclaw_instances).values({ - id: instanceId, - user_id: userId, - sandbox_id: `ki_${instanceId.replace(/-/g, '')}`, - }); - const [subscription] = await db - .insert(kiloclaw_subscriptions) - .values({ - user_id: userId, - instance_id: instanceId, - payment_source: 'credits', - plan: 'standard', - status: 'active', - current_period_start: '2026-04-01T00:00:00.000Z', - current_period_end: '2026-06-01T00:00:00.000Z', - credit_renewal_at: '2026-06-01T00:00:00.000Z', - }) - .returning({ - id: kiloclaw_subscriptions.id, - instanceId: kiloclaw_subscriptions.instance_id, - }); - - return { - subscriptionId: subscription.id, - instanceId: subscription.instanceId ?? instanceId, - }; - } - - async function insertAppliedReferralReward(params: { - beneficiaryUserId: string; - subscriptionId: string; - role: 'referrer' | 'referee'; - sourcePaymentId: string; - }) { - const referee = await insertTestUser({ - google_user_email: `kiloclaw-reward-referee-${Math.random()}@example.com`, - }); - const [conversion] = await db - .insert(impact_referral_conversions) - .values({ - referee_user_id: referee.id, - referrer_user_id: params.role === 'referrer' ? params.beneficiaryUserId : null, - winning_touch_type: 'referral', - source_payment_id: params.sourcePaymentId, - qualified: true, - converted_at: '2026-04-10T00:00:00.000Z', - }) - .returning({ id: impact_referral_conversions.id }); - const [decision] = await db - .insert(impact_referral_reward_decisions) - .values({ - conversion_id: conversion.id, - beneficiary_user_id: params.beneficiaryUserId, - beneficiary_role: params.role, - outcome: 'granted', - months_granted: 1, - }) - .returning({ id: impact_referral_reward_decisions.id }); - const [reward] = await db - .insert(impact_referral_rewards) - .values({ - conversion_id: conversion.id, - decision_id: decision.id, - beneficiary_user_id: params.beneficiaryUserId, - beneficiary_role: params.role, - months_granted: 1, - status: 'applied', - applies_to_subscription_id: params.subscriptionId, - earned_at: '2026-04-10T00:00:00.000Z', - applied_at: '2026-04-10T00:05:00.000Z', - }) - .returning({ id: impact_referral_rewards.id }); - await db.insert(impact_referral_reward_applications).values({ - reward_id: reward.id, - beneficiary_user_id: params.beneficiaryUserId, - subscription_id: params.subscriptionId, - previous_renewal_boundary: '2026-05-01T00:00:00.000Z', - new_renewal_boundary: '2026-06-01T00:00:00.000Z', - applied_at: '2026-04-10T00:05:00.000Z', - }); - } - - it('returns applied referral rewards for the active personal subscription', async () => { - const user = await insertTestUser({ - google_user_email: `kiloclaw-reward-status-${Math.random()}@example.com`, - }); - const { subscriptionId, instanceId } = await insertActivePersonalSubscription(user.id); - await insertAppliedReferralReward({ - beneficiaryUserId: user.id, - subscriptionId, - role: 'referrer', - sourcePaymentId: `kiloclaw-subscription:${instanceId}:2026-04`, - }); - - const billing = await createCaller({ - user, - }).getActivePersonalBillingStatus(); - - expect(billing.subscription?.referralRewards).toEqual({ - totalAppliedMonths: 1, - applications: [ - { - role: 'referrer', - appliedAt: '2026-04-10T00:05:00.000Z', - monthsGranted: 1, - previousRenewalBoundary: '2026-05-01T00:00:00.000Z', - newRenewalBoundary: '2026-06-01T00:00:00.000Z', - }, - ], - }); - }); - - it('returns an empty referral reward summary when no applications belong to the subscription owner', async () => { - const user = await insertTestUser({ - google_user_email: `kiloclaw-empty-reward-status-${Math.random()}@example.com`, - }); - const otherUser = await insertTestUser({ - google_user_email: `kiloclaw-other-reward-status-${Math.random()}@example.com`, - }); - const { subscriptionId, instanceId } = await insertActivePersonalSubscription(user.id); - await insertAppliedReferralReward({ - beneficiaryUserId: otherUser.id, - subscriptionId, - role: 'referrer', - sourcePaymentId: `kiloclaw-subscription:${instanceId}:other-user`, - }); - - const billing = await createCaller({ - user, - }).getActivePersonalBillingStatus(); - - expect(billing.subscription?.referralRewards).toEqual({ - totalAppliedMonths: 0, - applications: [], - }); - }); - - it('returns rewards for an explicitly viewed user-owned subscription', async () => { - const user = await insertTestUser({ - google_user_email: `kiloclaw-detail-reward-status-${Math.random()}@example.com`, - }); - const { subscriptionId, instanceId } = await insertActivePersonalSubscription(user.id); - await insertAppliedReferralReward({ - beneficiaryUserId: user.id, - subscriptionId, - role: 'referee', - sourcePaymentId: `kiloclaw-subscription:${instanceId}:detail`, - }); - - const detail = await createCaller({ user }).getSubscriptionDetail({ - instanceId, - }); - - expect(detail.referralRewards).toEqual({ - totalAppliedMonths: 1, - applications: [ - { - role: 'referee', - appliedAt: '2026-04-10T00:05:00.000Z', - monthsGranted: 1, - previousRenewalBoundary: '2026-05-01T00:00:00.000Z', - newRenewalBoundary: '2026-06-01T00:00:00.000Z', - }, - ], - }); - }); -}); - -describe('kiloclawRouter getReferralRewardSummary', () => { - beforeEach(async () => { - await cleanupDbForTest(); - }); - - async function insertRewardSummaryReward(params: { - userId: string; - role: 'referrer' | 'referee'; - status: 'pending' | 'applied'; - sourcePaymentId: string; - }) { - const otherUser = await insertTestUser({ - google_user_email: `kiloclaw-summary-other-${Math.random()}@example.com`, - }); - const [conversion] = await db - .insert(impact_referral_conversions) - .values({ - referee_user_id: params.role === 'referee' ? params.userId : otherUser.id, - referrer_user_id: params.role === 'referrer' ? params.userId : otherUser.id, - winning_touch_type: 'referral', - source_payment_id: params.sourcePaymentId, - qualified: true, - converted_at: '2026-04-10T00:00:00.000Z', - }) - .returning({ id: impact_referral_conversions.id }); - const [decision] = await db - .insert(impact_referral_reward_decisions) - .values({ - conversion_id: conversion.id, - beneficiary_user_id: params.userId, - beneficiary_role: params.role, - outcome: 'granted', - months_granted: 1, - }) - .returning({ id: impact_referral_reward_decisions.id }); - const [reward] = await db - .insert(impact_referral_rewards) - .values({ - conversion_id: conversion.id, - decision_id: decision.id, - beneficiary_user_id: params.userId, - beneficiary_role: params.role, - months_granted: 1, - status: params.status, - earned_at: '2026-04-10T00:00:00.000Z', - applied_at: params.status === 'applied' ? '2026-04-10T00:05:00.000Z' : null, - }) - .returning({ id: impact_referral_rewards.id }); - - if (params.status === 'applied') { - await db.insert(impact_referral_reward_applications).values({ - reward_id: reward.id, - beneficiary_user_id: params.userId, - subscription_id: crypto.randomUUID(), - previous_renewal_boundary: '2026-05-01T00:00:00.000Z', - new_renewal_boundary: '2026-06-01T00:00:00.000Z', - applied_at: '2026-04-10T00:05:00.000Z', - }); - } - } - - async function insertReferralRelationship(params: { - referrerId: string; - refereeEmail: string; - sourcePaymentId?: string; - qualified?: boolean; - disqualificationReason?: string | null; - }) { - const referee = await insertTestUser({ - google_user_email: params.refereeEmail, - normalized_email: params.refereeEmail, - }); - const [touch] = await db - .insert(impact_attribution_touches) - .values({ - dedupe_key: `summary-relationship-touch-${params.refereeEmail}`, - user_id: referee.id, - touch_type: 'referral', - provider: 'impact_advocate', - opaque_tracking_value: 'private-cookie-value', - tracking_value_length: 20, - is_tracking_value_accepted: true, - rs_code: 'RS-CUSTOMER', - im_ref: 'private-impact-click', - touched_at: '2026-04-01T00:00:00.000Z', - expires_at: '2026-05-01T00:00:00.000Z', - }) - .returning({ id: impact_attribution_touches.id }); - await db.insert(impact_referrals).values({ - referee_user_id: referee.id, - referrer_user_id: params.referrerId, - source_touch_id: touch.id, - impact_referral_id: 'RS-CUSTOMER', - }); - - if (params.sourcePaymentId) { - await db.insert(impact_referral_conversions).values({ - referee_user_id: referee.id, - referrer_user_id: params.referrerId, - source_touch_id: touch.id, - winning_touch_type: 'referral', - source_payment_id: params.sourcePaymentId, - qualified: params.qualified ?? true, - disqualification_reason: params.disqualificationReason ?? null, - converted_at: '2026-04-10T00:00:00.000Z', - }); - } - } - - it('lists current-user rewards with status and application details', async () => { - const user = await insertTestUser({ - google_user_email: `kiloclaw-summary-${Math.random()}@example.com`, - }); - const otherUser = await insertTestUser({ - google_user_email: `kiloclaw-summary-hidden-${Math.random()}@example.com`, - }); - await insertRewardSummaryReward({ - userId: user.id, - role: 'referrer', - status: 'applied', - sourcePaymentId: 'summary-applied', - }); - await insertRewardSummaryReward({ - userId: user.id, - role: 'referee', - status: 'pending', - sourcePaymentId: 'summary-pending', - }); - await insertRewardSummaryReward({ - userId: otherUser.id, - role: 'referrer', - status: 'applied', - sourcePaymentId: 'summary-other', - }); - - const summary = await createCaller({ user }).getReferralRewardSummary(); - - expect(summary.totals).toEqual({ - totalRewards: 2, - pendingRewards: 1, - totalAppliedMonths: 1, - }); - expect(summary.rewards).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - role: 'referrer', - status: 'applied', - monthsGranted: 1, - earnedAt: '2026-04-10T00:00:00.000Z', - appliedAt: '2026-04-10T00:05:00.000Z', - application: expect.objectContaining({ - previousRenewalBoundary: '2026-05-01T00:00:00.000Z', - newRenewalBoundary: '2026-06-01T00:00:00.000Z', - }), - }), - expect.objectContaining({ - role: 'referee', - status: 'pending', - monthsGranted: 1, - application: null, - }), - ]) - ); - }); - - it('returns customer-safe referred people and pending reward CTA state', async () => { - const user = await insertTestUser({ - google_user_email: `kiloclaw-summary-referrer-${Math.random()}@example.com`, - }); - await insertRewardSummaryReward({ - userId: user.id, - role: 'referrer', - status: 'pending', - sourcePaymentId: 'summary-pending-cta', - }); - await insertReferralRelationship({ - referrerId: user.id, - refereeEmail: 'qualified-referee@example.com', - sourcePaymentId: 'summary-qualified-referee', - qualified: true, - }); - await insertReferralRelationship({ - referrerId: user.id, - refereeEmail: 'signed-up-referee@example.com', - }); - await insertReferralRelationship({ - referrerId: user.id, - refereeEmail: 'disqualified-referee@example.com', - sourcePaymentId: 'summary-disqualified-referee', - qualified: false, - disqualificationReason: 'referral_self_referral', - }); - - const summary = await createCaller({ user }).getReferralRewardSummary(); - - expect(summary.pendingRewardAction).toEqual({ - showStartReactivateCta: true, - pendingRewardCount: 1, - }); - expect(summary.referredPeople).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - maskedEmail: 'q***@example.com', - state: 'reward_granted', - rewardGranted: true, - }), - expect.objectContaining({ - maskedEmail: 's***@example.com', - state: 'waiting_for_paid_conversion', - rewardGranted: false, - }), - ]) - ); - expect(summary.referredPeople).toHaveLength(2); - expect(JSON.stringify(summary.referredPeople)).not.toContain('qualified-referee@example.com'); - expect(JSON.stringify(summary.referredPeople)).not.toContain('private-cookie-value'); - expect(JSON.stringify(summary.referredPeople)).not.toContain('private-impact-click'); - expect(JSON.stringify(summary.referredPeople)).not.toContain('referral_self_referral'); - }); -}); - describe('kiloclawRouter destroy', () => { beforeEach(async () => { await cleanupDbForTest(); diff --git a/apps/web/src/routers/kiloclaw-router.ts b/apps/web/src/routers/kiloclaw-router.ts index c47ca45026..5f96fbbb21 100644 --- a/apps/web/src/routers/kiloclaw-router.ts +++ b/apps/web/src/routers/kiloclaw-router.ts @@ -49,10 +49,6 @@ import { kiloclaw_earlybird_purchases, kiloclaw_subscriptions, kiloclaw_instances, - impact_referrals, - impact_referral_conversions, - impact_referral_reward_applications, - impact_referral_rewards, kiloclaw_email_log, kiloclaw_cli_runs, kiloclaw_scheduled_actions, @@ -65,7 +61,6 @@ import { organizations, } from '@kilocode/db/schema'; import { and, asc, eq, ne, desc, isNull, inArray, sql, like, or } from 'drizzle-orm'; -import { ImpactReferralProduct, ImpactReferralRewardKind } from '@kilocode/db/schema-types'; import { alias } from 'drizzle-orm/pg-core'; import { deleteWorkerTrigger } from '@/lib/webhook-agent/webhook-agent-client'; import { sentryLogger } from '@/lib/utils.server'; @@ -1453,29 +1448,6 @@ const KiloclawCommitRetirementStateSchema = z .enum(['pending_final_term', 'final_term', 'standard_scheduled', 'manual_review']) .nullable(); const KiloclawActivationStateSchema = z.enum(['pending_settlement', 'activated']); -const KiloclawReferralRewardRoleSchema = z.enum(['referrer', 'referee']); -const KiloclawReferralRewardStatusSchema = z.enum([ - 'pending', - 'earned', - 'applied', - 'expired', - 'canceled', - 'reversed', - 'review_required', -]); -const KiloclawSubscriptionReferralRewardsSchema = z.object({ - totalAppliedMonths: z.number(), - applications: z.array( - z.object({ - role: KiloclawReferralRewardRoleSchema, - appliedAt: z.string(), - monthsGranted: z.number(), - previousRenewalBoundary: z.string(), - newRenewalBoundary: z.string(), - }) - ), -}); - const KiloclawPersonalSubscriptionSchema = z.object({ instanceId: z.string().uuid(), sandboxId: z.string(), @@ -1511,51 +1483,11 @@ const KiloclawPersonalSubscriptionSchema = z.object({ currentFundingSource: z.enum(['stripe', 'credits']).nullable(), futureFundingSource: z.enum(['stripe', 'credits']).nullable(), needsSupportReview: z.boolean(), - referralRewards: KiloclawSubscriptionReferralRewardsSchema, }); const KiloclawPersonalSubscriptionsOutputSchema = z.object({ commitPlanAvailable: z.boolean(), subscriptions: z.array(KiloclawPersonalSubscriptionSchema), }); -const KiloclawReferredPersonStateSchema = z.enum(['reward_granted', 'waiting_for_paid_conversion']); -const KiloclawReferralRewardSummarySchema = z.object({ - totals: z.object({ - totalRewards: z.number(), - pendingRewards: z.number(), - totalAppliedMonths: z.number(), - }), - pendingRewardAction: z.object({ - showStartReactivateCta: z.boolean(), - pendingRewardCount: z.number(), - }), - referredPeople: z.array( - z.object({ - maskedEmail: z.string().nullable(), - state: KiloclawReferredPersonStateSchema, - rewardGranted: z.boolean(), - }) - ), - rewards: z.array( - z.object({ - role: KiloclawReferralRewardRoleSchema, - status: KiloclawReferralRewardStatusSchema, - monthsGranted: z.number(), - earnedAt: z.string(), - appliedAt: z.string().nullable(), - expiresAt: z.string().nullable(), - reviewReason: z.string().nullable(), - application: z - .object({ - appliedAt: z.string(), - subscriptionId: z.string().uuid().nullable(), - previousRenewalBoundary: z.string(), - newRenewalBoundary: z.string(), - }) - .nullable(), - }) - ), -}); - const KiloclawBillingHistoryInputSchema = KiloclawInstanceInputSchema.extend({ cursor: z.string().optional(), }); @@ -1571,11 +1503,6 @@ const KiloclawReprovisionCreditEnrollmentResultSchema = z.object({ message: z.string().optional(), }); -type KiloclawSubscriptionReferralRewards = z.infer< - typeof KiloclawSubscriptionReferralRewardsSchema ->; -type KiloclawReferralRewardSummary = z.infer; - type KiloclawPersonalSubscriptionRow = { subscription: typeof kiloclaw_subscriptions.$inferSelect; instance: { @@ -1887,13 +1814,6 @@ async function getPersonalBillingStatus(user: { const renewalCostSource: KiloclawRenewalCostSource | null = hasPaidSubscription ? getKiloclawRenewalCostSource(hasStripeFunding) : null; - const referralRewards = hasPaidSubscription - ? await getAppliedReferralRewardsForSubscription({ - userId: user.id, - subscriptionId: sub.id, - }) - : null; - const subscriptionCommitRetirementState = sub ? await getCommitRetirementDisplayState(sub) : null; const subscriptionIsFinalCommitTerm = sub ? classifyKiloClawCommitTerm(await getCommitRetirementEvidence(sub)) === 'final_term' @@ -1932,10 +1852,6 @@ async function getPersonalBillingStatus(user: { ? 'credits' : (sub.payment_source ?? null), needsSupportReview: subscriptionCommitRetirementState === 'manual_review', - referralRewards: referralRewards ?? { - totalAppliedMonths: 0, - applications: [], - }, } : null; @@ -2143,19 +2059,6 @@ function throwCreditReprovisionRecoveryUnavailable(): never { }); } -function maskCustomerEmail(email: string | null): string | null { - if (!email) return null; - const [localPart, domain] = email.toLowerCase().split('@'); - if (!localPart || !domain) return null; - return `${localPart.slice(0, 1)}***@${domain}`; -} - -function referredPersonState( - qualified: boolean | null -): 'reward_granted' | 'waiting_for_paid_conversion' { - return qualified === true ? 'reward_granted' : 'waiting_for_paid_conversion'; -} - function summarizePersonalBillingStatus(billing: ClawBillingStatus) { const hasActiveInstance = billing.instance?.exists ?? false; const activeInstanceId = hasActiveInstance ? (billing.instance?.id ?? null) : null; @@ -2175,188 +2078,12 @@ function summarizePersonalBillingStatus(billing: ClawBillingStatus) { }; } -async function hasEligiblePersonalSubscriptionForReferralReward(userId: string): Promise { - let currentRow: Awaited>; - try { - currentRow = await resolveCurrentPersonalSubscriptionRow({ - userId, - dbOrTx: db, - }); - } catch (error) { - mapCurrentSubscriptionResolutionError(error); - } - const subscription = currentRow?.subscription; - if (!subscription) return false; - - return ( - subscription.plan !== 'trial' && - subscription.status === 'active' && - !subscription.cancel_at_period_end && - subscription.suspended_at === null && - subscription.past_due_since === null - ); -} - -async function getCustomerReferralRewardSummary( - userId: string -): Promise { - const rows = await db - .select({ - role: impact_referral_rewards.beneficiary_role, - status: impact_referral_rewards.status, - monthsGranted: impact_referral_rewards.months_granted, - earnedAt: impact_referral_rewards.earned_at, - appliedAt: impact_referral_rewards.applied_at, - expiresAt: impact_referral_rewards.expires_at, - reviewReason: impact_referral_rewards.review_reason, - applicationAppliedAt: impact_referral_reward_applications.applied_at, - applicationSubscriptionId: impact_referral_reward_applications.subscription_id, - previousRenewalBoundary: impact_referral_reward_applications.previous_renewal_boundary, - newRenewalBoundary: impact_referral_reward_applications.new_renewal_boundary, - }) - .from(impact_referral_rewards) - .leftJoin( - impact_referral_reward_applications, - eq(impact_referral_reward_applications.reward_id, impact_referral_rewards.id) - ) - .where( - and( - eq(impact_referral_rewards.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloClawFreeMonth), - eq(impact_referral_rewards.beneficiary_user_id, userId) - ) - ) - .orderBy(desc(impact_referral_rewards.earned_at), desc(impact_referral_rewards.created_at)); - - const rewards = rows.map(row => ({ - role: row.role, - status: row.status, - monthsGranted: row.monthsGranted, - earnedAt: normalizeTimestamp(row.earnedAt) ?? row.earnedAt, - appliedAt: normalizeTimestamp(row.appliedAt), - expiresAt: normalizeTimestamp(row.expiresAt), - reviewReason: row.reviewReason, - application: - row.applicationAppliedAt && row.previousRenewalBoundary && row.newRenewalBoundary - ? { - appliedAt: normalizeTimestamp(row.applicationAppliedAt) ?? row.applicationAppliedAt, - subscriptionId: row.applicationSubscriptionId, - previousRenewalBoundary: - normalizeTimestamp(row.previousRenewalBoundary) ?? row.previousRenewalBoundary, - newRenewalBoundary: - normalizeTimestamp(row.newRenewalBoundary) ?? row.newRenewalBoundary, - } - : null, - })); - - const referredRows = await db - .select({ - refereeEmail: kilocode_users.google_user_email, - qualified: impact_referral_conversions.qualified, - }) - .from(impact_referrals) - .innerJoin(kilocode_users, eq(kilocode_users.id, impact_referrals.referee_user_id)) - .leftJoin( - impact_referral_conversions, - and( - eq(impact_referral_conversions.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_conversions.referee_user_id, impact_referrals.referee_user_id), - eq(impact_referral_conversions.referrer_user_id, userId) - ) - ) - .where( - and( - eq(impact_referrals.product, ImpactReferralProduct.KiloClaw), - eq(impact_referrals.referrer_user_id, userId) - ) - ) - .orderBy(desc(impact_referrals.created_at)); - const referredPeople = referredRows - .filter(row => row.qualified !== false) - .map(row => ({ - maskedEmail: maskCustomerEmail(row.refereeEmail), - state: referredPersonState(row.qualified), - rewardGranted: row.qualified === true, - })); - const pendingRewardCount = rewards.filter( - reward => reward.role === 'referrer' && reward.status === 'pending' - ).length; - const hasEligibleSubscription = await hasEligiblePersonalSubscriptionForReferralReward(userId); - - return { - totals: { - totalRewards: rewards.length, - pendingRewards: rewards.filter(reward => reward.status === 'pending').length, - totalAppliedMonths: rewards - .filter(reward => reward.status === 'applied') - .reduce((total, reward) => total + reward.monthsGranted, 0), - }, - pendingRewardAction: { - showStartReactivateCta: pendingRewardCount > 0 && !hasEligibleSubscription, - pendingRewardCount, - }, - referredPeople, - rewards, - }; -} - -async function getAppliedReferralRewardsForSubscription(params: { - userId: string; - subscriptionId: string; -}): Promise { - const rows = await db - .select({ - role: impact_referral_rewards.beneficiary_role, - appliedAt: impact_referral_reward_applications.applied_at, - monthsGranted: impact_referral_rewards.months_granted, - previousRenewalBoundary: impact_referral_reward_applications.previous_renewal_boundary, - newRenewalBoundary: impact_referral_reward_applications.new_renewal_boundary, - }) - .from(impact_referral_reward_applications) - .innerJoin( - impact_referral_rewards, - eq(impact_referral_rewards.id, impact_referral_reward_applications.reward_id) - ) - .where( - and( - eq(impact_referral_reward_applications.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_reward_applications.subscription_id, params.subscriptionId), - eq(impact_referral_reward_applications.beneficiary_user_id, params.userId), - eq(impact_referral_rewards.product, ImpactReferralProduct.KiloClaw), - eq(impact_referral_rewards.reward_kind, ImpactReferralRewardKind.KiloClawFreeMonth), - eq(impact_referral_rewards.applies_to_subscription_id, params.subscriptionId), - eq(impact_referral_rewards.beneficiary_user_id, params.userId), - eq(impact_referral_rewards.status, 'applied') - ) - ) - .orderBy( - asc(impact_referral_reward_applications.applied_at), - asc(impact_referral_reward_applications.created_at) - ); - - return { - totalAppliedMonths: rows.reduce((total, row) => total + row.monthsGranted, 0), - applications: rows.map(row => ({ - role: row.role, - appliedAt: normalizeTimestamp(row.appliedAt) ?? row.appliedAt, - monthsGranted: row.monthsGranted, - previousRenewalBoundary: - normalizeTimestamp(row.previousRenewalBoundary) ?? row.previousRenewalBoundary, - newRenewalBoundary: normalizeTimestamp(row.newRenewalBoundary) ?? row.newRenewalBoundary, - })), - }; -} - async function serializeKiloclawPersonalSubscription( row: KiloclawPersonalSubscriptionRow, hasActiveKiloPass: boolean ) { const hasStripeFunding = Boolean(row.subscription.stripe_subscription_id); const activationState = getKiloClawSubscriptionActivationState(row.subscription); - const referralRewards = await getAppliedReferralRewardsForSubscription({ - userId: row.subscription.user_id, - subscriptionId: row.subscription.id, - }); const commitRetirementState = await getCommitRetirementDisplayState(row.subscription); const isFinalCommitTerm = classifyKiloClawCommitTerm(await getCommitRetirementEvidence(row.subscription)) === @@ -2408,7 +2135,6 @@ async function serializeKiloclawPersonalSubscription( ? 'credits' : (row.subscription.payment_source ?? null), needsSupportReview: commitRetirementState === 'manual_review', - referralRewards, }; } @@ -4929,12 +4655,6 @@ export const kiloclawRouter = createTRPCRouter({ return summarizePersonalBillingStatus(billing); }), - getReferralRewardSummary: baseProcedure - .output(KiloclawReferralRewardSummarySchema) - .query(async ({ ctx }) => { - return await getCustomerReferralRewardSummary(ctx.user.id); - }), - // ── Personal subscription management ───────────────────────────────── listPersonalSubscriptions: baseProcedure diff --git a/dev/seed/AGENTS.md b/dev/seed/AGENTS.md index 26d25f6e84..b517182e64 100644 --- a/dev/seed/AGENTS.md +++ b/dev/seed/AGENTS.md @@ -11,7 +11,6 @@ dev/seed/ preflight.ts Import FIRST; mutates process.env from argv. db.ts Lazy drizzle client. stripe.ts Lazy Stripe test-mode client/customer helpers. - kiloclaw-referrals.ts KiloClaw referral fixtures/helpers. /.ts Topic module. Scope = folder; topic = filename. ``` @@ -41,7 +40,7 @@ Topic files MUST: - `type SeedResult = Record`: flat JSON primitives only; no nested objects; stringify Dates. - Return every id/email/handle/balance needed by follow-up commands; the runner formats all output from this object. - Support `--help`/`-h` via local `printUsage()` and early return. -- Reset only their own data at start for idempotent reruns. Referral seeds use `cleanupKiloClawReferralSeedScenario`; ad-hoc topics delete by stable ids/emails, stable sandbox prefixes, or `dev-seed:` category prefixes. +- Reset only their own data at start for idempotent reruns. Ad-hoc topics delete by stable ids/emails, stable sandbox prefixes, or `dev-seed:` category prefixes. - Avoid module-level side effects (DB writes/network); no-args listing imports modules. Topic files SHOULD: @@ -65,7 +64,6 @@ Topic files MUST NOT: - `deleteSeedStripeCustomer(id)`: rollback helper; swallows "no such customer". - `lib/stripe.ts` rejects missing/non-`sk_test_...` `STRIPE_SECRET_KEY`. - For seeded users used by Stripe-touching app code (`/profile`, billing pages, KiloClaw subscriptions), create a real Stripe customer. Never use `cus_seed_...`: it causes `StripeInvalidRequestError: No such customer` 400s. Order matches `createUserOnSignIn`: create Stripe customer, insert DB row, delete Stripe customer in `catch` on insert failure. -- `lib/kiloclaw-referrals.ts`: deterministic id/email/payment-id factories (`seedUserId`, `seedEmail`, `seedOpaqueReferralIdentifier`, ...), `cleanupKiloClawReferralSeedScenario`, and `insertSeedUsers`. Use for new referral scenarios so cleanup stays consistent. ## Direct user inserts diff --git a/dev/seed/kiloclaw/referrals-cap-boundary.ts b/dev/seed/kiloclaw/referrals-cap-boundary.ts deleted file mode 100644 index 53c8ddbcee..0000000000 --- a/dev/seed/kiloclaw/referrals-cap-boundary.ts +++ /dev/null @@ -1,278 +0,0 @@ -import { - kiloclaw_referral_conversions, - kiloclaw_referral_reward_decisions, - kiloclaw_referral_rewards, - kiloclaw_referrals, -} from '@kilocode/db/schema'; -import { and, eq } from 'drizzle-orm'; -import { - KiloClawReferralBeneficiaryRole, - KiloClawReferralDecisionOutcome, - KiloClawReferralRewardStatus, - KiloClawReferralWinningTouchType, -} from '@kilocode/db/schema-types'; - -import { getSeedDb } from '../lib/db'; -import type { SeedResult } from '../index'; -import { - addDays, - assertUserCount, - cleanupKiloClawReferralSeedScenario, - insertImpactAdvocateParticipant, - insertPersonalSubscription, - insertSeedUsers, - seedEmail, - seedOpaqueReferralIdentifier, - seedSourcePaymentId, - seedUserId, -} from '../lib/kiloclaw-referrals'; - -const SCENARIO = 'referrals-cap-boundary'; -const SEED_SCOPE = `kiloclaw/${SCENARIO}`; -const referrerUserId = seedUserId(SCENARIO, 'referrer'); -const referrerEmail = seedEmail(SCENARIO, 'referrer'); -const currentRefereeUserId = seedUserId(SCENARIO, 'current-referee'); -const currentRefereeEmail = seedEmail(SCENARIO, 'current-referee'); -const opaqueReferralIdentifier = seedOpaqueReferralIdentifier(SCENARIO, 'primary'); - -function buildHistoricalReferee(i: number) { - const role = `historical-referee-${i}`; - return { - id: seedUserId(SCENARIO, role), - email: seedEmail(SCENARIO, role), - name: `Seed Cap Boundary Referee ${i}`, - }; -} - -export async function run(): Promise { - const db = getSeedDb(); - const historicalReferees = Array.from({ length: 12 }, (_, index) => - buildHistoricalReferee(index + 1) - ); - const userIds = [ - referrerUserId, - currentRefereeUserId, - ...historicalReferees.map(user => user.id), - ]; - - console.log(`[${SEED_SCOPE}] Resetting existing seed data`); - await cleanupKiloClawReferralSeedScenario({ - scenario: SCENARIO, - userIds, - }); - - console.log(`[${SEED_SCOPE}] Inserting referrer plus historical and current referees`); - await insertSeedUsers([ - { - id: referrerUserId, - email: referrerEmail, - name: 'Seed Cap Boundary Referrer', - }, - { - id: currentRefereeUserId, - email: currentRefereeEmail, - name: 'Seed Cap Boundary Current Referee', - }, - ...historicalReferees, - ]); - await assertUserCount({ userIds, expectedCount: userIds.length }); - - console.log( - `[${SEED_SCOPE}] Inserting the referrer participant and an active personal subscription` - ); - await insertImpactAdvocateParticipant({ - userId: referrerUserId, - email: referrerEmail, - opaqueReferralIdentifier, - registeredAt: '2026-01-01T12:00:00.000Z', - }); - const { subscription: referrerSubscription } = await insertPersonalSubscription({ - userId: referrerUserId, - sandboxId: `sandbox-${referrerUserId}`, - name: 'Seed Cap Boundary Referrer', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-12-01T00:00:00.000Z', - currentPeriodEnd: '2027-01-01T00:00:00.000Z', - creditRenewalAt: '2027-01-01T00:00:00.000Z', - }); - - console.log(`[${SEED_SCOPE}] Inserting 12 previously granted referrer months`); - for (const [index, historicalReferee] of historicalReferees.entries()) { - const convertedAt = addDays('2026-01-15T12:00:00.000Z', index * 20); - const [referral] = await db - .insert(kiloclaw_referrals) - .values({ - referee_user_id: historicalReferee.id, - referrer_user_id: referrerUserId, - impact_referral_id: opaqueReferralIdentifier, - }) - .returning({ id: kiloclaw_referrals.id }); - - const [conversion] = await db - .insert(kiloclaw_referral_conversions) - .values({ - referee_user_id: historicalReferee.id, - referrer_user_id: referrerUserId, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: seedSourcePaymentId(SCENARIO, `historical-${index + 1}`), - qualified: true, - converted_at: convertedAt, - }) - .returning({ id: kiloclaw_referral_conversions.id }); - - const [refereeDecision, referrerDecision] = await db - .insert(kiloclaw_referral_reward_decisions) - .values([ - { - conversion_id: conversion.id, - beneficiary_user_id: historicalReferee.id, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - { - conversion_id: conversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - ]) - .returning({ - id: kiloclaw_referral_reward_decisions.id, - beneficiaryRole: kiloclaw_referral_reward_decisions.beneficiary_role, - }); - - const refereeDecisionId = - refereeDecision.beneficiaryRole === 'referee' ? refereeDecision.id : referrerDecision.id; - const referrerDecisionId = - refereeDecision.beneficiaryRole === 'referrer' ? refereeDecision.id : referrerDecision.id; - - await db.insert(kiloclaw_referral_rewards).values([ - { - conversion_id: conversion.id, - decision_id: refereeDecisionId, - beneficiary_user_id: historicalReferee.id, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - months_granted: 1, - status: KiloClawReferralRewardStatus.Earned, - earned_at: convertedAt, - }, - { - conversion_id: conversion.id, - decision_id: referrerDecisionId, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - months_granted: 1, - status: KiloClawReferralRewardStatus.Earned, - applies_to_subscription_id: referrerSubscription.id, - earned_at: convertedAt, - }, - ]); - - console.log( - ` - historical referee ${index + 1}: referral ${referral.id}, conversion ${conversion.id}` - ); - } - - console.log( - `[${SEED_SCOPE}] Inserting the next qualified conversion with a cap-limited referrer outcome` - ); - const [currentReferral] = await db - .insert(kiloclaw_referrals) - .values({ - referee_user_id: currentRefereeUserId, - referrer_user_id: referrerUserId, - impact_referral_id: opaqueReferralIdentifier, - }) - .returning({ id: kiloclaw_referrals.id }); - - const [currentConversion] = await db - .insert(kiloclaw_referral_conversions) - .values({ - referee_user_id: currentRefereeUserId, - referrer_user_id: referrerUserId, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: seedSourcePaymentId(SCENARIO, 'current-13th'), - qualified: true, - converted_at: '2026-12-15T12:00:00.000Z', - }) - .returning({ id: kiloclaw_referral_conversions.id }); - - const [currentRefereeDecision, currentReferrerDecision] = await db - .insert(kiloclaw_referral_reward_decisions) - .values([ - { - conversion_id: currentConversion.id, - beneficiary_user_id: currentRefereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - { - conversion_id: currentConversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: KiloClawReferralDecisionOutcome.CapLimited, - reason: 'referral_referrer_cap_reached', - months_granted: 0, - }, - ]) - .returning({ - id: kiloclaw_referral_reward_decisions.id, - beneficiaryRole: kiloclaw_referral_reward_decisions.beneficiary_role, - }); - - const currentGrantedDecisionId = - currentRefereeDecision.beneficiaryRole === 'referee' - ? currentRefereeDecision.id - : currentReferrerDecision.id; - const currentCapLimitedDecisionId = - currentRefereeDecision.beneficiaryRole === 'referrer' - ? currentRefereeDecision.id - : currentReferrerDecision.id; - - await db.insert(kiloclaw_referral_rewards).values({ - conversion_id: currentConversion.id, - decision_id: currentGrantedDecisionId, - beneficiary_user_id: currentRefereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - months_granted: 1, - status: KiloClawReferralRewardStatus.Earned, - earned_at: '2026-12-15T12:00:00.000Z', - }); - - const referrerGrantedMonths = await db - .select({ id: kiloclaw_referral_reward_decisions.id }) - .from(kiloclaw_referral_reward_decisions) - .where( - and( - eq(kiloclaw_referral_reward_decisions.beneficiary_user_id, referrerUserId), - eq( - kiloclaw_referral_reward_decisions.beneficiary_role, - KiloClawReferralBeneficiaryRole.Referrer - ), - eq(kiloclaw_referral_reward_decisions.outcome, KiloClawReferralDecisionOutcome.Granted) - ) - ); - - console.log(''); - console.log('This fixture represents:'); - console.log('- 12 previously granted referrer reward months already recorded'); - console.log('- a 13th qualified referral where the referee still gets a reward'); - console.log( - '- the referrer decision is recorded as cap-limited with no extra referrer reward row' - ); - - return { - referrerUserId, - currentRefereeUserId, - currentReferralId: currentReferral.id, - currentConversionId: currentConversion.id, - currentCapLimitedDecisionId, - referrerSubscriptionId: referrerSubscription.id, - grantedReferrerMonthsBeforeCapDecision: referrerGrantedMonths.length, - }; -} diff --git a/dev/seed/kiloclaw/referrals-happy-path.ts b/dev/seed/kiloclaw/referrals-happy-path.ts deleted file mode 100644 index 65798f0b85..0000000000 --- a/dev/seed/kiloclaw/referrals-happy-path.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { - credit_transactions, - impact_conversion_reports, - kiloclaw_attribution_touches, - kiloclaw_referral_conversions, - kiloclaw_referral_reward_applications, - kiloclaw_referral_reward_decisions, - kiloclaw_referral_rewards, - kiloclaw_referrals, -} from '@kilocode/db/schema'; -import { - ImpactConversionReportState, - ImpactAttributionTouchProvider, - ImpactAttributionTouchType, - KiloClawReferralBeneficiaryRole, - KiloClawReferralDecisionOutcome, - KiloClawReferralRewardStatus, - KiloClawReferralWinningTouchType, -} from '@kilocode/db/schema-types'; - -import { getSeedDb } from '../lib/db'; -import type { SeedResult } from '../index'; -import { - assertUserCount, - cleanupKiloClawReferralSeedScenario, - insertAppliedRewardChangeLog, - insertImpactAdvocateParticipant, - insertPersonalSubscription, - insertSeedUsers, - seedEmail, - seedLabelForScenario, - seedOpaqueReferralIdentifier, - seedOrderId, - seedSourcePaymentId, - seedUserId, -} from '../lib/kiloclaw-referrals'; - -const SCENARIO = 'referrals-happy-path'; -const SEED_SCOPE = `kiloclaw/${SCENARIO}`; - -const referrerUserId = seedUserId(SCENARIO, 'referrer'); -const refereeUserId = seedUserId(SCENARIO, 'referee'); -const userIds = [referrerUserId, refereeUserId]; -const referrerEmail = seedEmail(SCENARIO, 'referrer'); -const refereeEmail = seedEmail(SCENARIO, 'referee'); -const opaqueReferralIdentifier = seedOpaqueReferralIdentifier(SCENARIO, 'primary'); -const sourcePaymentId = seedSourcePaymentId(SCENARIO, 'period-1'); -const orderId = seedOrderId(SCENARIO, 'period-1'); -const touchedAtAffiliate = '2026-04-10T12:00:00.000Z'; -const touchedAtReferral = '2026-04-11T09:00:00.000Z'; -const convertedAt = '2026-04-15T16:30:00.000Z'; -const previousRenewalBoundary = '2026-05-01T00:00:00.000Z'; -const newRenewalBoundary = '2026-06-01T00:00:00.000Z'; - -export async function run(): Promise { - const db = getSeedDb(); - - console.log(`[${SEED_SCOPE}] Resetting existing seed data`); - await cleanupKiloClawReferralSeedScenario({ - scenario: SCENARIO, - userIds, - }); - - console.log(`[${SEED_SCOPE}] Inserting referrer and referee users`); - await insertSeedUsers([ - { - id: referrerUserId, - email: referrerEmail, - name: 'Seed Referrals Happy Referrer', - }, - { - id: refereeUserId, - email: refereeEmail, - name: 'Seed Referrals Happy Referee', - }, - ]); - await assertUserCount({ userIds, expectedCount: 2 }); - - console.log(`[${SEED_SCOPE}] Inserting active personal subscriptions with applied reward state`); - const { subscription: referrerSubscription } = await insertPersonalSubscription({ - userId: referrerUserId, - sandboxId: `sandbox-${referrerUserId}`, - name: 'Seed Happy Path Referrer', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-04-01T00:00:00.000Z', - currentPeriodEnd: newRenewalBoundary, - creditRenewalAt: newRenewalBoundary, - }); - const { subscription: refereeSubscription } = await insertPersonalSubscription({ - userId: refereeUserId, - sandboxId: `sandbox-${refereeUserId}`, - name: 'Seed Happy Path Referee', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-04-01T00:00:00.000Z', - currentPeriodEnd: newRenewalBoundary, - creditRenewalAt: newRenewalBoundary, - }); - - console.log(`[${SEED_SCOPE}] Inserting registered Advocate participant for the referrer`); - await insertImpactAdvocateParticipant({ - userId: referrerUserId, - email: referrerEmail, - opaqueReferralIdentifier, - registeredAt: '2026-04-01T12:00:00.000Z', - }); - - console.log(`[${SEED_SCOPE}] Inserting affiliate and referral touches for the referee`); - const [affiliateTouch] = await db - .insert(kiloclaw_attribution_touches) - .values({ - dedupe_key: `${seedLabelForScenario(SCENARIO)}:touch:affiliate`, - user_id: refereeUserId, - touch_type: ImpactAttributionTouchType.Affiliate, - provider: ImpactAttributionTouchProvider.ImpactPerformance, - opaque_tracking_value: `${seedLabelForScenario(SCENARIO)}:im-ref`, - tracking_value_length: 42, - is_tracking_value_accepted: true, - im_ref: `${seedLabelForScenario(SCENARIO)}:im-ref`, - landing_path: '/pricing?im_ref=seed', - touched_at: touchedAtAffiliate, - expires_at: '2026-05-10T12:00:00.000Z', - }) - .returning({ id: kiloclaw_attribution_touches.id }); - - const [referralTouch] = await db - .insert(kiloclaw_attribution_touches) - .values({ - dedupe_key: `${seedLabelForScenario(SCENARIO)}:touch:referral`, - user_id: refereeUserId, - touch_type: ImpactAttributionTouchType.Referral, - provider: ImpactAttributionTouchProvider.ImpactAdvocate, - opaque_tracking_value: `${seedLabelForScenario(SCENARIO)}:cookie`, - tracking_value_length: 40, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - rs_share_medium: 'copy_link', - rs_engagement_medium: 'direct', - landing_path: '/pricing?_saasquatch=seed', - touched_at: touchedAtReferral, - expires_at: '2026-05-11T09:00:00.000Z', - }) - .returning({ id: kiloclaw_attribution_touches.id }); - - console.log(`[${SEED_SCOPE}] Materializing the qualified referral conversion and rewards`); - const [referral] = await db - .insert(kiloclaw_referrals) - .values({ - referee_user_id: refereeUserId, - referrer_user_id: referrerUserId, - source_touch_id: referralTouch.id, - impact_referral_id: opaqueReferralIdentifier, - }) - .returning({ id: kiloclaw_referrals.id }); - - const [conversion] = await db - .insert(kiloclaw_referral_conversions) - .values({ - referee_user_id: refereeUserId, - referrer_user_id: referrerUserId, - source_touch_id: referralTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: sourcePaymentId, - qualified: true, - converted_at: convertedAt, - }) - .returning({ id: kiloclaw_referral_conversions.id }); - - const [refereeDecision, referrerDecision] = await db - .insert(kiloclaw_referral_reward_decisions) - .values([ - { - conversion_id: conversion.id, - beneficiary_user_id: refereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - { - conversion_id: conversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - ]) - .returning({ - id: kiloclaw_referral_reward_decisions.id, - beneficiaryRole: kiloclaw_referral_reward_decisions.beneficiary_role, - }); - - const refereeDecisionId = - refereeDecision.beneficiaryRole === 'referee' ? refereeDecision.id : referrerDecision.id; - const referrerDecisionId = - refereeDecision.beneficiaryRole === 'referrer' ? refereeDecision.id : referrerDecision.id; - - const [refereeReward, referrerReward] = await db - .insert(kiloclaw_referral_rewards) - .values([ - { - conversion_id: conversion.id, - decision_id: refereeDecisionId, - beneficiary_user_id: refereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - months_granted: 1, - status: KiloClawReferralRewardStatus.Applied, - applies_to_subscription_id: refereeSubscription.id, - earned_at: convertedAt, - applied_at: '2026-04-15T16:40:00.000Z', - }, - { - conversion_id: conversion.id, - decision_id: referrerDecisionId, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - months_granted: 1, - status: KiloClawReferralRewardStatus.Applied, - applies_to_subscription_id: referrerSubscription.id, - earned_at: convertedAt, - applied_at: '2026-04-15T16:42:00.000Z', - }, - ]) - .returning({ - id: kiloclaw_referral_rewards.id, - beneficiaryUserId: kiloclaw_referral_rewards.beneficiary_user_id, - }); - - const refereeRewardId = - refereeReward.beneficiaryUserId === refereeUserId ? refereeReward.id : referrerReward.id; - const referrerRewardId = - refereeReward.beneficiaryUserId === referrerUserId ? refereeReward.id : referrerReward.id; - - await db.insert(kiloclaw_referral_reward_applications).values([ - { - reward_id: refereeRewardId, - beneficiary_user_id: refereeUserId, - subscription_id: refereeSubscription.id, - previous_renewal_boundary: previousRenewalBoundary, - new_renewal_boundary: newRenewalBoundary, - local_operation_id: `${seedLabelForScenario(SCENARIO)}:reward:referee`, - applied_at: '2026-04-15T16:40:00.000Z', - }, - { - reward_id: referrerRewardId, - beneficiary_user_id: referrerUserId, - subscription_id: referrerSubscription.id, - previous_renewal_boundary: previousRenewalBoundary, - new_renewal_boundary: newRenewalBoundary, - local_operation_id: `${seedLabelForScenario(SCENARIO)}:reward:referrer`, - applied_at: '2026-04-15T16:42:00.000Z', - }, - ]); - - await insertAppliedRewardChangeLog({ - subscription: refereeSubscription, - previousBoundary: previousRenewalBoundary, - newBoundary: newRenewalBoundary, - }); - await insertAppliedRewardChangeLog({ - subscription: referrerSubscription, - previousBoundary: previousRenewalBoundary, - newBoundary: newRenewalBoundary, - }); - - await db.insert(credit_transactions).values({ - kilo_user_id: refereeUserId, - amount_microdollars: -2000000, - is_free: false, - description: 'Seed referral happy path paid period', - credit_category: sourcePaymentId, - created_at: convertedAt, - }); - - await db.insert(impact_conversion_reports).values({ - conversion_id: conversion.id, - dedupe_key: `${seedLabelForScenario(SCENARIO)}:impact-report`, - action_tracker_id: 71659, - order_id: orderId, - state: ImpactConversionReportState.Delivered, - request_payload: { - orderId, - sourcePaymentId, - scenario: SCENARIO, - winningTouchType: 'referral', - }, - response_payload: { - ok: true, - actionId: `${seedLabelForScenario(SCENARIO)}:impact-action`, - }, - response_status_code: 200, - attempt_count: 1, - delivered_at: '2026-04-15T16:35:00.000Z', - }); - - console.log(''); - console.log('This fixture represents:'); - console.log('- affiliate touch first, referral touch second'); - console.log('- no prior affiliate SALE attribution'); - console.log('- referral wins at first paid conversion'); - console.log('- both rewards already applied to personal credits subscriptions'); - console.log('- Impact sale report already delivered'); - - return { - referrerUserId, - refereeUserId, - referralId: referral.id, - conversionId: conversion.id, - affiliateTouchId: affiliateTouch.id, - referralTouchId: referralTouch.id, - sourcePaymentId, - orderId, - referrerSubscriptionId: referrerSubscription.id, - refereeSubscriptionId: refereeSubscription.id, - }; -} diff --git a/dev/seed/kiloclaw/referrals-pending-referrer.ts b/dev/seed/kiloclaw/referrals-pending-referrer.ts deleted file mode 100644 index f4d80e3ce1..0000000000 --- a/dev/seed/kiloclaw/referrals-pending-referrer.ts +++ /dev/null @@ -1,282 +0,0 @@ -import { - credit_transactions, - impact_conversion_reports, - kiloclaw_attribution_touches, - kiloclaw_referral_conversions, - kiloclaw_referral_reward_applications, - kiloclaw_referral_reward_decisions, - kiloclaw_referral_rewards, - kiloclaw_referrals, -} from '@kilocode/db/schema'; -import { - ImpactConversionReportState, - ImpactAttributionTouchProvider, - ImpactAttributionTouchType, - KiloClawReferralBeneficiaryRole, - KiloClawReferralDecisionOutcome, - KiloClawReferralRewardStatus, - KiloClawReferralWinningTouchType, -} from '@kilocode/db/schema-types'; - -import { getSeedDb } from '../lib/db'; -import type { SeedResult } from '../index'; -import { - addMonthsUtc, - assertUserCount, - cleanupKiloClawReferralSeedScenario, - insertAppliedRewardChangeLog, - insertImpactAdvocateParticipant, - insertPersonalSubscription, - insertSeedUsers, - seedEmail, - seedLabelForScenario, - seedOpaqueReferralIdentifier, - seedOrderId, - seedSourcePaymentId, - seedUserId, -} from '../lib/kiloclaw-referrals'; - -const SCENARIO = 'referrals-pending-referrer'; -const SEED_SCOPE = `kiloclaw/${SCENARIO}`; - -const referrerUserId = seedUserId(SCENARIO, 'referrer'); -const refereeUserId = seedUserId(SCENARIO, 'referee'); -const userIds = [referrerUserId, refereeUserId]; -const referrerEmail = seedEmail(SCENARIO, 'referrer'); -const refereeEmail = seedEmail(SCENARIO, 'referee'); -const opaqueReferralIdentifier = seedOpaqueReferralIdentifier(SCENARIO, 'primary'); -const sourcePaymentId = seedSourcePaymentId(SCENARIO, 'period-1'); -const orderId = seedOrderId(SCENARIO, 'period-1'); -const convertedAt = '2026-04-15T16:30:00.000Z'; -const previousRenewalBoundary = '2026-05-01T00:00:00.000Z'; -const newRenewalBoundary = '2026-06-01T00:00:00.000Z'; - -export async function run(): Promise { - const db = getSeedDb(); - - console.log(`[${SEED_SCOPE}] Resetting existing seed data`); - await cleanupKiloClawReferralSeedScenario({ - scenario: SCENARIO, - userIds, - }); - - console.log(`[${SEED_SCOPE}] Inserting referrer and referee users`); - await insertSeedUsers([ - { - id: referrerUserId, - email: referrerEmail, - name: 'Seed Pending Referrer', - }, - { - id: refereeUserId, - email: refereeEmail, - name: 'Seed Pending Referee', - }, - ]); - await assertUserCount({ userIds, expectedCount: 2 }); - - console.log( - `[${SEED_SCOPE}] Inserting a trial subscription for the referrer and an active subscription for the referee` - ); - const { subscription: referrerTrialSubscription } = await insertPersonalSubscription({ - userId: referrerUserId, - sandboxId: `sandbox-${referrerUserId}`, - name: 'Seed Pending Referrer Trial', - plan: 'trial', - status: 'trialing', - trialStartedAt: '2026-04-01T00:00:00.000Z', - trialEndsAt: '2026-04-20T00:00:00.000Z', - }); - const { subscription: refereeSubscription } = await insertPersonalSubscription({ - userId: refereeUserId, - sandboxId: `sandbox-${refereeUserId}`, - name: 'Seed Pending Referee Active', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-04-01T00:00:00.000Z', - currentPeriodEnd: newRenewalBoundary, - creditRenewalAt: newRenewalBoundary, - }); - - console.log(`[${SEED_SCOPE}] Inserting registered Advocate participant for the referrer`); - await insertImpactAdvocateParticipant({ - userId: referrerUserId, - email: referrerEmail, - opaqueReferralIdentifier, - registeredAt: '2026-04-01T12:00:00.000Z', - }); - - const [referralTouch] = await db - .insert(kiloclaw_attribution_touches) - .values({ - dedupe_key: `${seedLabelForScenario(SCENARIO)}:touch:referral`, - user_id: refereeUserId, - touch_type: ImpactAttributionTouchType.Referral, - provider: ImpactAttributionTouchProvider.ImpactAdvocate, - opaque_tracking_value: `${seedLabelForScenario(SCENARIO)}:cookie`, - tracking_value_length: 44, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - rs_share_medium: 'email', - rs_engagement_medium: 'share', - landing_path: '/pricing?_saasquatch=seed', - touched_at: '2026-04-11T09:00:00.000Z', - expires_at: '2026-05-11T09:00:00.000Z', - }) - .returning({ id: kiloclaw_attribution_touches.id }); - - console.log( - `[${SEED_SCOPE}] Materializing the qualified referral with a pending referrer reward` - ); - const [referral] = await db - .insert(kiloclaw_referrals) - .values({ - referee_user_id: refereeUserId, - referrer_user_id: referrerUserId, - source_touch_id: referralTouch.id, - impact_referral_id: opaqueReferralIdentifier, - }) - .returning({ id: kiloclaw_referrals.id }); - - const [conversion] = await db - .insert(kiloclaw_referral_conversions) - .values({ - referee_user_id: refereeUserId, - referrer_user_id: referrerUserId, - source_touch_id: referralTouch.id, - winning_touch_type: KiloClawReferralWinningTouchType.Referral, - source_payment_id: sourcePaymentId, - qualified: true, - converted_at: convertedAt, - }) - .returning({ id: kiloclaw_referral_conversions.id }); - - const [refereeDecision, referrerDecision] = await db - .insert(kiloclaw_referral_reward_decisions) - .values([ - { - conversion_id: conversion.id, - beneficiary_user_id: refereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - { - conversion_id: conversion.id, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - outcome: KiloClawReferralDecisionOutcome.Granted, - months_granted: 1, - }, - ]) - .returning({ - id: kiloclaw_referral_reward_decisions.id, - beneficiaryRole: kiloclaw_referral_reward_decisions.beneficiary_role, - }); - - const refereeDecisionId = - refereeDecision.beneficiaryRole === 'referee' ? refereeDecision.id : referrerDecision.id; - const referrerDecisionId = - refereeDecision.beneficiaryRole === 'referrer' ? refereeDecision.id : referrerDecision.id; - - const [refereeReward, referrerReward] = await db - .insert(kiloclaw_referral_rewards) - .values([ - { - conversion_id: conversion.id, - decision_id: refereeDecisionId, - beneficiary_user_id: refereeUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referee, - months_granted: 1, - status: KiloClawReferralRewardStatus.Applied, - applies_to_subscription_id: refereeSubscription.id, - earned_at: convertedAt, - applied_at: '2026-04-15T16:41:00.000Z', - }, - { - conversion_id: conversion.id, - decision_id: referrerDecisionId, - beneficiary_user_id: referrerUserId, - beneficiary_role: KiloClawReferralBeneficiaryRole.Referrer, - months_granted: 1, - status: KiloClawReferralRewardStatus.Pending, - earned_at: convertedAt, - expires_at: addMonthsUtc(convertedAt, 12), - }, - ]) - .returning({ - id: kiloclaw_referral_rewards.id, - beneficiaryUserId: kiloclaw_referral_rewards.beneficiary_user_id, - }); - - const refereeRewardId = - refereeReward.beneficiaryUserId === refereeUserId ? refereeReward.id : referrerReward.id; - const referrerRewardId = - refereeReward.beneficiaryUserId === referrerUserId ? refereeReward.id : referrerReward.id; - - await db.insert(kiloclaw_referral_reward_applications).values({ - reward_id: refereeRewardId, - beneficiary_user_id: refereeUserId, - subscription_id: refereeSubscription.id, - previous_renewal_boundary: previousRenewalBoundary, - new_renewal_boundary: newRenewalBoundary, - local_operation_id: `${seedLabelForScenario(SCENARIO)}:reward:referee`, - applied_at: '2026-04-15T16:41:00.000Z', - }); - - await insertAppliedRewardChangeLog({ - subscription: refereeSubscription, - previousBoundary: previousRenewalBoundary, - newBoundary: newRenewalBoundary, - }); - - await db.insert(credit_transactions).values({ - kilo_user_id: refereeUserId, - amount_microdollars: -2000000, - is_free: false, - description: 'Seed pending-referrer paid period', - credit_category: sourcePaymentId, - created_at: convertedAt, - }); - - await db.insert(impact_conversion_reports).values({ - conversion_id: conversion.id, - dedupe_key: `${seedLabelForScenario(SCENARIO)}:impact-report`, - action_tracker_id: 71659, - order_id: orderId, - state: ImpactConversionReportState.Delivered, - request_payload: { - orderId, - sourcePaymentId, - scenario: SCENARIO, - rewardState: 'pending-referrer', - }, - response_payload: { - ok: true, - actionId: `${seedLabelForScenario(SCENARIO)}:impact-action`, - }, - response_status_code: 200, - attempt_count: 1, - delivered_at: '2026-04-15T16:35:00.000Z', - }); - - console.log(''); - console.log('This fixture represents:'); - console.log('- a qualified referral conversion'); - console.log('- the referee reward already applied'); - console.log('- the referrer still on a trial, so their reward remains pending'); - console.log('- the pending reward already has a 12-month expiration timestamp'); - - return { - referrerUserId, - refereeUserId, - referralId: referral.id, - conversionId: conversion.id, - sourcePaymentId, - orderId, - referrerTrialSubscriptionId: referrerTrialSubscription.id, - refereeSubscriptionId: refereeSubscription.id, - pendingReferrerRewardId: referrerRewardId, - }; -} diff --git a/dev/seed/kiloclaw/referrals-support-override.ts b/dev/seed/kiloclaw/referrals-support-override.ts deleted file mode 100644 index 4ff6a7e417..0000000000 --- a/dev/seed/kiloclaw/referrals-support-override.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { credit_transactions, impact_attribution_touches } from '@kilocode/db/schema'; -import { - ImpactAttributionTouchProvider, - ImpactAttributionTouchType, -} from '@kilocode/db/schema-types'; - -import { getSeedDb } from '../lib/db'; -import type { SeedResult } from '../index'; -import { - assertUserCount, - cleanupKiloClawReferralSeedScenario, - insertImpactAdvocateParticipant, - insertPersonalSubscription, - insertSeedUsers, - seedEmail, - seedLabelForScenario, - seedOpaqueReferralIdentifier, - seedOrderId, - seedSourcePaymentId, - seedUserId, -} from '../lib/kiloclaw-referrals'; - -const SCENARIO = 'referrals-support-override'; -const SEED_SCOPE = `kiloclaw/${SCENARIO}`; -const referrerUserId = seedUserId(SCENARIO, 'referrer'); -const refereeUserId = seedUserId(SCENARIO, 'referee'); -const userIds = [referrerUserId, refereeUserId]; -const referrerEmail = seedEmail(SCENARIO, 'referrer'); -const refereeEmail = seedEmail(SCENARIO, 'referee'); -const opaqueReferralIdentifier = seedOpaqueReferralIdentifier(SCENARIO, 'primary'); -const sourcePaymentId = seedSourcePaymentId(SCENARIO, 'manual-adjustment'); -const orderId = seedOrderId(SCENARIO, 'manual-adjustment'); -const convertedAt = '2026-04-15T16:30:00.000Z'; - -export async function run(): Promise { - const db = getSeedDb(); - - console.log(`[${SEED_SCOPE}] Resetting existing seed data`); - await cleanupKiloClawReferralSeedScenario({ - scenario: SCENARIO, - userIds, - }); - - console.log(`[${SEED_SCOPE}] Inserting referrer and referee users`); - await insertSeedUsers([ - { - id: referrerUserId, - email: referrerEmail, - name: 'Seed Support Override Referrer', - }, - { - id: refereeUserId, - email: refereeEmail, - name: 'Seed Support Override Referee', - }, - ]); - await assertUserCount({ userIds, expectedCount: 2 }); - - console.log(`[${SEED_SCOPE}] Inserting active personal subscriptions for both users`); - const { subscription: referrerSubscription } = await insertPersonalSubscription({ - userId: referrerUserId, - sandboxId: `sandbox-${referrerUserId}`, - name: 'Seed Support Override Referrer', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-04-01T00:00:00.000Z', - currentPeriodEnd: '2026-05-01T00:00:00.000Z', - creditRenewalAt: '2026-05-01T00:00:00.000Z', - }); - const { subscription: refereeSubscription } = await insertPersonalSubscription({ - userId: refereeUserId, - sandboxId: `sandbox-${refereeUserId}`, - name: 'Seed Support Override Referee', - plan: 'standard', - status: 'active', - paymentSource: 'credits', - currentPeriodStart: '2026-04-01T00:00:00.000Z', - currentPeriodEnd: '2026-05-01T00:00:00.000Z', - creditRenewalAt: '2026-05-01T00:00:00.000Z', - }); - - console.log( - `[${SEED_SCOPE}] Inserting the referrer participant and a valid referral touch on the referee` - ); - await insertImpactAdvocateParticipant({ - userId: referrerUserId, - email: referrerEmail, - opaqueReferralIdentifier, - registeredAt: '2026-04-01T12:00:00.000Z', - }); - - const [affiliateTouch] = await db - .insert(impact_attribution_touches) - .values({ - dedupe_key: `${seedLabelForScenario(SCENARIO)}:touch:affiliate`, - user_id: refereeUserId, - touch_type: ImpactAttributionTouchType.Affiliate, - provider: ImpactAttributionTouchProvider.ImpactPerformance, - opaque_tracking_value: `${seedLabelForScenario(SCENARIO)}:im-ref`, - tracking_value_length: 50, - is_tracking_value_accepted: true, - im_ref: `${seedLabelForScenario(SCENARIO)}:im-ref`, - landing_path: '/pricing?im_ref=seed', - touched_at: '2026-04-10T12:00:00.000Z', - expires_at: '2026-05-10T12:00:00.000Z', - }) - .returning({ id: impact_attribution_touches.id }); - - const [referralTouch] = await db - .insert(impact_attribution_touches) - .values({ - dedupe_key: `${seedLabelForScenario(SCENARIO)}:touch:referral`, - user_id: refereeUserId, - touch_type: ImpactAttributionTouchType.Referral, - provider: ImpactAttributionTouchProvider.ImpactAdvocate, - opaque_tracking_value: `${seedLabelForScenario(SCENARIO)}:cookie`, - tracking_value_length: 48, - is_tracking_value_accepted: true, - rs_code: opaqueReferralIdentifier, - rs_share_medium: 'support', - rs_engagement_medium: 'manual', - landing_path: '/pricing?_saasquatch=seed', - touched_at: '2026-04-11T09:00:00.000Z', - expires_at: '2026-05-11T09:00:00.000Z', - }) - .returning({ id: impact_attribution_touches.id }); - - console.log( - `[${SEED_SCOPE}] Inserting a manual-adjustment payment record ready for admin override processing` - ); - await db.insert(credit_transactions).values({ - kilo_user_id: refereeUserId, - amount_microdollars: -2000000, - is_free: false, - description: 'Manual seed adjustment for referral override verification', - credit_category: sourcePaymentId, - created_at: convertedAt, - }); - - console.log(''); - console.log('This fixture represents:'); - console.log('- a valid referral touch that would normally win over the affiliate touch'); - console.log('- a source payment that heuristically looks like a manual adjustment'); - console.log('- no conversion rows yet, so an authorized operator can test the override flow'); - console.log(''); - console.log('Suggested next step (requires an authenticated admin session):'); - console.log( - ` curl -X POST http://localhost:3000/admin/api/users/${refereeUserId}/kiloclaw-referral-eligibility \\\n -H 'content-type: application/json' \\\n --data '${JSON.stringify( - { - sourcePaymentId, - orderId, - amount: 20, - currencyCode: 'USD', - itemCategory: 'kiloclaw_subscription', - itemName: 'KiloClaw Standard', - convertedAt, - sourceType: 'manual_adjustment', - } - )}'` - ); - - return { - referrerUserId, - refereeUserId, - referrerSubscriptionId: referrerSubscription.id, - refereeSubscriptionId: refereeSubscription.id, - affiliateTouchId: affiliateTouch.id, - referralTouchId: referralTouch.id, - sourcePaymentId, - orderId, - }; -} diff --git a/dev/seed/lib/kiloclaw-referrals.ts b/dev/seed/lib/kiloclaw-referrals.ts deleted file mode 100644 index 3c35a3f49d..0000000000 --- a/dev/seed/lib/kiloclaw-referrals.ts +++ /dev/null @@ -1,364 +0,0 @@ -import { insertKiloClawSubscriptionChangeLog } from '@kilocode/db'; -import type { KiloClawPaymentSource, KiloClawSubscriptionStatus } from '@kilocode/db/schema-types'; -import { - credit_transactions, - impact_advocate_participants, - impact_advocate_registration_attempts, - impact_conversion_reports, - kiloclaw_attribution_touches, - kiloclaw_instances, - kiloclaw_referral_conversions, - kiloclaw_referral_reward_applications, - kiloclaw_referral_reward_decisions, - kiloclaw_referral_rewards, - kiloclaw_referrals, - kiloclaw_subscription_change_log, - kiloclaw_subscriptions, - kilocode_users, - referral_codes, -} from '@kilocode/db/schema'; -import { and, eq, inArray, like, or } from 'drizzle-orm'; - -import { getSeedDb } from './db'; - -type SeedUserFixture = { - id: string; - email: string; - name: string; - imageUrl?: string; - stripeCustomerId?: string; - normalizedEmail?: string; - isAdmin?: boolean; -}; - -type PersonalSubscriptionFixture = { - userId: string; - sandboxId: string; - name?: string | null; - organizationId?: string | null; - plan: 'trial' | 'standard' | 'commit'; - status: KiloClawSubscriptionStatus; - paymentSource?: KiloClawPaymentSource; - currentPeriodStart?: string | null; - currentPeriodEnd?: string | null; - creditRenewalAt?: string | null; - trialStartedAt?: string | null; - trialEndsAt?: string | null; - commitEndsAt?: string | null; - cancelAtPeriodEnd?: boolean; -}; - -function buildOrConditions(conditions: Array): TCondition[] { - return conditions.filter(condition => condition !== undefined); -} - -export function seedLabelForScenario(scenario: string): string { - return `seed:kiloclaw:${scenario}`; -} - -export function seedUserId(scenario: string, role: string): string { - return `seed-kiloclaw-${scenario}-${role}`; -} - -export function seedEmail(scenario: string, role: string): string { - return `${seedUserId(scenario, role)}@example.com`; -} - -export function seedOpaqueReferralIdentifier(scenario: string, slug: string): string { - return `${seedLabelForScenario(scenario)}:share:${slug}`; -} - -export function seedSourcePaymentId(scenario: string, slug: string): string { - return `kiloclaw-subscription:seed-kiloclaw-${scenario}-${slug}`; -} - -export function seedOrderId(scenario: string, slug: string): string { - return `${seedLabelForScenario(scenario)}:order:${slug}`; -} - -export function addDays(iso: string, days: number): string { - const date = new Date(iso); - date.setUTCDate(date.getUTCDate() + days); - return date.toISOString(); -} - -export function addMonthsUtc(iso: string, months: number): string { - const date = new Date(iso); - const originalDay = date.getUTCDate(); - - date.setUTCDate(1); - date.setUTCMonth(date.getUTCMonth() + months); - - const lastDayOfTargetMonth = new Date( - Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0) - ).getUTCDate(); - - date.setUTCDate(Math.min(originalDay, lastDayOfTargetMonth)); - return date.toISOString(); -} - -export async function cleanupKiloClawReferralSeedScenario(params: { - scenario: string; - userIds: string[]; -}): Promise { - const db = getSeedDb(); - const scenarioPrefix = `${seedLabelForScenario(params.scenario)}%`; - - const conversionRows = await db - .select({ id: kiloclaw_referral_conversions.id }) - .from(kiloclaw_referral_conversions) - .where( - or( - like(kiloclaw_referral_conversions.source_payment_id, scenarioPrefix), - inArray(kiloclaw_referral_conversions.referee_user_id, params.userIds), - inArray(kiloclaw_referral_conversions.referrer_user_id, params.userIds) - ) - ); - const conversionIds = conversionRows.map(row => row.id); - - const rewardRows = conversionIds.length - ? await db - .select({ id: kiloclaw_referral_rewards.id }) - .from(kiloclaw_referral_rewards) - .where( - or( - inArray(kiloclaw_referral_rewards.conversion_id, conversionIds), - inArray(kiloclaw_referral_rewards.beneficiary_user_id, params.userIds) - ) - ) - : await db - .select({ id: kiloclaw_referral_rewards.id }) - .from(kiloclaw_referral_rewards) - .where(inArray(kiloclaw_referral_rewards.beneficiary_user_id, params.userIds)); - const rewardIds = rewardRows.map(row => row.id); - - const participantRows = await db - .select({ id: impact_advocate_participants.id }) - .from(impact_advocate_participants) - .where(inArray(impact_advocate_participants.user_id, params.userIds)); - const participantIds = participantRows.map(row => row.id); - - const subscriptionRows = await db - .select({ id: kiloclaw_subscriptions.id }) - .from(kiloclaw_subscriptions) - .where(inArray(kiloclaw_subscriptions.user_id, params.userIds)); - const subscriptionIds = subscriptionRows.map(row => row.id); - - const rewardApplicationConditions = buildOrConditions([ - rewardIds.length - ? inArray(kiloclaw_referral_reward_applications.reward_id, rewardIds) - : undefined, - params.userIds.length - ? inArray(kiloclaw_referral_reward_applications.beneficiary_user_id, params.userIds) - : undefined, - ]); - if (rewardApplicationConditions.length > 0) { - await db - .delete(kiloclaw_referral_reward_applications) - .where(or(...rewardApplicationConditions)); - } - - const reportConditions = buildOrConditions([ - conversionIds.length - ? inArray(impact_conversion_reports.conversion_id, conversionIds) - : undefined, - like(impact_conversion_reports.dedupe_key, scenarioPrefix), - ]); - await db.delete(impact_conversion_reports).where(or(...reportConditions)); - - const rewardConditions = buildOrConditions([ - rewardIds.length ? inArray(kiloclaw_referral_rewards.id, rewardIds) : undefined, - params.userIds.length - ? inArray(kiloclaw_referral_rewards.beneficiary_user_id, params.userIds) - : undefined, - ]); - if (rewardConditions.length > 0) { - await db.delete(kiloclaw_referral_rewards).where(or(...rewardConditions)); - } - - if (conversionIds.length > 0) { - await db - .delete(kiloclaw_referral_reward_decisions) - .where(inArray(kiloclaw_referral_reward_decisions.conversion_id, conversionIds)); - } - - await db - .delete(kiloclaw_referrals) - .where( - or( - inArray(kiloclaw_referrals.referee_user_id, params.userIds), - inArray(kiloclaw_referrals.referrer_user_id, params.userIds) - ) - ); - - const conversionConditions = buildOrConditions([ - like(kiloclaw_referral_conversions.source_payment_id, scenarioPrefix), - inArray(kiloclaw_referral_conversions.referee_user_id, params.userIds), - inArray(kiloclaw_referral_conversions.referrer_user_id, params.userIds), - ]); - await db.delete(kiloclaw_referral_conversions).where(or(...conversionConditions)); - - const attemptConditions = buildOrConditions([ - like(impact_advocate_registration_attempts.dedupe_key, scenarioPrefix), - participantIds.length - ? inArray(impact_advocate_registration_attempts.participant_id, participantIds) - : undefined, - ]); - await db.delete(impact_advocate_registration_attempts).where(or(...attemptConditions)); - - await db - .delete(kiloclaw_attribution_touches) - .where( - or( - like(kiloclaw_attribution_touches.dedupe_key, scenarioPrefix), - inArray(kiloclaw_attribution_touches.user_id, params.userIds) - ) - ); - - await db - .delete(credit_transactions) - .where( - or( - inArray(credit_transactions.kilo_user_id, params.userIds), - like(credit_transactions.credit_category, scenarioPrefix), - like( - credit_transactions.credit_category, - `kiloclaw-subscription:seed-kiloclaw-${params.scenario}%` - ) - ) - ); - - if (subscriptionIds.length > 0) { - await db - .delete(kiloclaw_subscription_change_log) - .where(inArray(kiloclaw_subscription_change_log.subscription_id, subscriptionIds)); - } - - await db - .delete(kiloclaw_subscriptions) - .where(inArray(kiloclaw_subscriptions.user_id, params.userIds)); - await db.delete(kiloclaw_instances).where(inArray(kiloclaw_instances.user_id, params.userIds)); - await db - .delete(impact_advocate_participants) - .where(inArray(impact_advocate_participants.user_id, params.userIds)); - await db.delete(referral_codes).where(inArray(referral_codes.kilo_user_id, params.userIds)); - await db.delete(kilocode_users).where(inArray(kilocode_users.id, params.userIds)); -} - -export async function insertSeedUsers(users: SeedUserFixture[]): Promise { - const db = getSeedDb(); - await db.insert(kilocode_users).values( - users.map(user => ({ - id: user.id, - google_user_email: user.email, - google_user_name: user.name, - google_user_image_url: - user.imageUrl ?? `https://example.com/${encodeURIComponent(user.id)}.png`, - stripe_customer_id: - user.stripeCustomerId ?? `cus_${user.id.replaceAll(/[^a-zA-Z0-9]/g, '_')}`, - normalized_email: user.normalizedEmail ?? user.email.toLowerCase(), - is_admin: user.isAdmin ?? false, - })) - ); -} - -export async function insertImpactAdvocateParticipant(params: { - userId: string; - email: string; - opaqueReferralIdentifier: string; - registeredAt?: string; -}): Promise { - const db = getSeedDb(); - await db.insert(referral_codes).values({ - kilo_user_id: params.userId, - code: params.opaqueReferralIdentifier, - }); - await db.insert(impact_advocate_participants).values({ - user_id: params.userId, - advocate_id: params.userId, - advocate_account_id: params.userId, - opaque_referral_identifier: params.opaqueReferralIdentifier, - contact_email: params.email, - registration_state: 'registered', - registered_at: params.registeredAt ?? new Date().toISOString(), - }); -} - -export async function insertPersonalSubscription(fixture: PersonalSubscriptionFixture): Promise<{ - subscription: typeof kiloclaw_subscriptions.$inferSelect; - instance: typeof kiloclaw_instances.$inferSelect; -}> { - const db = getSeedDb(); - - const [instance] = await db - .insert(kiloclaw_instances) - .values({ - user_id: fixture.userId, - sandbox_id: fixture.sandboxId, - provider: 'docker-local', - name: fixture.name ?? null, - organization_id: fixture.organizationId ?? null, - }) - .returning(); - - const [subscription] = await db - .insert(kiloclaw_subscriptions) - .values({ - user_id: fixture.userId, - instance_id: instance.id, - payment_source: fixture.paymentSource, - plan: fixture.plan, - status: fixture.status, - cancel_at_period_end: fixture.cancelAtPeriodEnd ?? false, - current_period_start: fixture.currentPeriodStart ?? null, - current_period_end: fixture.currentPeriodEnd ?? null, - credit_renewal_at: fixture.creditRenewalAt ?? null, - trial_started_at: fixture.trialStartedAt ?? null, - trial_ends_at: fixture.trialEndsAt ?? null, - commit_ends_at: fixture.commitEndsAt ?? null, - }) - .returning(); - - return { subscription, instance }; -} - -export async function insertAppliedRewardChangeLog(params: { - subscription: typeof kiloclaw_subscriptions.$inferSelect; - previousBoundary: string; - newBoundary: string; -}): Promise { - const beforeSubscription = { - ...params.subscription, - current_period_end: params.previousBoundary, - credit_renewal_at: params.previousBoundary, - }; - const afterSubscription = { - ...params.subscription, - current_period_end: params.newBoundary, - credit_renewal_at: params.newBoundary, - }; - - await insertKiloClawSubscriptionChangeLog(getSeedDb(), { - subscriptionId: params.subscription.id, - actor: { - actorType: 'system', - actorId: 'kiloclaw-referrals', - }, - action: 'period_advanced', - reason: 'referral_reward:applied', - before: beforeSubscription, - after: afterSubscription, - }); -} - -export async function assertUserCount(params: { userIds: string[]; expectedCount: number }) { - const db = getSeedDb(); - const rows = await db - .select({ id: kilocode_users.id }) - .from(kilocode_users) - .where(inArray(kilocode_users.id, params.userIds)); - - if (rows.length !== params.expectedCount) { - throw new Error(`Expected ${params.expectedCount} seed users, found ${rows.length}`); - } -} diff --git a/packages/db/src/migrations/0221_retire_kiloclaw_referral_rewards.sql b/packages/db/src/migrations/0221_retire_kiloclaw_referral_rewards.sql new file mode 100644 index 0000000000..7460a16901 --- /dev/null +++ b/packages/db/src/migrations/0221_retire_kiloclaw_referral_rewards.sql @@ -0,0 +1,30 @@ +-- Retire the KiloClaw Impact Advocate referral program. +-- +-- KiloClaw referral rewards can no longer be earned or applied: fresh KiloClaw +-- instance provisioning is closed, so no account can make a first paid KiloClaw +-- subscription payment, and the reward application sweep has been removed. +-- +-- Historical referral rows are retained for accounting and support history, and +-- already-applied free months stay applied. This migration only closes out the +-- work that can never complete: +-- 1. rewards still awaiting application are canceled; +-- 2. queued Impact Advocate redemptions for those rewards are terminated so +-- the shared redemption sweep stops retrying them forever. +UPDATE "impact_referral_rewards" +SET "status" = 'canceled', + "review_reason" = 'kiloclaw_referral_program_retired' +WHERE "product" = 'kiloclaw' + AND "reward_kind" = 'kiloclaw_free_month' + AND "status" IN ('pending', 'earned'); +--> statement-breakpoint +UPDATE "impact_advocate_reward_redemptions" +SET "state" = 'failed', + "next_retry_at" = NULL, + "redeem_response_payload" = jsonb_build_object('error', 'retired_advocate_program') +WHERE "state" IN ('queued', 'retrying') + AND "reward_id" IN ( + SELECT "id" + FROM "impact_referral_rewards" + WHERE "product" = 'kiloclaw' + AND "reward_kind" = 'kiloclaw_free_month' + ); diff --git a/packages/db/src/migrations/meta/0221_snapshot.json b/packages/db/src/migrations/meta/0221_snapshot.json new file mode 100644 index 0000000000..ad02901f72 --- /dev/null +++ b/packages/db/src/migrations/meta/0221_snapshot.json @@ -0,0 +1,39128 @@ +{ + "id": "a565214a-b609-499a-8a45-02ad1824fb02", + "prevId": "0092dbfb-1da4-490e-bd4c-8421dc20cd5a", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.agent_configs": { + "name": "agent_configs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent_type": { + "name": "agent_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "is_enabled": { + "name": "is_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "runtime_state": { + "name": "runtime_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'::jsonb" + }, + "created_by": { + "name": "created_by", + "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()" + }, + "config_revision": { + "name": "config_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + } + }, + "indexes": { + "IDX_agent_configs_org_id": { + "name": "IDX_agent_configs_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_agent_configs_owned_by_user_id": { + "name": "IDX_agent_configs_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_agent_configs_agent_type": { + "name": "IDX_agent_configs_agent_type", + "columns": [ + { + "expression": "agent_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_agent_configs_platform": { + "name": "IDX_agent_configs_platform", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_configs_owned_by_organization_id_organizations_id_fk": { + "name": "agent_configs_owned_by_organization_id_organizations_id_fk", + "tableFrom": "agent_configs", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "agent_configs_owned_by_user_id_kilocode_users_id_fk": { + "name": "agent_configs_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "agent_configs", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_configs_org_agent_platform": { + "name": "UQ_agent_configs_org_agent_platform", + "columns": [ + "owned_by_organization_id", + "agent_type", + "platform" + ], + "nullsNotDistinct": false + }, + "UQ_agent_configs_user_agent_platform": { + "name": "UQ_agent_configs_user_agent_platform", + "columns": [ + "owned_by_user_id", + "agent_type", + "platform" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "agent_configs_owner_check": { + "name": "agent_configs_owner_check", + "value": "(\n (\"agent_configs\".\"owned_by_user_id\" IS NOT NULL AND \"agent_configs\".\"owned_by_organization_id\" IS NULL) OR\n (\"agent_configs\".\"owned_by_user_id\" IS NULL AND \"agent_configs\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "agent_configs_agent_type_check": { + "name": "agent_configs_agent_type_check", + "value": "\"agent_configs\".\"agent_type\" IN ('code_review', 'auto_triage', 'auto_fix', 'security_scan')" + }, + "agent_configs_config_revision_check": { + "name": "agent_configs_config_revision_check", + "value": "\"agent_configs\".\"config_revision\" >= 1" + } + }, + "isRLSEnabled": false + }, + "public.agent_environment_profile_agents": { + "name": "agent_environment_profile_agents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::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": { + "IDX_agent_env_profile_agents_profile_id": { + "name": "IDX_agent_env_profile_agents_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_agents_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_agents_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_agents", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_agents_profile_slug": { + "name": "UQ_agent_env_profile_agents_profile_slug", + "columns": [ + "profile_id", + "slug" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profile_commands": { + "name": "agent_environment_profile_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "sequence": { + "name": "sequence", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_agent_env_profile_commands_profile_id": { + "name": "IDX_agent_env_profile_commands_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_commands_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_commands_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_commands", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_commands_profile_sequence": { + "name": "UQ_agent_env_profile_commands_profile_sequence", + "columns": [ + "profile_id", + "sequence" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profile_kilo_commands": { + "name": "agent_environment_profile_kilo_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_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 + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "agent": { + "name": "agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subtask": { + "name": "subtask", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_agent_env_profile_kilo_cmds_profile_id": { + "name": "IDX_agent_env_profile_kilo_cmds_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_kilo_commands_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_kilo_commands_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_kilo_commands", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_kilo_cmds_profile_name": { + "name": "UQ_agent_env_profile_kilo_cmds_profile_name", + "columns": [ + "profile_id", + "name" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profile_mcp_servers": { + "name": "agent_environment_profile_mcp_servers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "timeout": { + "name": "timeout", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "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": { + "IDX_agent_env_profile_mcp_servers_profile_id": { + "name": "IDX_agent_env_profile_mcp_servers_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_mcp_servers_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_mcp_servers_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_mcp_servers", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_mcp_servers_profile_name": { + "name": "UQ_agent_env_profile_mcp_servers_profile_name", + "columns": [ + "profile_id", + "name" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profile_repo_bindings": { + "name": "agent_environment_profile_repo_bindings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_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": { + "UQ_agent_env_profile_repo_bindings_user": { + "name": "UQ_agent_env_profile_repo_bindings_user", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profile_repo_bindings\".\"owned_by_user_id\" is not null", + "concurrently": false + }, + "UQ_agent_env_profile_repo_bindings_org": { + "name": "UQ_agent_env_profile_repo_bindings_org", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profile_repo_bindings\".\"owned_by_organization_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_repo_bindings_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_repo_bindings_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_repo_bindings", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "agent_environment_profile_repo_bindings_owned_by_organization_id_organizations_id_fk": { + "name": "agent_environment_profile_repo_bindings_owned_by_organization_id_organizations_id_fk", + "tableFrom": "agent_environment_profile_repo_bindings", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "agent_environment_profile_repo_bindings_owned_by_user_id_kilocode_users_id_fk": { + "name": "agent_environment_profile_repo_bindings_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "agent_environment_profile_repo_bindings", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "agent_env_profile_repo_bindings_owner_check": { + "name": "agent_env_profile_repo_bindings_owner_check", + "value": "(\n (\"agent_environment_profile_repo_bindings\".\"owned_by_user_id\" IS NOT NULL AND \"agent_environment_profile_repo_bindings\".\"owned_by_organization_id\" IS NULL) OR\n (\"agent_environment_profile_repo_bindings\".\"owned_by_user_id\" IS NULL AND \"agent_environment_profile_repo_bindings\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.agent_environment_profile_skills": { + "name": "agent_environment_profile_skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_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 + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "raw_markdown": { + "name": "raw_markdown", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": { + "IDX_agent_env_profile_skills_profile_id": { + "name": "IDX_agent_env_profile_skills_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_skills_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_skills_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_skills", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_skills_profile_name": { + "name": "UQ_agent_env_profile_skills_profile_name", + "columns": [ + "profile_id", + "name" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profile_vars": { + "name": "agent_environment_profile_vars", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "profile_id": { + "name": "profile_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_secret": { + "name": "is_secret", + "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": { + "IDX_agent_env_profile_vars_profile_id": { + "name": "IDX_agent_env_profile_vars_profile_id", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profile_vars_profile_id_agent_environment_profiles_id_fk": { + "name": "agent_environment_profile_vars_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "agent_environment_profile_vars", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_agent_env_profile_vars_profile_key": { + "name": "UQ_agent_env_profile_vars_profile_key", + "columns": [ + "profile_id", + "key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.agent_environment_profiles": { + "name": "agent_environment_profiles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_default": { + "name": "is_default", + "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": { + "UQ_agent_env_profiles_org_name": { + "name": "UQ_agent_env_profiles_org_name", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profiles\".\"owned_by_organization_id\" is not null", + "concurrently": false + }, + "UQ_agent_env_profiles_user_name": { + "name": "UQ_agent_env_profiles_user_name", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profiles\".\"owned_by_user_id\" is not null", + "concurrently": false + }, + "UQ_agent_env_profiles_org_default": { + "name": "UQ_agent_env_profiles_org_default", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profiles\".\"is_default\" = true AND \"agent_environment_profiles\".\"owned_by_organization_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_agent_env_profiles_user_default": { + "name": "UQ_agent_env_profiles_user_default", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"agent_environment_profiles\".\"is_default\" = true AND \"agent_environment_profiles\".\"owned_by_user_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_agent_env_profiles_org_id": { + "name": "IDX_agent_env_profiles_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_agent_env_profiles_user_id": { + "name": "IDX_agent_env_profiles_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_agent_env_profiles_created_by_user_id": { + "name": "IDX_agent_env_profiles_created_by_user_id", + "columns": [ + { + "expression": "created_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "agent_environment_profiles_owned_by_organization_id_organizations_id_fk": { + "name": "agent_environment_profiles_owned_by_organization_id_organizations_id_fk", + "tableFrom": "agent_environment_profiles", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "agent_environment_profiles_owned_by_user_id_kilocode_users_id_fk": { + "name": "agent_environment_profiles_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "agent_environment_profiles", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "agent_env_profiles_owner_check": { + "name": "agent_env_profiles_owner_check", + "value": "(\n (\"agent_environment_profiles\".\"owned_by_user_id\" IS NOT NULL AND \"agent_environment_profiles\".\"owned_by_organization_id\" IS NULL) OR\n (\"agent_environment_profiles\".\"owned_by_user_id\" IS NULL AND \"agent_environment_profiles\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.analytics_event_outbox": { + "name": "analytics_event_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "event_uuid": { + "name": "event_uuid", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_name": { + "name": "event_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "distinct_id": { + "name": "distinct_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "properties": { + "name": "properties", + "type": "jsonb", + "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": false + }, + "claimed_at": { + "name": "claimed_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()" + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_analytics_event_outbox_event_uuid": { + "name": "UQ_analytics_event_outbox_event_uuid", + "columns": [ + { + "expression": "event_uuid", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_analytics_event_outbox_status_next_attempt_at": { + "name": "IDX_analytics_event_outbox_status_next_attempt_at", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_kind": { + "name": "api_kind", + "schema": "", + "columns": { + "api_kind_id": { + "name": "api_kind_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "api_kind": { + "name": "api_kind", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_api_kind": { + "name": "UQ_api_kind", + "columns": [ + { + "expression": "api_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.api_request_log": { + "name": "api_request_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "vercel_request_id": { + "name": "vercel_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_code": { + "name": "status_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response": { + "name": "response", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_api_request_log_created_at": { + "name": "idx_api_request_log_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_builder_feedback": { + "name": "app_builder_feedback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "preview_status": { + "name": "preview_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_streaming": { + "name": "is_streaming", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "message_count": { + "name": "message_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "feedback_text": { + "name": "feedback_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recent_messages": { + "name": "recent_messages", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_app_builder_feedback_created_at": { + "name": "IDX_app_builder_feedback_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_feedback_kilo_user_id": { + "name": "IDX_app_builder_feedback_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_feedback_project_id": { + "name": "IDX_app_builder_feedback_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "app_builder_feedback_kilo_user_id_kilocode_users_id_fk": { + "name": "app_builder_feedback_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "app_builder_feedback", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "app_builder_feedback_project_id_app_builder_projects_id_fk": { + "name": "app_builder_feedback_project_id_app_builder_projects_id_fk", + "tableFrom": "app_builder_feedback", + "columnsFrom": [ + "project_id" + ], + "tableTo": "app_builder_projects", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_builder_project_sessions": { + "name": "app_builder_project_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "project_id": { + "name": "project_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "worker_version": { + "name": "worker_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'v2'" + } + }, + "indexes": { + "IDX_app_builder_project_sessions_project_id": { + "name": "IDX_app_builder_project_sessions_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "app_builder_project_sessions_project_id_app_builder_projects_id_fk": { + "name": "app_builder_project_sessions_project_id_app_builder_projects_id_fk", + "tableFrom": "app_builder_project_sessions", + "columnsFrom": [ + "project_id" + ], + "tableTo": "app_builder_projects", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_app_builder_project_sessions_cloud_agent_session_id": { + "name": "UQ_app_builder_project_sessions_cloud_agent_session_id", + "columns": [ + "cloud_agent_session_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_builder_projects": { + "name": "app_builder_projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deployment_id": { + "name": "deployment_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "last_message_at": { + "name": "last_message_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "git_repo_full_name": { + "name": "git_repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_platform_integration_id": { + "name": "git_platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "migrated_at": { + "name": "migrated_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": { + "IDX_app_builder_projects_created_by_user_id": { + "name": "IDX_app_builder_projects_created_by_user_id", + "columns": [ + { + "expression": "created_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_projects_owned_by_user_id": { + "name": "IDX_app_builder_projects_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_projects_owned_by_organization_id": { + "name": "IDX_app_builder_projects_owned_by_organization_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_projects_created_at": { + "name": "IDX_app_builder_projects_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_projects_last_message_at": { + "name": "IDX_app_builder_projects_last_message_at", + "columns": [ + { + "expression": "last_message_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_app_builder_projects_git_repo_integration": { + "name": "IDX_app_builder_projects_git_repo_integration", + "columns": [ + { + "expression": "git_repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "git_platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"app_builder_projects\".\"git_repo_full_name\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "app_builder_projects_owned_by_user_id_kilocode_users_id_fk": { + "name": "app_builder_projects_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "app_builder_projects", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "app_builder_projects_owned_by_organization_id_organizations_id_fk": { + "name": "app_builder_projects_owned_by_organization_id_organizations_id_fk", + "tableFrom": "app_builder_projects", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "app_builder_projects_deployment_id_deployments_id_fk": { + "name": "app_builder_projects_deployment_id_deployments_id_fk", + "tableFrom": "app_builder_projects", + "columnsFrom": [ + "deployment_id" + ], + "tableTo": "deployments", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "app_builder_projects_git_platform_integration_id_platform_integrations_id_fk": { + "name": "app_builder_projects_git_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "app_builder_projects", + "columnsFrom": [ + "git_platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "app_builder_projects_owner_check": { + "name": "app_builder_projects_owner_check", + "value": "(\n (\"app_builder_projects\".\"owned_by_user_id\" IS NOT NULL AND \"app_builder_projects\".\"owned_by_organization_id\" IS NULL) OR\n (\"app_builder_projects\".\"owned_by_user_id\" IS NULL AND \"app_builder_projects\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.app_min_versions": { + "name": "app_min_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "ios_min_version": { + "name": "ios_min_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'1.0.0'" + }, + "android_min_version": { + "name": "android_min_version", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'1.0.0'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_reported_messages": { + "name": "app_reported_messages", + "schema": "", + "columns": { + "report_id": { + "name": "report_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "report_type": { + "name": "report_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "signature": { + "name": "signature", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "cli_session_id": { + "name": "cli_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "app_reported_messages_cli_session_id_cli_sessions_session_id_fk": { + "name": "app_reported_messages_cli_session_id_cli_sessions_session_id_fk", + "tableFrom": "app_reported_messages", + "columnsFrom": [ + "cli_session_id" + ], + "tableTo": "cli_sessions", + "columnsTo": [ + "session_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auto_fix_tickets": { + "name": "auto_fix_tickets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "triage_ticket_id": { + "name": "triage_ticket_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_number": { + "name": "issue_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "issue_url": { + "name": "issue_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_title": { + "name": "issue_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_body": { + "name": "issue_body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_author": { + "name": "issue_author", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_labels": { + "name": "issue_labels", + "type": "text[]", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "trigger_source": { + "name": "trigger_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'label'" + }, + "review_comment_id": { + "name": "review_comment_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "review_comment_body": { + "name": "review_comment_body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file_path": { + "name": "file_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "line_number": { + "name": "line_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "diff_hunk": { + "name": "diff_hunk", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_head_ref": { + "name": "pr_head_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "classification": { + "name": "classification", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confidence": { + "name": "confidence", + "type": "numeric(3, 2)", + "primaryKey": false, + "notNull": false + }, + "intent_summary": { + "name": "intent_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "related_files": { + "name": "related_files", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_session_id": { + "name": "cli_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_branch": { + "name": "pr_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "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": { + "UQ_auto_fix_tickets_repo_issue": { + "name": "UQ_auto_fix_tickets_repo_issue", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"auto_fix_tickets\".\"trigger_source\" = 'label'", + "concurrently": false + }, + "UQ_auto_fix_tickets_repo_review_comment": { + "name": "UQ_auto_fix_tickets_repo_review_comment", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "review_comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"auto_fix_tickets\".\"review_comment_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_auto_fix_tickets_owned_by_org": { + "name": "IDX_auto_fix_tickets_owned_by_org", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_fix_tickets_owned_by_user": { + "name": "IDX_auto_fix_tickets_owned_by_user", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_fix_tickets_status": { + "name": "IDX_auto_fix_tickets_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_fix_tickets_created_at": { + "name": "IDX_auto_fix_tickets_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_fix_tickets_triage_ticket_id": { + "name": "IDX_auto_fix_tickets_triage_ticket_id", + "columns": [ + { + "expression": "triage_ticket_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_fix_tickets_session_id": { + "name": "IDX_auto_fix_tickets_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "auto_fix_tickets_owned_by_organization_id_organizations_id_fk": { + "name": "auto_fix_tickets_owned_by_organization_id_organizations_id_fk", + "tableFrom": "auto_fix_tickets", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "auto_fix_tickets_owned_by_user_id_kilocode_users_id_fk": { + "name": "auto_fix_tickets_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "auto_fix_tickets", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "auto_fix_tickets_platform_integration_id_platform_integrations_id_fk": { + "name": "auto_fix_tickets_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "auto_fix_tickets", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "auto_fix_tickets_triage_ticket_id_auto_triage_tickets_id_fk": { + "name": "auto_fix_tickets_triage_ticket_id_auto_triage_tickets_id_fk", + "tableFrom": "auto_fix_tickets", + "columnsFrom": [ + "triage_ticket_id" + ], + "tableTo": "auto_triage_tickets", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "auto_fix_tickets_cli_session_id_cli_sessions_session_id_fk": { + "name": "auto_fix_tickets_cli_session_id_cli_sessions_session_id_fk", + "tableFrom": "auto_fix_tickets", + "columnsFrom": [ + "cli_session_id" + ], + "tableTo": "cli_sessions", + "columnsTo": [ + "session_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "auto_fix_tickets_owner_check": { + "name": "auto_fix_tickets_owner_check", + "value": "(\n (\"auto_fix_tickets\".\"owned_by_user_id\" IS NOT NULL AND \"auto_fix_tickets\".\"owned_by_organization_id\" IS NULL) OR\n (\"auto_fix_tickets\".\"owned_by_user_id\" IS NULL AND \"auto_fix_tickets\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "auto_fix_tickets_status_check": { + "name": "auto_fix_tickets_status_check", + "value": "\"auto_fix_tickets\".\"status\" IN ('pending', 'running', 'completed', 'failed', 'cancelled')" + }, + "auto_fix_tickets_classification_check": { + "name": "auto_fix_tickets_classification_check", + "value": "\"auto_fix_tickets\".\"classification\" IN ('bug', 'feature', 'question', 'unclear')" + }, + "auto_fix_tickets_confidence_check": { + "name": "auto_fix_tickets_confidence_check", + "value": "\"auto_fix_tickets\".\"confidence\" >= 0 AND \"auto_fix_tickets\".\"confidence\" <= 1" + }, + "auto_fix_tickets_trigger_source_check": { + "name": "auto_fix_tickets_trigger_source_check", + "value": "\"auto_fix_tickets\".\"trigger_source\" IN ('label', 'review_comment')" + } + }, + "isRLSEnabled": false + }, + "public.auto_model": { + "name": "auto_model", + "schema": "", + "columns": { + "auto_model_id": { + "name": "auto_model_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "auto_model": { + "name": "auto_model", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_auto_model": { + "name": "UQ_auto_model", + "columns": [ + { + "expression": "auto_model", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auto_top_up_configs": { + "name": "auto_top_up_configs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_payment_method_id": { + "name": "stripe_payment_method_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 5000 + }, + "last_auto_top_up_at": { + "name": "last_auto_top_up_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "attempt_started_at": { + "name": "attempt_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "disabled_reason": { + "name": "disabled_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": { + "UQ_auto_top_up_configs_owned_by_user_id": { + "name": "UQ_auto_top_up_configs_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"auto_top_up_configs\".\"owned_by_user_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_auto_top_up_configs_owned_by_organization_id": { + "name": "UQ_auto_top_up_configs_owned_by_organization_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"auto_top_up_configs\".\"owned_by_organization_id\" IS NOT NULL", + "concurrently": false + } + }, + "foreignKeys": { + "auto_top_up_configs_owned_by_user_id_kilocode_users_id_fk": { + "name": "auto_top_up_configs_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "auto_top_up_configs", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "auto_top_up_configs_owned_by_organization_id_organizations_id_fk": { + "name": "auto_top_up_configs_owned_by_organization_id_organizations_id_fk", + "tableFrom": "auto_top_up_configs", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "auto_top_up_configs_exactly_one_owner": { + "name": "auto_top_up_configs_exactly_one_owner", + "value": "(\"auto_top_up_configs\".\"owned_by_user_id\" IS NOT NULL AND \"auto_top_up_configs\".\"owned_by_organization_id\" IS NULL) OR (\"auto_top_up_configs\".\"owned_by_user_id\" IS NULL AND \"auto_top_up_configs\".\"owned_by_organization_id\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.auto_triage_tickets": { + "name": "auto_triage_tickets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_number": { + "name": "issue_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "issue_url": { + "name": "issue_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_title": { + "name": "issue_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_body": { + "name": "issue_body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_author": { + "name": "issue_author", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_type": { + "name": "issue_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_labels": { + "name": "issue_labels", + "type": "text[]", + "primaryKey": false, + "notNull": false, + "default": "'{}'" + }, + "classification": { + "name": "classification", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confidence": { + "name": "confidence", + "type": "numeric(3, 2)", + "primaryKey": false, + "notNull": false + }, + "intent_summary": { + "name": "intent_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "related_files": { + "name": "related_files", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "is_duplicate": { + "name": "is_duplicate", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "duplicate_of_ticket_id": { + "name": "duplicate_of_ticket_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "similarity_score": { + "name": "similarity_score", + "type": "numeric(3, 2)", + "primaryKey": false, + "notNull": false + }, + "qdrant_point_id": { + "name": "qdrant_point_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "should_auto_fix": { + "name": "should_auto_fix", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "action_taken": { + "name": "action_taken", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action_metadata": { + "name": "action_metadata", + "type": "jsonb", + "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": { + "UQ_auto_triage_tickets_repo_issue": { + "name": "UQ_auto_triage_tickets_repo_issue", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_owned_by_org": { + "name": "IDX_auto_triage_tickets_owned_by_org", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_owned_by_user": { + "name": "IDX_auto_triage_tickets_owned_by_user", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_status": { + "name": "IDX_auto_triage_tickets_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_created_at": { + "name": "IDX_auto_triage_tickets_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_qdrant_point_id": { + "name": "IDX_auto_triage_tickets_qdrant_point_id", + "columns": [ + { + "expression": "qdrant_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_owner_status_created": { + "name": "IDX_auto_triage_tickets_owner_status_created", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_user_status_created": { + "name": "IDX_auto_triage_tickets_user_status_created", + "columns": [ + { + "expression": "owned_by_user_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, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_auto_triage_tickets_repo_classification": { + "name": "IDX_auto_triage_tickets_repo_classification", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "classification", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "auto_triage_tickets_owned_by_organization_id_organizations_id_fk": { + "name": "auto_triage_tickets_owned_by_organization_id_organizations_id_fk", + "tableFrom": "auto_triage_tickets", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "auto_triage_tickets_owned_by_user_id_kilocode_users_id_fk": { + "name": "auto_triage_tickets_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "auto_triage_tickets", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "auto_triage_tickets_platform_integration_id_platform_integrations_id_fk": { + "name": "auto_triage_tickets_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "auto_triage_tickets", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "auto_triage_tickets_duplicate_of_ticket_id_auto_triage_tickets_id_fk": { + "name": "auto_triage_tickets_duplicate_of_ticket_id_auto_triage_tickets_id_fk", + "tableFrom": "auto_triage_tickets", + "columnsFrom": [ + "duplicate_of_ticket_id" + ], + "tableTo": "auto_triage_tickets", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "auto_triage_tickets_owner_check": { + "name": "auto_triage_tickets_owner_check", + "value": "(\n (\"auto_triage_tickets\".\"owned_by_user_id\" IS NOT NULL AND \"auto_triage_tickets\".\"owned_by_organization_id\" IS NULL) OR\n (\"auto_triage_tickets\".\"owned_by_user_id\" IS NULL AND \"auto_triage_tickets\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "auto_triage_tickets_issue_type_check": { + "name": "auto_triage_tickets_issue_type_check", + "value": "\"auto_triage_tickets\".\"issue_type\" IN ('issue', 'pull_request')" + }, + "auto_triage_tickets_classification_check": { + "name": "auto_triage_tickets_classification_check", + "value": "\"auto_triage_tickets\".\"classification\" IN ('bug', 'feature', 'question', 'duplicate', 'unclear')" + }, + "auto_triage_tickets_confidence_check": { + "name": "auto_triage_tickets_confidence_check", + "value": "\"auto_triage_tickets\".\"confidence\" >= 0 AND \"auto_triage_tickets\".\"confidence\" <= 1" + }, + "auto_triage_tickets_similarity_score_check": { + "name": "auto_triage_tickets_similarity_score_check", + "value": "\"auto_triage_tickets\".\"similarity_score\" >= 0 AND \"auto_triage_tickets\".\"similarity_score\" <= 1" + }, + "auto_triage_tickets_status_check": { + "name": "auto_triage_tickets_status_check", + "value": "\"auto_triage_tickets\".\"status\" IN ('pending', 'analyzing', 'actioned', 'failed', 'skipped')" + }, + "auto_triage_tickets_action_taken_check": { + "name": "auto_triage_tickets_action_taken_check", + "value": "\"auto_triage_tickets\".\"action_taken\" IN ('pr_created', 'comment_posted', 'closed_duplicate', 'needs_clarification')" + } + }, + "isRLSEnabled": false + }, + "public.bot_request_cloud_agent_sessions": { + "name": "bot_request_cloud_agent_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "bot_request_id": { + "name": "bot_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "spawn_group_id": { + "name": "spawn_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_session_id": { + "name": "kilo_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_repo": { + "name": "github_repo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitlab_project": { + "name": "gitlab_project", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "callback_step": { + "name": "callback_step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "final_message": { + "name": "final_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "final_message_fetched_at": { + "name": "final_message_fetched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "final_message_error": { + "name": "final_message_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "terminal_at": { + "name": "terminal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "continuation_started_at": { + "name": "continuation_started_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": { + "UQ_bot_request_cas_cloud_agent_session_id": { + "name": "UQ_bot_request_cas_cloud_agent_session_id", + "columns": [ + { + "expression": "cloud_agent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_request_cas_bot_request_id": { + "name": "IDX_bot_request_cas_bot_request_id", + "columns": [ + { + "expression": "bot_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_request_cas_bot_request_id_spawn_group_id": { + "name": "IDX_bot_request_cas_bot_request_id_spawn_group_id", + "columns": [ + { + "expression": "bot_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spawn_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_request_cas_bot_request_id_spawn_group_id_status": { + "name": "IDX_bot_request_cas_bot_request_id_spawn_group_id_status", + "columns": [ + { + "expression": "bot_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "spawn_group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "bot_request_cloud_agent_sessions_bot_request_id_bot_requests_id_fk": { + "name": "bot_request_cloud_agent_sessions_bot_request_id_bot_requests_id_fk", + "tableFrom": "bot_request_cloud_agent_sessions", + "columnsFrom": [ + "bot_request_id" + ], + "tableTo": "bot_requests", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.bot_requests": { + "name": "bot_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform_thread_id": { + "name": "platform_thread_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform_message_id": { + "name": "platform_message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_message": { + "name": "user_message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model_used": { + "name": "model_used", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "steps": { + "name": "steps", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_time_ms": { + "name": "response_time_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": { + "IDX_bot_requests_created_at": { + "name": "IDX_bot_requests_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_requests_created_by": { + "name": "IDX_bot_requests_created_by", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_requests_organization_id": { + "name": "IDX_bot_requests_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_requests_platform_integration_id": { + "name": "IDX_bot_requests_platform_integration_id", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_bot_requests_status": { + "name": "IDX_bot_requests_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "bot_requests_created_by_kilocode_users_id_fk": { + "name": "bot_requests_created_by_kilocode_users_id_fk", + "tableFrom": "bot_requests", + "columnsFrom": [ + "created_by" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "bot_requests_organization_id_organizations_id_fk": { + "name": "bot_requests_organization_id_organizations_id_fk", + "tableFrom": "bot_requests", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "bot_requests_platform_integration_id_platform_integrations_id_fk": { + "name": "bot_requests_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "bot_requests", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.byok_api_keys": { + "name": "byok_api_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "management_source": { + "name": "management_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'user'" + }, + "is_enabled": { + "name": "is_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "IDX_byok_api_keys_organization_id": { + "name": "IDX_byok_api_keys_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_byok_api_keys_kilo_user_id": { + "name": "IDX_byok_api_keys_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_byok_api_keys_provider_id": { + "name": "IDX_byok_api_keys_provider_id", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "byok_api_keys_organization_id_organizations_id_fk": { + "name": "byok_api_keys_organization_id_organizations_id_fk", + "tableFrom": "byok_api_keys", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "byok_api_keys_kilo_user_id_kilocode_users_id_fk": { + "name": "byok_api_keys_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "byok_api_keys", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_byok_api_keys_org_provider": { + "name": "UQ_byok_api_keys_org_provider", + "columns": [ + "organization_id", + "provider_id" + ], + "nullsNotDistinct": false + }, + "UQ_byok_api_keys_user_provider": { + "name": "UQ_byok_api_keys_user_provider", + "columns": [ + "kilo_user_id", + "provider_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "byok_api_keys_management_source_check": { + "name": "byok_api_keys_management_source_check", + "value": "\"byok_api_keys\".\"management_source\" IN ('user', 'coding_plan')" + }, + "byok_api_keys_owner_check": { + "name": "byok_api_keys_owner_check", + "value": "(\n (\"byok_api_keys\".\"kilo_user_id\" IS NOT NULL AND \"byok_api_keys\".\"organization_id\" IS NULL) OR\n (\"byok_api_keys\".\"kilo_user_id\" IS NULL AND \"byok_api_keys\".\"organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.cli_sessions": { + "name": "cli_sessions", + "schema": "", + "columns": { + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_on_platform": { + "name": "created_on_platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "api_conversation_history_blob_url": { + "name": "api_conversation_history_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_metadata_blob_url": { + "name": "task_metadata_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ui_messages_blob_url": { + "name": "ui_messages_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_state_blob_url": { + "name": "git_state_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_url": { + "name": "git_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "forked_from": { + "name": "forked_from", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "parent_session_id": { + "name": "parent_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "last_mode": { + "name": "last_mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_model": { + "name": "last_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "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": { + "IDX_cli_sessions_kilo_user_id": { + "name": "IDX_cli_sessions_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_created_at": { + "name": "IDX_cli_sessions_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_updated_at": { + "name": "IDX_cli_sessions_updated_at", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_organization_id": { + "name": "IDX_cli_sessions_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_user_updated": { + "name": "IDX_cli_sessions_user_updated", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cli_sessions_kilo_user_id_kilocode_users_id_fk": { + "name": "cli_sessions_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "cli_sessions", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "cli_sessions_forked_from_cli_sessions_session_id_fk": { + "name": "cli_sessions_forked_from_cli_sessions_session_id_fk", + "tableFrom": "cli_sessions", + "columnsFrom": [ + "forked_from" + ], + "tableTo": "cli_sessions", + "columnsTo": [ + "session_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "cli_sessions_parent_session_id_cli_sessions_session_id_fk": { + "name": "cli_sessions_parent_session_id_cli_sessions_session_id_fk", + "tableFrom": "cli_sessions", + "columnsFrom": [ + "parent_session_id" + ], + "tableTo": "cli_sessions", + "columnsTo": [ + "session_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "cli_sessions_organization_id_organizations_id_fk": { + "name": "cli_sessions_organization_id_organizations_id_fk", + "tableFrom": "cli_sessions", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "cli_sessions_cloud_agent_session_id_unique": { + "name": "cli_sessions_cloud_agent_session_id_unique", + "columns": [ + "cloud_agent_session_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.cli_sessions_v2": { + "name": "cli_sessions_v2", + "schema": "", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_id": { + "name": "public_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "parent_session_id": { + "name": "parent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_scope_id": { + "name": "cloud_agent_session_scope_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_on_platform": { + "name": "created_on_platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "git_url": { + "name": "git_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_branch": { + "name": "git_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_updated_at": { + "name": "status_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "total_cost_microdollars": { + "name": "total_cost_microdollars", + "type": "bigint", + "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": { + "IDX_cli_sessions_v2_parent_session_id_kilo_user_id": { + "name": "IDX_cli_sessions_v2_parent_session_id_kilo_user_id", + "columns": [ + { + "expression": "parent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_cli_sessions_v2_public_id": { + "name": "UQ_cli_sessions_v2_public_id", + "columns": [ + { + "expression": "public_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cli_sessions_v2\".\"public_id\" is not null", + "concurrently": false + }, + "UQ_cli_sessions_v2_cloud_agent_session_id": { + "name": "UQ_cli_sessions_v2_cloud_agent_session_id", + "columns": [ + { + "expression": "cloud_agent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cli_sessions_v2\".\"cloud_agent_session_id\" is not null", + "concurrently": false + }, + "IDX_cli_sessions_v2_organization_id": { + "name": "IDX_cli_sessions_v2_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_v2_kilo_user_id": { + "name": "IDX_cli_sessions_v2_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_v2_created_at": { + "name": "IDX_cli_sessions_v2_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cli_sessions_v2_user_updated": { + "name": "IDX_cli_sessions_v2_user_updated", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "cli_sessions_v2_git_url_branch_idx": { + "name": "cli_sessions_v2_git_url_branch_idx", + "columns": [ + { + "expression": "git_url", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cli_sessions_v2_kilo_user_id_kilocode_users_id_fk": { + "name": "cli_sessions_v2_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "cli_sessions_v2", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "cli_sessions_v2_organization_id_organizations_id_fk": { + "name": "cli_sessions_v2_organization_id_organizations_id_fk", + "tableFrom": "cli_sessions_v2", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "cli_sessions_v2_parent_session_id_kilo_user_id_fk": { + "name": "cli_sessions_v2_parent_session_id_kilo_user_id_fk", + "tableFrom": "cli_sessions_v2", + "columnsFrom": [ + "parent_session_id", + "kilo_user_id" + ], + "tableTo": "cli_sessions_v2", + "columnsTo": [ + "session_id", + "kilo_user_id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": { + "cli_sessions_v2_session_id_kilo_user_id_pk": { + "name": "cli_sessions_v2_session_id_kilo_user_id_pk", + "columns": [ + "session_id", + "kilo_user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.cloud_agent_code_review_attempts": { + "name": "cloud_agent_code_review_attempts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "code_review_id": { + "name": "code_review_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "attempt_number": { + "name": "attempt_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_of_attempt_id": { + "name": "retry_of_attempt_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "retry_reason": { + "name": "retry_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_session_id": { + "name": "cli_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analytics_enabled_at_dispatch": { + "name": "analytics_enabled_at_dispatch", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "terminal_reason": { + "name": "terminal_reason", + "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": { + "UQ_cloud_agent_code_review_attempts_review_attempt_number": { + "name": "UQ_cloud_agent_code_review_attempts_review_attempt_number", + "columns": [ + { + "expression": "code_review_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "attempt_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_review_attempts_code_review_id": { + "name": "idx_cloud_agent_code_review_attempts_code_review_id", + "columns": [ + { + "expression": "code_review_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_review_attempts_session_id": { + "name": "idx_cloud_agent_code_review_attempts_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_review_attempts_cli_session_id": { + "name": "idx_cloud_agent_code_review_attempts_cli_session_id", + "columns": [ + { + "expression": "cli_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_review_attempts_status": { + "name": "idx_cloud_agent_code_review_attempts_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_review_attempts_retry_reason": { + "name": "idx_cloud_agent_code_review_attempts_retry_reason", + "columns": [ + { + "expression": "retry_reason", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cloud_agent_code_review_attempts_code_review_id_cloud_agent_code_reviews_id_fk": { + "name": "cloud_agent_code_review_attempts_code_review_id_cloud_agent_code_reviews_id_fk", + "tableFrom": "cloud_agent_code_review_attempts", + "columnsFrom": [ + "code_review_id" + ], + "tableTo": "cloud_agent_code_reviews", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "cloud_agent_code_review_attempts_retry_of_attempt_id_cloud_agent_code_review_attempts_id_fk": { + "name": "cloud_agent_code_review_attempts_retry_of_attempt_id_cloud_agent_code_review_attempts_id_fk", + "tableFrom": "cloud_agent_code_review_attempts", + "columnsFrom": [ + "retry_of_attempt_id" + ], + "tableTo": "cloud_agent_code_review_attempts", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "cloud_agent_code_review_attempts_attempt_number_check": { + "name": "cloud_agent_code_review_attempts_attempt_number_check", + "value": "\"cloud_agent_code_review_attempts\".\"attempt_number\" >= 1" + } + }, + "isRLSEnabled": false + }, + "public.cloud_agent_code_reviews": { + "name": "cloud_agent_code_reviews", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "manual_config": { + "name": "manual_config", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "review_type": { + "name": "review_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'standard'" + }, + "trigger_source": { + "name": "trigger_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "council_result": { + "name": "council_result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_title": { + "name": "pr_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_author": { + "name": "pr_author", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_author_github_id": { + "name": "pr_author_github_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_ref": { + "name": "base_ref", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head_ref": { + "name": "head_ref", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "head_sha": { + "name": "head_sha", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "platform_project_id": { + "name": "platform_project_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_session_id": { + "name": "cli_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "dispatch_reservation_id": { + "name": "dispatch_reservation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "terminal_reason": { + "name": "terminal_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "agent_version": { + "name": "agent_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'v1'" + }, + "check_run_id": { + "name": "check_run_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "repository_review_instructions_used": { + "name": "repository_review_instructions_used", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "repository_review_instructions_ref": { + "name": "repository_review_instructions_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repository_review_instructions_truncated": { + "name": "repository_review_instructions_truncated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "previous_summary_body": { + "name": "previous_summary_body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "previous_summary_head_sha": { + "name": "previous_summary_head_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "total_tokens_in": { + "name": "total_tokens_in", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_tokens_out": { + "name": "total_tokens_out", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_cost_musd": { + "name": "total_cost_musd", + "type": "integer", + "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": { + "UQ_cloud_agent_code_reviews_webhook_integration_repo_pr_sha": { + "name": "UQ_cloud_agent_code_reviews_webhook_integration_repo_pr_sha", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pr_number", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "head_sha", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_code_reviews\".\"manual_config\" IS NULL", + "concurrently": false + }, + "UQ_cloud_agent_code_reviews_active_provider_publisher": { + "name": "UQ_cloud_agent_code_reviews_active_provider_publisher", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pr_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_code_reviews\".\"platform_integration_id\" IS NOT NULL\n AND \"cloud_agent_code_reviews\".\"status\" IN ('pending', 'queued', 'running')\n AND (\"cloud_agent_code_reviews\".\"manual_config\" IS NULL OR \"cloud_agent_code_reviews\".\"manual_config\"->>'outputMode' = 'provider')", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_owned_by_org_id": { + "name": "idx_cloud_agent_code_reviews_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_owned_by_user_id": { + "name": "idx_cloud_agent_code_reviews_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_session_id": { + "name": "idx_cloud_agent_code_reviews_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_cli_session_id": { + "name": "idx_cloud_agent_code_reviews_cli_session_id", + "columns": [ + { + "expression": "cli_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_status": { + "name": "idx_cloud_agent_code_reviews_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_repo": { + "name": "idx_cloud_agent_code_reviews_repo", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_pr_number": { + "name": "idx_cloud_agent_code_reviews_pr_number", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "pr_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_created_at": { + "name": "idx_cloud_agent_code_reviews_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_cloud_agent_code_reviews_pr_author_github_id": { + "name": "idx_cloud_agent_code_reviews_pr_author_github_id", + "columns": [ + { + "expression": "pr_author_github_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cloud_agent_code_reviews_owned_by_organization_id_organizations_id_fk": { + "name": "cloud_agent_code_reviews_owned_by_organization_id_organizations_id_fk", + "tableFrom": "cloud_agent_code_reviews", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "cloud_agent_code_reviews_owned_by_user_id_kilocode_users_id_fk": { + "name": "cloud_agent_code_reviews_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "cloud_agent_code_reviews", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "cloud_agent_code_reviews_platform_integration_id_platform_integrations_id_fk": { + "name": "cloud_agent_code_reviews_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "cloud_agent_code_reviews", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "cloud_agent_code_reviews_owner_check": { + "name": "cloud_agent_code_reviews_owner_check", + "value": "(\n (\"cloud_agent_code_reviews\".\"owned_by_user_id\" IS NOT NULL AND \"cloud_agent_code_reviews\".\"owned_by_organization_id\" IS NULL) OR\n (\"cloud_agent_code_reviews\".\"owned_by_user_id\" IS NULL AND \"cloud_agent_code_reviews\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.cloud_agent_feedback": { + "name": "cloud_agent_feedback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_type": { + "name": "session_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repository": { + "name": "repository", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_streaming": { + "name": "is_streaming", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "message_count": { + "name": "message_count", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "feedback_text": { + "name": "feedback_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recent_messages": { + "name": "recent_messages", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_cloud_agent_feedback_created_at": { + "name": "IDX_cloud_agent_feedback_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_feedback_kilo_user_id": { + "name": "IDX_cloud_agent_feedback_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_feedback_cloud_agent_session_id": { + "name": "IDX_cloud_agent_feedback_cloud_agent_session_id", + "columns": [ + { + "expression": "cloud_agent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cloud_agent_feedback_kilo_user_id_kilocode_users_id_fk": { + "name": "cloud_agent_feedback_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "cloud_agent_feedback", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "cloud_agent_feedback_organization_id_organizations_id_fk": { + "name": "cloud_agent_feedback_organization_id_organizations_id_fk", + "tableFrom": "cloud_agent_feedback", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.cloud_agent_session_runs": { + "name": "cloud_agent_session_runs", + "schema": "", + "columns": { + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "wrapper_run_id": { + "name": "wrapper_run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "dispatch_accepted_at": { + "name": "dispatch_accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "agent_activity_observed_at": { + "name": "agent_activity_observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "terminal_at": { + "name": "terminal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failure_stage": { + "name": "failure_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_responsibility": { + "name": "failure_responsibility", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message_redacted": { + "name": "error_message_redacted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_expires_at": { + "name": "error_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_cloud_agent_session_runs_wrapper_run_id": { + "name": "IDX_cloud_agent_session_runs_wrapper_run_id", + "columns": [ + { + "expression": "wrapper_run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_session_runs\".\"wrapper_run_id\" is not null", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_session_queued": { + "name": "IDX_cloud_agent_session_runs_session_queued", + "columns": [ + { + "expression": "cloud_agent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_queued_at": { + "name": "IDX_cloud_agent_session_runs_queued_at", + "columns": [ + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_terminal_at": { + "name": "IDX_cloud_agent_session_runs_terminal_at", + "columns": [ + { + "expression": "terminal_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_status_terminal": { + "name": "IDX_cloud_agent_session_runs_status_terminal", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "terminal_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_failure_terminal": { + "name": "IDX_cloud_agent_session_runs_failure_terminal", + "columns": [ + { + "expression": "failure_stage", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failure_code", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "terminal_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_session_runs_responsibility_reason_terminal": { + "name": "IDX_cloud_agent_session_runs_responsibility_reason_terminal", + "columns": [ + { + "expression": "failure_responsibility", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failure_reason", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "terminal_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_session_runs\".\"status\" = 'failed'", + "concurrently": true + }, + "IDX_cloud_agent_session_runs_error_expires_at": { + "name": "IDX_cloud_agent_session_runs_error_expires_at", + "columns": [ + { + "expression": "error_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_session_runs\".\"error_expires_at\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "cloud_agent_session_runs_cloud_agent_session_id_cloud_agent_sessions_cloud_agent_session_id_fk": { + "name": "cloud_agent_session_runs_cloud_agent_session_id_cloud_agent_sessions_cloud_agent_session_id_fk", + "tableFrom": "cloud_agent_session_runs", + "columnsFrom": [ + "cloud_agent_session_id" + ], + "tableTo": "cloud_agent_sessions", + "columnsTo": [ + "cloud_agent_session_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "cloud_agent_session_runs_cloud_agent_session_id_message_id_pk": { + "name": "cloud_agent_session_runs_cloud_agent_session_id_message_id_pk", + "columns": [ + "cloud_agent_session_id", + "message_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "cloud_agent_session_runs_status_check": { + "name": "cloud_agent_session_runs_status_check", + "value": "\"cloud_agent_session_runs\".\"status\" IN ('queued', 'accepted', 'completed', 'failed', 'interrupted')" + }, + "cloud_agent_session_runs_error_message_bounded_check": { + "name": "cloud_agent_session_runs_error_message_bounded_check", + "value": "\"cloud_agent_session_runs\".\"error_message_redacted\" IS NULL OR char_length(\"cloud_agent_session_runs\".\"error_message_redacted\") <= 4096" + }, + "cloud_agent_session_runs_error_expiry_check": { + "name": "cloud_agent_session_runs_error_expiry_check", + "value": "(\"cloud_agent_session_runs\".\"error_message_redacted\" IS NULL AND \"cloud_agent_session_runs\".\"error_expires_at\" IS NULL) OR\n (\"cloud_agent_session_runs\".\"error_message_redacted\" IS NOT NULL AND \"cloud_agent_session_runs\".\"error_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.cloud_agent_sessions": { + "name": "cloud_agent_sessions", + "schema": "", + "columns": { + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kilo_session_id": { + "name": "kilo_session_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "initial_message_id": { + "name": "initial_message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sandbox_id": { + "name": "sandbox_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "failure_at": { + "name": "failure_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failure_stage": { + "name": "failure_stage", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_responsibility": { + "name": "failure_responsibility", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_reason": { + "name": "failure_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message_redacted": { + "name": "error_message_redacted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_expires_at": { + "name": "error_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_cloud_agent_sessions_kilo_session_id": { + "name": "UQ_cloud_agent_sessions_kilo_session_id", + "columns": [ + { + "expression": "kilo_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_cloud_agent_sessions_initial_message_id": { + "name": "UQ_cloud_agent_sessions_initial_message_id", + "columns": [ + { + "expression": "initial_message_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_sessions_sandbox_id": { + "name": "IDX_cloud_agent_sessions_sandbox_id", + "columns": [ + { + "expression": "sandbox_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_sessions\".\"sandbox_id\" is not null", + "concurrently": false + }, + "IDX_cloud_agent_sessions_created_at": { + "name": "IDX_cloud_agent_sessions_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_sessions_failure_created": { + "name": "IDX_cloud_agent_sessions_failure_created", + "columns": [ + { + "expression": "failure_stage", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failure_code", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_sessions_failure_at": { + "name": "IDX_cloud_agent_sessions_failure_at", + "columns": [ + { + "expression": "failure_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_sessions\".\"failure_at\" is not null", + "concurrently": false + }, + "IDX_cloud_agent_sessions_failure_classification_at": { + "name": "IDX_cloud_agent_sessions_failure_classification_at", + "columns": [ + { + "expression": "failure_stage", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failure_code", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "failure_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_sessions\".\"failure_at\" is not null", + "concurrently": false + }, + "IDX_cloud_agent_sessions_error_expires_at": { + "name": "IDX_cloud_agent_sessions_error_expires_at", + "columns": [ + { + "expression": "error_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_sessions\".\"error_expires_at\" is not null", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "cloud_agent_sessions_failure_classification_check": { + "name": "cloud_agent_sessions_failure_classification_check", + "value": "(\"cloud_agent_sessions\".\"failure_at\" IS NULL AND \"cloud_agent_sessions\".\"failure_stage\" IS NULL AND \"cloud_agent_sessions\".\"failure_code\" IS NULL) OR\n (\"cloud_agent_sessions\".\"failure_at\" IS NOT NULL AND \"cloud_agent_sessions\".\"failure_stage\" = 'sandbox_identity' AND \"cloud_agent_sessions\".\"failure_code\" = 'sandbox_id_derivation_failed') OR\n (\"cloud_agent_sessions\".\"failure_at\" IS NOT NULL AND \"cloud_agent_sessions\".\"failure_stage\" = 'registration' AND \"cloud_agent_sessions\".\"failure_code\" = 'do_registration_rejected') OR\n (\"cloud_agent_sessions\".\"failure_at\" IS NOT NULL AND \"cloud_agent_sessions\".\"failure_stage\" = 'initial_admission' AND \"cloud_agent_sessions\".\"failure_code\" IN ('initial_admission_rejected', 'initial_queue_full', 'invalid_initial_intent')) OR\n (\"cloud_agent_sessions\".\"failure_at\" IS NOT NULL AND \"cloud_agent_sessions\".\"failure_stage\" = 'transport' AND \"cloud_agent_sessions\".\"failure_code\" = 'do_rpc_outcome_unknown')" + }, + "cloud_agent_sessions_error_message_bounded_check": { + "name": "cloud_agent_sessions_error_message_bounded_check", + "value": "\"cloud_agent_sessions\".\"error_message_redacted\" IS NULL OR char_length(\"cloud_agent_sessions\".\"error_message_redacted\") <= 4096" + }, + "cloud_agent_sessions_error_expiry_check": { + "name": "cloud_agent_sessions_error_expiry_check", + "value": "(\"cloud_agent_sessions\".\"error_message_redacted\" IS NULL AND \"cloud_agent_sessions\".\"error_expires_at\" IS NULL) OR\n (\"cloud_agent_sessions\".\"error_message_redacted\" IS NOT NULL AND \"cloud_agent_sessions\".\"error_expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.cloud_agent_webhook_triggers": { + "name": "cloud_agent_webhook_triggers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "trigger_id": { + "name": "trigger_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'cloud_agent'" + }, + "kiloclaw_instance_id": { + "name": "kiloclaw_instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "activation_mode": { + "name": "activation_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'webhook'" + }, + "cron_expression": { + "name": "cron_expression", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cron_timezone": { + "name": "cron_timezone", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'UTC'" + }, + "github_repo": { + "name": "github_repo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "profile_id": { + "name": "profile_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": { + "UQ_cloud_agent_webhook_triggers_user_trigger": { + "name": "UQ_cloud_agent_webhook_triggers_user_trigger", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_webhook_triggers\".\"user_id\" is not null", + "concurrently": false + }, + "UQ_cloud_agent_webhook_triggers_org_trigger": { + "name": "UQ_cloud_agent_webhook_triggers_org_trigger", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "trigger_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"cloud_agent_webhook_triggers\".\"organization_id\" is not null", + "concurrently": false + }, + "IDX_cloud_agent_webhook_triggers_user": { + "name": "IDX_cloud_agent_webhook_triggers_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_webhook_triggers_org": { + "name": "IDX_cloud_agent_webhook_triggers_org", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_webhook_triggers_active": { + "name": "IDX_cloud_agent_webhook_triggers_active", + "columns": [ + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_cloud_agent_webhook_triggers_profile": { + "name": "IDX_cloud_agent_webhook_triggers_profile", + "columns": [ + { + "expression": "profile_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "cloud_agent_webhook_triggers_user_id_kilocode_users_id_fk": { + "name": "cloud_agent_webhook_triggers_user_id_kilocode_users_id_fk", + "tableFrom": "cloud_agent_webhook_triggers", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "cloud_agent_webhook_triggers_organization_id_organizations_id_fk": { + "name": "cloud_agent_webhook_triggers_organization_id_organizations_id_fk", + "tableFrom": "cloud_agent_webhook_triggers", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "cloud_agent_webhook_triggers_kiloclaw_instance_id_kiloclaw_instances_id_fk": { + "name": "cloud_agent_webhook_triggers_kiloclaw_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "cloud_agent_webhook_triggers", + "columnsFrom": [ + "kiloclaw_instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "cloud_agent_webhook_triggers_profile_id_agent_environment_profiles_id_fk": { + "name": "cloud_agent_webhook_triggers_profile_id_agent_environment_profiles_id_fk", + "tableFrom": "cloud_agent_webhook_triggers", + "columnsFrom": [ + "profile_id" + ], + "tableTo": "agent_environment_profiles", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "CHK_cloud_agent_webhook_triggers_owner": { + "name": "CHK_cloud_agent_webhook_triggers_owner", + "value": "(\n (\"cloud_agent_webhook_triggers\".\"user_id\" IS NOT NULL AND \"cloud_agent_webhook_triggers\".\"organization_id\" IS NULL) OR\n (\"cloud_agent_webhook_triggers\".\"user_id\" IS NULL AND \"cloud_agent_webhook_triggers\".\"organization_id\" IS NOT NULL)\n )" + }, + "CHK_cloud_agent_webhook_triggers_cloud_agent_fields": { + "name": "CHK_cloud_agent_webhook_triggers_cloud_agent_fields", + "value": "(\n \"cloud_agent_webhook_triggers\".\"target_type\" != 'cloud_agent' OR\n (\"cloud_agent_webhook_triggers\".\"github_repo\" IS NOT NULL AND \"cloud_agent_webhook_triggers\".\"profile_id\" IS NOT NULL)\n )" + }, + "CHK_cloud_agent_webhook_triggers_kiloclaw_fields": { + "name": "CHK_cloud_agent_webhook_triggers_kiloclaw_fields", + "value": "(\n \"cloud_agent_webhook_triggers\".\"target_type\" != 'kiloclaw_chat' OR\n \"cloud_agent_webhook_triggers\".\"kiloclaw_instance_id\" IS NOT NULL\n )" + }, + "CHK_cloud_agent_webhook_triggers_scheduled_fields": { + "name": "CHK_cloud_agent_webhook_triggers_scheduled_fields", + "value": "(\n \"cloud_agent_webhook_triggers\".\"activation_mode\" != 'scheduled' OR\n \"cloud_agent_webhook_triggers\".\"cron_expression\" IS NOT NULL\n )" + } + }, + "isRLSEnabled": false + }, + "public.cloud_billing_sku": { + "name": "cloud_billing_sku", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rate_cents_per_unit": { + "name": "rate_cents_per_unit", + "type": "numeric(24, 12)", + "primaryKey": false, + "notNull": true + }, + "accepts_new_usage": { + "name": "accepts_new_usage", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "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": {}, + "foreignKeys": { + "cloud_billing_sku_created_by_user_id_kilocode_users_id_fk": { + "name": "cloud_billing_sku_created_by_user_id_kilocode_users_id_fk", + "tableFrom": "cloud_billing_sku", + "columnsFrom": [ + "created_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "cloud_billing_sku_id_format": { + "name": "cloud_billing_sku_id_format", + "value": "\"cloud_billing_sku\".\"id\" ~ '^[a-z0-9][a-z0-9-]{2,79}$'" + }, + "cloud_billing_sku_name_nonempty": { + "name": "cloud_billing_sku_name_nonempty", + "value": "length(btrim(\"cloud_billing_sku\".\"name\")) > 0" + }, + "cloud_billing_sku_rate_positive": { + "name": "cloud_billing_sku_rate_positive", + "value": "\"cloud_billing_sku\".\"rate_cents_per_unit\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.code_indexing_manifest": { + "name": "code_indexing_manifest", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "git_branch": { + "name": "git_branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_hash": { + "name": "file_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_path": { + "name": "file_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "total_lines": { + "name": "total_lines", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_ai_lines": { + "name": "total_ai_lines", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_code_indexing_manifest_organization_id": { + "name": "IDX_code_indexing_manifest_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_manifest_kilo_user_id": { + "name": "IDX_code_indexing_manifest_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_manifest_project_id": { + "name": "IDX_code_indexing_manifest_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_manifest_git_branch": { + "name": "IDX_code_indexing_manifest_git_branch", + "columns": [ + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_manifest_created_at": { + "name": "IDX_code_indexing_manifest_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "code_indexing_manifest_kilo_user_id_kilocode_users_id_fk": { + "name": "code_indexing_manifest_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "code_indexing_manifest", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_code_indexing_manifest_org_user_project_hash_branch": { + "name": "UQ_code_indexing_manifest_org_user_project_hash_branch", + "columns": [ + "organization_id", + "kilo_user_id", + "project_id", + "file_path", + "git_branch" + ], + "nullsNotDistinct": true + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.code_indexing_search": { + "name": "code_indexing_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_code_indexing_search_organization_id": { + "name": "IDX_code_indexing_search_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_search_kilo_user_id": { + "name": "IDX_code_indexing_search_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_search_project_id": { + "name": "IDX_code_indexing_search_project_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_code_indexing_search_created_at": { + "name": "IDX_code_indexing_search_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "code_indexing_search_kilo_user_id_kilocode_users_id_fk": { + "name": "code_indexing_search_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "code_indexing_search", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.code_review_analytics_findings": { + "name": "code_review_analytics_findings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "analytics_result_id": { + "name": "analytics_result_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "ordinal": { + "name": "ordinal", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "security_class": { + "name": "security_class", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "code_review_analytics_findings_analytics_result_id_code_review_analytics_results_id_fk": { + "name": "code_review_analytics_findings_analytics_result_id_code_review_analytics_results_id_fk", + "tableFrom": "code_review_analytics_findings", + "columnsFrom": [ + "analytics_result_id" + ], + "tableTo": "code_review_analytics_results", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_code_review_analytics_findings_result_ordinal": { + "name": "UQ_code_review_analytics_findings_result_ordinal", + "columns": [ + "analytics_result_id", + "ordinal" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "code_review_analytics_findings_severity_check": { + "name": "code_review_analytics_findings_severity_check", + "value": "\"code_review_analytics_findings\".\"severity\" IN ('critical', 'warning', 'suggestion')" + }, + "code_review_analytics_findings_category_check": { + "name": "code_review_analytics_findings_category_check", + "value": "\"code_review_analytics_findings\".\"category\" IN ('security', 'correctness', 'reliability', 'data_integrity', 'performance', 'compatibility', 'maintainability', 'test_quality', 'documentation', 'accessibility', 'other')" + }, + "code_review_analytics_findings_security_class_check": { + "name": "code_review_analytics_findings_security_class_check", + "value": "\"code_review_analytics_findings\".\"security_class\" IN ('auth_access', 'injection', 'data_protection', 'request_resource_boundary', 'deserialization_object_integrity', 'dependency_supply_chain', 'memory_safety', 'availability', 'concurrency', 'security_configuration', 'other')" + }, + "code_review_analytics_findings_ordinal_check": { + "name": "code_review_analytics_findings_ordinal_check", + "value": "\"code_review_analytics_findings\".\"ordinal\" >= 0" + }, + "code_review_analytics_findings_security_class_presence_check": { + "name": "code_review_analytics_findings_security_class_presence_check", + "value": "(\n (\"code_review_analytics_findings\".\"category\" = 'security' AND \"code_review_analytics_findings\".\"security_class\" IS NOT NULL) OR\n (\"code_review_analytics_findings\".\"category\" <> 'security' AND \"code_review_analytics_findings\".\"security_class\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.code_review_analytics_results": { + "name": "code_review_analytics_results", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "code_review_id": { + "name": "code_review_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_attempt_id": { + "name": "source_attempt_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "capture_status": { + "name": "capture_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "taxonomy_version": { + "name": "taxonomy_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "change_type": { + "name": "change_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impact_level": { + "name": "impact_level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "complexity_level": { + "name": "complexity_level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "classification_confidence": { + "name": "classification_confidence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "finalized_at": { + "name": "finalized_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": { + "idx_code_review_analytics_results_source_attempt_id": { + "name": "idx_code_review_analytics_results_source_attempt_id", + "columns": [ + { + "expression": "source_attempt_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_analytics_results_finalized_at": { + "name": "idx_code_review_analytics_results_finalized_at", + "columns": [ + { + "expression": "finalized_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "code_review_analytics_results_code_review_id_cloud_agent_code_reviews_id_fk": { + "name": "code_review_analytics_results_code_review_id_cloud_agent_code_reviews_id_fk", + "tableFrom": "code_review_analytics_results", + "columnsFrom": [ + "code_review_id" + ], + "tableTo": "cloud_agent_code_reviews", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "code_review_analytics_results_source_attempt_id_cloud_agent_code_review_attempts_id_fk": { + "name": "code_review_analytics_results_source_attempt_id_cloud_agent_code_review_attempts_id_fk", + "tableFrom": "code_review_analytics_results", + "columnsFrom": [ + "source_attempt_id" + ], + "tableTo": "cloud_agent_code_review_attempts", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_code_review_analytics_results_code_review_id": { + "name": "UQ_code_review_analytics_results_code_review_id", + "columns": [ + "code_review_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "code_review_analytics_results_capture_status_check": { + "name": "code_review_analytics_results_capture_status_check", + "value": "\"code_review_analytics_results\".\"capture_status\" IN ('captured', 'missing', 'invalid', 'omitted')" + }, + "code_review_analytics_results_change_type_check": { + "name": "code_review_analytics_results_change_type_check", + "value": "\"code_review_analytics_results\".\"change_type\" IN ('bug_fix', 'feature', 'refactor', 'maintenance', 'dependency', 'test', 'documentation', 'mixed', 'other')" + }, + "code_review_analytics_results_impact_level_check": { + "name": "code_review_analytics_results_impact_level_check", + "value": "\"code_review_analytics_results\".\"impact_level\" IN ('low', 'medium', 'high')" + }, + "code_review_analytics_results_complexity_level_check": { + "name": "code_review_analytics_results_complexity_level_check", + "value": "\"code_review_analytics_results\".\"complexity_level\" IN ('low', 'medium', 'high')" + }, + "code_review_analytics_results_classification_confidence_check": { + "name": "code_review_analytics_results_classification_confidence_check", + "value": "\"code_review_analytics_results\".\"classification_confidence\" IN ('low', 'medium', 'high')" + }, + "code_review_analytics_results_classification_presence_check": { + "name": "code_review_analytics_results_classification_presence_check", + "value": "(\n (\n \"code_review_analytics_results\".\"capture_status\" = 'captured'\n AND \"code_review_analytics_results\".\"change_type\" IS NOT NULL\n AND \"code_review_analytics_results\".\"impact_level\" IS NOT NULL\n AND \"code_review_analytics_results\".\"complexity_level\" IS NOT NULL\n AND \"code_review_analytics_results\".\"classification_confidence\" IS NOT NULL\n ) OR (\n \"code_review_analytics_results\".\"capture_status\" <> 'captured'\n AND \"code_review_analytics_results\".\"change_type\" IS NULL\n AND \"code_review_analytics_results\".\"impact_level\" IS NULL\n AND \"code_review_analytics_results\".\"complexity_level\" IS NULL\n AND \"code_review_analytics_results\".\"classification_confidence\" IS NULL\n )\n )" + } + }, + "isRLSEnabled": false + }, + "public.code_review_feedback_events": { + "name": "code_review_feedback_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kilo_comment_id": { + "name": "kilo_comment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reply_excerpt": { + "name": "reply_excerpt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_comment_excerpt": { + "name": "kilo_comment_excerpt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dedupe_hash": { + "name": "dedupe_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurred_at": { + "name": "occurred_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()" + } + }, + "indexes": { + "idx_code_review_feedback_events_owned_by_org_id": { + "name": "idx_code_review_feedback_events_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_feedback_events_owned_by_user_id": { + "name": "idx_code_review_feedback_events_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_feedback_events_platform_repo": { + "name": "idx_code_review_feedback_events_platform_repo", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_feedback_events_created_at": { + "name": "idx_code_review_feedback_events_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "code_review_feedback_events_owned_by_organization_id_organizations_id_fk": { + "name": "code_review_feedback_events_owned_by_organization_id_organizations_id_fk", + "tableFrom": "code_review_feedback_events", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "code_review_feedback_events_owned_by_user_id_kilocode_users_id_fk": { + "name": "code_review_feedback_events_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "code_review_feedback_events", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_code_review_feedback_events_dedupe_hash": { + "name": "UQ_code_review_feedback_events_dedupe_hash", + "columns": [ + "dedupe_hash" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "code_review_feedback_events_owner_check": { + "name": "code_review_feedback_events_owner_check", + "value": "(\n (\"code_review_feedback_events\".\"owned_by_user_id\" IS NOT NULL AND \"code_review_feedback_events\".\"owned_by_organization_id\" IS NULL) OR\n (\"code_review_feedback_events\".\"owned_by_user_id\" IS NULL AND \"code_review_feedback_events\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.code_review_memory_proposals": { + "name": "code_review_memory_proposals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rationale": { + "name": "rationale", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "proposed_markdown": { + "name": "proposed_markdown", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "evidence": { + "name": "evidence", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "positive_count": { + "name": "positive_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "negative_count": { + "name": "negative_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "neutral_count": { + "name": "neutral_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "change_request_url": { + "name": "change_request_url", + "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": { + "idx_code_review_memory_proposals_owned_by_org_id": { + "name": "idx_code_review_memory_proposals_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_memory_proposals_owned_by_user_id": { + "name": "idx_code_review_memory_proposals_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_memory_proposals_platform_repo_status": { + "name": "idx_code_review_memory_proposals_platform_repo_status", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_code_review_memory_proposals_updated_at": { + "name": "idx_code_review_memory_proposals_updated_at", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_code_review_memory_proposals_org_active_scope": { + "name": "UQ_code_review_memory_proposals_org_active_scope", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"code_review_memory_proposals\".\"owned_by_organization_id\" IS NOT NULL AND \"code_review_memory_proposals\".\"status\" IN ('open', 'edited', 'opening_change_request')", + "concurrently": false + }, + "UQ_code_review_memory_proposals_user_active_scope": { + "name": "UQ_code_review_memory_proposals_user_active_scope", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"code_review_memory_proposals\".\"owned_by_user_id\" IS NOT NULL AND \"code_review_memory_proposals\".\"status\" IN ('open', 'edited', 'opening_change_request')", + "concurrently": false + } + }, + "foreignKeys": { + "code_review_memory_proposals_owned_by_organization_id_organizations_id_fk": { + "name": "code_review_memory_proposals_owned_by_organization_id_organizations_id_fk", + "tableFrom": "code_review_memory_proposals", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "code_review_memory_proposals_owned_by_user_id_kilocode_users_id_fk": { + "name": "code_review_memory_proposals_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "code_review_memory_proposals", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "code_review_memory_proposals_owner_check": { + "name": "code_review_memory_proposals_owner_check", + "value": "(\n (\"code_review_memory_proposals\".\"owned_by_user_id\" IS NOT NULL AND \"code_review_memory_proposals\".\"owned_by_organization_id\" IS NULL) OR\n (\"code_review_memory_proposals\".\"owned_by_user_id\" IS NULL AND \"code_review_memory_proposals\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.coding_plan_availability_intents": { + "name": "coding_plan_availability_intents", + "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 + }, + "plan_id": { + "name": "plan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_coding_plan_availability_intents_user_plan": { + "name": "UQ_coding_plan_availability_intents_user_plan", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_coding_plan_availability_intents_plan": { + "name": "IDX_coding_plan_availability_intents_plan", + "columns": [ + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "coding_plan_availability_intents_user_id_kilocode_users_id_fk": { + "name": "coding_plan_availability_intents_user_id_kilocode_users_id_fk", + "tableFrom": "coding_plan_availability_intents", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.coding_plan_key_inventory": { + "name": "coding_plan_key_inventory", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "plan_id": { + "name": "plan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "upstream_plan_id": { + "name": "upstream_plan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "upstream_usage_id": { + "name": "upstream_usage_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "credential_fingerprint": { + "name": "credential_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'available'" + }, + "assigned_to_user_id": { + "name": "assigned_to_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_requested_at": { + "name": "revocation_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_attempt_count": { + "name": "revocation_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_revocation_error": { + "name": "last_revocation_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": { + "UQ_coding_plan_key_inv_fingerprint": { + "name": "UQ_coding_plan_key_inv_fingerprint", + "columns": [ + { + "expression": "credential_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_coding_plan_key_inv_provider_usage_id": { + "name": "UQ_coding_plan_key_inv_provider_usage_id", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "upstream_usage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"coding_plan_key_inventory\".\"upstream_usage_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_coding_plan_key_inv_plan_status": { + "name": "IDX_coding_plan_key_inv_plan_status", + "columns": [ + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_coding_plan_key_inv_available": { + "name": "IDX_coding_plan_key_inv_available", + "columns": [ + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"coding_plan_key_inventory\".\"status\" = 'available'", + "concurrently": false + } + }, + "foreignKeys": { + "coding_plan_key_inventory_assigned_to_user_id_kilocode_users_id_fk": { + "name": "coding_plan_key_inventory_assigned_to_user_id_kilocode_users_id_fk", + "tableFrom": "coding_plan_key_inventory", + "columnsFrom": [ + "assigned_to_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "coding_plan_key_inventory_status_check": { + "name": "coding_plan_key_inventory_status_check", + "value": "\"coding_plan_key_inventory\".\"status\" IN ('available', 'assigned', 'revocation_pending', 'revoked', 'revocation_failed')" + } + }, + "isRLSEnabled": false + }, + "public.coding_plan_subscriptions": { + "name": "coding_plan_subscriptions", + "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 + }, + "plan_id": { + "name": "plan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_inventory_id": { + "name": "key_inventory_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "installed_byok_key_id": { + "name": "installed_byok_key_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_microdollars": { + "name": "cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "billing_period_days": { + "name": "billing_period_days", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "current_period_start": { + "name": "current_period_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "current_period_end": { + "name": "current_period_end", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "credit_renewal_at": { + "name": "credit_renewal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "past_due_started_at": { + "name": "past_due_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "payment_grace_expires_at": { + "name": "payment_grace_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auto_top_up_attempted_for_due": { + "name": "auto_top_up_attempted_for_due", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_reason": { + "name": "cancellation_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": { + "UQ_coding_plan_sub_live_user_plan": { + "name": "UQ_coding_plan_sub_live_user_plan", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"coding_plan_subscriptions\".\"status\" IN ('active', 'past_due')", + "concurrently": false + }, + "UQ_coding_plan_sub_live_user_provider": { + "name": "UQ_coding_plan_sub_live_user_provider", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"coding_plan_subscriptions\".\"status\" IN ('active', 'past_due')", + "concurrently": false + }, + "IDX_coding_plan_sub_status": { + "name": "IDX_coding_plan_sub_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_coding_plan_sub_renewal": { + "name": "IDX_coding_plan_sub_renewal", + "columns": [ + { + "expression": "credit_renewal_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_coding_plan_sub_inventory": { + "name": "IDX_coding_plan_sub_inventory", + "columns": [ + { + "expression": "key_inventory_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "coding_plan_subscriptions_user_id_kilocode_users_id_fk": { + "name": "coding_plan_subscriptions_user_id_kilocode_users_id_fk", + "tableFrom": "coding_plan_subscriptions", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "coding_plan_subscriptions_key_inventory_id_coding_plan_key_inventory_id_fk": { + "name": "coding_plan_subscriptions_key_inventory_id_coding_plan_key_inventory_id_fk", + "tableFrom": "coding_plan_subscriptions", + "columnsFrom": [ + "key_inventory_id" + ], + "tableTo": "coding_plan_key_inventory", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "coding_plan_subscriptions_installed_byok_key_id_byok_api_keys_id_fk": { + "name": "coding_plan_subscriptions_installed_byok_key_id_byok_api_keys_id_fk", + "tableFrom": "coding_plan_subscriptions", + "columnsFrom": [ + "installed_byok_key_id" + ], + "tableTo": "byok_api_keys", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "coding_plan_subscriptions_status_check": { + "name": "coding_plan_subscriptions_status_check", + "value": "\"coding_plan_subscriptions\".\"status\" IN ('active', 'past_due', 'canceled')" + }, + "coding_plan_subscriptions_live_access_check": { + "name": "coding_plan_subscriptions_live_access_check", + "value": "\"coding_plan_subscriptions\".\"status\" = 'canceled' OR \"coding_plan_subscriptions\".\"key_inventory_id\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.coding_plan_terms": { + "name": "coding_plan_terms", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "subscription_id": { + "name": "subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "plan_id": { + "name": "plan_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "period_end": { + "name": "period_end", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "cost_microdollars": { + "name": "cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "credit_transaction_id": { + "name": "credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_coding_plan_terms_request": { + "name": "UQ_coding_plan_terms_request", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "plan_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_coding_plan_terms_subscription": { + "name": "IDX_coding_plan_terms_subscription", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "coding_plan_terms_subscription_id_coding_plan_subscriptions_id_fk": { + "name": "coding_plan_terms_subscription_id_coding_plan_subscriptions_id_fk", + "tableFrom": "coding_plan_terms", + "columnsFrom": [ + "subscription_id" + ], + "tableTo": "coding_plan_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "coding_plan_terms_user_id_kilocode_users_id_fk": { + "name": "coding_plan_terms_user_id_kilocode_users_id_fk", + "tableFrom": "coding_plan_terms", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "coding_plan_terms_credit_transaction_id_credit_transactions_id_fk": { + "name": "coding_plan_terms_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "coding_plan_terms", + "columnsFrom": [ + "credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "coding_plan_terms_kind_check": { + "name": "coding_plan_terms_kind_check", + "value": "\"coding_plan_terms\".\"kind\" IN ('activation', 'extension', 'renewal')" + } + }, + "isRLSEnabled": false + }, + "public.compute_usage_charge": { + "name": "compute_usage_charge", + "schema": "", + "columns": { + "usage_source": { + "name": "usage_source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_source_id": { + "name": "usage_source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cloud_billing_sku_id": { + "name": "cloud_billing_sku_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "quantity": { + "name": "quantity", + "type": "numeric(24, 12)", + "primaryKey": false, + "notNull": true + }, + "settled_quantity_after": { + "name": "settled_quantity_after", + "type": "numeric(24, 12)", + "primaryKey": false, + "notNull": false + }, + "rate_cents_per_unit": { + "name": "rate_cents_per_unit", + "type": "numeric(24, 12)", + "primaryKey": false, + "notNull": true + }, + "amount_microdollars": { + "name": "amount_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "IDX_compute_usage_charge_user_created": { + "name": "IDX_compute_usage_charge_user_created", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_compute_usage_charge_organization_created": { + "name": "IDX_compute_usage_charge_organization_created", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "compute_usage_charge_user_id_kilocode_users_id_fk": { + "name": "compute_usage_charge_user_id_kilocode_users_id_fk", + "tableFrom": "compute_usage_charge", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "compute_usage_charge_organization_id_organizations_id_fk": { + "name": "compute_usage_charge_organization_id_organizations_id_fk", + "tableFrom": "compute_usage_charge", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "compute_usage_charge_cloud_billing_sku_id_cloud_billing_sku_id_fk": { + "name": "compute_usage_charge_cloud_billing_sku_id_cloud_billing_sku_id_fk", + "tableFrom": "compute_usage_charge", + "columnsFrom": [ + "cloud_billing_sku_id" + ], + "tableTo": "cloud_billing_sku", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": { + "compute_usage_charge_usage_source_usage_source_id_created_at_pk": { + "name": "compute_usage_charge_usage_source_usage_source_id_created_at_pk", + "columns": [ + "usage_source", + "usage_source_id", + "created_at" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "compute_usage_charge_exactly_one_payer": { + "name": "compute_usage_charge_exactly_one_payer", + "value": "(\"compute_usage_charge\".\"user_id\" IS NULL) <> (\"compute_usage_charge\".\"organization_id\" IS NULL)" + }, + "compute_usage_charge_quantity_positive": { + "name": "compute_usage_charge_quantity_positive", + "value": "\"compute_usage_charge\".\"quantity\" > 0" + }, + "compute_usage_charge_settled_quantity_positive": { + "name": "compute_usage_charge_settled_quantity_positive", + "value": "\"compute_usage_charge\".\"settled_quantity_after\" IS NULL OR \"compute_usage_charge\".\"settled_quantity_after\" > 0" + }, + "compute_usage_charge_rate_positive": { + "name": "compute_usage_charge_rate_positive", + "value": "\"compute_usage_charge\".\"rate_cents_per_unit\" > 0" + }, + "compute_usage_charge_amount_positive": { + "name": "compute_usage_charge_amount_positive", + "value": "\"compute_usage_charge\".\"amount_microdollars\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.container_usage_interval": { + "name": "container_usage_interval", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "start_epoch_ms": { + "name": "start_epoch_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "cloud_billing_sku_id": { + "name": "cloud_billing_sku_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_fingerprint": { + "name": "context_fingerprint", + "type": "text", + "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 + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_heartbeat_seq": { + "name": "last_heartbeat_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "confirmed_seconds": { + "name": "confirmed_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "billing_mode": { + "name": "billing_mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'shadow'" + }, + "rate_cents_per_unit": { + "name": "rate_cents_per_unit", + "type": "numeric(24, 12)", + "primaryKey": false, + "notNull": false + }, + "settled_billable_seconds": { + "name": "settled_billable_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "stopped_at": { + "name": "stopped_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "close_reason": { + "name": "close_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "final_stop_seq": { + "name": "final_stop_seq", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_container_usage_interval_sweep": { + "name": "IDX_container_usage_interval_sweep", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_seen_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_container_usage_interval_subject_started": { + "name": "IDX_container_usage_interval_subject_started", + "columns": [ + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_container_usage_interval_single_open": { + "name": "UQ_container_usage_interval_single_open", + "columns": [ + { + "expression": "service", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"container_usage_interval\".\"status\" = 'open'", + "concurrently": false + } + }, + "foreignKeys": { + "container_usage_interval_cloud_billing_sku_id_cloud_billing_sku_id_fk": { + "name": "container_usage_interval_cloud_billing_sku_id_cloud_billing_sku_id_fk", + "tableFrom": "container_usage_interval", + "columnsFrom": [ + "cloud_billing_sku_id" + ], + "tableTo": "cloud_billing_sku", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "container_usage_interval_subject_type": { + "name": "container_usage_interval_subject_type", + "value": "\"container_usage_interval\".\"subject_type\" IN ('user', 'org')" + }, + "container_usage_interval_actor_type": { + "name": "container_usage_interval_actor_type", + "value": "\"container_usage_interval\".\"actor_type\" IN ('user', 'bot')" + }, + "container_usage_interval_context_fingerprint": { + "name": "container_usage_interval_context_fingerprint", + "value": "\"container_usage_interval\".\"context_fingerprint\" ~ '^[a-f0-9]{64}$'" + }, + "container_usage_interval_attribution": { + "name": "container_usage_interval_attribution", + "value": "\"container_usage_interval\".\"actor_type\" = 'bot' OR (\"container_usage_interval\".\"actor_type\" = 'user' AND (\"container_usage_interval\".\"subject_type\" <> 'user' OR \"container_usage_interval\".\"actor_id\" = \"container_usage_interval\".\"subject_id\"))" + }, + "container_usage_interval_status": { + "name": "container_usage_interval_status", + "value": "\"container_usage_interval\".\"status\" IN ('open', 'closed')" + }, + "container_usage_interval_billing_mode": { + "name": "container_usage_interval_billing_mode", + "value": "\"container_usage_interval\".\"billing_mode\" IN ('shadow', 'paid')" + }, + "container_usage_interval_paid_rate": { + "name": "container_usage_interval_paid_rate", + "value": "(\"container_usage_interval\".\"billing_mode\" = 'shadow' AND \"container_usage_interval\".\"rate_cents_per_unit\" IS NULL) OR (\"container_usage_interval\".\"billing_mode\" = 'paid' AND \"container_usage_interval\".\"rate_cents_per_unit\" > 0)" + }, + "container_usage_interval_open_closed_shape": { + "name": "container_usage_interval_open_closed_shape", + "value": "(\"container_usage_interval\".\"status\" = 'open' AND \"container_usage_interval\".\"stopped_at\" IS NULL AND \"container_usage_interval\".\"close_reason\" IS NULL) OR (\"container_usage_interval\".\"status\" = 'closed' AND \"container_usage_interval\".\"stopped_at\" IS NOT NULL AND \"container_usage_interval\".\"close_reason\" IS NOT NULL)" + }, + "container_usage_interval_time_order": { + "name": "container_usage_interval_time_order", + "value": "\"container_usage_interval\".\"last_seen_at\" >= \"container_usage_interval\".\"started_at\" AND (\"container_usage_interval\".\"stopped_at\" IS NULL OR (\"container_usage_interval\".\"stopped_at\" >= \"container_usage_interval\".\"started_at\" AND \"container_usage_interval\".\"stopped_at\" <= \"container_usage_interval\".\"last_seen_at\"))" + }, + "container_usage_interval_last_heartbeat_seq_nonnegative": { + "name": "container_usage_interval_last_heartbeat_seq_nonnegative", + "value": "\"container_usage_interval\".\"last_heartbeat_seq\" >= 0" + }, + "container_usage_interval_confirmed_seconds_nonnegative": { + "name": "container_usage_interval_confirmed_seconds_nonnegative", + "value": "\"container_usage_interval\".\"confirmed_seconds\" >= 0" + }, + "container_usage_interval_settled_billable_seconds_nonnegative": { + "name": "container_usage_interval_settled_billable_seconds_nonnegative", + "value": "\"container_usage_interval\".\"settled_billable_seconds\" >= 0 AND \"container_usage_interval\".\"settled_billable_seconds\" <= \"container_usage_interval\".\"confirmed_seconds\"" + }, + "container_usage_interval_final_stop_seq_positive": { + "name": "container_usage_interval_final_stop_seq_positive", + "value": "\"container_usage_interval\".\"final_stop_seq\" IS NULL OR \"container_usage_interval\".\"final_stop_seq\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.container_usage_segment": { + "name": "container_usage_segment", + "schema": "", + "columns": { + "interval_id": { + "name": "interval_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reported_seconds": { + "name": "reported_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "usage_seconds": { + "name": "usage_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "IDX_container_usage_segment_received": { + "name": "IDX_container_usage_segment_received", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "container_usage_segment_interval_id_container_usage_interval_id_fk": { + "name": "container_usage_segment_interval_id_container_usage_interval_id_fk", + "tableFrom": "container_usage_segment", + "columnsFrom": [ + "interval_id" + ], + "tableTo": "container_usage_interval", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "container_usage_segment_interval_id_seq_pk": { + "name": "container_usage_segment_interval_id_seq_pk", + "columns": [ + "interval_id", + "seq" + ] + } + }, + "uniqueConstraints": { + "container_usage_segment_idempotency_key_unique": { + "name": "container_usage_segment_idempotency_key_unique", + "columns": [ + "idempotency_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "container_usage_segment_seq_positive": { + "name": "container_usage_segment_seq_positive", + "value": "\"container_usage_segment\".\"seq\" > 0" + }, + "container_usage_segment_reported_seconds_nonnegative": { + "name": "container_usage_segment_reported_seconds_nonnegative", + "value": "\"container_usage_segment\".\"reported_seconds\" >= 0" + }, + "container_usage_segment_usage_seconds_nonnegative": { + "name": "container_usage_segment_usage_seconds_nonnegative", + "value": "\"container_usage_segment\".\"usage_seconds\" >= 0" + }, + "container_usage_segment_usage_within_reported": { + "name": "container_usage_segment_usage_within_reported", + "value": "\"container_usage_segment\".\"usage_seconds\" <= \"container_usage_segment\".\"reported_seconds\"" + } + }, + "isRLSEnabled": false + }, + "public.content_moderation_reports": { + "name": "content_moderation_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "surface": { + "name": "surface", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_kind": { + "name": "target_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context_json": { + "name": "context_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "receipt_id": { + "name": "receipt_id", + "type": "uuid", + "primaryKey": false, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "triage_status": { + "name": "triage_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'received'" + }, + "appeal_status": { + "name": "appeal_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "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": { + "IDX_content_moderation_reports_user_created": { + "name": "IDX_content_moderation_reports_user_created", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_content_moderation_reports_target": { + "name": "IDX_content_moderation_reports_target", + "columns": [ + { + "expression": "target_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "content_moderation_reports_receipt_id_unique": { + "name": "content_moderation_reports_receipt_id_unique", + "columns": [ + "receipt_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.contributor_champion_contributors": { + "name": "contributor_champion_contributors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "github_login": { + "name": "github_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_profile_url": { + "name": "github_profile_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_user_id": { + "name": "github_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "first_contribution_at": { + "name": "first_contribution_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_contribution_at": { + "name": "last_contribution_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "all_time_contributions": { + "name": "all_time_contributions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "manual_email": { + "name": "manual_email", + "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": { + "IDX_contributor_champion_contributors_last_contribution_at": { + "name": "IDX_contributor_champion_contributors_last_contribution_at", + "columns": [ + { + "expression": "last_contribution_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_contributor_champion_contributors_manual_email": { + "name": "IDX_contributor_champion_contributors_manual_email", + "columns": [ + { + "expression": "manual_email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_contributor_champion_contributors_github_login": { + "name": "UQ_contributor_champion_contributors_github_login", + "columns": [ + "github_login" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.contributor_champion_events": { + "name": "contributor_champion_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "contributor_id": { + "name": "contributor_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_pr_number": { + "name": "github_pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "github_pr_url": { + "name": "github_pr_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_pr_title": { + "name": "github_pr_title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_author_login": { + "name": "github_author_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_author_email": { + "name": "github_author_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "merged_at": { + "name": "merged_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": { + "IDX_contributor_champion_events_contributor_id": { + "name": "IDX_contributor_champion_events_contributor_id", + "columns": [ + { + "expression": "contributor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_contributor_champion_events_merged_at": { + "name": "IDX_contributor_champion_events_merged_at", + "columns": [ + { + "expression": "merged_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_contributor_champion_events_author_email": { + "name": "IDX_contributor_champion_events_author_email", + "columns": [ + { + "expression": "github_author_email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "contributor_champion_events_contributor_id_contributor_champion_contributors_id_fk": { + "name": "contributor_champion_events_contributor_id_contributor_champion_contributors_id_fk", + "tableFrom": "contributor_champion_events", + "columnsFrom": [ + "contributor_id" + ], + "tableTo": "contributor_champion_contributors", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_contributor_champion_events_repo_pr": { + "name": "UQ_contributor_champion_events_repo_pr", + "columns": [ + "repo_full_name", + "github_pr_number" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.contributor_champion_memberships": { + "name": "contributor_champion_memberships", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "contributor_id": { + "name": "contributor_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "selected_tier": { + "name": "selected_tier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrolled_tier": { + "name": "enrolled_tier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enrolled_at": { + "name": "enrolled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "credit_amount_microdollars": { + "name": "credit_amount_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "credits_last_granted_at": { + "name": "credits_last_granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "linked_kilo_user_id": { + "name": "linked_kilo_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": { + "IDX_contributor_champion_memberships_credits_due": { + "name": "IDX_contributor_champion_memberships_credits_due", + "columns": [ + { + "expression": "credits_last_granted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"contributor_champion_memberships\".\"enrolled_tier\" IS NOT NULL AND \"contributor_champion_memberships\".\"credit_amount_microdollars\" > 0", + "concurrently": false + }, + "IDX_contributor_champion_memberships_linked_kilo_user_id": { + "name": "IDX_contributor_champion_memberships_linked_kilo_user_id", + "columns": [ + { + "expression": "linked_kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "contributor_champion_memberships_contributor_id_contributor_champion_contributors_id_fk": { + "name": "contributor_champion_memberships_contributor_id_contributor_champion_contributors_id_fk", + "tableFrom": "contributor_champion_memberships", + "columnsFrom": [ + "contributor_id" + ], + "tableTo": "contributor_champion_contributors", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "contributor_champion_memberships_linked_kilo_user_id_kilocode_users_id_fk": { + "name": "contributor_champion_memberships_linked_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "contributor_champion_memberships", + "columnsFrom": [ + "linked_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_contributor_champion_memberships_contributor_id": { + "name": "UQ_contributor_champion_memberships_contributor_id", + "columns": [ + "contributor_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "contributor_champion_memberships_selected_tier_check": { + "name": "contributor_champion_memberships_selected_tier_check", + "value": "\"contributor_champion_memberships\".\"selected_tier\" IS NULL OR \"contributor_champion_memberships\".\"selected_tier\" IN ('contributor', 'ambassador', 'champion')" + }, + "contributor_champion_memberships_enrolled_tier_check": { + "name": "contributor_champion_memberships_enrolled_tier_check", + "value": "\"contributor_champion_memberships\".\"enrolled_tier\" IS NULL OR \"contributor_champion_memberships\".\"enrolled_tier\" IN ('contributor', 'ambassador', 'champion')" + } + }, + "isRLSEnabled": false + }, + "public.contributor_champion_sync_state": { + "name": "contributor_champion_sync_state", + "schema": "", + "columns": { + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "last_merged_at": { + "name": "last_merged_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_synced_at": { + "name": "last_synced_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": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credit_campaigns": { + "name": "credit_campaigns", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credit_category": { + "name": "credit_category", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_microdollars": { + "name": "amount_microdollars", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "credit_expiry_hours": { + "name": "credit_expiry_hours", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "campaign_ends_at": { + "name": "campaign_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "total_redemptions_allowed": { + "name": "total_redemptions_allowed", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_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": { + "UQ_credit_campaigns_slug": { + "name": "UQ_credit_campaigns_slug", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_credit_campaigns_credit_category": { + "name": "UQ_credit_campaigns_credit_category", + "columns": [ + { + "expression": "credit_category", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credit_campaigns_slug_format_check": { + "name": "credit_campaigns_slug_format_check", + "value": "\"credit_campaigns\".\"slug\" ~ '^[a-z0-9-]{5,40}$'" + }, + "credit_campaigns_amount_positive_check": { + "name": "credit_campaigns_amount_positive_check", + "value": "\"credit_campaigns\".\"amount_microdollars\" > 0" + }, + "credit_campaigns_credit_expiry_hours_positive_check": { + "name": "credit_campaigns_credit_expiry_hours_positive_check", + "value": "\"credit_campaigns\".\"credit_expiry_hours\" IS NULL OR \"credit_campaigns\".\"credit_expiry_hours\" > 0" + }, + "credit_campaigns_total_redemptions_allowed_positive_check": { + "name": "credit_campaigns_total_redemptions_allowed_positive_check", + "value": "\"credit_campaigns\".\"total_redemptions_allowed\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.credit_transactions": { + "name": "credit_transactions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_microdollars": { + "name": "amount_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "expiration_baseline_microdollars_used": { + "name": "expiration_baseline_microdollars_used", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "original_baseline_microdollars_used": { + "name": "original_baseline_microdollars_used", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "is_free": { + "name": "is_free", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "original_transaction_id": { + "name": "original_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "stripe_payment_id": { + "name": "stripe_payment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "coinbase_credit_block_id": { + "name": "coinbase_credit_block_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credit_category": { + "name": "credit_category", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expiry_date": { + "name": "expiry_date", + "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()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "check_category_uniqueness": { + "name": "check_category_uniqueness", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "IDX_credit_transactions_created_at": { + "name": "IDX_credit_transactions_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_is_free": { + "name": "IDX_credit_transactions_is_free", + "columns": [ + { + "expression": "is_free", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_kilo_user_id": { + "name": "IDX_credit_transactions_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_credit_category": { + "name": "IDX_credit_transactions_credit_category", + "columns": [ + { + "expression": "credit_category", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_stripe_payment_id": { + "name": "IDX_credit_transactions_stripe_payment_id", + "columns": [ + { + "expression": "stripe_payment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_original_transaction_id": { + "name": "IDX_credit_transactions_original_transaction_id", + "columns": [ + { + "expression": "original_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_coinbase_credit_block_id": { + "name": "IDX_credit_transactions_coinbase_credit_block_id", + "columns": [ + { + "expression": "coinbase_credit_block_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_organization_id": { + "name": "IDX_credit_transactions_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_credit_transactions_unique_category": { + "name": "IDX_credit_transactions_unique_category", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "credit_category", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"credit_transactions\".\"check_category_uniqueness\" = TRUE", + "concurrently": false + } + }, + "foreignKeys": { + "credit_transactions_created_by_kilo_user_id_kilocode_users_id_fk": { + "name": "credit_transactions_created_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "credit_transactions", + "columnsFrom": [ + "created_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.custom_llm2": { + "name": "custom_llm2", + "schema": "", + "columns": { + "public_id": { + "name": "public_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "definition": { + "name": "definition", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deleted_user_email_tombstones": { + "name": "deleted_user_email_tombstones", + "schema": "", + "columns": { + "normalized_email_hash": { + "name": "normalized_email_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "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.deployment_builds": { + "name": "deployment_builds", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "deployment_id": { + "name": "deployment_id", + "type": "uuid", + "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": 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()" + } + }, + "indexes": { + "idx_deployment_builds_deployment_id": { + "name": "idx_deployment_builds_deployment_id", + "columns": [ + { + "expression": "deployment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployment_builds_status": { + "name": "idx_deployment_builds_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "deployment_builds_deployment_id_deployments_id_fk": { + "name": "deployment_builds_deployment_id_deployments_id_fk", + "tableFrom": "deployment_builds", + "columnsFrom": [ + "deployment_id" + ], + "tableTo": "deployments", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployment_env_vars": { + "name": "deployment_env_vars", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "deployment_id": { + "name": "deployment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_secret": { + "name": "is_secret", + "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": { + "idx_deployment_env_vars_deployment_id": { + "name": "idx_deployment_env_vars_deployment_id", + "columns": [ + { + "expression": "deployment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "deployment_env_vars_deployment_id_deployments_id_fk": { + "name": "deployment_env_vars_deployment_id_deployments_id_fk", + "tableFrom": "deployment_env_vars", + "columnsFrom": [ + "deployment_id" + ], + "tableTo": "deployments", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_deployment_env_vars_deployment_key": { + "name": "UQ_deployment_env_vars_deployment_key", + "columns": [ + "deployment_id", + "key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployment_events": { + "name": "deployment_events", + "schema": "", + "columns": { + "build_id": { + "name": "build_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'log'" + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "idx_deployment_events_build_id": { + "name": "idx_deployment_events_build_id", + "columns": [ + { + "expression": "build_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployment_events_timestamp": { + "name": "idx_deployment_events_timestamp", + "columns": [ + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployment_events_type": { + "name": "idx_deployment_events_type", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "deployment_events_build_id_deployment_builds_id_fk": { + "name": "deployment_events_build_id_deployment_builds_id_fk", + "tableFrom": "deployment_events", + "columnsFrom": [ + "build_id" + ], + "tableTo": "deployment_builds", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "deployment_events_build_id_event_id_pk": { + "name": "deployment_events_build_id_event_id_pk", + "columns": [ + "build_id", + "event_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployment_threat_detections": { + "name": "deployment_threat_detections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "deployment_id": { + "name": "deployment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "build_id": { + "name": "build_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "threat_type": { + "name": "threat_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_deployment_threat_detections_deployment_id": { + "name": "idx_deployment_threat_detections_deployment_id", + "columns": [ + { + "expression": "deployment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployment_threat_detections_created_at": { + "name": "idx_deployment_threat_detections_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "deployment_threat_detections_deployment_id_deployments_id_fk": { + "name": "deployment_threat_detections_deployment_id_deployments_id_fk", + "tableFrom": "deployment_threat_detections", + "columnsFrom": [ + "deployment_id" + ], + "tableTo": "deployments", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "deployment_threat_detections_build_id_deployment_builds_id_fk": { + "name": "deployment_threat_detections_build_id_deployment_builds_id_fk", + "tableFrom": "deployment_threat_detections", + "columnsFrom": [ + "build_id" + ], + "tableTo": "deployment_builds", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.deployments": { + "name": "deployments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "deployment_slug": { + "name": "deployment_slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_worker_name": { + "name": "internal_worker_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "repository_source": { + "name": "repository_source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_url": { + "name": "deployment_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'github'" + }, + "git_auth_token": { + "name": "git_auth_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_deployed_at": { + "name": "last_deployed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_build_id": { + "name": "last_build_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "threat_status": { + "name": "threat_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_from": { + "name": "created_from", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_deployments_owned_by_user_id": { + "name": "idx_deployments_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployments_owned_by_organization_id": { + "name": "idx_deployments_owned_by_organization_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployments_platform_integration_id": { + "name": "idx_deployments_platform_integration_id", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployments_repository_source_branch": { + "name": "idx_deployments_repository_source_branch", + "columns": [ + { + "expression": "repository_source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployments_threat_status_pending": { + "name": "idx_deployments_threat_status_pending", + "columns": [ + { + "expression": "threat_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"deployments\".\"threat_status\" = 'pending_scan'", + "concurrently": false + } + }, + "foreignKeys": { + "deployments_owned_by_user_id_kilocode_users_id_fk": { + "name": "deployments_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "deployments", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "deployments_owned_by_organization_id_organizations_id_fk": { + "name": "deployments_owned_by_organization_id_organizations_id_fk", + "tableFrom": "deployments", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_deployments_deployment_slug": { + "name": "UQ_deployments_deployment_slug", + "columns": [ + "deployment_slug" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "deployments_owner_check": { + "name": "deployments_owner_check", + "value": "(\n (\"deployments\".\"owned_by_user_id\" IS NOT NULL AND \"deployments\".\"owned_by_organization_id\" IS NULL) OR\n (\"deployments\".\"owned_by_user_id\" IS NULL AND \"deployments\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "deployments_source_type_check": { + "name": "deployments_source_type_check", + "value": "\"deployments\".\"source_type\" IN ('github', 'git', 'app-builder')" + } + }, + "isRLSEnabled": false + }, + "public.deployments_ephemeral": { + "name": "deployments_ephemeral", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_type": { + "name": "source_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_worker_name": { + "name": "internal_worker_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "deployment_slug": { + "name": "deployment_slug", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_cleanup_at": { + "name": "next_cleanup_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "cleanup_claim_token": { + "name": "cleanup_claim_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "cleanup_claimed_until": { + "name": "cleanup_claimed_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": { + "idx_deployments_ephemeral_owned_by_user_id": { + "name": "idx_deployments_ephemeral_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_deployments_ephemeral_next_cleanup_at": { + "name": "idx_deployments_ephemeral_next_cleanup_at", + "columns": [ + { + "expression": "next_cleanup_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "deployments_ephemeral_owned_by_user_id_kilocode_users_id_fk": { + "name": "deployments_ephemeral_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "deployments_ephemeral", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_deployments_ephemeral_internal_worker_name": { + "name": "UQ_deployments_ephemeral_internal_worker_name", + "columns": [ + "internal_worker_name" + ], + "nullsNotDistinct": false + }, + "UQ_deployments_ephemeral_deployment_slug": { + "name": "UQ_deployments_ephemeral_deployment_slug", + "columns": [ + "deployment_slug" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "deployments_ephemeral_source_type_check": { + "name": "deployments_ephemeral_source_type_check", + "value": "\"deployments_ephemeral\".\"source_type\" IN ('html')" + }, + "deployments_ephemeral_status_check": { + "name": "deployments_ephemeral_status_check", + "value": "\"deployments_ephemeral\".\"status\" IN ('pending', 'active', 'cleanup_retry')" + }, + "deployments_ephemeral_claim_fields_check": { + "name": "deployments_ephemeral_claim_fields_check", + "value": "(\"deployments_ephemeral\".\"cleanup_claim_token\" IS NULL) = (\"deployments_ephemeral\".\"cleanup_claimed_until\" IS NULL)" + }, + "deployments_ephemeral_active_fields_check": { + "name": "deployments_ephemeral_active_fields_check", + "value": "\"deployments_ephemeral\".\"status\" <> 'active' OR (\"deployments_ephemeral\".\"deployment_slug\" IS NOT NULL AND \"deployments_ephemeral\".\"expires_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.device_auth_requests": { + "name": "device_auth_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "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 + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "consumed_at": { + "name": "consumed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "user_code": { + "name": "user_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "device_code_hash": { + "name": "device_code_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ip_address": { + "name": "ip_address", + "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": { + "UQ_device_auth_requests_code": { + "name": "UQ_device_auth_requests_code", + "columns": [ + { + "expression": "code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_device_auth_requests_status": { + "name": "IDX_device_auth_requests_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_device_auth_requests_expires_at": { + "name": "IDX_device_auth_requests_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_device_auth_requests_kilo_user_id": { + "name": "IDX_device_auth_requests_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_device_auth_requests_device_code_hash": { + "name": "UQ_device_auth_requests_device_code_hash", + "columns": [ + { + "expression": "device_code_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"device_auth_requests\".\"device_code_hash\" IS NOT NULL", + "concurrently": true + }, + "IDX_device_auth_requests_user_code": { + "name": "IDX_device_auth_requests_user_code", + "columns": [ + { + "expression": "user_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"device_auth_requests\".\"user_code\" IS NOT NULL", + "concurrently": true + } + }, + "foreignKeys": { + "device_auth_requests_kilo_user_id_kilocode_users_id_fk": { + "name": "device_auth_requests_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "device_auth_requests", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.device_refresh_tokens": { + "name": "device_refresh_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "device_session_id": { + "name": "device_session_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "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": { + "IDX_device_refresh_tokens_device_session_id": { + "name": "IDX_device_refresh_tokens_device_session_id", + "columns": [ + { + "expression": "device_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_device_refresh_tokens_expires_at": { + "name": "IDX_device_refresh_tokens_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "device_refresh_tokens_device_session_id_device_sessions_id_fk": { + "name": "device_refresh_tokens_device_session_id_device_sessions_id_fk", + "tableFrom": "device_refresh_tokens", + "columnsFrom": [ + "device_session_id" + ], + "tableTo": "device_sessions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.device_sessions": { + "name": "device_sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "device_auth_request_id": { + "name": "device_auth_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_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()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_reason": { + "name": "revoked_reason", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_device_sessions_kilo_user_id": { + "name": "IDX_device_sessions_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_device_sessions_revoked_at": { + "name": "IDX_device_sessions_revoked_at", + "columns": [ + { + "expression": "revoked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "device_sessions_kilo_user_id_kilocode_users_id_fk": { + "name": "device_sessions_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "device_sessions", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.discord_gateway_listener": { + "name": "discord_gateway_listener", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "default": 1 + }, + "listener_id": { + "name": "listener_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_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 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.editor_name": { + "name": "editor_name", + "schema": "", + "columns": { + "editor_name_id": { + "name": "editor_name_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "editor_name": { + "name": "editor_name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_editor_name": { + "name": "UQ_editor_name", + "columns": [ + { + "expression": "editor_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.enrichment_data": { + "name": "enrichment_data", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_enrichment_data": { + "name": "github_enrichment_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "linkedin_enrichment_data": { + "name": "linkedin_enrichment_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "clay_enrichment_data": { + "name": "clay_enrichment_data", + "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": { + "IDX_enrichment_data_user_id": { + "name": "IDX_enrichment_data_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "enrichment_data_user_id_kilocode_users_id_fk": { + "name": "enrichment_data_user_id_kilocode_users_id_fk", + "tableFrom": "enrichment_data", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_enrichment_data_user_id": { + "name": "UQ_enrichment_data_user_id", + "columns": [ + "user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.exa_monthly_usage": { + "name": "exa_monthly_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "month": { + "name": "month", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "total_cost_microdollars": { + "name": "total_cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "total_charged_microdollars": { + "name": "total_charged_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "free_allowance_microdollars": { + "name": "free_allowance_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 10000000 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_exa_monthly_usage_personal": { + "name": "idx_exa_monthly_usage_personal", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"exa_monthly_usage\".\"organization_id\" is null", + "concurrently": false + }, + "idx_exa_monthly_usage_org": { + "name": "idx_exa_monthly_usage_org", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "month", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"exa_monthly_usage\".\"organization_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.exa_usage_log": { + "name": "exa_usage_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": false, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost_microdollars": { + "name": "cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "charged_to_balance": { + "name": "charged_to_balance", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "feature_id": { + "name": "feature_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_exa_usage_log_user_created": { + "name": "idx_exa_usage_log_user_created", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "exa_usage_log_id_created_at_pk": { + "name": "exa_usage_log_id_created_at_pk", + "columns": [ + "id", + "created_at" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.external_side_effect_outbox": { + "name": "external_side_effect_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'send_org_invite_email'" + }, + "invitation_id": { + "name": "invitation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "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": false + }, + "claimed_at": { + "name": "claimed_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()" + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_external_side_effect_outbox_invitation_id": { + "name": "UQ_external_side_effect_outbox_invitation_id", + "columns": [ + { + "expression": "invitation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_external_side_effect_outbox_status_next_attempt_at": { + "name": "IDX_external_side_effect_outbox_status_next_attempt_at", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.feature": { + "name": "feature", + "schema": "", + "columns": { + "feature_id": { + "name": "feature_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_feature": { + "name": "UQ_feature", + "columns": [ + { + "expression": "feature", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.finish_reason": { + "name": "finish_reason", + "schema": "", + "columns": { + "finish_reason_id": { + "name": "finish_reason_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "finish_reason": { + "name": "finish_reason", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_finish_reason": { + "name": "UQ_finish_reason", + "columns": [ + { + "expression": "finish_reason", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.free_model_usage": { + "name": "free_model_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_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": { + "idx_free_model_usage_ip_created_at": { + "name": "idx_free_model_usage_ip_created_at", + "columns": [ + { + "expression": "ip_address", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_free_model_usage_created_at": { + "name": "idx_free_model_usage_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_branch_pull_requests": { + "name": "github_branch_pull_requests", + "schema": "", + "columns": { + "git_url": { + "name": "git_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "git_branch": { + "name": "git_branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "pr_state": { + "name": "pr_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_title": { + "name": "pr_title", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_head_sha": { + "name": "pr_head_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_review_decision": { + "name": "pr_review_decision", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "review_decision_pending": { + "name": "review_decision_pending", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "review_decision_fetching_at": { + "name": "review_decision_fetching_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "pr_last_synced_at": { + "name": "pr_last_synced_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": { + "UQ_github_branch_prs_org": { + "name": "UQ_github_branch_prs_org", + "columns": [ + { + "expression": "git_url", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"github_branch_pull_requests\".\"owned_by_organization_id\" is not null", + "concurrently": false + }, + "UQ_github_branch_prs_user": { + "name": "UQ_github_branch_prs_user", + "columns": [ + { + "expression": "git_url", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"github_branch_pull_requests\".\"owned_by_user_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "github_branch_pull_requests_owned_by_organization_id_organizations_id_fk": { + "name": "github_branch_pull_requests_owned_by_organization_id_organizations_id_fk", + "tableFrom": "github_branch_pull_requests", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "github_branch_pull_requests_owned_by_user_id_kilocode_users_id_fk": { + "name": "github_branch_pull_requests_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "github_branch_pull_requests", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "github_branch_pull_requests_owner_check": { + "name": "github_branch_pull_requests_owner_check", + "value": "(\n (\"github_branch_pull_requests\".\"owned_by_organization_id\" IS NOT NULL AND \"github_branch_pull_requests\".\"owned_by_user_id\" IS NULL) OR\n (\"github_branch_pull_requests\".\"owned_by_organization_id\" IS NULL AND \"github_branch_pull_requests\".\"owned_by_user_id\" IS NOT NULL)\n )" + }, + "github_branch_pull_requests_review_decision_check": { + "name": "github_branch_pull_requests_review_decision_check", + "value": "\"github_branch_pull_requests\".\"pr_review_decision\" IS NULL OR \"github_branch_pull_requests\".\"pr_review_decision\" IN ('approved', 'changes_requested', 'review_required')" + } + }, + "isRLSEnabled": false + }, + "public.github_install_states": { + "name": "github_install_states", + "schema": "", + "columns": { + "token": { + "name": "token", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_type": { + "name": "owner_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_app_type": { + "name": "github_app_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "return_to": { + "name": "return_to", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "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": { + "IDX_github_install_states_expires_at": { + "name": "IDX_github_install_states_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "github_install_states_kilo_user_id_kilocode_users_id_fk": { + "name": "github_install_states_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "github_install_states", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "github_install_states_owner_type_check": { + "name": "github_install_states_owner_type_check", + "value": "\"github_install_states\".\"owner_type\" IN ('org', 'user')" + } + }, + "isRLSEnabled": false + }, + "public.http_ip": { + "name": "http_ip", + "schema": "", + "columns": { + "http_ip_id": { + "name": "http_ip_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "http_ip": { + "name": "http_ip", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_http_ip": { + "name": "UQ_http_ip", + "columns": [ + { + "expression": "http_ip", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.http_user_agent": { + "name": "http_user_agent", + "schema": "", + "columns": { + "http_user_agent_id": { + "name": "http_user_agent_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "http_user_agent": { + "name": "http_user_agent", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_http_user_agent": { + "name": "UQ_http_user_agent", + "columns": [ + { + "expression": "http_user_agent", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.impact_advocate_participants": { + "name": "impact_advocate_participants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "program_key": { + "name": "program_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "advocate_id": { + "name": "advocate_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "advocate_account_id": { + "name": "advocate_account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "opaque_referral_identifier": { + "name": "opaque_referral_identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "locale": { + "name": "locale", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "country_code": { + "name": "country_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_state": { + "name": "registration_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "registered_at": { + "name": "registered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_registration_attempt_at": { + "name": "last_registration_attempt_at", + "type": "timestamp with time zone", + "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": { + "UQ_impact_advocate_participants_program_referral_identifier": { + "name": "UQ_impact_advocate_participants_program_referral_identifier", + "columns": [ + { + "expression": "program_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "opaque_referral_identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"impact_advocate_participants\".\"opaque_referral_identifier\" IS NOT NULL", + "concurrently": false + }, + "IDX_impact_advocate_participants_registration_state": { + "name": "IDX_impact_advocate_participants_registration_state", + "columns": [ + { + "expression": "registration_state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_advocate_participants_user_id_kilocode_users_id_fk": { + "name": "impact_advocate_participants_user_id_kilocode_users_id_fk", + "tableFrom": "impact_advocate_participants", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_advocate_participants_program_user": { + "name": "UQ_impact_advocate_participants_program_user", + "columns": [ + "program_key", + "user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_advocate_participants_program_key_check": { + "name": "impact_advocate_participants_program_key_check", + "value": "\"impact_advocate_participants\".\"program_key\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_advocate_participants_registration_state_check": { + "name": "impact_advocate_participants_registration_state_check", + "value": "\"impact_advocate_participants\".\"registration_state\" IN ('pending', 'retrying', 'registered', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.impact_advocate_registration_attempts": { + "name": "impact_advocate_registration_attempts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "program_key": { + "name": "program_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "participant_id": { + "name": "participant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "opaque_cookie_value": { + "name": "opaque_cookie_value", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cookie_value_length": { + "name": "cookie_value_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "delivery_state": { + "name": "delivery_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "request_payload": { + "name": "request_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response_payload": { + "name": "response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response_status_code": { + "name": "response_status_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_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": { + "IDX_impact_advocate_registration_attempts_participant_id": { + "name": "IDX_impact_advocate_registration_attempts_participant_id", + "columns": [ + { + "expression": "participant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_advocate_registration_attempts_delivery_state": { + "name": "IDX_impact_advocate_registration_attempts_delivery_state", + "columns": [ + { + "expression": "delivery_state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_advocate_registration_attempts_participant_id_impact_advocate_participants_id_fk": { + "name": "impact_advocate_registration_attempts_participant_id_impact_advocate_participants_id_fk", + "tableFrom": "impact_advocate_registration_attempts", + "columnsFrom": [ + "participant_id" + ], + "tableTo": "impact_advocate_participants", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_advocate_registration_attempts_dedupe_key": { + "name": "UQ_impact_advocate_registration_attempts_dedupe_key", + "columns": [ + "dedupe_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_advocate_registration_attempts_program_key_check": { + "name": "impact_advocate_registration_attempts_program_key_check", + "value": "\"impact_advocate_registration_attempts\".\"program_key\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_advocate_registration_attempts_delivery_state_check": { + "name": "impact_advocate_registration_attempts_delivery_state_check", + "value": "\"impact_advocate_registration_attempts\".\"delivery_state\" IN ('queued', 'sending', 'succeeded', 'failed')" + }, + "impact_advocate_registration_attempts_cookie_value_length_non_negative_check": { + "name": "impact_advocate_registration_attempts_cookie_value_length_non_negative_check", + "value": "\"impact_advocate_registration_attempts\".\"cookie_value_length\" >= 0" + }, + "impact_advocate_registration_attempts_attempt_count_non_negative_check": { + "name": "impact_advocate_registration_attempts_attempt_count_non_negative_check", + "value": "\"impact_advocate_registration_attempts\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_advocate_reward_redemptions": { + "name": "impact_advocate_reward_redemptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "reward_id": { + "name": "reward_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "beneficiary_user_id": { + "name": "beneficiary_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "impact_reward_id": { + "name": "impact_reward_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_payload": { + "name": "request_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "lookup_response_payload": { + "name": "lookup_response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "redeem_response_payload": { + "name": "redeem_response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response_status_code": { + "name": "response_status_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "redeemed_at": { + "name": "redeemed_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": { + "IDX_impact_advocate_reward_redemptions_beneficiary_user_id": { + "name": "IDX_impact_advocate_reward_redemptions_beneficiary_user_id", + "columns": [ + { + "expression": "beneficiary_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_advocate_reward_redemptions_state": { + "name": "IDX_impact_advocate_reward_redemptions_state", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_advocate_reward_redemptions_reward_id_impact_referral_rewards_id_fk": { + "name": "impact_advocate_reward_redemptions_reward_id_impact_referral_rewards_id_fk", + "tableFrom": "impact_advocate_reward_redemptions", + "columnsFrom": [ + "reward_id" + ], + "tableTo": "impact_referral_rewards", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_advocate_reward_redemptions_beneficiary_user_id_kilocode_users_id_fk": { + "name": "impact_advocate_reward_redemptions_beneficiary_user_id_kilocode_users_id_fk", + "tableFrom": "impact_advocate_reward_redemptions", + "columnsFrom": [ + "beneficiary_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_advocate_reward_redemptions_reward_id": { + "name": "UQ_impact_advocate_reward_redemptions_reward_id", + "columns": [ + "reward_id" + ], + "nullsNotDistinct": false + }, + "UQ_impact_advocate_reward_redemptions_dedupe_key": { + "name": "UQ_impact_advocate_reward_redemptions_dedupe_key", + "columns": [ + "dedupe_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_advocate_reward_redemptions_state_check": { + "name": "impact_advocate_reward_redemptions_state_check", + "value": "\"impact_advocate_reward_redemptions\".\"state\" IN ('queued', 'retrying', 'redeemed', 'failed')" + }, + "impact_advocate_reward_redemptions_attempt_count_non_negative_check": { + "name": "impact_advocate_reward_redemptions_attempt_count_non_negative_check", + "value": "\"impact_advocate_reward_redemptions\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_attribution_touches": { + "name": "impact_attribution_touches", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "program_key": { + "name": "program_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'kiloclaw'" + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "anonymous_id": { + "name": "anonymous_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "touch_type": { + "name": "touch_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "opaque_tracking_value": { + "name": "opaque_tracking_value", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tracking_value_length": { + "name": "tracking_value_length", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "is_tracking_value_accepted": { + "name": "is_tracking_value_accepted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rs_code": { + "name": "rs_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rs_share_medium": { + "name": "rs_share_medium", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rs_engagement_medium": { + "name": "rs_engagement_medium", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "im_ref": { + "name": "im_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "landing_path": { + "name": "landing_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "utm_source": { + "name": "utm_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "utm_medium": { + "name": "utm_medium", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "utm_campaign": { + "name": "utm_campaign", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "utm_term": { + "name": "utm_term", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "utm_content": { + "name": "utm_content", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "touched_at": { + "name": "touched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "sale_attributed_at": { + "name": "sale_attributed_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": { + "IDX_impact_attribution_touches_product_user_id": { + "name": "IDX_impact_attribution_touches_product_user_id", + "columns": [ + { + "expression": "product", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_attribution_touches_user_id": { + "name": "IDX_impact_attribution_touches_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_attribution_touches_anonymous_id": { + "name": "IDX_impact_attribution_touches_anonymous_id", + "columns": [ + { + "expression": "anonymous_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_attribution_touches_expires_at": { + "name": "IDX_impact_attribution_touches_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_attribution_touches_sale_attributed_at": { + "name": "IDX_impact_attribution_touches_sale_attributed_at", + "columns": [ + { + "expression": "sale_attributed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_attribution_touches_user_id_kilocode_users_id_fk": { + "name": "impact_attribution_touches_user_id_kilocode_users_id_fk", + "tableFrom": "impact_attribution_touches", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_attribution_touches_dedupe_key": { + "name": "UQ_impact_attribution_touches_dedupe_key", + "columns": [ + "dedupe_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_attribution_touches_product_check": { + "name": "impact_attribution_touches_product_check", + "value": "\"impact_attribution_touches\".\"product\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_attribution_touches_program_key_check": { + "name": "impact_attribution_touches_program_key_check", + "value": "\"impact_attribution_touches\".\"program_key\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_attribution_touches_touch_type_check": { + "name": "impact_attribution_touches_touch_type_check", + "value": "\"impact_attribution_touches\".\"touch_type\" IN ('affiliate', 'referral')" + }, + "impact_attribution_touches_provider_check": { + "name": "impact_attribution_touches_provider_check", + "value": "\"impact_attribution_touches\".\"provider\" IN ('impact_performance', 'impact_advocate')" + }, + "impact_attribution_touches_tracking_value_length_non_negative_check": { + "name": "impact_attribution_touches_tracking_value_length_non_negative_check", + "value": "\"impact_attribution_touches\".\"tracking_value_length\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_conversion_reports": { + "name": "impact_conversion_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "conversion_id": { + "name": "conversion_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action_tracker_id": { + "name": "action_tracker_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "order_id": { + "name": "order_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "request_payload": { + "name": "request_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response_payload": { + "name": "response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "response_status_code": { + "name": "response_status_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_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": { + "IDX_impact_conversion_reports_conversion_id": { + "name": "IDX_impact_conversion_reports_conversion_id", + "columns": [ + { + "expression": "conversion_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_conversion_reports_state": { + "name": "IDX_impact_conversion_reports_state", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_conversion_reports_conversion_id_impact_referral_conversions_id_fk": { + "name": "impact_conversion_reports_conversion_id_impact_referral_conversions_id_fk", + "tableFrom": "impact_conversion_reports", + "columnsFrom": [ + "conversion_id" + ], + "tableTo": "impact_referral_conversions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_conversion_reports_dedupe_key": { + "name": "UQ_impact_conversion_reports_dedupe_key", + "columns": [ + "dedupe_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_conversion_reports_state_check": { + "name": "impact_conversion_reports_state_check", + "value": "\"impact_conversion_reports\".\"state\" IN ('queued', 'retrying', 'delivered', 'failed')" + }, + "impact_conversion_reports_attempt_count_non_negative_check": { + "name": "impact_conversion_reports_attempt_count_non_negative_check", + "value": "\"impact_conversion_reports\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_referral_conversions": { + "name": "impact_referral_conversions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "referee_user_id": { + "name": "referee_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "referrer_user_id": { + "name": "referrer_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_touch_id": { + "name": "source_touch_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "winning_touch_type": { + "name": "winning_touch_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payment_provider": { + "name": "payment_provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'credits'" + }, + "source_payment_id": { + "name": "source_payment_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "qualified": { + "name": "qualified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "disqualification_reason": { + "name": "disqualification_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "converted_at": { + "name": "converted_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": { + "IDX_impact_referral_conversions_referee_user_id": { + "name": "IDX_impact_referral_conversions_referee_user_id", + "columns": [ + { + "expression": "referee_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_referral_conversions_referrer_user_id": { + "name": "IDX_impact_referral_conversions_referrer_user_id", + "columns": [ + { + "expression": "referrer_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_referral_conversions_referee_user_id_kilocode_users_id_fk": { + "name": "impact_referral_conversions_referee_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referral_conversions", + "columnsFrom": [ + "referee_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referral_conversions_referrer_user_id_kilocode_users_id_fk": { + "name": "impact_referral_conversions_referrer_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referral_conversions", + "columnsFrom": [ + "referrer_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "impact_referral_conversions_source_touch_id_impact_attribution_touches_id_fk": { + "name": "impact_referral_conversions_source_touch_id_impact_attribution_touches_id_fk", + "tableFrom": "impact_referral_conversions", + "columnsFrom": [ + "source_touch_id" + ], + "tableTo": "impact_attribution_touches", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_referral_conversions_product_payment_source": { + "name": "UQ_impact_referral_conversions_product_payment_source", + "columns": [ + "product", + "payment_provider", + "source_payment_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_referral_conversions_product_check": { + "name": "impact_referral_conversions_product_check", + "value": "\"impact_referral_conversions\".\"product\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_referral_conversions_winning_touch_type_check": { + "name": "impact_referral_conversions_winning_touch_type_check", + "value": "\"impact_referral_conversions\".\"winning_touch_type\" IN ('referral', 'affiliate', 'none')" + }, + "impact_referral_conversions_payment_provider_check": { + "name": "impact_referral_conversions_payment_provider_check", + "value": "\"impact_referral_conversions\".\"payment_provider\" IN ('stripe', 'credits', 'app_store', 'google_play')" + } + }, + "isRLSEnabled": false + }, + "public.impact_referral_reward_applications": { + "name": "impact_referral_reward_applications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "reward_id": { + "name": "reward_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "beneficiary_user_id": { + "name": "beneficiary_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subscription_id": { + "name": "subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "previous_renewal_boundary": { + "name": "previous_renewal_boundary", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "new_renewal_boundary": { + "name": "new_renewal_boundary", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "local_operation_id": { + "name": "local_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_operation_id": { + "name": "stripe_operation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_idempotency_key": { + "name": "stripe_idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "applied_at": { + "name": "applied_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": { + "IDX_impact_referral_reward_applications_reward_id": { + "name": "IDX_impact_referral_reward_applications_reward_id", + "columns": [ + { + "expression": "reward_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_referral_reward_applications_beneficiary_user_id": { + "name": "IDX_impact_referral_reward_applications_beneficiary_user_id", + "columns": [ + { + "expression": "beneficiary_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_referral_reward_applications_reward_id_impact_referral_rewards_id_fk": { + "name": "impact_referral_reward_applications_reward_id_impact_referral_rewards_id_fk", + "tableFrom": "impact_referral_reward_applications", + "columnsFrom": [ + "reward_id" + ], + "tableTo": "impact_referral_rewards", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referral_reward_applications_beneficiary_user_id_kilocode_users_id_fk": { + "name": "impact_referral_reward_applications_beneficiary_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referral_reward_applications", + "columnsFrom": [ + "beneficiary_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "impact_referral_reward_applications_product_check": { + "name": "impact_referral_reward_applications_product_check", + "value": "\"impact_referral_reward_applications\".\"product\" IN ('kiloclaw', 'kilo_pass')" + } + }, + "isRLSEnabled": false + }, + "public.impact_referral_reward_decisions": { + "name": "impact_referral_reward_decisions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "conversion_id": { + "name": "conversion_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "beneficiary_user_id": { + "name": "beneficiary_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "beneficiary_role": { + "name": "beneficiary_role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reward_kind": { + "name": "reward_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw_free_month'" + }, + "months_granted": { + "name": "months_granted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reward_percent": { + "name": "reward_percent", + "type": "numeric(6, 4)", + "primaryKey": false, + "notNull": false + }, + "source_tier": { + "name": "source_tier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reward_amount_usd": { + "name": "reward_amount_usd", + "type": "numeric(12, 2)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_impact_referral_reward_decisions_beneficiary_user_id": { + "name": "IDX_impact_referral_reward_decisions_beneficiary_user_id", + "columns": [ + { + "expression": "beneficiary_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_referral_reward_decisions_conversion_id_impact_referral_conversions_id_fk": { + "name": "impact_referral_reward_decisions_conversion_id_impact_referral_conversions_id_fk", + "tableFrom": "impact_referral_reward_decisions", + "columnsFrom": [ + "conversion_id" + ], + "tableTo": "impact_referral_conversions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referral_reward_decisions_beneficiary_user_id_kilocode_users_id_fk": { + "name": "impact_referral_reward_decisions_beneficiary_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referral_reward_decisions", + "columnsFrom": [ + "beneficiary_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_referral_reward_decisions_conversion_role": { + "name": "UQ_impact_referral_reward_decisions_conversion_role", + "columns": [ + "conversion_id", + "beneficiary_role" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_referral_reward_decisions_product_check": { + "name": "impact_referral_reward_decisions_product_check", + "value": "\"impact_referral_reward_decisions\".\"product\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_referral_reward_decisions_beneficiary_role_check": { + "name": "impact_referral_reward_decisions_beneficiary_role_check", + "value": "\"impact_referral_reward_decisions\".\"beneficiary_role\" IN ('referrer', 'referee')" + }, + "impact_referral_reward_decisions_outcome_check": { + "name": "impact_referral_reward_decisions_outcome_check", + "value": "\"impact_referral_reward_decisions\".\"outcome\" IN ('granted', 'cap_limited', 'disqualified')" + }, + "impact_referral_reward_decisions_reward_kind_check": { + "name": "impact_referral_reward_decisions_reward_kind_check", + "value": "\"impact_referral_reward_decisions\".\"reward_kind\" IN ('kiloclaw_free_month', 'kilo_pass_bonus')" + }, + "impact_referral_reward_decisions_months_granted_non_negative_check": { + "name": "impact_referral_reward_decisions_months_granted_non_negative_check", + "value": "\"impact_referral_reward_decisions\".\"months_granted\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_referral_rewards": { + "name": "impact_referral_rewards", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "conversion_id": { + "name": "conversion_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "decision_id": { + "name": "decision_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "beneficiary_user_id": { + "name": "beneficiary_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "beneficiary_role": { + "name": "beneficiary_role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reward_kind": { + "name": "reward_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw_free_month'" + }, + "months_granted": { + "name": "months_granted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "reward_percent": { + "name": "reward_percent", + "type": "numeric(6, 4)", + "primaryKey": false, + "notNull": false + }, + "source_tier": { + "name": "source_tier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reward_amount_usd": { + "name": "reward_amount_usd", + "type": "numeric(12, 2)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "applies_to_subscription_id": { + "name": "applies_to_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "applies_to_kilo_pass_subscription_id": { + "name": "applies_to_kilo_pass_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "consumed_kilo_pass_issuance_id": { + "name": "consumed_kilo_pass_issuance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "consumed_kilo_pass_issuance_item_id": { + "name": "consumed_kilo_pass_issuance_item_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "earned_at": { + "name": "earned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "applied_at": { + "name": "applied_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reversed_at": { + "name": "reversed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "review_reason": { + "name": "review_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_impact_referral_rewards_beneficiary_user_id": { + "name": "IDX_impact_referral_rewards_beneficiary_user_id", + "columns": [ + { + "expression": "beneficiary_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_referral_rewards_status": { + "name": "IDX_impact_referral_rewards_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_referral_rewards_conversion_id_impact_referral_conversions_id_fk": { + "name": "impact_referral_rewards_conversion_id_impact_referral_conversions_id_fk", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "conversion_id" + ], + "tableTo": "impact_referral_conversions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referral_rewards_decision_id_impact_referral_reward_decisions_id_fk": { + "name": "impact_referral_rewards_decision_id_impact_referral_reward_decisions_id_fk", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "decision_id" + ], + "tableTo": "impact_referral_reward_decisions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referral_rewards_beneficiary_user_id_kilocode_users_id_fk": { + "name": "impact_referral_rewards_beneficiary_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "beneficiary_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "FK_impact_referral_rewards_kilo_pass_subscription": { + "name": "FK_impact_referral_rewards_kilo_pass_subscription", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "applies_to_kilo_pass_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "FK_impact_referral_rewards_kilo_pass_issuance": { + "name": "FK_impact_referral_rewards_kilo_pass_issuance", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "consumed_kilo_pass_issuance_id" + ], + "tableTo": "kilo_pass_issuances", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "FK_impact_referral_rewards_kilo_pass_issuance_item": { + "name": "FK_impact_referral_rewards_kilo_pass_issuance_item", + "tableFrom": "impact_referral_rewards", + "columnsFrom": [ + "consumed_kilo_pass_issuance_item_id" + ], + "tableTo": "kilo_pass_issuance_items", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_referral_rewards_conversion_role": { + "name": "UQ_impact_referral_rewards_conversion_role", + "columns": [ + "conversion_id", + "beneficiary_role" + ], + "nullsNotDistinct": false + }, + "UQ_impact_referral_rewards_decision_id": { + "name": "UQ_impact_referral_rewards_decision_id", + "columns": [ + "decision_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_referral_rewards_product_check": { + "name": "impact_referral_rewards_product_check", + "value": "\"impact_referral_rewards\".\"product\" IN ('kiloclaw', 'kilo_pass')" + }, + "impact_referral_rewards_beneficiary_role_check": { + "name": "impact_referral_rewards_beneficiary_role_check", + "value": "\"impact_referral_rewards\".\"beneficiary_role\" IN ('referrer', 'referee')" + }, + "impact_referral_rewards_reward_kind_check": { + "name": "impact_referral_rewards_reward_kind_check", + "value": "\"impact_referral_rewards\".\"reward_kind\" IN ('kiloclaw_free_month', 'kilo_pass_bonus')" + }, + "impact_referral_rewards_status_check": { + "name": "impact_referral_rewards_status_check", + "value": "\"impact_referral_rewards\".\"status\" IN ('pending', 'earned', 'applied', 'reversed', 'expired', 'canceled', 'review_required')" + }, + "impact_referral_rewards_months_granted_non_negative_check": { + "name": "impact_referral_rewards_months_granted_non_negative_check", + "value": "\"impact_referral_rewards\".\"months_granted\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.impact_referrals": { + "name": "impact_referrals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "product": { + "name": "product", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kiloclaw'" + }, + "referee_user_id": { + "name": "referee_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "referrer_user_id": { + "name": "referrer_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_touch_id": { + "name": "source_touch_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "impact_referral_id": { + "name": "impact_referral_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_impact_referrals_referrer_user_id": { + "name": "IDX_impact_referrals_referrer_user_id", + "columns": [ + { + "expression": "referrer_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_impact_referrals_source_touch_id": { + "name": "IDX_impact_referrals_source_touch_id", + "columns": [ + { + "expression": "source_touch_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "impact_referrals_referee_user_id_kilocode_users_id_fk": { + "name": "impact_referrals_referee_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referrals", + "columnsFrom": [ + "referee_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "impact_referrals_referrer_user_id_kilocode_users_id_fk": { + "name": "impact_referrals_referrer_user_id_kilocode_users_id_fk", + "tableFrom": "impact_referrals", + "columnsFrom": [ + "referrer_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "impact_referrals_source_touch_id_impact_attribution_touches_id_fk": { + "name": "impact_referrals_source_touch_id_impact_attribution_touches_id_fk", + "tableFrom": "impact_referrals", + "columnsFrom": [ + "source_touch_id" + ], + "tableTo": "impact_attribution_touches", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_impact_referrals_product_referee_user_id": { + "name": "UQ_impact_referrals_product_referee_user_id", + "columns": [ + "product", + "referee_user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "impact_referrals_product_check": { + "name": "impact_referrals_product_check", + "value": "\"impact_referrals\".\"product\" IN ('kiloclaw', 'kilo_pass')" + } + }, + "isRLSEnabled": false + }, + "public.ja4_digest": { + "name": "ja4_digest", + "schema": "", + "columns": { + "ja4_digest_id": { + "name": "ja4_digest_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "ja4_digest": { + "name": "ja4_digest", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_ja4_digest": { + "name": "UQ_ja4_digest", + "columns": [ + { + "expression": "ja4_digest", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kilo_pass_audit_log": { + "name": "kilo_pass_audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kilo_pass_subscription_id": { + "name": "kilo_pass_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_event_id": { + "name": "stripe_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_invoice_id": { + "name": "stripe_invoice_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "related_credit_transaction_id": { + "name": "related_credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "related_monthly_issuance_id": { + "name": "related_monthly_issuance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "payload_json": { + "name": "payload_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": { + "IDX_kilo_pass_audit_log_created_at": { + "name": "IDX_kilo_pass_audit_log_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_kilo_user_id": { + "name": "IDX_kilo_pass_audit_log_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_kilo_pass_subscription_id": { + "name": "IDX_kilo_pass_audit_log_kilo_pass_subscription_id", + "columns": [ + { + "expression": "kilo_pass_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_action": { + "name": "IDX_kilo_pass_audit_log_action", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_result": { + "name": "IDX_kilo_pass_audit_log_result", + "columns": [ + { + "expression": "result", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_idempotency_key": { + "name": "IDX_kilo_pass_audit_log_idempotency_key", + "columns": [ + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_stripe_event_id": { + "name": "IDX_kilo_pass_audit_log_stripe_event_id", + "columns": [ + { + "expression": "stripe_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_stripe_invoice_id": { + "name": "IDX_kilo_pass_audit_log_stripe_invoice_id", + "columns": [ + { + "expression": "stripe_invoice_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_stripe_subscription_id": { + "name": "IDX_kilo_pass_audit_log_stripe_subscription_id", + "columns": [ + { + "expression": "stripe_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_related_credit_transaction_id": { + "name": "IDX_kilo_pass_audit_log_related_credit_transaction_id", + "columns": [ + { + "expression": "related_credit_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_audit_log_related_monthly_issuance_id": { + "name": "IDX_kilo_pass_audit_log_related_monthly_issuance_id", + "columns": [ + { + "expression": "related_monthly_issuance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_audit_log_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_audit_log_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_audit_log", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_audit_log_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk": { + "name": "kilo_pass_audit_log_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk", + "tableFrom": "kilo_pass_audit_log", + "columnsFrom": [ + "kilo_pass_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_audit_log_related_credit_transaction_id_credit_transactions_id_fk": { + "name": "kilo_pass_audit_log_related_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "kilo_pass_audit_log", + "columnsFrom": [ + "related_credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_audit_log_related_monthly_issuance_id_kilo_pass_issuances_id_fk": { + "name": "kilo_pass_audit_log_related_monthly_issuance_id_kilo_pass_issuances_id_fk", + "tableFrom": "kilo_pass_audit_log", + "columnsFrom": [ + "related_monthly_issuance_id" + ], + "tableTo": "kilo_pass_issuances", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_audit_log_action_check": { + "name": "kilo_pass_audit_log_action_check", + "value": "\"kilo_pass_audit_log\".\"action\" IN ('stripe_webhook_received', 'kilo_pass_invoice_paid_handled', 'store_purchase_completed', 'store_notification_received', 'store_subscription_renewed', 'store_subscription_canceled', 'store_subscription_expired', 'store_subscription_refunded', 'base_credits_issued', 'bonus_credits_issued', 'bonus_credits_skipped_idempotent', 'first_month_50pct_promo_issued', 'yearly_monthly_base_cron_started', 'yearly_monthly_base_cron_completed', 'issue_yearly_remaining_credits', 'duplicate_card_subscription_canceled', 'yearly_monthly_bonus_cron_started', 'yearly_monthly_bonus_cron_completed')" + }, + "kilo_pass_audit_log_result_check": { + "name": "kilo_pass_audit_log_result_check", + "value": "\"kilo_pass_audit_log\".\"result\" IN ('success', 'skipped_idempotent', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_issuance_items": { + "name": "kilo_pass_issuance_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_pass_issuance_id": { + "name": "kilo_pass_issuance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "credit_transaction_id": { + "name": "credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "amount_usd": { + "name": "amount_usd", + "type": "numeric(12, 2)", + "primaryKey": false, + "notNull": true + }, + "bonus_percent_applied": { + "name": "bonus_percent_applied", + "type": "numeric(6, 4)", + "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": { + "IDX_kilo_pass_issuance_items_issuance_id": { + "name": "IDX_kilo_pass_issuance_items_issuance_id", + "columns": [ + { + "expression": "kilo_pass_issuance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_issuance_items_credit_transaction_id": { + "name": "IDX_kilo_pass_issuance_items_credit_transaction_id", + "columns": [ + { + "expression": "credit_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_issuance_items_kilo_pass_issuance_id_kilo_pass_issuances_id_fk": { + "name": "kilo_pass_issuance_items_kilo_pass_issuance_id_kilo_pass_issuances_id_fk", + "tableFrom": "kilo_pass_issuance_items", + "columnsFrom": [ + "kilo_pass_issuance_id" + ], + "tableTo": "kilo_pass_issuances", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_issuance_items_credit_transaction_id_credit_transactions_id_fk": { + "name": "kilo_pass_issuance_items_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "kilo_pass_issuance_items", + "columnsFrom": [ + "credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kilo_pass_issuance_items_credit_transaction_id_unique": { + "name": "kilo_pass_issuance_items_credit_transaction_id_unique", + "columns": [ + "credit_transaction_id" + ], + "nullsNotDistinct": false + }, + "UQ_kilo_pass_issuance_items_issuance_kind": { + "name": "UQ_kilo_pass_issuance_items_issuance_kind", + "columns": [ + "kilo_pass_issuance_id", + "kind" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_issuance_items_bonus_percent_applied_range_check": { + "name": "kilo_pass_issuance_items_bonus_percent_applied_range_check", + "value": "\"kilo_pass_issuance_items\".\"bonus_percent_applied\" IS NULL OR (\"kilo_pass_issuance_items\".\"bonus_percent_applied\" >= 0 AND \"kilo_pass_issuance_items\".\"bonus_percent_applied\" <= 1)" + }, + "kilo_pass_issuance_items_amount_usd_non_negative_check": { + "name": "kilo_pass_issuance_items_amount_usd_non_negative_check", + "value": "\"kilo_pass_issuance_items\".\"amount_usd\" >= 0" + }, + "kilo_pass_issuance_items_kind_check": { + "name": "kilo_pass_issuance_items_kind_check", + "value": "\"kilo_pass_issuance_items\".\"kind\" IN ('base', 'bonus', 'promo_first_month_50pct', 'referral_bonus')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_issuances": { + "name": "kilo_pass_issuances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_pass_subscription_id": { + "name": "kilo_pass_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_month": { + "name": "issue_month", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_invoice_id": { + "name": "stripe_invoice_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "initial_welcome_promo_eligibility_reason": { + "name": "initial_welcome_promo_eligibility_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": { + "UQ_kilo_pass_issuances_stripe_invoice_id": { + "name": "UQ_kilo_pass_issuances_stripe_invoice_id", + "columns": [ + { + "expression": "stripe_invoice_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_issuances\".\"stripe_invoice_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_kilo_pass_issuances_subscription_id": { + "name": "IDX_kilo_pass_issuances_subscription_id", + "columns": [ + { + "expression": "kilo_pass_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_issuances_issue_month": { + "name": "IDX_kilo_pass_issuances_issue_month", + "columns": [ + { + "expression": "issue_month", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_issuances_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk": { + "name": "kilo_pass_issuances_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk", + "tableFrom": "kilo_pass_issuances", + "columnsFrom": [ + "kilo_pass_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_issuances_subscription_issue_month": { + "name": "UQ_kilo_pass_issuances_subscription_issue_month", + "columns": [ + "kilo_pass_subscription_id", + "issue_month" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_issuances_issue_month_day_one_check": { + "name": "kilo_pass_issuances_issue_month_day_one_check", + "value": "EXTRACT(DAY FROM \"kilo_pass_issuances\".\"issue_month\") = 1" + }, + "kilo_pass_issuances_source_check": { + "name": "kilo_pass_issuances_source_check", + "value": "\"kilo_pass_issuances\".\"source\" IN ('stripe_invoice', 'app_store_transaction', 'google_play_transaction', 'cron')" + }, + "kilo_pass_issuances_initial_welcome_promo_reason_check": { + "name": "kilo_pass_issuances_initial_welcome_promo_reason_check", + "value": "\"kilo_pass_issuances\".\"initial_welcome_promo_eligibility_reason\" IN ('first_payment_fingerprint_claim', 'fingerprint_previously_claimed', 'missing_fingerprint', 'no_supported_fingerprint', 'no_positive_settlement', 'settlement_unresolved')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_agreements": { + "name": "kilo_pass_org_agreements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "parent_organization_id": { + "name": "parent_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "term_version_id": { + "name": "term_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "processing_condition": { + "name": "processing_condition", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'ready'" + }, + "purchase_channel": { + "name": "purchase_channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cadence": { + "name": "cadence", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purchased_pass_capacity": { + "name": "purchased_pass_capacity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "next_purchased_pass_capacity": { + "name": "next_purchased_pass_capacity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_capacity_effective_at": { + "name": "next_capacity_effective_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "paid_from": { + "name": "paid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "paid_until": { + "name": "paid_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "issuance_anchor_at": { + "name": "issuance_anchor_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "provider_subscription_id": { + "name": "provider_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_seat_add_on_item_id": { + "name": "provider_seat_add_on_item_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "activation_provider_event_id": { + "name": "activation_provider_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "external_contract_id": { + "name": "external_contract_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payment_review_required_at": { + "name": "payment_review_required_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_effective_at": { + "name": "cancellation_effective_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "manually_issued_through": { + "name": "manually_issued_through", + "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": { + "UQ_kilo_pass_org_agreements_one_non_ended_parent": { + "name": "UQ_kilo_pass_org_agreements_one_non_ended_parent", + "columns": [ + { + "expression": "parent_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_agreements\".\"state\" <> 'ended'", + "concurrently": false + }, + "UQ_kilo_pass_org_agreements_provider_subscription": { + "name": "UQ_kilo_pass_org_agreements_provider_subscription", + "columns": [ + { + "expression": "provider_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_agreements\".\"provider_subscription_id\" IS NOT NULL AND \"kilo_pass_org_agreements\".\"state\" <> 'ended'", + "concurrently": false + }, + "UQ_kilo_pass_org_agreements_provider_seat_add_on_item": { + "name": "UQ_kilo_pass_org_agreements_provider_seat_add_on_item", + "columns": [ + { + "expression": "provider_seat_add_on_item_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_agreements\".\"provider_seat_add_on_item_id\" IS NOT NULL AND \"kilo_pass_org_agreements\".\"state\" <> 'ended'", + "concurrently": false + }, + "UQ_kilo_pass_org_agreements_external_contract": { + "name": "UQ_kilo_pass_org_agreements_external_contract", + "columns": [ + { + "expression": "external_contract_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_agreements\".\"external_contract_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_kilo_pass_org_agreements_activation_provider_event": { + "name": "UQ_kilo_pass_org_agreements_activation_provider_event", + "columns": [ + { + "expression": "activation_provider_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_agreements\".\"activation_provider_event_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_kilo_pass_org_agreements_processing": { + "name": "IDX_kilo_pass_org_agreements_processing", + "columns": [ + { + "expression": "processing_condition", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_agreements_parent_organization_id_organizations_id_fk": { + "name": "kilo_pass_org_agreements_parent_organization_id_organizations_id_fk", + "tableFrom": "kilo_pass_org_agreements", + "columnsFrom": [ + "parent_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_agreements_term_version_id_kilo_pass_org_term_versions_id_fk": { + "name": "kilo_pass_org_agreements_term_version_id_kilo_pass_org_term_versions_id_fk", + "tableFrom": "kilo_pass_org_agreements", + "columnsFrom": [ + "term_version_id" + ], + "tableTo": "kilo_pass_org_term_versions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_agreements_purchased_capacity_non_negative_check": { + "name": "kilo_pass_org_agreements_purchased_capacity_non_negative_check", + "value": "\"kilo_pass_org_agreements\".\"purchased_pass_capacity\" >= 0" + }, + "kilo_pass_org_agreements_next_capacity_check": { + "name": "kilo_pass_org_agreements_next_capacity_check", + "value": "(\"kilo_pass_org_agreements\".\"next_purchased_pass_capacity\" IS NULL AND \"kilo_pass_org_agreements\".\"next_capacity_effective_at\" IS NULL) OR (\"kilo_pass_org_agreements\".\"next_purchased_pass_capacity\" >= 0 AND \"kilo_pass_org_agreements\".\"next_capacity_effective_at\" IS NOT NULL)" + }, + "kilo_pass_org_agreements_paid_interval_check": { + "name": "kilo_pass_org_agreements_paid_interval_check", + "value": "(\"kilo_pass_org_agreements\".\"paid_from\" IS NULL AND \"kilo_pass_org_agreements\".\"paid_until\" IS NULL) OR (\"kilo_pass_org_agreements\".\"paid_from\" IS NOT NULL AND \"kilo_pass_org_agreements\".\"paid_until\" IS NOT NULL AND \"kilo_pass_org_agreements\".\"paid_from\" < \"kilo_pass_org_agreements\".\"paid_until\")" + }, + "kilo_pass_org_agreements_state_check": { + "name": "kilo_pass_org_agreements_state_check", + "value": "\"kilo_pass_org_agreements\".\"state\" IN ('pending_payment', 'active', 'cancel_at_period_end', 'ended')" + }, + "kilo_pass_org_agreements_processing_condition_check": { + "name": "kilo_pass_org_agreements_processing_condition_check", + "value": "\"kilo_pass_org_agreements\".\"processing_condition\" IN ('ready', 'manual', 'blocked', 'overallocated', 'failed', 'suspended_for_review')" + }, + "kilo_pass_org_agreements_purchase_channel_check": { + "name": "kilo_pass_org_agreements_purchase_channel_check", + "value": "\"kilo_pass_org_agreements\".\"purchase_channel\" IN ('self_serve', 'manual')" + }, + "kilo_pass_org_agreements_cadence_check": { + "name": "kilo_pass_org_agreements_cadence_check", + "value": "\"kilo_pass_org_agreements\".\"cadence\" IN ('monthly', 'yearly')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_allocation_plan_rows": { + "name": "kilo_pass_org_allocation_plan_rows", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "allocation_plan_id": { + "name": "allocation_plan_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "allocation_container_organization_id": { + "name": "allocation_container_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "pass_capacity": { + "name": "pass_capacity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_kilo_pass_org_allocation_plan_rows_positive_container": { + "name": "IDX_kilo_pass_org_allocation_plan_rows_positive_container", + "columns": [ + { + "expression": "allocation_container_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_allocation_plan_rows\".\"pass_capacity\" > 0", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_allocation_plan_rows_allocation_plan_id_kilo_pass_org_allocation_plans_id_fk": { + "name": "kilo_pass_org_allocation_plan_rows_allocation_plan_id_kilo_pass_org_allocation_plans_id_fk", + "tableFrom": "kilo_pass_org_allocation_plan_rows", + "columnsFrom": [ + "allocation_plan_id" + ], + "tableTo": "kilo_pass_org_allocation_plans", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_org_allocation_plan_rows_allocation_container_organization_id_organizations_id_fk": { + "name": "kilo_pass_org_allocation_plan_rows_allocation_container_organization_id_organizations_id_fk", + "tableFrom": "kilo_pass_org_allocation_plan_rows", + "columnsFrom": [ + "allocation_container_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_allocation_plan_rows_plan_container": { + "name": "UQ_kilo_pass_org_allocation_plan_rows_plan_container", + "columns": [ + "allocation_plan_id", + "allocation_container_organization_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_allocation_plan_rows_capacity_non_negative_check": { + "name": "kilo_pass_org_allocation_plan_rows_capacity_non_negative_check", + "value": "\"kilo_pass_org_allocation_plan_rows\".\"pass_capacity\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_allocation_plans": { + "name": "kilo_pass_org_allocation_plans", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "agreement_id": { + "name": "agreement_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effective_window_start": { + "name": "effective_window_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_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": {}, + "foreignKeys": { + "kilo_pass_org_allocation_plans_agreement_id_kilo_pass_org_agreements_id_fk": { + "name": "kilo_pass_org_allocation_plans_agreement_id_kilo_pass_org_agreements_id_fk", + "tableFrom": "kilo_pass_org_allocation_plans", + "columnsFrom": [ + "agreement_id" + ], + "tableTo": "kilo_pass_org_agreements", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_org_allocation_plans_created_by_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_org_allocation_plans_created_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_org_allocation_plans", + "columnsFrom": [ + "created_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_allocation_plans_agreement_window": { + "name": "UQ_kilo_pass_org_allocation_plans_agreement_window", + "columns": [ + "agreement_id", + "effective_window_start" + ], + "nullsNotDistinct": false + }, + "UQ_kilo_pass_org_allocation_plans_agreement_version": { + "name": "UQ_kilo_pass_org_allocation_plans_agreement_version", + "columns": [ + "agreement_id", + "version" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_allocation_plans_version_positive_check": { + "name": "kilo_pass_org_allocation_plans_version_positive_check", + "value": "\"kilo_pass_org_allocation_plans\".\"version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_audit_records": { + "name": "kilo_pass_org_audit_records", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "agreement_id": { + "name": "agreement_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_kilo_user_id": { + "name": "actor_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "before_json": { + "name": "before_json", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "after_json": { + "name": "after_json", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_kilo_pass_org_audit_records_idempotency": { + "name": "UQ_kilo_pass_org_audit_records_idempotency", + "columns": [ + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_audit_records\".\"idempotency_key\" IS NOT NULL", + "concurrently": false + }, + "IDX_kilo_pass_org_audit_records_agreement_created": { + "name": "IDX_kilo_pass_org_audit_records_agreement_created", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_audit_records_agreement_id_kilo_pass_org_agreements_id_fk": { + "name": "kilo_pass_org_audit_records_agreement_id_kilo_pass_org_agreements_id_fk", + "tableFrom": "kilo_pass_org_audit_records", + "columnsFrom": [ + "agreement_id" + ], + "tableTo": "kilo_pass_org_agreements", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_org_audit_records_actor_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_org_audit_records_actor_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_org_audit_records", + "columnsFrom": [ + "actor_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kilo_pass_org_issuance_snapshots": { + "name": "kilo_pass_org_issuance_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "agreement_id": { + "name": "agreement_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "processing_run_id": { + "name": "processing_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "allocation_plan_id": { + "name": "allocation_plan_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "term_version_id": { + "name": "term_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "allocation_container_organization_id": { + "name": "allocation_container_organization_id", + "type": "uuid", + "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 + }, + "qualifying_spend_starts_at": { + "name": "qualifying_spend_starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tranche_key": { + "name": "tranche_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "allocated_pass_capacity": { + "name": "allocated_pass_capacity", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "base_credit_microdollars": { + "name": "base_credit_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "bonus_credit_microdollars": { + "name": "bonus_credit_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "unlock_spend_microdollars": { + "name": "unlock_spend_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "qualifying_spend_microdollars": { + "name": "qualifying_spend_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "bonus_mode": { + "name": "bonus_mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bonus_unlocked_at": { + "name": "bonus_unlocked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "repair_completed_at": { + "name": "repair_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "bonus_credit_transaction_id": { + "name": "bonus_credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "base_credit_transaction_id": { + "name": "base_credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_kilo_pass_org_issuance_snapshots_base_credit_transaction": { + "name": "UQ_kilo_pass_org_issuance_snapshots_base_credit_transaction", + "columns": [ + { + "expression": "base_credit_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_issuance_snapshots\".\"base_credit_transaction_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_kilo_pass_org_issuance_snapshots_bonus_credit_transaction": { + "name": "UQ_kilo_pass_org_issuance_snapshots_bonus_credit_transaction", + "columns": [ + { + "expression": "bonus_credit_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_org_issuance_snapshots\".\"bonus_credit_transaction_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_kilo_pass_org_issuance_snapshots_window": { + "name": "IDX_kilo_pass_org_issuance_snapshots_window", + "columns": [ + { + "expression": "agreement_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_issuance_snapshots_agreement_id_kilo_pass_org_agreements_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_agreement_id_kilo_pass_org_agreements_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "agreement_id" + ], + "tableTo": "kilo_pass_org_agreements", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_issuance_snapshots_processing_run_id_kilo_pass_org_processing_runs_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_processing_run_id_kilo_pass_org_processing_runs_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "processing_run_id" + ], + "tableTo": "kilo_pass_org_processing_runs", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_org_issuance_snapshots_allocation_plan_id_kilo_pass_org_allocation_plans_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_allocation_plan_id_kilo_pass_org_allocation_plans_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "allocation_plan_id" + ], + "tableTo": "kilo_pass_org_allocation_plans", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "kilo_pass_org_issuance_snapshots_term_version_id_kilo_pass_org_term_versions_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_term_version_id_kilo_pass_org_term_versions_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "term_version_id" + ], + "tableTo": "kilo_pass_org_term_versions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_issuance_snapshots_allocation_container_organization_id_organizations_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_allocation_container_organization_id_organizations_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "allocation_container_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_issuance_snapshots_bonus_credit_transaction_id_credit_transactions_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_bonus_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "bonus_credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_issuance_snapshots_base_credit_transaction_id_credit_transactions_id_fk": { + "name": "kilo_pass_org_issuance_snapshots_base_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "kilo_pass_org_issuance_snapshots", + "columnsFrom": [ + "base_credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_issuance_snapshots_container_window_tranche": { + "name": "UQ_kilo_pass_org_issuance_snapshots_container_window_tranche", + "columns": [ + "agreement_id", + "allocation_container_organization_id", + "window_start", + "tranche_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_issuance_snapshots_window_check": { + "name": "kilo_pass_org_issuance_snapshots_window_check", + "value": "\"kilo_pass_org_issuance_snapshots\".\"window_start\" < \"kilo_pass_org_issuance_snapshots\".\"window_end\"" + }, + "kilo_pass_org_issuance_snapshots_qualifying_spend_window_check": { + "name": "kilo_pass_org_issuance_snapshots_qualifying_spend_window_check", + "value": "\"kilo_pass_org_issuance_snapshots\".\"window_start\" <= \"kilo_pass_org_issuance_snapshots\".\"qualifying_spend_starts_at\" AND \"kilo_pass_org_issuance_snapshots\".\"qualifying_spend_starts_at\" < \"kilo_pass_org_issuance_snapshots\".\"window_end\"" + }, + "kilo_pass_org_issuance_snapshots_values_non_negative_check": { + "name": "kilo_pass_org_issuance_snapshots_values_non_negative_check", + "value": "\"kilo_pass_org_issuance_snapshots\".\"allocated_pass_capacity\" >= 0 AND \"kilo_pass_org_issuance_snapshots\".\"base_credit_microdollars\" >= 0 AND \"kilo_pass_org_issuance_snapshots\".\"bonus_credit_microdollars\" >= 0 AND \"kilo_pass_org_issuance_snapshots\".\"unlock_spend_microdollars\" >= 0 AND \"kilo_pass_org_issuance_snapshots\".\"qualifying_spend_microdollars\" >= 0" + }, + "kilo_pass_org_issuance_snapshots_kind_check": { + "name": "kilo_pass_org_issuance_snapshots_kind_check", + "value": "\"kilo_pass_org_issuance_snapshots\".\"kind\" IN ('regular', 'bridge', 'supplement')" + }, + "kilo_pass_org_issuance_snapshots_bonus_mode_check": { + "name": "kilo_pass_org_issuance_snapshots_bonus_mode_check", + "value": "\"kilo_pass_org_issuance_snapshots\".\"bonus_mode\" IN ('after_base', 'upfront')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_notification_deliveries": { + "name": "kilo_pass_org_notification_deliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "processing_run_id": { + "name": "processing_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipient_kilo_user_id": { + "name": "recipient_kilo_user_id", + "type": "text", + "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 + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_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": { + "IDX_kilo_pass_org_notification_deliveries_status": { + "name": "IDX_kilo_pass_org_notification_deliveries_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_notification_deliveries_processing_run_id_kilo_pass_org_processing_runs_id_fk": { + "name": "kilo_pass_org_notification_deliveries_processing_run_id_kilo_pass_org_processing_runs_id_fk", + "tableFrom": "kilo_pass_org_notification_deliveries", + "columnsFrom": [ + "processing_run_id" + ], + "tableTo": "kilo_pass_org_processing_runs", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_org_notification_deliveries_recipient_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_org_notification_deliveries_recipient_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_org_notification_deliveries", + "columnsFrom": [ + "recipient_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_notification_deliveries_run_recipient": { + "name": "UQ_kilo_pass_org_notification_deliveries_run_recipient", + "columns": [ + "processing_run_id", + "recipient_kilo_user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_notification_deliveries_status_check": { + "name": "kilo_pass_org_notification_deliveries_status_check", + "value": "\"kilo_pass_org_notification_deliveries\".\"status\" IN ('pending', 'sending', 'sent', 'failed')" + }, + "kilo_pass_org_notification_deliveries_attempt_count_check": { + "name": "kilo_pass_org_notification_deliveries_attempt_count_check", + "value": "\"kilo_pass_org_notification_deliveries\".\"attempt_count\" >= 0" + }, + "kilo_pass_org_notification_deliveries_sent_check": { + "name": "kilo_pass_org_notification_deliveries_sent_check", + "value": "(\"kilo_pass_org_notification_deliveries\".\"status\" = 'sent' AND \"kilo_pass_org_notification_deliveries\".\"sent_at\" IS NOT NULL AND \"kilo_pass_org_notification_deliveries\".\"lease_expires_at\" IS NULL) OR (\"kilo_pass_org_notification_deliveries\".\"status\" = 'sending' AND \"kilo_pass_org_notification_deliveries\".\"sent_at\" IS NULL AND \"kilo_pass_org_notification_deliveries\".\"lease_expires_at\" IS NOT NULL) OR (\"kilo_pass_org_notification_deliveries\".\"status\" IN ('pending', 'failed') AND \"kilo_pass_org_notification_deliveries\".\"sent_at\" IS NULL AND \"kilo_pass_org_notification_deliveries\".\"lease_expires_at\" IS NULL)" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_processing_runs": { + "name": "kilo_pass_org_processing_runs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "agreement_id": { + "name": "agreement_id", + "type": "uuid", + "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 + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_kilo_pass_org_processing_runs_state_lease": { + "name": "IDX_kilo_pass_org_processing_runs_state_lease", + "columns": [ + { + "expression": "state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_processing_runs_agreement_id_kilo_pass_org_agreements_id_fk": { + "name": "kilo_pass_org_processing_runs_agreement_id_kilo_pass_org_agreements_id_fk", + "tableFrom": "kilo_pass_org_processing_runs", + "columnsFrom": [ + "agreement_id" + ], + "tableTo": "kilo_pass_org_agreements", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_processing_runs_agreement_window": { + "name": "UQ_kilo_pass_org_processing_runs_agreement_window", + "columns": [ + "agreement_id", + "window_start" + ], + "nullsNotDistinct": false + }, + "UQ_kilo_pass_org_processing_runs_idempotency": { + "name": "UQ_kilo_pass_org_processing_runs_idempotency", + "columns": [ + "idempotency_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_processing_runs_window_check": { + "name": "kilo_pass_org_processing_runs_window_check", + "value": "\"kilo_pass_org_processing_runs\".\"window_start\" < \"kilo_pass_org_processing_runs\".\"window_end\"" + }, + "kilo_pass_org_processing_runs_attempt_count_non_negative_check": { + "name": "kilo_pass_org_processing_runs_attempt_count_non_negative_check", + "value": "\"kilo_pass_org_processing_runs\".\"attempt_count\" >= 0" + }, + "kilo_pass_org_processing_runs_state_check": { + "name": "kilo_pass_org_processing_runs_state_check", + "value": "\"kilo_pass_org_processing_runs\".\"state\" IN ('pending', 'running', 'succeeded', 'blocked', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_qualifying_spend_events": { + "name": "kilo_pass_org_qualifying_spend_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "issuance_snapshot_id": { + "name": "issuance_snapshot_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "allocation_container_organization_id": { + "name": "allocation_container_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "credit_transaction_id": { + "name": "credit_transaction_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "spent_microdollars": { + "name": "spent_microdollars", + "type": "bigint", + "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": { + "IDX_kilo_pass_org_qualifying_spend_events_snapshot_occurred": { + "name": "IDX_kilo_pass_org_qualifying_spend_events_snapshot_occurred", + "columns": [ + { + "expression": "issuance_snapshot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "occurred_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_org_qualifying_spend_events_issuance_snapshot_id_kilo_pass_org_issuance_snapshots_id_fk": { + "name": "kilo_pass_org_qualifying_spend_events_issuance_snapshot_id_kilo_pass_org_issuance_snapshots_id_fk", + "tableFrom": "kilo_pass_org_qualifying_spend_events", + "columnsFrom": [ + "issuance_snapshot_id" + ], + "tableTo": "kilo_pass_org_issuance_snapshots", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_org_qualifying_spend_events_allocation_container_organization_id_organizations_id_fk": { + "name": "kilo_pass_org_qualifying_spend_events_allocation_container_organization_id_organizations_id_fk", + "tableFrom": "kilo_pass_org_qualifying_spend_events", + "columnsFrom": [ + "allocation_container_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_qualifying_spend_events_credit_transaction_id_credit_transactions_id_fk": { + "name": "kilo_pass_org_qualifying_spend_events_credit_transaction_id_credit_transactions_id_fk", + "tableFrom": "kilo_pass_org_qualifying_spend_events", + "columnsFrom": [ + "credit_transaction_id" + ], + "tableTo": "credit_transactions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_qualifying_spend_events_snapshot_credit_transaction": { + "name": "UQ_kilo_pass_org_qualifying_spend_events_snapshot_credit_transaction", + "columns": [ + "issuance_snapshot_id", + "credit_transaction_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_qualifying_spend_events_amount_positive_check": { + "name": "kilo_pass_org_qualifying_spend_events_amount_positive_check", + "value": "\"kilo_pass_org_qualifying_spend_events\".\"spent_microdollars\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_supplements": { + "name": "kilo_pass_org_supplements", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "issuance_snapshot_id": { + "name": "issuance_snapshot_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider_invoice_line_id": { + "name": "provider_invoice_line_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "remaining_service_numerator": { + "name": "remaining_service_numerator", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "remaining_service_denominator": { + "name": "remaining_service_denominator", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "kilo_pass_org_supplements_issuance_snapshot_id_kilo_pass_org_issuance_snapshots_id_fk": { + "name": "kilo_pass_org_supplements_issuance_snapshot_id_kilo_pass_org_issuance_snapshots_id_fk", + "tableFrom": "kilo_pass_org_supplements", + "columnsFrom": [ + "issuance_snapshot_id" + ], + "tableTo": "kilo_pass_org_issuance_snapshots", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_supplements_provider_invoice_line": { + "name": "UQ_kilo_pass_org_supplements_provider_invoice_line", + "columns": [ + "provider_invoice_line_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_supplements_ratio_check": { + "name": "kilo_pass_org_supplements_ratio_check", + "value": "\"kilo_pass_org_supplements\".\"remaining_service_numerator\" > 0 AND \"kilo_pass_org_supplements\".\"remaining_service_denominator\" > 0 AND \"kilo_pass_org_supplements\".\"remaining_service_numerator\" <= \"kilo_pass_org_supplements\".\"remaining_service_denominator\"" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_term_transitions": { + "name": "kilo_pass_org_term_transitions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "agreement_id": { + "name": "agreement_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "from_term_version_id": { + "name": "from_term_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "to_term_version_id": { + "name": "to_term_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "effective_at": { + "name": "effective_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "kilo_pass_org_term_transitions_agreement_id_kilo_pass_org_agreements_id_fk": { + "name": "kilo_pass_org_term_transitions_agreement_id_kilo_pass_org_agreements_id_fk", + "tableFrom": "kilo_pass_org_term_transitions", + "columnsFrom": [ + "agreement_id" + ], + "tableTo": "kilo_pass_org_agreements", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_org_term_transitions_from_term_version_id_kilo_pass_org_term_versions_id_fk": { + "name": "kilo_pass_org_term_transitions_from_term_version_id_kilo_pass_org_term_versions_id_fk", + "tableFrom": "kilo_pass_org_term_transitions", + "columnsFrom": [ + "from_term_version_id" + ], + "tableTo": "kilo_pass_org_term_versions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_term_transitions_to_term_version_id_kilo_pass_org_term_versions_id_fk": { + "name": "kilo_pass_org_term_transitions_to_term_version_id_kilo_pass_org_term_versions_id_fk", + "tableFrom": "kilo_pass_org_term_transitions", + "columnsFrom": [ + "to_term_version_id" + ], + "tableTo": "kilo_pass_org_term_versions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + }, + "kilo_pass_org_term_transitions_created_by_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_org_term_transitions_created_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_org_term_transitions", + "columnsFrom": [ + "created_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_term_transitions_agreement_effective": { + "name": "UQ_kilo_pass_org_term_transitions_agreement_effective", + "columns": [ + "agreement_id", + "effective_at" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_term_transitions_changes_version_check": { + "name": "kilo_pass_org_term_transitions_changes_version_check", + "value": "\"kilo_pass_org_term_transitions\".\"from_term_version_id\" <> \"kilo_pass_org_term_transitions\".\"to_term_version_id\"" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_org_term_versions": { + "name": "kilo_pass_org_term_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "version_key": { + "name": "version_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tier": { + "name": "tier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cadence": { + "name": "cadence", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "billing_price_microdollars_per_pass": { + "name": "billing_price_microdollars_per_pass", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "base_credit_microdollars_per_pass": { + "name": "base_credit_microdollars_per_pass", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "bonus_credit_microdollars_per_pass": { + "name": "bonus_credit_microdollars_per_pass", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "unlock_spend_microdollars_per_pass": { + "name": "unlock_spend_microdollars_per_pass", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "bonus_mode": { + "name": "bonus_mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_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": {}, + "foreignKeys": { + "kilo_pass_org_term_versions_created_by_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_org_term_versions_created_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_org_term_versions", + "columnsFrom": [ + "created_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_kilo_pass_org_term_versions_version_key": { + "name": "UQ_kilo_pass_org_term_versions_version_key", + "columns": [ + "version_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_org_term_versions_amounts_non_negative_check": { + "name": "kilo_pass_org_term_versions_amounts_non_negative_check", + "value": "\"kilo_pass_org_term_versions\".\"billing_price_microdollars_per_pass\" >= 0 AND \"kilo_pass_org_term_versions\".\"base_credit_microdollars_per_pass\" >= 0 AND \"kilo_pass_org_term_versions\".\"bonus_credit_microdollars_per_pass\" >= 0 AND \"kilo_pass_org_term_versions\".\"unlock_spend_microdollars_per_pass\" >= 0" + }, + "kilo_pass_org_term_versions_tier_check": { + "name": "kilo_pass_org_term_versions_tier_check", + "value": "\"kilo_pass_org_term_versions\".\"tier\" IN ('tier_19', 'tier_49', 'tier_199')" + }, + "kilo_pass_org_term_versions_cadence_check": { + "name": "kilo_pass_org_term_versions_cadence_check", + "value": "\"kilo_pass_org_term_versions\".\"cadence\" IN ('monthly', 'yearly')" + }, + "kilo_pass_org_term_versions_bonus_mode_check": { + "name": "kilo_pass_org_term_versions_bonus_mode_check", + "value": "\"kilo_pass_org_term_versions\".\"bonus_mode\" IN ('after_base', 'upfront')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_pause_events": { + "name": "kilo_pass_pause_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_pass_subscription_id": { + "name": "kilo_pass_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "paused_at": { + "name": "paused_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "resumes_at": { + "name": "resumes_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resumed_at": { + "name": "resumed_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": { + "IDX_kilo_pass_pause_events_subscription_id": { + "name": "IDX_kilo_pass_pause_events_subscription_id", + "columns": [ + { + "expression": "kilo_pass_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kilo_pass_pause_events_one_open_per_sub": { + "name": "UQ_kilo_pass_pause_events_one_open_per_sub", + "columns": [ + { + "expression": "kilo_pass_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_pause_events\".\"resumed_at\" IS NULL", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_pause_events_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk": { + "name": "kilo_pass_pause_events_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk", + "tableFrom": "kilo_pass_pause_events", + "columnsFrom": [ + "kilo_pass_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_pause_events_resumed_at_after_paused_at_check": { + "name": "kilo_pass_pause_events_resumed_at_after_paused_at_check", + "value": "\"kilo_pass_pause_events\".\"resumed_at\" IS NULL OR \"kilo_pass_pause_events\".\"resumed_at\" >= \"kilo_pass_pause_events\".\"paused_at\"" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_scheduled_changes": { + "name": "kilo_pass_scheduled_changes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_tier": { + "name": "from_tier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "from_cadence": { + "name": "from_cadence", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to_tier": { + "name": "to_tier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to_cadence": { + "name": "to_cadence", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "effective_at": { + "name": "effective_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "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": { + "IDX_kilo_pass_scheduled_changes_kilo_user_id": { + "name": "IDX_kilo_pass_scheduled_changes_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_scheduled_changes_status": { + "name": "IDX_kilo_pass_scheduled_changes_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_scheduled_changes_stripe_subscription_id": { + "name": "IDX_kilo_pass_scheduled_changes_stripe_subscription_id", + "columns": [ + { + "expression": "stripe_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kilo_pass_scheduled_changes_active_stripe_subscription_id": { + "name": "UQ_kilo_pass_scheduled_changes_active_stripe_subscription_id", + "columns": [ + { + "expression": "stripe_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_scheduled_changes\".\"deleted_at\" is null", + "concurrently": false + }, + "IDX_kilo_pass_scheduled_changes_effective_at": { + "name": "IDX_kilo_pass_scheduled_changes_effective_at", + "columns": [ + { + "expression": "effective_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_scheduled_changes_deleted_at": { + "name": "IDX_kilo_pass_scheduled_changes_deleted_at", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_scheduled_changes_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_scheduled_changes_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_scheduled_changes", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_scheduled_changes_stripe_subscription_id_kilo_pass_subscriptions_stripe_subscription_id_fk": { + "name": "kilo_pass_scheduled_changes_stripe_subscription_id_kilo_pass_subscriptions_stripe_subscription_id_fk", + "tableFrom": "kilo_pass_scheduled_changes", + "columnsFrom": [ + "stripe_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "stripe_subscription_id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_scheduled_changes_from_tier_check": { + "name": "kilo_pass_scheduled_changes_from_tier_check", + "value": "\"kilo_pass_scheduled_changes\".\"from_tier\" IN ('tier_19', 'tier_49', 'tier_199')" + }, + "kilo_pass_scheduled_changes_from_cadence_check": { + "name": "kilo_pass_scheduled_changes_from_cadence_check", + "value": "\"kilo_pass_scheduled_changes\".\"from_cadence\" IN ('monthly', 'yearly')" + }, + "kilo_pass_scheduled_changes_to_tier_check": { + "name": "kilo_pass_scheduled_changes_to_tier_check", + "value": "\"kilo_pass_scheduled_changes\".\"to_tier\" IN ('tier_19', 'tier_49', 'tier_199')" + }, + "kilo_pass_scheduled_changes_to_cadence_check": { + "name": "kilo_pass_scheduled_changes_to_cadence_check", + "value": "\"kilo_pass_scheduled_changes\".\"to_cadence\" IN ('monthly', 'yearly')" + }, + "kilo_pass_scheduled_changes_status_check": { + "name": "kilo_pass_scheduled_changes_status_check", + "value": "\"kilo_pass_scheduled_changes\".\"status\" IN ('not_started', 'active', 'completed', 'released', 'canceled')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_store_events": { + "name": "kilo_pass_store_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "payment_provider": { + "name": "payment_provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_subscription_id": { + "name": "provider_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_transaction_id": { + "name": "provider_transaction_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "app_account_token": { + "name": "app_account_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "product_id": { + "name": "product_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload_json": { + "name": "payload_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "processing_started_at": { + "name": "processing_started_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()" + } + }, + "indexes": { + "UQ_kilo_pass_store_events_provider_event": { + "name": "UQ_kilo_pass_store_events_provider_event", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_events_provider_subscription": { + "name": "IDX_kilo_pass_store_events_provider_subscription", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_events_app_account_token": { + "name": "IDX_kilo_pass_store_events_app_account_token", + "columns": [ + { + "expression": "app_account_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_store_events_payment_provider_check": { + "name": "kilo_pass_store_events_payment_provider_check", + "value": "\"kilo_pass_store_events\".\"payment_provider\" IN ('stripe', 'app_store', 'google_play')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_store_purchases": { + "name": "kilo_pass_store_purchases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_pass_subscription_id": { + "name": "kilo_pass_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payment_provider": { + "name": "payment_provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "product_id": { + "name": "product_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_subscription_id": { + "name": "provider_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_transaction_id": { + "name": "provider_transaction_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_original_transaction_id": { + "name": "provider_original_transaction_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "app_account_token": { + "name": "app_account_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "purchase_token": { + "name": "purchase_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purchased_at": { + "name": "purchased_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "raw_payload_json": { + "name": "raw_payload_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": { + "UQ_kilo_pass_store_purchases_provider_transaction": { + "name": "UQ_kilo_pass_store_purchases_provider_transaction", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_purchases_subscription_id": { + "name": "IDX_kilo_pass_store_purchases_subscription_id", + "columns": [ + { + "expression": "kilo_pass_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_purchases_user_id": { + "name": "IDX_kilo_pass_store_purchases_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_purchases_app_account_token": { + "name": "IDX_kilo_pass_store_purchases_app_account_token", + "columns": [ + { + "expression": "app_account_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_store_purchases_latest_subscription_purchase": { + "name": "IDX_kilo_pass_store_purchases_latest_subscription_purchase", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "purchased_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_store_purchases_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk": { + "name": "kilo_pass_store_purchases_kilo_pass_subscription_id_kilo_pass_subscriptions_id_fk", + "tableFrom": "kilo_pass_store_purchases", + "columnsFrom": [ + "kilo_pass_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "kilo_pass_store_purchases_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_store_purchases_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_store_purchases", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "FK_kilo_pass_store_purchases_subscription_owner_provider": { + "name": "FK_kilo_pass_store_purchases_subscription_owner_provider", + "tableFrom": "kilo_pass_store_purchases", + "columnsFrom": [ + "kilo_pass_subscription_id", + "kilo_user_id", + "payment_provider", + "provider_subscription_id" + ], + "tableTo": "kilo_pass_subscriptions", + "columnsTo": [ + "id", + "kilo_user_id", + "payment_provider", + "provider_subscription_id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kilo_pass_store_purchases_store_provider_check": { + "name": "kilo_pass_store_purchases_store_provider_check", + "value": "\"kilo_pass_store_purchases\".\"payment_provider\" IN ('app_store', 'google_play')" + }, + "kilo_pass_store_purchases_payment_provider_check": { + "name": "kilo_pass_store_purchases_payment_provider_check", + "value": "\"kilo_pass_store_purchases\".\"payment_provider\" IN ('stripe', 'app_store', 'google_play')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_subscriptions": { + "name": "kilo_pass_subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payment_provider": { + "name": "payment_provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'stripe'" + }, + "provider_subscription_id": { + "name": "provider_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tier": { + "name": "tier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cadence": { + "name": "cadence", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "current_streak_months": { + "name": "current_streak_months", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_yearly_issue_at": { + "name": "next_yearly_issue_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": { + "IDX_kilo_pass_subscriptions_kilo_user_id": { + "name": "IDX_kilo_pass_subscriptions_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_subscriptions_payment_provider": { + "name": "IDX_kilo_pass_subscriptions_payment_provider", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_subscriptions_status": { + "name": "IDX_kilo_pass_subscriptions_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilo_pass_subscriptions_cadence": { + "name": "IDX_kilo_pass_subscriptions_cadence", + "columns": [ + { + "expression": "cadence", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kilo_pass_subscriptions_provider_subscription": { + "name": "UQ_kilo_pass_subscriptions_provider_subscription", + "columns": [ + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilo_pass_subscriptions\".\"provider_subscription_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_kilo_pass_subscriptions_store_purchase_reference": { + "name": "UQ_kilo_pass_subscriptions_store_purchase_reference", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "payment_provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kilo_pass_subscriptions_kilo_user_id_kilocode_users_id_fk": { + "name": "kilo_pass_subscriptions_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kilo_pass_subscriptions", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kilo_pass_subscriptions_stripe_subscription_id_unique": { + "name": "kilo_pass_subscriptions_stripe_subscription_id_unique", + "columns": [ + "stripe_subscription_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_subscriptions_current_streak_months_non_negative_check": { + "name": "kilo_pass_subscriptions_current_streak_months_non_negative_check", + "value": "\"kilo_pass_subscriptions\".\"current_streak_months\" >= 0" + }, + "kilo_pass_subscriptions_provider_ids_check": { + "name": "kilo_pass_subscriptions_provider_ids_check", + "value": "(\n \"kilo_pass_subscriptions\".\"payment_provider\" = 'stripe'\n AND \"kilo_pass_subscriptions\".\"provider_subscription_id\" IS NOT NULL\n AND \"kilo_pass_subscriptions\".\"stripe_subscription_id\" IS NOT NULL\n AND \"kilo_pass_subscriptions\".\"provider_subscription_id\" = \"kilo_pass_subscriptions\".\"stripe_subscription_id\"\n ) OR (\n \"kilo_pass_subscriptions\".\"payment_provider\" IN ('app_store', 'google_play')\n AND \"kilo_pass_subscriptions\".\"provider_subscription_id\" IS NOT NULL\n AND \"kilo_pass_subscriptions\".\"stripe_subscription_id\" IS NULL\n )" + }, + "kilo_pass_subscriptions_payment_provider_check": { + "name": "kilo_pass_subscriptions_payment_provider_check", + "value": "\"kilo_pass_subscriptions\".\"payment_provider\" IN ('stripe', 'app_store', 'google_play')" + }, + "kilo_pass_subscriptions_tier_check": { + "name": "kilo_pass_subscriptions_tier_check", + "value": "\"kilo_pass_subscriptions\".\"tier\" IN ('tier_19', 'tier_49', 'tier_199')" + }, + "kilo_pass_subscriptions_cadence_check": { + "name": "kilo_pass_subscriptions_cadence_check", + "value": "\"kilo_pass_subscriptions\".\"cadence\" IN ('monthly', 'yearly')" + } + }, + "isRLSEnabled": false + }, + "public.kilo_pass_welcome_promo_payment_fingerprint_claims": { + "name": "kilo_pass_welcome_promo_payment_fingerprint_claims", + "schema": "", + "columns": { + "stripe_payment_method_type": { + "name": "stripe_payment_method_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_fingerprint": { + "name": "stripe_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_stripe_invoice_id": { + "name": "source_stripe_invoice_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "kilo_pass_welcome_promo_payment_fingerprint_claims_stripe_payment_method_type_stripe_fingerprint_pk": { + "name": "kilo_pass_welcome_promo_payment_fingerprint_claims_stripe_payment_method_type_stripe_fingerprint_pk", + "columns": [ + "stripe_payment_method_type", + "stripe_fingerprint" + ] + } + }, + "uniqueConstraints": { + "UQ_kilo_pass_welcome_promo_payment_fingerprint_claims_source_invoice_id": { + "name": "UQ_kilo_pass_welcome_promo_payment_fingerprint_claims_source_invoice_id", + "columns": [ + "source_stripe_invoice_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kilo_pass_welcome_promo_payment_fingerprint_claims_type_check": { + "name": "kilo_pass_welcome_promo_payment_fingerprint_claims_type_check", + "value": "\"kilo_pass_welcome_promo_payment_fingerprint_claims\".\"stripe_payment_method_type\" IN ('card', 'sepa_debit', 'us_bank_account', 'bacs_debit', 'au_becs_debit')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_access_codes": { + "name": "kiloclaw_access_codes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "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": true + }, + "redeemed_at": { + "name": "redeemed_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": { + "UQ_kiloclaw_access_codes_code": { + "name": "UQ_kiloclaw_access_codes_code", + "columns": [ + { + "expression": "code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_access_codes_user_status": { + "name": "IDX_kiloclaw_access_codes_user_status", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kiloclaw_access_codes_one_active_per_user": { + "name": "UQ_kiloclaw_access_codes_one_active_per_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "status = 'active'", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_access_codes_kilo_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_access_codes_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_access_codes", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_admin_audit_logs": { + "name": "kiloclaw_admin_audit_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_user_id": { + "name": "target_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "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()" + } + }, + "indexes": { + "IDX_kiloclaw_admin_audit_logs_target_user_id": { + "name": "IDX_kiloclaw_admin_audit_logs_target_user_id", + "columns": [ + { + "expression": "target_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_admin_audit_logs_action": { + "name": "IDX_kiloclaw_admin_audit_logs_action", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_admin_audit_logs_created_at": { + "name": "IDX_kiloclaw_admin_audit_logs_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_cli_runs": { + "name": "kiloclaw_cli_runs", + "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 + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "initiated_by_admin_id": { + "name": "initiated_by_admin_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "prompt": { + "name": "prompt", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "output": { + "name": "output", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_kiloclaw_cli_runs_user_id": { + "name": "IDX_kiloclaw_cli_runs_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_cli_runs_started_at": { + "name": "IDX_kiloclaw_cli_runs_started_at", + "columns": [ + { + "expression": "started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_cli_runs_instance_id": { + "name": "IDX_kiloclaw_cli_runs_instance_id", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_cli_runs_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_cli_runs_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_cli_runs", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "kiloclaw_cli_runs_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_cli_runs_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_cli_runs", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_cli_runs_initiated_by_admin_id_kilocode_users_id_fk": { + "name": "kiloclaw_cli_runs_initiated_by_admin_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_cli_runs", + "columnsFrom": [ + "initiated_by_admin_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_earlybird_purchases": { + "name": "kiloclaw_earlybird_purchases", + "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 + }, + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manual_payment_id": { + "name": "manual_payment_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "kiloclaw_earlybird_purchases_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_earlybird_purchases_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_earlybird_purchases", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kiloclaw_earlybird_purchases_user_id_unique": { + "name": "kiloclaw_earlybird_purchases_user_id_unique", + "columns": [ + "user_id" + ], + "nullsNotDistinct": false + }, + "kiloclaw_earlybird_purchases_stripe_charge_id_unique": { + "name": "kiloclaw_earlybird_purchases_stripe_charge_id_unique", + "columns": [ + "stripe_charge_id" + ], + "nullsNotDistinct": false + }, + "kiloclaw_earlybird_purchases_manual_payment_id_unique": { + "name": "kiloclaw_earlybird_purchases_manual_payment_id_unique", + "columns": [ + "manual_payment_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_email_log": { + "name": "kiloclaw_email_log", + "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 + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_type": { + "name": "email_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "'epoch'" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_kiloclaw_email_log_user_type_global": { + "name": "UQ_kiloclaw_email_log_user_type_global", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_email_log\".\"instance_id\" is null", + "concurrently": false + }, + "UQ_kiloclaw_email_log_user_instance_type_period": { + "name": "UQ_kiloclaw_email_log_user_instance_type_period", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "email_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_email_log\".\"instance_id\" is not null", + "concurrently": false + }, + "IDX_kiloclaw_email_log_type_sent_instance": { + "name": "IDX_kiloclaw_email_log_type_sent_instance", + "columns": [ + { + "expression": "email_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sent_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_email_log\".\"instance_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_email_log_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_email_log_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_email_log", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_email_log_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_email_log_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_email_log", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_google_oauth_connections": { + "name": "kiloclaw_google_oauth_connections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'google'" + }, + "account_email": { + "name": "account_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "account_subject": { + "name": "account_subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_secret_encrypted": { + "name": "oauth_client_secret_encrypted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_profile": { + "name": "credential_profile", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'kilo_owned'" + }, + "refresh_token_encrypted": { + "name": "refresh_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "grants_by_source": { + "name": "grants_by_source", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "capabilities": { + "name": "capabilities", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error_at": { + "name": "last_error_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "connected_at": { + "name": "connected_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": { + "UQ_kiloclaw_google_oauth_connections_instance": { + "name": "UQ_kiloclaw_google_oauth_connections_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_google_oauth_connections_status": { + "name": "IDX_kiloclaw_google_oauth_connections_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_google_oauth_connections_provider": { + "name": "IDX_kiloclaw_google_oauth_connections_provider", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_google_oauth_connections_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_google_oauth_connections_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_google_oauth_connections", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kiloclaw_google_oauth_connections_status_check": { + "name": "kiloclaw_google_oauth_connections_status_check", + "value": "\"kiloclaw_google_oauth_connections\".\"status\" IN ('active', 'action_required', 'disconnected')" + }, + "kiloclaw_google_oauth_connections_credential_profile_check": { + "name": "kiloclaw_google_oauth_connections_credential_profile_check", + "value": "\"kiloclaw_google_oauth_connections\".\"credential_profile\" IN ('legacy', 'kilo_owned')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_image_catalog": { + "name": "kiloclaw_image_catalog", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "openclaw_version": { + "name": "openclaw_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "variant": { + "name": "variant", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "image_tag": { + "name": "image_tag", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "image_digest": { + "name": "image_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'available'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "synced_at": { + "name": "synced_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()" + }, + "rollout_percent": { + "name": "rollout_percent", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_latest": { + "name": "is_latest", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "IDX_kiloclaw_image_catalog_status": { + "name": "IDX_kiloclaw_image_catalog_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_image_catalog_variant": { + "name": "IDX_kiloclaw_image_catalog_variant", + "columns": [ + { + "expression": "variant", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kiloclaw_image_catalog_one_latest_per_variant": { + "name": "UQ_kiloclaw_image_catalog_one_latest_per_variant", + "columns": [ + { + "expression": "variant", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_image_catalog\".\"is_latest\" = true", + "concurrently": false + }, + "UQ_kiloclaw_image_catalog_one_candidate_per_variant": { + "name": "UQ_kiloclaw_image_catalog_one_candidate_per_variant", + "columns": [ + { + "expression": "variant", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_image_catalog\".\"is_latest\" = false AND \"kiloclaw_image_catalog\".\"rollout_percent\" > 0 AND \"kiloclaw_image_catalog\".\"status\" = 'available'", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kiloclaw_image_catalog_image_tag_unique": { + "name": "kiloclaw_image_catalog_image_tag_unique", + "columns": [ + "image_tag" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_inbound_email_aliases": { + "name": "kiloclaw_inbound_email_aliases", + "schema": "", + "columns": { + "alias": { + "name": "alias", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "retired_at": { + "name": "retired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_kiloclaw_inbound_email_aliases_instance_id": { + "name": "IDX_kiloclaw_inbound_email_aliases_instance_id", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kiloclaw_inbound_email_aliases_active_instance": { + "name": "UQ_kiloclaw_inbound_email_aliases_active_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_inbound_email_aliases\".\"retired_at\" is null", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_inbound_email_aliases_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_inbound_email_aliases_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_inbound_email_aliases", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_inbound_email_reserved_aliases": { + "name": "kiloclaw_inbound_email_reserved_aliases", + "schema": "", + "columns": { + "alias": { + "name": "alias", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "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.kiloclaw_instances": { + "name": "kiloclaw_instances", + "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 + }, + "sandbox_id": { + "name": "sandbox_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'fly'" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "inbound_email_enabled": { + "name": "inbound_email_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "inactive_trial_stopped_at": { + "name": "inactive_trial_stopped_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()" + }, + "destroyed_at": { + "name": "destroyed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "tracked_image_tag": { + "name": "tracked_image_tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "instance_type": { + "name": "instance_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admin_size_override": { + "name": "admin_size_override", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_kiloclaw_instances_active": { + "name": "UQ_kiloclaw_instances_active", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sandbox_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"destroyed_at\" is null", + "concurrently": false + }, + "IDX_kiloclaw_instances_active_personal_by_user": { + "name": "IDX_kiloclaw_instances_active_personal_by_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"organization_id\" IS NULL AND \"kiloclaw_instances\".\"destroyed_at\" IS NULL", + "concurrently": false + }, + "IDX_kiloclaw_instances_active_org_by_user_org": { + "name": "IDX_kiloclaw_instances_active_org_by_user_org", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"organization_id\" IS NOT NULL AND \"kiloclaw_instances\".\"destroyed_at\" IS NULL", + "concurrently": false + }, + "IDX_kiloclaw_instances_active_org_by_org_created": { + "name": "IDX_kiloclaw_instances_active_org_by_org_created", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"organization_id\" IS NOT NULL AND \"kiloclaw_instances\".\"destroyed_at\" IS NULL", + "concurrently": false + }, + "IDX_kiloclaw_instances_user_id_created_at": { + "name": "IDX_kiloclaw_instances_user_id_created_at", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_instances_tracked_image_tag": { + "name": "IDX_kiloclaw_instances_tracked_image_tag", + "columns": [ + { + "expression": "tracked_image_tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"destroyed_at\" is null", + "concurrently": false + }, + "IDX_kiloclaw_instances_instance_type": { + "name": "IDX_kiloclaw_instances_instance_type", + "columns": [ + { + "expression": "instance_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"destroyed_at\" is null", + "concurrently": false + }, + "IDX_kiloclaw_instances_admin_size_override": { + "name": "IDX_kiloclaw_instances_admin_size_override", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_instances\".\"admin_size_override\" IS NOT NULL AND \"kiloclaw_instances\".\"destroyed_at\" IS NULL", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_instances_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_instances_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_instances", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_instances_organization_id_organizations_id_fk": { + "name": "kiloclaw_instances_organization_id_organizations_id_fk", + "tableFrom": "kiloclaw_instances", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "CHK_kiloclaw_instances_instance_type": { + "name": "CHK_kiloclaw_instances_instance_type", + "value": "\"kiloclaw_instances\".\"instance_type\" IS NULL OR \"kiloclaw_instances\".\"instance_type\" IN ('perf-1-3', 'perf-4-8', 'perf-4-16', 'shared-2-3', 'shared-2-4', 'custom')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_morning_briefing_configs": { + "name": "kiloclaw_morning_briefing_configs", + "schema": "", + "columns": { + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "cron": { + "name": "cron", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'0 7 * * *'" + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "interest_topics": { + "name": "interest_topics", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "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": { + "IDX_kiloclaw_morning_briefing_configs_enabled": { + "name": "IDX_kiloclaw_morning_briefing_configs_enabled", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_morning_briefing_configs\".\"enabled\" = true", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_morning_briefing_configs_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_morning_briefing_configs_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_morning_briefing_configs", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_scheduled_action_notifications": { + "name": "kiloclaw_scheduled_action_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "target_id": { + "name": "target_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'notice'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_kiloclaw_scheduled_action_notifications_target_kind_channel": { + "name": "UQ_kiloclaw_scheduled_action_notifications_target_kind_channel", + "columns": [ + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_action_notifications_pending": { + "name": "IDX_kiloclaw_scheduled_action_notifications_pending", + "columns": [ + { + "expression": "target_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_scheduled_action_notifications\".\"status\" = 'pending'", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_scheduled_action_notifications_target_id_kiloclaw_scheduled_action_targets_id_fk": { + "name": "kiloclaw_scheduled_action_notifications_target_id_kiloclaw_scheduled_action_targets_id_fk", + "tableFrom": "kiloclaw_scheduled_action_notifications", + "columnsFrom": [ + "target_id" + ], + "tableTo": "kiloclaw_scheduled_action_targets", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_scheduled_action_stages": { + "name": "kiloclaw_scheduled_action_stages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "scheduled_action_id": { + "name": "scheduled_action_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "stage_index": { + "name": "stage_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scheduled_at": { + "name": "scheduled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "notice_sent_at": { + "name": "notice_sent_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 + }, + "applied_count": { + "name": "applied_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped_count": { + "name": "skipped_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "UQ_kiloclaw_scheduled_action_stages_parent_index": { + "name": "UQ_kiloclaw_scheduled_action_stages_parent_index", + "columns": [ + { + "expression": "scheduled_action_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stage_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_action_stages_notice_due": { + "name": "IDX_kiloclaw_scheduled_action_stages_notice_due", + "columns": [ + { + "expression": "scheduled_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_scheduled_action_stages\".\"notice_sent_at\" IS NULL AND \"kiloclaw_scheduled_action_stages\".\"status\" = 'pending'", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_scheduled_action_stages_scheduled_action_id_kiloclaw_scheduled_actions_id_fk": { + "name": "kiloclaw_scheduled_action_stages_scheduled_action_id_kiloclaw_scheduled_actions_id_fk", + "tableFrom": "kiloclaw_scheduled_action_stages", + "columnsFrom": [ + "scheduled_action_id" + ], + "tableTo": "kiloclaw_scheduled_actions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_scheduled_action_targets": { + "name": "kiloclaw_scheduled_action_targets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "scheduled_action_id": { + "name": "scheduled_action_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "stage_id": { + "name": "stage_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "source_image_tag": { + "name": "source_image_tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_image_tag": { + "name": "target_image_tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "applied_at": { + "name": "applied_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "skip_reason": { + "name": "skip_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_kiloclaw_scheduled_action_targets_parent_instance": { + "name": "UQ_kiloclaw_scheduled_action_targets_parent_instance", + "columns": [ + { + "expression": "scheduled_action_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_action_targets_stage": { + "name": "IDX_kiloclaw_scheduled_action_targets_stage", + "columns": [ + { + "expression": "stage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_action_targets_pending_by_instance": { + "name": "IDX_kiloclaw_scheduled_action_targets_pending_by_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_scheduled_action_targets\".\"status\" = 'pending'", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_scheduled_action_targets_scheduled_action_id_kiloclaw_scheduled_actions_id_fk": { + "name": "kiloclaw_scheduled_action_targets_scheduled_action_id_kiloclaw_scheduled_actions_id_fk", + "tableFrom": "kiloclaw_scheduled_action_targets", + "columnsFrom": [ + "scheduled_action_id" + ], + "tableTo": "kiloclaw_scheduled_actions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "kiloclaw_scheduled_action_targets_stage_id_kiloclaw_scheduled_action_stages_id_fk": { + "name": "kiloclaw_scheduled_action_targets_stage_id_kiloclaw_scheduled_action_stages_id_fk", + "tableFrom": "kiloclaw_scheduled_action_targets", + "columnsFrom": [ + "stage_id" + ], + "tableTo": "kiloclaw_scheduled_action_stages", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "kiloclaw_scheduled_action_targets_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_scheduled_action_targets_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_scheduled_action_targets", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "kiloclaw_scheduled_action_targets_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_scheduled_action_targets_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_scheduled_action_targets", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_scheduled_actions": { + "name": "kiloclaw_scheduled_actions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "action_type": { + "name": "action_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_image_tag": { + "name": "target_image_tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "override_pins": { + "name": "override_pins", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "notice_lead_hours": { + "name": "notice_lead_hours", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 24 + }, + "notice_subject": { + "name": "notice_subject", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "notice_body": { + "name": "notice_body", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_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": 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 + }, + "total_count": { + "name": "total_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "applied_count": { + "name": "applied_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "skipped_count": { + "name": "skipped_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "failed_count": { + "name": "failed_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "IDX_kiloclaw_scheduled_actions_status": { + "name": "IDX_kiloclaw_scheduled_actions_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_actions_action_type": { + "name": "IDX_kiloclaw_scheduled_actions_action_type", + "columns": [ + { + "expression": "action_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_scheduled_actions_created_by": { + "name": "IDX_kiloclaw_scheduled_actions_created_by", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_scheduled_actions_target_image_tag_kiloclaw_image_catalog_image_tag_fk": { + "name": "kiloclaw_scheduled_actions_target_image_tag_kiloclaw_image_catalog_image_tag_fk", + "tableFrom": "kiloclaw_scheduled_actions", + "columnsFrom": [ + "target_image_tag" + ], + "tableTo": "kiloclaw_image_catalog", + "columnsTo": [ + "image_tag" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "kiloclaw_scheduled_actions_created_by_kilocode_users_id_fk": { + "name": "kiloclaw_scheduled_actions_created_by_kilocode_users_id_fk", + "tableFrom": "kiloclaw_scheduled_actions", + "columnsFrom": [ + "created_by" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kiloclaw_subscription_change_log": { + "name": "kiloclaw_subscription_change_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "subscription_id": { + "name": "subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "before_state": { + "name": "before_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "after_state": { + "name": "after_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_kiloclaw_subscription_change_log_subscription_created_at": { + "name": "IDX_kiloclaw_subscription_change_log_subscription_created_at", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscription_change_log_created_at": { + "name": "IDX_kiloclaw_subscription_change_log_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_subscription_change_log_subscription_id_kiloclaw_subscriptions_id_fk": { + "name": "kiloclaw_subscription_change_log_subscription_id_kiloclaw_subscriptions_id_fk", + "tableFrom": "kiloclaw_subscription_change_log", + "columnsFrom": [ + "subscription_id" + ], + "tableTo": "kiloclaw_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kiloclaw_subscription_change_log_actor_type_check": { + "name": "kiloclaw_subscription_change_log_actor_type_check", + "value": "\"kiloclaw_subscription_change_log\".\"actor_type\" IN ('user', 'system')" + }, + "kiloclaw_subscription_change_log_action_check": { + "name": "kiloclaw_subscription_change_log_action_check", + "value": "\"kiloclaw_subscription_change_log\".\"action\" IN ('created', 'status_changed', 'plan_switched', 'period_advanced', 'canceled', 'reactivated', 'suspended', 'destruction_scheduled', 'reassigned', 'backfilled', 'payment_source_changed', 'schedule_changed', 'admin_override')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_subscriptions": { + "name": "kiloclaw_subscriptions", + "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 + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_schedule_id": { + "name": "stripe_schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "transferred_to_subscription_id": { + "name": "transferred_to_subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "access_origin": { + "name": "access_origin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payment_source": { + "name": "payment_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kiloclaw_price_version": { + "name": "kiloclaw_price_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scheduled_plan": { + "name": "scheduled_plan", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scheduled_by": { + "name": "scheduled_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "pending_conversion": { + "name": "pending_conversion", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "trial_started_at": { + "name": "trial_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "trial_ends_at": { + "name": "trial_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "current_period_start": { + "name": "current_period_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "current_period_end": { + "name": "current_period_end", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "credit_renewal_at": { + "name": "credit_renewal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "commit_ends_at": { + "name": "commit_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "past_due_since": { + "name": "past_due_since", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "destruction_deadline": { + "name": "destruction_deadline", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auto_resume_requested_at": { + "name": "auto_resume_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auto_resume_retry_after": { + "name": "auto_resume_retry_after", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auto_resume_attempt_count": { + "name": "auto_resume_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_top_up_triggered_for_period": { + "name": "auto_top_up_triggered_for_period", + "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": { + "IDX_kiloclaw_subscriptions_status": { + "name": "IDX_kiloclaw_subscriptions_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_user_id": { + "name": "IDX_kiloclaw_subscriptions_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_user_status": { + "name": "IDX_kiloclaw_subscriptions_user_status", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_price_version": { + "name": "IDX_kiloclaw_subscriptions_price_version", + "columns": [ + { + "expression": "kiloclaw_price_version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_transferred_to": { + "name": "IDX_kiloclaw_subscriptions_transferred_to", + "columns": [ + { + "expression": "transferred_to_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_stripe_schedule_id": { + "name": "IDX_kiloclaw_subscriptions_stripe_schedule_id", + "columns": [ + { + "expression": "stripe_schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_auto_resume_retry_after": { + "name": "IDX_kiloclaw_subscriptions_auto_resume_retry_after", + "columns": [ + { + "expression": "auto_resume_retry_after", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kiloclaw_subscriptions_instance": { + "name": "UQ_kiloclaw_subscriptions_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_subscriptions\".\"instance_id\" is not null", + "concurrently": false + }, + "UQ_kiloclaw_subscriptions_transferred_to": { + "name": "UQ_kiloclaw_subscriptions_transferred_to", + "columns": [ + { + "expression": "transferred_to_subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_subscriptions\".\"transferred_to_subscription_id\" is not null", + "concurrently": false + }, + "IDX_kiloclaw_subscriptions_earlybird_origin": { + "name": "IDX_kiloclaw_subscriptions_earlybird_origin", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "access_origin", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_subscriptions\".\"access_origin\" = 'earlybird'", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_subscriptions_user_id_kilocode_users_id_fk": { + "name": "kiloclaw_subscriptions_user_id_kilocode_users_id_fk", + "tableFrom": "kiloclaw_subscriptions", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_subscriptions_transferred_to_subscription_id_kiloclaw_subscriptions_id_fk": { + "name": "kiloclaw_subscriptions_transferred_to_subscription_id_kiloclaw_subscriptions_id_fk", + "tableFrom": "kiloclaw_subscriptions", + "columnsFrom": [ + "transferred_to_subscription_id" + ], + "tableTo": "kiloclaw_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_subscriptions_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_subscriptions_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_subscriptions", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kiloclaw_subscriptions_stripe_subscription_id_unique": { + "name": "kiloclaw_subscriptions_stripe_subscription_id_unique", + "columns": [ + "stripe_subscription_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "kiloclaw_subscriptions_price_version_check": { + "name": "kiloclaw_subscriptions_price_version_check", + "value": "\"kiloclaw_subscriptions\".\"kiloclaw_price_version\" IN ('2026-03-19', '2026-05-10')" + }, + "kiloclaw_subscriptions_plan_check": { + "name": "kiloclaw_subscriptions_plan_check", + "value": "\"kiloclaw_subscriptions\".\"plan\" IN ('trial', 'commit', 'standard')" + }, + "kiloclaw_subscriptions_scheduled_plan_check": { + "name": "kiloclaw_subscriptions_scheduled_plan_check", + "value": "\"kiloclaw_subscriptions\".\"scheduled_plan\" IN ('commit', 'standard')" + }, + "kiloclaw_subscriptions_scheduled_by_check": { + "name": "kiloclaw_subscriptions_scheduled_by_check", + "value": "\"kiloclaw_subscriptions\".\"scheduled_by\" IN ('auto', 'user')" + }, + "kiloclaw_subscriptions_status_check": { + "name": "kiloclaw_subscriptions_status_check", + "value": "\"kiloclaw_subscriptions\".\"status\" IN ('trialing', 'active', 'past_due', 'canceled', 'unpaid')" + }, + "kiloclaw_subscriptions_access_origin_check": { + "name": "kiloclaw_subscriptions_access_origin_check", + "value": "\"kiloclaw_subscriptions\".\"access_origin\" IN ('earlybird')" + }, + "kiloclaw_subscriptions_payment_source_check": { + "name": "kiloclaw_subscriptions_payment_source_check", + "value": "\"kiloclaw_subscriptions\".\"payment_source\" IN ('stripe', 'credits')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_terminal_renewal_failures": { + "name": "kiloclaw_terminal_renewal_failures", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "subscription_id": { + "name": "subscription_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "renewal_boundary": { + "name": "renewal_boundary", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'unresolved'" + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "first_failure_at": { + "name": "first_failure_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_failure_at": { + "name": "last_failure_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_failure_code": { + "name": "last_failure_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_failure_message": { + "name": "last_failure_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolution_actor_type": { + "name": "resolution_actor_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolution_actor_id": { + "name": "resolution_actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resolution_at": { + "name": "resolution_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "resolution_reason": { + "name": "resolution_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": { + "UQ_kiloclaw_terminal_renewal_failures_subscription_boundary": { + "name": "UQ_kiloclaw_terminal_renewal_failures_subscription_boundary", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "renewal_boundary", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kiloclaw_terminal_renewal_failures_unresolved": { + "name": "IDX_kiloclaw_terminal_renewal_failures_unresolved", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "renewal_boundary", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"kiloclaw_terminal_renewal_failures\".\"status\" = 'unresolved'", + "concurrently": false + }, + "IDX_kiloclaw_terminal_renewal_failures_status_last_failure_at": { + "name": "IDX_kiloclaw_terminal_renewal_failures_status_last_failure_at", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_failure_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "kiloclaw_terminal_renewal_failures_subscription_id_kiloclaw_subscriptions_id_fk": { + "name": "kiloclaw_terminal_renewal_failures_subscription_id_kiloclaw_subscriptions_id_fk", + "tableFrom": "kiloclaw_terminal_renewal_failures", + "columnsFrom": [ + "subscription_id" + ], + "tableTo": "kiloclaw_subscriptions", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "kiloclaw_terminal_renewal_failures_status_check": { + "name": "kiloclaw_terminal_renewal_failures_status_check", + "value": "\"kiloclaw_terminal_renewal_failures\".\"status\" IN ('unresolved', 'resolved', 'waived', 'superseded')" + }, + "kiloclaw_terminal_renewal_failures_last_failure_code_check": { + "name": "kiloclaw_terminal_renewal_failures_last_failure_code_check", + "value": "\"kiloclaw_terminal_renewal_failures\".\"last_failure_code\" IN ('credit_balance_read_failed', 'renewal_transaction_failed', 'auto_top_up_marker_write_failed', 'worker_timeout', 'poison_payload', 'queue_delivery_exhausted')" + }, + "kiloclaw_terminal_renewal_failures_resolution_actor_type_check": { + "name": "kiloclaw_terminal_renewal_failures_resolution_actor_type_check", + "value": "\"kiloclaw_terminal_renewal_failures\".\"resolution_actor_type\" IN ('operator', 'system')" + } + }, + "isRLSEnabled": false + }, + "public.kiloclaw_version_pins": { + "name": "kiloclaw_version_pins", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "image_tag": { + "name": "image_tag", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pinned_by": { + "name": "pinned_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "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": {}, + "foreignKeys": { + "kiloclaw_version_pins_instance_id_kiloclaw_instances_id_fk": { + "name": "kiloclaw_version_pins_instance_id_kiloclaw_instances_id_fk", + "tableFrom": "kiloclaw_version_pins", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "kiloclaw_instances", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "kiloclaw_version_pins_image_tag_kiloclaw_image_catalog_image_tag_fk": { + "name": "kiloclaw_version_pins_image_tag_kiloclaw_image_catalog_image_tag_fk", + "tableFrom": "kiloclaw_version_pins", + "columnsFrom": [ + "image_tag" + ], + "tableTo": "kiloclaw_image_catalog", + "columnsTo": [ + "image_tag" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "kiloclaw_version_pins_pinned_by_kilocode_users_id_fk": { + "name": "kiloclaw_version_pins_pinned_by_kilocode_users_id_fk", + "tableFrom": "kiloclaw_version_pins", + "columnsFrom": [ + "pinned_by" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kiloclaw_version_pins_instance_id_unique": { + "name": "kiloclaw_version_pins_instance_id_unique", + "columns": [ + "instance_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.kilocode_users": { + "name": "kilocode_users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "google_user_email": { + "name": "google_user_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "google_user_name": { + "name": "google_user_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "google_user_image_url": { + "name": "google_user_image_url", + "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()" + }, + "hosted_domain": { + "name": "hosted_domain", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "microdollars_used": { + "name": "microdollars_used", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "kilo_pass_threshold": { + "name": "kilo_pass_threshold", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "app_store_account_token": { + "name": "app_store_account_token", + "type": "uuid", + "primaryKey": false, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "is_admin": { + "name": "is_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_super_admin": { + "name": "is_super_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "can_view_sessions": { + "name": "can_view_sessions", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "can_manage_credits": { + "name": "can_manage_credits", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "total_microdollars_acquired": { + "name": "total_microdollars_acquired", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "next_credit_expiration_at": { + "name": "next_credit_expiration_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "has_validation_stytch": { + "name": "has_validation_stytch", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "has_validation_novel_card_with_hold": { + "name": "has_validation_novel_card_with_hold", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "blocked_reason": { + "name": "blocked_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blocked_at": { + "name": "blocked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "blocked_by_kilo_user_id": { + "name": "blocked_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "api_token_pepper": { + "name": "api_token_pepper", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "web_session_pepper": { + "name": "web_session_pepper", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auto_top_up_enabled": { + "name": "auto_top_up_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_bot": { + "name": "is_bot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "kiloclaw_early_access": { + "name": "kiloclaw_early_access", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "default_model": { + "name": "default_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cohorts": { + "name": "cohorts", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "completed_welcome_form": { + "name": "completed_welcome_form", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "linkedin_url": { + "name": "linkedin_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_url": { + "name": "github_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "discord_server_membership_verified_at": { + "name": "discord_server_membership_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "openrouter_upstream_safety_identifier": { + "name": "openrouter_upstream_safety_identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "openrouter_downstream_safety_identifier": { + "name": "openrouter_downstream_safety_identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "vercel_downstream_safety_identifier": { + "name": "vercel_downstream_safety_identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "customer_source": { + "name": "customer_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "signup_ip": { + "name": "signup_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_deletion_requested_at": { + "name": "account_deletion_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "normalized_email": { + "name": "normalized_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email_domain": { + "name": "email_domain", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "personal_account_disabled": { + "name": "personal_account_disabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "IDX_kilocode_users_signup_ip_created_at": { + "name": "IDX_kilocode_users_signup_ip_created_at", + "columns": [ + { + "expression": "signup_ip", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilocode_users_blocked_at": { + "name": "IDX_kilocode_users_blocked_at", + "columns": [ + { + "expression": "blocked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilocode_users_blocked_by_kilo_user_id": { + "name": "IDX_kilocode_users_blocked_by_kilo_user_id", + "columns": [ + { + "expression": "blocked_by_kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_kilocode_users_openrouter_upstream_safety_identifier": { + "name": "UQ_kilocode_users_openrouter_upstream_safety_identifier", + "columns": [ + { + "expression": "openrouter_upstream_safety_identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilocode_users\".\"openrouter_upstream_safety_identifier\" IS NOT NULL", + "concurrently": false + }, + "UQ_kilocode_users_openrouter_downstream_safety_identifier": { + "name": "UQ_kilocode_users_openrouter_downstream_safety_identifier", + "columns": [ + { + "expression": "openrouter_downstream_safety_identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilocode_users\".\"openrouter_downstream_safety_identifier\" IS NOT NULL", + "concurrently": true + }, + "UQ_kilocode_users_vercel_downstream_safety_identifier": { + "name": "UQ_kilocode_users_vercel_downstream_safety_identifier", + "columns": [ + { + "expression": "vercel_downstream_safety_identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"kilocode_users\".\"vercel_downstream_safety_identifier\" IS NOT NULL", + "concurrently": false + }, + "IDX_kilocode_users_normalized_email": { + "name": "IDX_kilocode_users_normalized_email", + "columns": [ + { + "expression": "normalized_email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_kilocode_users_email_domain": { + "name": "IDX_kilocode_users_email_domain", + "columns": [ + { + "expression": "email_domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "kilocode_users_app_store_account_token_unique": { + "name": "kilocode_users_app_store_account_token_unique", + "columns": [ + "app_store_account_token" + ], + "nullsNotDistinct": false + }, + "UQ_b1afacbcf43f2c7c4cb9f7e7faa": { + "name": "UQ_b1afacbcf43f2c7c4cb9f7e7faa", + "columns": [ + "google_user_email" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "blocked_reason_not_empty": { + "name": "blocked_reason_not_empty", + "value": "length(blocked_reason) > 0" + }, + "kilocode_users_is_super_admin_requires_admin_check": { + "name": "kilocode_users_is_super_admin_requires_admin_check", + "value": "NOT \"kilocode_users\".\"is_super_admin\" OR \"kilocode_users\".\"is_admin\"" + }, + "kilocode_users_can_view_sessions_requires_admin_check": { + "name": "kilocode_users_can_view_sessions_requires_admin_check", + "value": "NOT \"kilocode_users\".\"can_view_sessions\" OR \"kilocode_users\".\"is_admin\"" + }, + "kilocode_users_can_manage_credits_requires_admin_check": { + "name": "kilocode_users_can_manage_credits_requires_admin_check", + "value": "NOT \"kilocode_users\".\"can_manage_credits\" OR \"kilocode_users\".\"is_admin\"" + } + }, + "isRLSEnabled": false + }, + "public.magic_link_tokens": { + "name": "magic_link_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "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()" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reserved_until": { + "name": "reserved_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'magic_link'" + }, + "challenge_id": { + "name": "challenge_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_magic_link_tokens_email": { + "name": "idx_magic_link_tokens_email", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_magic_link_tokens_expires_at": { + "name": "idx_magic_link_tokens_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_magic_link_tokens_challenge_id": { + "name": "UQ_magic_link_tokens_challenge_id", + "columns": [ + { + "expression": "challenge_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"magic_link_tokens\".\"challenge_id\" IS NOT NULL", + "concurrently": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "check_expires_at_future": { + "name": "check_expires_at_future", + "value": "\"magic_link_tokens\".\"expires_at\" > \"magic_link_tokens\".\"created_at\"" + }, + "check_magic_link_tokens_purpose": { + "name": "check_magic_link_tokens_purpose", + "value": "\"magic_link_tokens\".\"purpose\" IN ('magic_link', 'sign_in_code', 'data_export_download')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_assignments": { + "name": "mcp_gateway_assignments", + "schema": "", + "columns": { + "assignment_id": { + "name": "assignment_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by_kilo_user_id": { + "name": "assigned_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "single_user_slot": { + "name": "single_user_slot", + "type": "text", + "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": { + "UQ_mcp_gateway_assignments_active": { + "name": "UQ_mcp_gateway_assignments_active", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_assignments\".\"revoked_at\" is null", + "concurrently": false + }, + "UQ_mcp_gateway_assignments_single_user_slot": { + "name": "UQ_mcp_gateway_assignments_single_user_slot", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "single_user_slot", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_assignments\".\"revoked_at\" is null and \"mcp_gateway_assignments\".\"single_user_slot\" is not null", + "concurrently": false + }, + "IDX_mcp_gateway_assignments_config": { + "name": "IDX_mcp_gateway_assignments_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_assignments_user": { + "name": "IDX_mcp_gateway_assignments_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_assignments_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_assignments_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_assignments", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_assignments_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_assignments_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_assignments", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_assignments_assigned_by_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_assignments_assigned_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_assignments", + "columnsFrom": [ + "assigned_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mcp_gateway_audit_events": { + "name": "mcp_gateway_audit_events", + "schema": "", + "columns": { + "audit_event_id": { + "name": "audit_event_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "actor_kilo_user_id": { + "name": "actor_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "connect_resource_id": { + "name": "connect_resource_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "correlation_metadata": { + "name": "correlation_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": { + "IDX_mcp_gateway_audit_events_config": { + "name": "IDX_mcp_gateway_audit_events_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_audit_events_grant": { + "name": "IDX_mcp_gateway_audit_events_grant", + "columns": [ + { + "expression": "oauth_grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_audit_events\".\"oauth_grant_id\" is not null", + "concurrently": false + }, + "IDX_mcp_gateway_audit_events_owner": { + "name": "IDX_mcp_gateway_audit_events_owner", + "columns": [ + { + "expression": "owner_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_audit_events_created_at": { + "name": "IDX_mcp_gateway_audit_events_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_audit_events_actor_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_audit_events_actor_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_audit_events", + "columnsFrom": [ + "actor_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "mcp_gateway_audit_events_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_audit_events_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_audit_events", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "mcp_gateway_audit_events_connect_resource_id_mcp_gateway_connect_resources_connect_resource_id_fk": { + "name": "mcp_gateway_audit_events_connect_resource_id_mcp_gateway_connect_resources_connect_resource_id_fk", + "tableFrom": "mcp_gateway_audit_events", + "columnsFrom": [ + "connect_resource_id" + ], + "tableTo": "mcp_gateway_connect_resources", + "columnsTo": [ + "connect_resource_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "mcp_gateway_audit_events_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_audit_events_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_audit_events", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "mcp_gateway_audit_events_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk": { + "name": "mcp_gateway_audit_events_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk", + "tableFrom": "mcp_gateway_audit_events", + "columnsFrom": [ + "oauth_grant_id" + ], + "tableTo": "mcp_gateway_oauth_grants", + "columnsTo": [ + "oauth_grant_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_audit_events_owner_scope": { + "name": "mcp_gateway_audit_events_owner_scope", + "value": "\"mcp_gateway_audit_events\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_audit_events_outcome": { + "name": "mcp_gateway_audit_events_outcome", + "value": "\"mcp_gateway_audit_events\".\"outcome\" IN ('success', 'failure', 'blocked')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_authorization_codes": { + "name": "mcp_gateway_authorization_codes", + "schema": "", + "columns": { + "authorization_code_id": { + "name": "authorization_code_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorization_request_id": { + "name": "authorization_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "route_key": { + "name": "route_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_resource_url": { + "name": "canonical_resource_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_challenge_method": { + "name": "code_challenge_method", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'S256'" + }, + "execution_context": { + "name": "execution_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "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": { + "UQ_mcp_gateway_authorization_codes_code_hash": { + "name": "UQ_mcp_gateway_authorization_codes_code_hash", + "columns": [ + { + "expression": "code_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_codes_expires_at": { + "name": "IDX_mcp_gateway_authorization_codes_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_codes_client": { + "name": "IDX_mcp_gateway_authorization_codes_client", + "columns": [ + { + "expression": "oauth_client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_codes_grant": { + "name": "IDX_mcp_gateway_authorization_codes_grant", + "columns": [ + { + "expression": "oauth_grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_authorization_codes\".\"oauth_grant_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_authorization_codes_authorization_request_id_mcp_gateway_authorization_requests_authorization_request_id_fk": { + "name": "mcp_gateway_authorization_codes_authorization_request_id_mcp_gateway_authorization_requests_authorization_request_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "authorization_request_id" + ], + "tableTo": "mcp_gateway_authorization_requests", + "columnsTo": [ + "authorization_request_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_codes_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk": { + "name": "mcp_gateway_authorization_codes_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "oauth_client_id" + ], + "tableTo": "mcp_gateway_oauth_clients", + "columnsTo": [ + "oauth_client_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_codes_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk": { + "name": "mcp_gateway_authorization_codes_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "oauth_grant_id" + ], + "tableTo": "mcp_gateway_oauth_grants", + "columnsTo": [ + "oauth_grant_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_codes_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_authorization_codes_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_codes_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_authorization_codes_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_codes_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_authorization_codes_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_authorization_codes", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_authorization_codes_owner_scope": { + "name": "mcp_gateway_authorization_codes_owner_scope", + "value": "\"mcp_gateway_authorization_codes\".\"owner_scope\" IN ('personal', 'organization')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_authorization_requests": { + "name": "mcp_gateway_authorization_requests", + "schema": "", + "columns": { + "authorization_request_id": { + "name": "authorization_request_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "request_state_hash": { + "name": "request_state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "route_key": { + "name": "route_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_resource_url": { + "name": "canonical_resource_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "requested_scopes": { + "name": "requested_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "oauth_state": { + "name": "oauth_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "code_challenge_method": { + "name": "code_challenge_method", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'S256'" + }, + "execution_context": { + "name": "execution_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "request_status": { + "name": "request_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()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_mcp_gateway_authorization_requests_state_hash": { + "name": "UQ_mcp_gateway_authorization_requests_state_hash", + "columns": [ + { + "expression": "request_state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_requests_config": { + "name": "IDX_mcp_gateway_authorization_requests_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_requests_grant": { + "name": "IDX_mcp_gateway_authorization_requests_grant", + "columns": [ + { + "expression": "oauth_grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_authorization_requests\".\"oauth_grant_id\" is not null", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_requests_user": { + "name": "IDX_mcp_gateway_authorization_requests_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_authorization_requests_expires_at": { + "name": "IDX_mcp_gateway_authorization_requests_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_authorization_requests_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk": { + "name": "mcp_gateway_authorization_requests_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk", + "tableFrom": "mcp_gateway_authorization_requests", + "columnsFrom": [ + "oauth_client_id" + ], + "tableTo": "mcp_gateway_oauth_clients", + "columnsTo": [ + "oauth_client_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_requests_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk": { + "name": "mcp_gateway_authorization_requests_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk", + "tableFrom": "mcp_gateway_authorization_requests", + "columnsFrom": [ + "oauth_grant_id" + ], + "tableTo": "mcp_gateway_oauth_grants", + "columnsTo": [ + "oauth_grant_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_requests_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_authorization_requests_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_authorization_requests", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_requests_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_authorization_requests_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_authorization_requests", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_authorization_requests_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_authorization_requests_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_authorization_requests", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_authorization_requests_owner_scope": { + "name": "mcp_gateway_authorization_requests_owner_scope", + "value": "\"mcp_gateway_authorization_requests\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_authorization_requests_status": { + "name": "mcp_gateway_authorization_requests_status", + "value": "\"mcp_gateway_authorization_requests\".\"request_status\" IN ('pending', 'completed', 'error')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_config_secrets": { + "name": "mcp_gateway_config_secrets", + "schema": "", + "columns": { + "config_secret_id": { + "name": "config_secret_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "secret_kind": { + "name": "secret_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_secret": { + "name": "encrypted_secret", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_version": { + "name": "secret_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "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": { + "UQ_mcp_gateway_config_secrets_active_kind": { + "name": "UQ_mcp_gateway_config_secrets_active_kind", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "secret_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_config_secrets\".\"revoked_at\" is null", + "concurrently": false + }, + "IDX_mcp_gateway_config_secrets_config": { + "name": "IDX_mcp_gateway_config_secrets_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_config_secrets_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_config_secrets_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_config_secrets", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_config_secrets_version_positive": { + "name": "mcp_gateway_config_secrets_version_positive", + "value": "\"mcp_gateway_config_secrets\".\"secret_version\" > 0" + }, + "mcp_gateway_config_secrets_kind": { + "name": "mcp_gateway_config_secrets_kind", + "value": "\"mcp_gateway_config_secrets\".\"secret_kind\" IN ('static_provider_credentials', 'dynamic_registration', 'static_headers')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_configs": { + "name": "mcp_gateway_configs", + "schema": "", + "columns": { + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "remote_url": { + "name": "remote_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "auth_mode": { + "name": "auth_mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sharing_mode": { + "name": "sharing_mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_scopes": { + "name": "provider_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_scope_source": { + "name": "provider_scope_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "provider_resource": { + "name": "provider_resource", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "path_passthrough": { + "name": "path_passthrough", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "config_version": { + "name": "config_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "discovered_provider_metadata": { + "name": "discovered_provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "registry_metadata": { + "name": "registry_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "auxiliary_headers": { + "name": "auxiliary_headers", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_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": { + "IDX_mcp_gateway_configs_owner": { + "name": "IDX_mcp_gateway_configs_owner", + "columns": [ + { + "expression": "owner_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_configs_enabled": { + "name": "IDX_mcp_gateway_configs_enabled", + "columns": [ + { + "expression": "enabled", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_configs_remote_url": { + "name": "IDX_mcp_gateway_configs_remote_url", + "columns": [ + { + "expression": "remote_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_configs_created_by_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_configs_created_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_configs", + "columnsFrom": [ + "created_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_configs_name_not_empty": { + "name": "mcp_gateway_configs_name_not_empty", + "value": "length(trim(\"mcp_gateway_configs\".\"name\")) > 0" + }, + "mcp_gateway_configs_config_version_positive": { + "name": "mcp_gateway_configs_config_version_positive", + "value": "\"mcp_gateway_configs\".\"config_version\" > 0" + }, + "mcp_gateway_configs_personal_single_user": { + "name": "mcp_gateway_configs_personal_single_user", + "value": "\"mcp_gateway_configs\".\"owner_scope\" <> 'personal' OR \"mcp_gateway_configs\".\"sharing_mode\" = 'single_user'" + }, + "mcp_gateway_configs_owner_scope": { + "name": "mcp_gateway_configs_owner_scope", + "value": "\"mcp_gateway_configs\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_configs_auth_mode": { + "name": "mcp_gateway_configs_auth_mode", + "value": "\"mcp_gateway_configs\".\"auth_mode\" IN ('none', 'static_headers', 'oauth_dynamic', 'oauth_static')" + }, + "mcp_gateway_configs_sharing_mode": { + "name": "mcp_gateway_configs_sharing_mode", + "value": "\"mcp_gateway_configs\".\"sharing_mode\" IN ('single_user', 'multi_user')" + }, + "mcp_gateway_configs_provider_scope_source": { + "name": "mcp_gateway_configs_provider_scope_source", + "value": "\"mcp_gateway_configs\".\"provider_scope_source\" IN ('none', 'discovered', 'override')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_connect_resources": { + "name": "mcp_gateway_connect_resources", + "schema": "", + "columns": { + "connect_resource_id": { + "name": "connect_resource_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "route_key": { + "name": "route_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_url": { + "name": "canonical_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "route_status": { + "name": "route_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "route_version": { + "name": "route_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "rotated_at": { + "name": "rotated_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": { + "UQ_mcp_gateway_connect_resources_route_key": { + "name": "UQ_mcp_gateway_connect_resources_route_key", + "columns": [ + { + "expression": "route_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_mcp_gateway_connect_resources_active_config": { + "name": "UQ_mcp_gateway_connect_resources_active_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_connect_resources\".\"route_status\" = 'active'", + "concurrently": false + }, + "IDX_mcp_gateway_connect_resources_config": { + "name": "IDX_mcp_gateway_connect_resources_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_connect_resources_canonical_url": { + "name": "IDX_mcp_gateway_connect_resources_canonical_url", + "columns": [ + { + "expression": "canonical_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_connect_resources_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_connect_resources_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_connect_resources", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_connect_resources_route_key_format": { + "name": "mcp_gateway_connect_resources_route_key_format", + "value": "\"mcp_gateway_connect_resources\".\"route_key\" ~ '^[A-Za-z0-9_-]{32,}$'" + }, + "mcp_gateway_connect_resources_route_version_positive": { + "name": "mcp_gateway_connect_resources_route_version_positive", + "value": "\"mcp_gateway_connect_resources\".\"route_version\" > 0" + }, + "mcp_gateway_connect_resources_owner_scope": { + "name": "mcp_gateway_connect_resources_owner_scope", + "value": "\"mcp_gateway_connect_resources\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_connect_resources_route_status": { + "name": "mcp_gateway_connect_resources_route_status", + "value": "\"mcp_gateway_connect_resources\".\"route_status\" IN ('active', 'rotated', 'revoked')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_connection_instances": { + "name": "mcp_gateway_connection_instances", + "schema": "", + "columns": { + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "instance_status": { + "name": "instance_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "instance_version": { + "name": "instance_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "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 + }, + "removed_at": { + "name": "removed_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": { + "UQ_mcp_gateway_connection_instances_non_terminal": { + "name": "UQ_mcp_gateway_connection_instances_non_terminal", + "columns": [ + { + "expression": "owner_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_connection_instances\".\"instance_status\" IN ('active', 'needs_reauth')", + "concurrently": false + }, + "IDX_mcp_gateway_connection_instances_config": { + "name": "IDX_mcp_gateway_connection_instances_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_connection_instances_user": { + "name": "IDX_mcp_gateway_connection_instances_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_connection_instances_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_connection_instances_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_connection_instances", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_connection_instances_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_connection_instances_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_connection_instances", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_connection_instances_version_positive": { + "name": "mcp_gateway_connection_instances_version_positive", + "value": "\"mcp_gateway_connection_instances\".\"instance_version\" > 0" + }, + "mcp_gateway_connection_instances_owner_scope": { + "name": "mcp_gateway_connection_instances_owner_scope", + "value": "\"mcp_gateway_connection_instances\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_connection_instances_status": { + "name": "mcp_gateway_connection_instances_status", + "value": "\"mcp_gateway_connection_instances\".\"instance_status\" IN ('active', 'needs_reauth', 'revoked', 'removed')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_oauth_clients": { + "name": "mcp_gateway_oauth_clients", + "schema": "", + "columns": { + "oauth_client_id": { + "name": "oauth_client_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_name": { + "name": "client_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "registration_token_hash": { + "name": "registration_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_secret_hash": { + "name": "client_secret_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_endpoint_auth_method": { + "name": "token_endpoint_auth_method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "grant_types": { + "name": "grant_types", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "response_types": { + "name": "response_types", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "declared_scopes": { + "name": "declared_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "registration_access_token_expires_at": { + "name": "registration_access_token_expires_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_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": { + "UQ_mcp_gateway_oauth_clients_client_id": { + "name": "UQ_mcp_gateway_oauth_clients_client_id", + "columns": [ + { + "expression": "client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_mcp_gateway_oauth_clients_registration_token_hash": { + "name": "UQ_mcp_gateway_oauth_clients_registration_token_hash", + "columns": [ + { + "expression": "registration_token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_clients_deleted_at": { + "name": "IDX_mcp_gateway_oauth_clients_deleted_at", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_oauth_clients_client_id_format": { + "name": "mcp_gateway_oauth_clients_client_id_format", + "value": "\"mcp_gateway_oauth_clients\".\"client_id\" ~ '^[A-Za-z0-9._-]+:[A-Za-z0-9._-]+$'" + }, + "mcp_gateway_oauth_clients_auth_method": { + "name": "mcp_gateway_oauth_clients_auth_method", + "value": "\"mcp_gateway_oauth_clients\".\"token_endpoint_auth_method\" IN ('none', 'client_secret_post', 'client_secret_basic')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_oauth_grants": { + "name": "mcp_gateway_oauth_grants", + "schema": "", + "columns": { + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connect_resource_id": { + "name": "connect_resource_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "execution_context": { + "name": "execution_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "config_version": { + "name": "config_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "grant_status": { + "name": "grant_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "approved_at": { + "name": "approved_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": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_reason": { + "name": "revocation_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": { + "UQ_mcp_gateway_oauth_grants_active_binding": { + "name": "UQ_mcp_gateway_oauth_grants_active_binding", + "columns": [ + { + "expression": "oauth_client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connect_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "redirect_uri", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_oauth_grants\".\"revoked_at\" is null and \"mcp_gateway_oauth_grants\".\"grant_status\" in ('pending', 'active')", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_client": { + "name": "IDX_mcp_gateway_oauth_grants_client", + "columns": [ + { + "expression": "oauth_client_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_user": { + "name": "IDX_mcp_gateway_oauth_grants_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_config": { + "name": "IDX_mcp_gateway_oauth_grants_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_owner": { + "name": "IDX_mcp_gateway_oauth_grants_owner", + "columns": [ + { + "expression": "owner_scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "owner_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_resource": { + "name": "IDX_mcp_gateway_oauth_grants_resource", + "columns": [ + { + "expression": "connect_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_instance": { + "name": "IDX_mcp_gateway_oauth_grants_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_oauth_grants_revoked_at": { + "name": "IDX_mcp_gateway_oauth_grants_revoked_at", + "columns": [ + { + "expression": "revoked_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_oauth_grants_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk": { + "name": "mcp_gateway_oauth_grants_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk", + "tableFrom": "mcp_gateway_oauth_grants", + "columnsFrom": [ + "oauth_client_id" + ], + "tableTo": "mcp_gateway_oauth_clients", + "columnsTo": [ + "oauth_client_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_oauth_grants_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_oauth_grants_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_oauth_grants", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_oauth_grants_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_oauth_grants_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_oauth_grants", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_oauth_grants_connect_resource_id_mcp_gateway_connect_resources_connect_resource_id_fk": { + "name": "mcp_gateway_oauth_grants_connect_resource_id_mcp_gateway_connect_resources_connect_resource_id_fk", + "tableFrom": "mcp_gateway_oauth_grants", + "columnsFrom": [ + "connect_resource_id" + ], + "tableTo": "mcp_gateway_connect_resources", + "columnsTo": [ + "connect_resource_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_oauth_grants_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_oauth_grants_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_oauth_grants", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_oauth_grants_config_version_positive": { + "name": "mcp_gateway_oauth_grants_config_version_positive", + "value": "\"mcp_gateway_oauth_grants\".\"config_version\" > 0" + }, + "mcp_gateway_oauth_grants_owner_scope": { + "name": "mcp_gateway_oauth_grants_owner_scope", + "value": "\"mcp_gateway_oauth_grants\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_oauth_grants_status": { + "name": "mcp_gateway_oauth_grants_status", + "value": "\"mcp_gateway_oauth_grants\".\"grant_status\" IN ('pending', 'active', 'revoked')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_pending_provider_authorizations": { + "name": "mcp_gateway_pending_provider_authorizations", + "schema": "", + "columns": { + "pending_provider_authorization_id": { + "name": "pending_provider_authorization_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "state_hash": { + "name": "state_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorization_request_id": { + "name": "authorization_request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "route_key": { + "name": "route_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_resource_url": { + "name": "canonical_resource_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "remote_url": { + "name": "remote_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "auth_mode": { + "name": "auth_mode", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_authorization_endpoint": { + "name": "provider_authorization_endpoint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_token_endpoint": { + "name": "provider_token_endpoint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "encrypted_state": { + "name": "encrypted_state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "execution_context": { + "name": "execution_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "config_version": { + "name": "config_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "pending_status": { + "name": "pending_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()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_mcp_gateway_pending_provider_authorizations_state_hash": { + "name": "UQ_mcp_gateway_pending_provider_authorizations_state_hash", + "columns": [ + { + "expression": "state_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_pending_provider_authorizations_config": { + "name": "IDX_mcp_gateway_pending_provider_authorizations_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_pending_provider_authorizations_grant": { + "name": "IDX_mcp_gateway_pending_provider_authorizations_grant", + "columns": [ + { + "expression": "oauth_grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_pending_provider_authorizations\".\"oauth_grant_id\" is not null", + "concurrently": false + }, + "IDX_mcp_gateway_pending_provider_authorizations_expires_at": { + "name": "IDX_mcp_gateway_pending_provider_authorizations_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_pending_provider_authorizations_authorization_request_id_mcp_gateway_authorization_requests_authorization_request_id_fk": { + "name": "mcp_gateway_pending_provider_authorizations_authorization_request_id_mcp_gateway_authorization_requests_authorization_request_id_fk", + "tableFrom": "mcp_gateway_pending_provider_authorizations", + "columnsFrom": [ + "authorization_request_id" + ], + "tableTo": "mcp_gateway_authorization_requests", + "columnsTo": [ + "authorization_request_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_pending_provider_authorizations_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk": { + "name": "mcp_gateway_pending_provider_authorizations_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk", + "tableFrom": "mcp_gateway_pending_provider_authorizations", + "columnsFrom": [ + "oauth_grant_id" + ], + "tableTo": "mcp_gateway_oauth_grants", + "columnsTo": [ + "oauth_grant_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_pending_provider_authorizations_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_pending_provider_authorizations_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_pending_provider_authorizations", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_pending_provider_authorizations_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_pending_provider_authorizations_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_pending_provider_authorizations", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_pending_provider_authorizations_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_pending_provider_authorizations_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_pending_provider_authorizations", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_pending_provider_authorizations_config_version_positive": { + "name": "mcp_gateway_pending_provider_authorizations_config_version_positive", + "value": "\"mcp_gateway_pending_provider_authorizations\".\"config_version\" > 0" + }, + "mcp_gateway_pending_provider_authorizations_owner_scope": { + "name": "mcp_gateway_pending_provider_authorizations_owner_scope", + "value": "\"mcp_gateway_pending_provider_authorizations\".\"owner_scope\" IN ('personal', 'organization')" + }, + "mcp_gateway_pending_provider_authorizations_auth_mode": { + "name": "mcp_gateway_pending_provider_authorizations_auth_mode", + "value": "\"mcp_gateway_pending_provider_authorizations\".\"auth_mode\" IN ('none', 'static_headers', 'oauth_dynamic', 'oauth_static')" + }, + "mcp_gateway_pending_provider_authorizations_status": { + "name": "mcp_gateway_pending_provider_authorizations_status", + "value": "\"mcp_gateway_pending_provider_authorizations\".\"pending_status\" IN ('pending', 'completed', 'error')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_provider_grants": { + "name": "mcp_gateway_provider_grants", + "schema": "", + "columns": { + "provider_grant_id": { + "name": "provider_grant_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "encrypted_grant": { + "name": "encrypted_grant", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_subject": { + "name": "provider_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "grant_scope": { + "name": "grant_scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "grant_status": { + "name": "grant_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "grant_version": { + "name": "grant_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "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": { + "UQ_mcp_gateway_provider_grants_active_instance": { + "name": "UQ_mcp_gateway_provider_grants_active_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_provider_grants\".\"grant_status\" = 'active'", + "concurrently": false + }, + "IDX_mcp_gateway_provider_grants_instance": { + "name": "IDX_mcp_gateway_provider_grants_instance", + "columns": [ + { + "expression": "instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_provider_grants_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_provider_grants_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_provider_grants", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_provider_grants_version_positive": { + "name": "mcp_gateway_provider_grants_version_positive", + "value": "\"mcp_gateway_provider_grants\".\"grant_version\" > 0" + }, + "mcp_gateway_provider_grants_status": { + "name": "mcp_gateway_provider_grants_status", + "value": "\"mcp_gateway_provider_grants\".\"grant_status\" IN ('active', 'revoked')" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_rate_limit_windows": { + "name": "mcp_gateway_rate_limit_windows", + "schema": "", + "columns": { + "rate_limit_window_id": { + "name": "rate_limit_window_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "ip_hash": { + "name": "ip_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_started_at": { + "name": "window_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempt_count": { + "name": "attempt_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": { + "UQ_mcp_gateway_rate_limit_windows_ip_window": { + "name": "UQ_mcp_gateway_rate_limit_windows_ip_window", + "columns": [ + { + "expression": "ip_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "window_started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_rate_limit_windows_window": { + "name": "IDX_mcp_gateway_rate_limit_windows_window", + "columns": [ + { + "expression": "window_started_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_rate_limit_windows_attempt_count_non_negative": { + "name": "mcp_gateway_rate_limit_windows_attempt_count_non_negative", + "value": "\"mcp_gateway_rate_limit_windows\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.mcp_gateway_refresh_tokens": { + "name": "mcp_gateway_refresh_tokens", + "schema": "", + "columns": { + "refresh_token_id": { + "name": "refresh_token_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rotated_from_refresh_token_id": { + "name": "rotated_from_refresh_token_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "oauth_client_id": { + "name": "oauth_client_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "oauth_grant_id": { + "name": "oauth_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_scope": { + "name": "owner_scope", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "route_key": { + "name": "route_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_resource_url": { + "name": "canonical_resource_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": true + }, + "execution_context": { + "name": "execution_context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "instance_id": { + "name": "instance_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "consumed_at": { + "name": "consumed_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": { + "UQ_mcp_gateway_refresh_tokens_token_hash": { + "name": "UQ_mcp_gateway_refresh_tokens_token_hash", + "columns": [ + { + "expression": "token_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_refresh_tokens_user": { + "name": "IDX_mcp_gateway_refresh_tokens_user", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_refresh_tokens_grant": { + "name": "IDX_mcp_gateway_refresh_tokens_grant", + "columns": [ + { + "expression": "oauth_grant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"mcp_gateway_refresh_tokens\".\"oauth_grant_id\" is not null", + "concurrently": false + }, + "IDX_mcp_gateway_refresh_tokens_config": { + "name": "IDX_mcp_gateway_refresh_tokens_config", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_mcp_gateway_refresh_tokens_consumed_at": { + "name": "IDX_mcp_gateway_refresh_tokens_consumed_at", + "columns": [ + { + "expression": "consumed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "mcp_gateway_refresh_tokens_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk": { + "name": "mcp_gateway_refresh_tokens_oauth_client_id_mcp_gateway_oauth_clients_oauth_client_id_fk", + "tableFrom": "mcp_gateway_refresh_tokens", + "columnsFrom": [ + "oauth_client_id" + ], + "tableTo": "mcp_gateway_oauth_clients", + "columnsTo": [ + "oauth_client_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_refresh_tokens_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk": { + "name": "mcp_gateway_refresh_tokens_oauth_grant_id_mcp_gateway_oauth_grants_oauth_grant_id_fk", + "tableFrom": "mcp_gateway_refresh_tokens", + "columnsFrom": [ + "oauth_grant_id" + ], + "tableTo": "mcp_gateway_oauth_grants", + "columnsTo": [ + "oauth_grant_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_refresh_tokens_config_id_mcp_gateway_configs_config_id_fk": { + "name": "mcp_gateway_refresh_tokens_config_id_mcp_gateway_configs_config_id_fk", + "tableFrom": "mcp_gateway_refresh_tokens", + "columnsFrom": [ + "config_id" + ], + "tableTo": "mcp_gateway_configs", + "columnsTo": [ + "config_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_refresh_tokens_kilo_user_id_kilocode_users_id_fk": { + "name": "mcp_gateway_refresh_tokens_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "mcp_gateway_refresh_tokens", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "mcp_gateway_refresh_tokens_instance_id_mcp_gateway_connection_instances_instance_id_fk": { + "name": "mcp_gateway_refresh_tokens_instance_id_mcp_gateway_connection_instances_instance_id_fk", + "tableFrom": "mcp_gateway_refresh_tokens", + "columnsFrom": [ + "instance_id" + ], + "tableTo": "mcp_gateway_connection_instances", + "columnsTo": [ + "instance_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "mcp_gateway_refresh_tokens_owner_scope": { + "name": "mcp_gateway_refresh_tokens_owner_scope", + "value": "\"mcp_gateway_refresh_tokens\".\"owner_scope\" IN ('personal', 'organization')" + } + }, + "isRLSEnabled": false + }, + "public.microdollar_usage": { + "name": "microdollar_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cost": { + "name": "cost", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "input_tokens": { + "name": "input_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "output_tokens": { + "name": "output_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "cache_write_tokens": { + "name": "cache_write_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "cache_hit_tokens": { + "name": "cache_hit_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_model": { + "name": "requested_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cache_discount": { + "name": "cache_discount", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "has_error": { + "name": "has_error", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "abuse_classification": { + "name": "abuse_classification", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "inference_provider": { + "name": "inference_provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_created_at": { + "name": "idx_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_abuse_classification": { + "name": "idx_abuse_classification", + "columns": [ + { + "expression": "abuse_classification", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_kilo_user_id_created_at2": { + "name": "idx_kilo_user_id_created_at2", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_microdollar_usage_organization_id": { + "name": "idx_microdollar_usage_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"microdollar_usage\".\"organization_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.microdollar_usage_daily": { + "name": "microdollar_usage_daily", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "total_cost_microdollars": { + "name": "total_cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_microdollar_usage_daily_personal": { + "name": "idx_microdollar_usage_daily_personal", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"microdollar_usage_daily\".\"organization_id\" is null", + "concurrently": false + }, + "idx_microdollar_usage_daily_org": { + "name": "idx_microdollar_usage_daily_org", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"microdollar_usage_daily\".\"organization_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.microdollar_usage_daily_repairs": { + "name": "microdollar_usage_daily_repairs", + "schema": "", + "columns": { + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_token": { + "name": "claim_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_error_redacted": { + "name": "last_error_redacted", + "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": { + "IDX_microdollar_usage_daily_repairs_claim": { + "name": "IDX_microdollar_usage_daily_repairs_claim", + "columns": [ + { + "expression": "attempt_count", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_date", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "microdollar_usage_daily_repairs_usage_id_microdollar_usage_id_fk": { + "name": "microdollar_usage_daily_repairs_usage_id_microdollar_usage_id_fk", + "tableFrom": "microdollar_usage_daily_repairs", + "columnsFrom": [ + "usage_id" + ], + "tableTo": "microdollar_usage", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "microdollar_usage_daily_repairs_attempt_count_check": { + "name": "microdollar_usage_daily_repairs_attempt_count_check", + "value": "\"microdollar_usage_daily_repairs\".\"attempt_count\" >= 0" + }, + "microdollar_usage_daily_repairs_claim_token_check": { + "name": "microdollar_usage_daily_repairs_claim_token_check", + "value": "(\"microdollar_usage_daily_repairs\".\"claimed_at\" IS NULL AND \"microdollar_usage_daily_repairs\".\"claim_token\" IS NULL) OR (\"microdollar_usage_daily_repairs\".\"claimed_at\" IS NOT NULL AND \"microdollar_usage_daily_repairs\".\"claim_token\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.microdollar_usage_metadata": { + "name": "microdollar_usage_metadata", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "http_user_agent_id": { + "name": "http_user_agent_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "http_ip_id": { + "name": "http_ip_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "vercel_ip_city_id": { + "name": "vercel_ip_city_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "vercel_ip_country_id": { + "name": "vercel_ip_country_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "vercel_ip_latitude": { + "name": "vercel_ip_latitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "vercel_ip_longitude": { + "name": "vercel_ip_longitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "ja4_digest_id": { + "name": "ja4_digest_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "user_prompt_prefix": { + "name": "user_prompt_prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_prompt_prefix_id": { + "name": "system_prompt_prefix_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "system_prompt_length": { + "name": "system_prompt_length", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "max_tokens": { + "name": "max_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "has_middle_out_transform": { + "name": "has_middle_out_transform", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "status_code": { + "name": "status_code", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "upstream_id": { + "name": "upstream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "finish_reason_id": { + "name": "finish_reason_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "latency": { + "name": "latency", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "moderation_latency": { + "name": "moderation_latency", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "generation_time": { + "name": "generation_time", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "is_byok": { + "name": "is_byok", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "is_user_byok": { + "name": "is_user_byok", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "streamed": { + "name": "streamed", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancelled": { + "name": "cancelled", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "editor_name_id": { + "name": "editor_name_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "api_kind_id": { + "name": "api_kind_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "has_tools": { + "name": "has_tools", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "machine_id": { + "name": "machine_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "feature_id": { + "name": "feature_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mode_id": { + "name": "mode_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "auto_model_id": { + "name": "auto_model_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "market_cost": { + "name": "market_cost", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "is_free": { + "name": "is_free", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "abuse_delay": { + "name": "abuse_delay", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "abuse_downgraded_from": { + "name": "abuse_downgraded_from", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_microdollar_usage_metadata_created_at": { + "name": "idx_microdollar_usage_metadata_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_microdollar_usage_metadata_session_id": { + "name": "idx_microdollar_usage_metadata_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"microdollar_usage_metadata\".\"session_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "microdollar_usage_metadata_http_user_agent_id_http_user_agent_http_user_agent_id_fk": { + "name": "microdollar_usage_metadata_http_user_agent_id_http_user_agent_http_user_agent_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "http_user_agent_id" + ], + "tableTo": "http_user_agent", + "columnsTo": [ + "http_user_agent_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "microdollar_usage_metadata_http_ip_id_http_ip_http_ip_id_fk": { + "name": "microdollar_usage_metadata_http_ip_id_http_ip_http_ip_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "http_ip_id" + ], + "tableTo": "http_ip", + "columnsTo": [ + "http_ip_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "microdollar_usage_metadata_vercel_ip_city_id_vercel_ip_city_vercel_ip_city_id_fk": { + "name": "microdollar_usage_metadata_vercel_ip_city_id_vercel_ip_city_vercel_ip_city_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "vercel_ip_city_id" + ], + "tableTo": "vercel_ip_city", + "columnsTo": [ + "vercel_ip_city_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "microdollar_usage_metadata_vercel_ip_country_id_vercel_ip_country_vercel_ip_country_id_fk": { + "name": "microdollar_usage_metadata_vercel_ip_country_id_vercel_ip_country_vercel_ip_country_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "vercel_ip_country_id" + ], + "tableTo": "vercel_ip_country", + "columnsTo": [ + "vercel_ip_country_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "microdollar_usage_metadata_ja4_digest_id_ja4_digest_ja4_digest_id_fk": { + "name": "microdollar_usage_metadata_ja4_digest_id_ja4_digest_ja4_digest_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "ja4_digest_id" + ], + "tableTo": "ja4_digest", + "columnsTo": [ + "ja4_digest_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "microdollar_usage_metadata_system_prompt_prefix_id_system_prompt_prefix_system_prompt_prefix_id_fk": { + "name": "microdollar_usage_metadata_system_prompt_prefix_id_system_prompt_prefix_system_prompt_prefix_id_fk", + "tableFrom": "microdollar_usage_metadata", + "columnsFrom": [ + "system_prompt_prefix_id" + ], + "tableTo": "system_prompt_prefix", + "columnsTo": [ + "system_prompt_prefix_id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.mode": { + "name": "mode", + "schema": "", + "columns": { + "mode_id": { + "name": "mode_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_mode": { + "name": "UQ_mode", + "columns": [ + { + "expression": "mode", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.model_stats": { + "name": "model_stats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": true + }, + "is_featured": { + "name": "is_featured", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_stealth": { + "name": "is_stealth", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "is_recommended": { + "name": "is_recommended", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "openrouter_id": { + "name": "openrouter_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "aa_slug": { + "name": "aa_slug", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model_creator": { + "name": "model_creator", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "creator_slug": { + "name": "creator_slug", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "release_date": { + "name": "release_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "price_input": { + "name": "price_input", + "type": "numeric(10, 6)", + "primaryKey": false, + "notNull": false + }, + "price_output": { + "name": "price_output", + "type": "numeric(10, 6)", + "primaryKey": false, + "notNull": false + }, + "coding_index": { + "name": "coding_index", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "speed_tokens_per_sec": { + "name": "speed_tokens_per_sec", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": false + }, + "context_length": { + "name": "context_length", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "max_output_tokens": { + "name": "max_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "input_modalities": { + "name": "input_modalities", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "openrouter_data": { + "name": "openrouter_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "benchmarks": { + "name": "benchmarks", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "chart_data": { + "name": "chart_data", + "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": { + "IDX_model_stats_openrouter_id": { + "name": "IDX_model_stats_openrouter_id", + "columns": [ + { + "expression": "openrouter_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_slug": { + "name": "IDX_model_stats_slug", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_is_active": { + "name": "IDX_model_stats_is_active", + "columns": [ + { + "expression": "is_active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_creator_slug": { + "name": "IDX_model_stats_creator_slug", + "columns": [ + { + "expression": "creator_slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_price_input": { + "name": "IDX_model_stats_price_input", + "columns": [ + { + "expression": "price_input", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_coding_index": { + "name": "IDX_model_stats_coding_index", + "columns": [ + { + "expression": "coding_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_stats_context_length": { + "name": "IDX_model_stats_context_length", + "columns": [ + { + "expression": "context_length", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "model_stats_openrouter_id_unique": { + "name": "model_stats_openrouter_id_unique", + "columns": [ + "openrouter_id" + ], + "nullsNotDistinct": false + }, + "model_stats_slug_unique": { + "name": "model_stats_slug_unique", + "columns": [ + "slug" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.model_eval_ingestions": { + "name": "model_eval_ingestions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "bench_eval_name": { + "name": "bench_eval_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "bench_eval_url": { + "name": "bench_eval_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_stats_id": { + "name": "model_stats_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "variant": { + "name": "variant", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_source": { + "name": "task_source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "n_total_trials": { + "name": "n_total_trials", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "n_attempts": { + "name": "n_attempts", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_score": { + "name": "total_score", + "type": "numeric(14, 6)", + "primaryKey": false, + "notNull": true + }, + "overall_score": { + "name": "overall_score", + "type": "numeric(12, 8)", + "primaryKey": false, + "notNull": true + }, + "n_errored": { + "name": "n_errored", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "avg_cost_microdollars": { + "name": "avg_cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "total_cost_microdollars": { + "name": "total_cost_microdollars", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "avg_input_tokens": { + "name": "avg_input_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_input_tokens": { + "name": "total_input_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "avg_output_tokens": { + "name": "avg_output_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_output_tokens": { + "name": "total_output_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "avg_cache_read_tokens": { + "name": "avg_cache_read_tokens", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "total_cache_read_tokens": { + "name": "total_cache_read_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "avg_execution_ms": { + "name": "avg_execution_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "promoted_at": { + "name": "promoted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "promoted_by_email": { + "name": "promoted_by_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "promotion_note": { + "name": "promotion_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_model_eval_ingestions_lookup": { + "name": "IDX_model_eval_ingestions_lookup", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "model", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "variant", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "task_source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "promoted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_eval_ingestions_model_stats": { + "name": "IDX_model_eval_ingestions_model_stats", + "columns": [ + { + "expression": "model_stats_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_eval_ingestions_promoted_by_email_lower": { + "name": "IDX_model_eval_ingestions_promoted_by_email_lower", + "columns": [ + { + "expression": "LOWER(\"promoted_by_email\")", + "isExpression": true, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "model_eval_ingestions_model_stats_id_model_stats_id_fk": { + "name": "model_eval_ingestions_model_stats_id_model_stats_id_fk", + "tableFrom": "model_eval_ingestions", + "columnsFrom": [ + "model_stats_id" + ], + "tableTo": "model_stats", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "model_eval_ingestions_bench_eval_name_unique": { + "name": "model_eval_ingestions_bench_eval_name_unique", + "columns": [ + "bench_eval_name" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.model_experiment": { + "name": "model_experiment", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "public_model_id": { + "name": "public_model_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "is_archived": { + "name": "is_archived", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "UQ_model_experiment_public_model_id_routing": { + "name": "UQ_model_experiment_public_model_id_routing", + "columns": [ + { + "expression": "public_model_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"model_experiment\".\"status\" IN ('active', 'paused')", + "concurrently": false + }, + "IDX_model_experiment_status": { + "name": "IDX_model_experiment_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "model_experiment_created_by_user_id_kilocode_users_id_fk": { + "name": "model_experiment_created_by_user_id_kilocode_users_id_fk", + "tableFrom": "model_experiment", + "columnsFrom": [ + "created_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "model_experiment_status_valid": { + "name": "model_experiment_status_valid", + "value": "\"model_experiment\".\"status\" IN ('draft', 'active', 'paused', 'completed')" + }, + "model_experiment_active_not_archived": { + "name": "model_experiment_active_not_archived", + "value": "\"model_experiment\".\"status\" <> 'active' OR \"model_experiment\".\"is_archived\" = false" + } + }, + "isRLSEnabled": false + }, + "public.model_experiment_request": { + "name": "model_experiment_request", + "schema": "", + "columns": { + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "variant_version_id": { + "name": "variant_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "allocation_subject": { + "name": "allocation_subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_request_id": { + "name": "client_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_kind": { + "name": "request_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_body_sha256": { + "name": "request_body_sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "was_truncated": { + "name": "was_truncated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_model_experiment_request_variant_version_created_at": { + "name": "IDX_model_experiment_request_variant_version_created_at", + "columns": [ + { + "expression": "variant_version_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_model_experiment_request_client_request_id": { + "name": "IDX_model_experiment_request_client_request_id", + "columns": [ + { + "expression": "client_request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"model_experiment_request\".\"client_request_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "model_experiment_request_usage_id_microdollar_usage_id_fk": { + "name": "model_experiment_request_usage_id_microdollar_usage_id_fk", + "tableFrom": "model_experiment_request", + "columnsFrom": [ + "usage_id" + ], + "tableTo": "microdollar_usage", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "model_experiment_request_variant_version_id_model_experiment_variant_version_id_fk": { + "name": "model_experiment_request_variant_version_id_model_experiment_variant_version_id_fk", + "tableFrom": "model_experiment_request", + "columnsFrom": [ + "variant_version_id" + ], + "tableTo": "model_experiment_variant_version", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": { + "model_experiment_request_usage_id_created_at_pk": { + "name": "model_experiment_request_usage_id_created_at_pk", + "columns": [ + "usage_id", + "created_at" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "model_experiment_request_allocation_subject_valid": { + "name": "model_experiment_request_allocation_subject_valid", + "value": "\"model_experiment_request\".\"allocation_subject\" IN ('user', 'machine', 'ip')" + }, + "model_experiment_request_request_kind_valid": { + "name": "model_experiment_request_request_kind_valid", + "value": "\"model_experiment_request\".\"request_kind\" IN ('chat_completions', 'messages', 'responses')" + }, + "model_experiment_request_request_body_sha256_format": { + "name": "model_experiment_request_request_body_sha256_format", + "value": "\"model_experiment_request\".\"request_body_sha256\" ~ '^[0-9a-f]{64}$' OR \"model_experiment_request\".\"request_body_sha256\" IN ('__failed__', '__deleted__')" + } + }, + "isRLSEnabled": false + }, + "public.model_experiment_variant": { + "name": "model_experiment_variant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "experiment_id": { + "name": "experiment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "weight": { + "name": "weight", + "type": "integer", + "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": { + "IDX_model_experiment_variant_experiment_id": { + "name": "IDX_model_experiment_variant_experiment_id", + "columns": [ + { + "expression": "experiment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "model_experiment_variant_experiment_id_model_experiment_id_fk": { + "name": "model_experiment_variant_experiment_id_model_experiment_id_fk", + "tableFrom": "model_experiment_variant", + "columnsFrom": [ + "experiment_id" + ], + "tableTo": "model_experiment", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_model_experiment_variant_experiment_label": { + "name": "UQ_model_experiment_variant_experiment_label", + "columns": [ + "experiment_id", + "label" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "model_experiment_variant_weight_positive": { + "name": "model_experiment_variant_weight_positive", + "value": "\"model_experiment_variant\".\"weight\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.model_experiment_variant_version": { + "name": "model_experiment_variant_version", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "variant_id": { + "name": "variant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "upstream": { + "name": "upstream", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "encrypted_api_key": { + "name": "encrypted_api_key", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "effective_at": { + "name": "effective_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_model_experiment_variant_version_variant_effective": { + "name": "IDX_model_experiment_variant_version_variant_effective", + "columns": [ + { + "expression": "variant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "effective_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "model_experiment_variant_version_variant_id_model_experiment_variant_id_fk": { + "name": "model_experiment_variant_version_variant_id_model_experiment_variant_id_fk", + "tableFrom": "model_experiment_variant_version", + "columnsFrom": [ + "variant_id" + ], + "tableTo": "model_experiment_variant", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "model_experiment_variant_version_created_by_kilocode_users_id_fk": { + "name": "model_experiment_variant_version_created_by_kilocode_users_id_fk", + "tableFrom": "model_experiment_variant_version", + "columnsFrom": [ + "created_by" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.models_by_provider": { + "name": "models_by_provider", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "openrouter": { + "name": "openrouter", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "vercel": { + "name": "vercel", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.native_admission_challenges": { + "name": "native_admission_challenges", + "schema": "", + "columns": { + "challenge": { + "name": "challenge", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "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": { + "IDX_native_admission_challenges_expires_at": { + "name": "IDX_native_admission_challenges_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.native_attested_keys": { + "name": "native_attested_keys", + "schema": "", + "columns": { + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sign_count": { + "name": "sign_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "attested_at": { + "name": "attested_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": { + "IDX_native_attested_keys_kilo_user_id": { + "name": "IDX_native_attested_keys_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "native_attested_keys_kilo_user_id_kilocode_users_id_fk": { + "name": "native_attested_keys_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "native_attested_keys", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "native_attested_keys_platform_check": { + "name": "native_attested_keys_platform_check", + "value": "\"native_attested_keys\".\"platform\" IN ('ios', 'android')" + } + }, + "isRLSEnabled": false + }, + "public.operation_ledgers": { + "name": "operation_ledgers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "operation_key": { + "name": "operation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "intent": { + "name": "intent", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "resource_key": { + "name": "resource_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_ref": { + "name": "provider_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "taxonomy": { + "name": "taxonomy", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'admitted'" + }, + "outcome_code": { + "name": "outcome_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "canonical_result": { + "name": "canonical_result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "admitted_at": { + "name": "admitted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "settled_at": { + "name": "settled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_operation_ledgers_kilo_user_id_domain_operation_key": { + "name": "UQ_operation_ledgers_kilo_user_id_domain_operation_key", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "domain", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "operation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_operation_ledgers_status_expires_at": { + "name": "IDX_operation_ledgers_status_expires_at", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_operation_ledgers_provider_ref": { + "name": "IDX_operation_ledgers_provider_ref", + "columns": [ + { + "expression": "provider_ref", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"operation_ledgers\".\"provider_ref\" IS NOT NULL", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_audit_logs": { + "name": "organization_audit_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_organization_audit_logs_organization_id": { + "name": "IDX_organization_audit_logs_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_audit_logs_action": { + "name": "IDX_organization_audit_logs_action", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_audit_logs_actor_id": { + "name": "IDX_organization_audit_logs_actor_id", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_audit_logs_created_at": { + "name": "IDX_organization_audit_logs_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_group_memberships": { + "name": "organization_group_memberships", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by_kilo_user_id": { + "name": "assigned_by_kilo_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": { + "IDX_organization_group_memberships_organization_user": { + "name": "IDX_organization_group_memberships_organization_user", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "FK_organization_group_memberships_group": { + "name": "FK_organization_group_memberships_group", + "tableFrom": "organization_group_memberships", + "columnsFrom": [ + "organization_id", + "group_id" + ], + "tableTo": "organization_groups", + "columnsTo": [ + "organization_id", + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "FK_organization_group_memberships_member": { + "name": "FK_organization_group_memberships_member", + "tableFrom": "organization_group_memberships", + "columnsFrom": [ + "organization_id", + "kilo_user_id" + ], + "tableTo": "organization_memberships", + "columnsTo": [ + "organization_id", + "kilo_user_id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "PK_organization_group_memberships": { + "name": "PK_organization_group_memberships", + "columns": [ + "organization_id", + "group_id", + "kilo_user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_group_policy_settings": { + "name": "organization_group_policy_settings", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "default_policies": { + "name": "default_policies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[{\"type\":\"model_access\",\"data\":{\"mode\":\"all\"}}]'::jsonb" + }, + "policy_revision": { + "name": "policy_revision", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "updated_by_kilo_user_id": { + "name": "updated_by_kilo_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": {}, + "foreignKeys": { + "organization_group_policy_settings_organization_id_organizations_id_fk": { + "name": "organization_group_policy_settings_organization_id_organizations_id_fk", + "tableFrom": "organization_group_policy_settings", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organization_group_policy_settings_revision_check": { + "name": "organization_group_policy_settings_revision_check", + "value": "\"organization_group_policy_settings\".\"policy_revision\" >= 1" + } + }, + "isRLSEnabled": false + }, + "public.organization_groups": { + "name": "organization_groups", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_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 + }, + "policies": { + "name": "policies", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_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": { + "UQ_organization_groups_organization_id_canonical_name": { + "name": "UQ_organization_groups_organization_id_canonical_name", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(btrim(\"name\"))", + "isExpression": true, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_groups_organization_id": { + "name": "IDX_organization_groups_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "organization_groups_organization_id_organizations_id_fk": { + "name": "organization_groups_organization_id_organizations_id_fk", + "tableFrom": "organization_groups", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_groups_organization_id_id": { + "name": "UQ_organization_groups_organization_id_id", + "columns": [ + "organization_id", + "id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "organization_groups_name_check": { + "name": "organization_groups_name_check", + "value": "char_length(btrim(\"organization_groups\".\"name\")) BETWEEN 1 AND 80" + }, + "organization_groups_description_check": { + "name": "organization_groups_description_check", + "value": "\"organization_groups\".\"description\" IS NULL OR char_length(\"organization_groups\".\"description\") <= 500" + } + }, + "isRLSEnabled": false + }, + "public.organization_invitations": { + "name": "organization_invitations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "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 + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "authentication_requirement": { + "name": "authentication_requirement", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "sso_source_organization_id": { + "name": "sso_source_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_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()" + } + }, + "indexes": { + "UQ_organization_invitations_token": { + "name": "UQ_organization_invitations_token", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_invitations_org_id": { + "name": "IDX_organization_invitations_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_invitations_email": { + "name": "IDX_organization_invitations_email", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_invitations_expires_at": { + "name": "IDX_organization_invitations_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "organization_invitations_sso_source_organization_id_organizations_id_fk": { + "name": "organization_invitations_sso_source_organization_id_organizations_id_fk", + "tableFrom": "organization_invitations", + "columnsFrom": [ + "sso_source_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_membership_removals": { + "name": "organization_membership_removals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_by": { + "name": "removed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "previous_role": { + "name": "previous_role", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "IDX_org_membership_removals_org_id": { + "name": "IDX_org_membership_removals_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_org_membership_removals_user_id": { + "name": "IDX_org_membership_removals_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_org_membership_removals_org_user": { + "name": "UQ_org_membership_removals_org_user", + "columns": [ + "organization_id", + "kilo_user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_memberships": { + "name": "organization_memberships", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "joined_at": { + "name": "joined_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "invited_by": { + "name": "invited_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_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()" + } + }, + "indexes": { + "IDX_organization_memberships_org_id": { + "name": "IDX_organization_memberships_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_memberships_user_id": { + "name": "IDX_organization_memberships_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_memberships_org_user": { + "name": "UQ_organization_memberships_org_user", + "columns": [ + "organization_id", + "kilo_user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_recommendation_dismissals": { + "name": "organization_recommendation_dismissals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recommendation_key": { + "name": "recommendation_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dismissed_by_user_id": { + "name": "dismissed_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dismissed_at": { + "name": "dismissed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "organization_recommendation_dismissals_owned_by_organization_id_organizations_id_fk": { + "name": "organization_recommendation_dismissals_owned_by_organization_id_organizations_id_fk", + "tableFrom": "organization_recommendation_dismissals", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "organization_recommendation_dismissals_dismissed_by_user_id_kilocode_users_id_fk": { + "name": "organization_recommendation_dismissals_dismissed_by_user_id_kilocode_users_id_fk", + "tableFrom": "organization_recommendation_dismissals", + "columnsFrom": [ + "dismissed_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_org_recommendation_dismissals_org_key": { + "name": "UQ_org_recommendation_dismissals_org_key", + "columns": [ + "owned_by_organization_id", + "recommendation_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_seats_purchases": { + "name": "organization_seats_purchases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "subscription_stripe_id": { + "name": "subscription_stripe_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "seat_count": { + "name": "seat_count", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "amount_usd": { + "name": "amount_usd", + "type": "numeric", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_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 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "subscription_status": { + "name": "subscription_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "billing_cycle": { + "name": "billing_cycle", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'monthly'" + } + }, + "indexes": { + "IDX_organization_seats_org_id": { + "name": "IDX_organization_seats_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_seats_expires_at": { + "name": "IDX_organization_seats_expires_at", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_seats_created_at": { + "name": "IDX_organization_seats_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_seats_updated_at": { + "name": "IDX_organization_seats_updated_at", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_seats_starts_at": { + "name": "IDX_organization_seats_starts_at", + "columns": [ + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_seats_idempotency_key": { + "name": "UQ_organization_seats_idempotency_key", + "columns": [ + "idempotency_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_user_limits": { + "name": "organization_user_limits", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "limit_type": { + "name": "limit_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "microdollar_limit": { + "name": "microdollar_limit", + "type": "bigint", + "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": { + "IDX_organization_user_limits_org_id": { + "name": "IDX_organization_user_limits_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_user_limits_user_id": { + "name": "IDX_organization_user_limits_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_user_limits_org_user": { + "name": "UQ_organization_user_limits_org_user", + "columns": [ + "organization_id", + "kilo_user_id", + "limit_type" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_user_usage": { + "name": "organization_user_usage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage_date": { + "name": "usage_date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "limit_type": { + "name": "limit_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "microdollar_usage": { + "name": "microdollar_usage", + "type": "bigint", + "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": { + "IDX_organization_user_daily_usage_org_id": { + "name": "IDX_organization_user_daily_usage_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organization_user_daily_usage_user_id": { + "name": "IDX_organization_user_daily_usage_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_user_daily_usage_org_user_date": { + "name": "UQ_organization_user_daily_usage_org_user_date", + "columns": [ + "organization_id", + "kilo_user_id", + "limit_type", + "usage_date" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organizations": { + "name": "organizations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "name": { + "name": "name", + "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()" + }, + "microdollars_used": { + "name": "microdollars_used", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "microdollars_balance": { + "name": "microdollars_balance", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "total_microdollars_acquired": { + "name": "total_microdollars_acquired", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "next_credit_expiration_at": { + "name": "next_credit_expiration_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auto_top_up_enabled": { + "name": "auto_top_up_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "settings": { + "name": "settings", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "seat_count": { + "name": "seat_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "require_seats": { + "name": "require_seats", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_by_kilo_user_id": { + "name": "created_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sso_domain": { + "name": "sso_domain", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "parent_organization_id": { + "name": "parent_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "plan": { + "name": "plan", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'teams'" + }, + "free_trial_end_at": { + "name": "free_trial_end_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "company_domain": { + "name": "company_domain", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_organizations_sso_domain": { + "name": "IDX_organizations_sso_domain", + "columns": [ + { + "expression": "sso_domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_organizations_parent_organization_id": { + "name": "IDX_organizations_parent_organization_id", + "columns": [ + { + "expression": "parent_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "organizations_parent_organization_id_organizations_id_fk": { + "name": "organizations_parent_organization_id_organizations_id_fk", + "tableFrom": "organizations", + "columnsFrom": [ + "parent_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "organizations_name_not_empty_check": { + "name": "organizations_name_not_empty_check", + "value": "length(trim(\"organizations\".\"name\")) > 0" + }, + "organizations_not_parented_by_self_check": { + "name": "organizations_not_parented_by_self_check", + "value": "\"organizations\".\"parent_organization_id\" IS NULL OR \"organizations\".\"parent_organization_id\" <> \"organizations\".\"id\"" + } + }, + "isRLSEnabled": false + }, + "public.organization_modes": { + "name": "organization_modes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "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()" + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": { + "IDX_organization_modes_organization_id": { + "name": "IDX_organization_modes_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_organization_modes_org_id_slug": { + "name": "UQ_organization_modes_org_id_slug", + "columns": [ + "organization_id", + "slug" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.payment_methods": { + "name": "payment_methods", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "stripe_fingerprint": { + "name": "stripe_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_id": { + "name": "stripe_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()" + }, + "last4": { + "name": "last4", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "brand": { + "name": "brand", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_line1": { + "name": "address_line1", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_line2": { + "name": "address_line2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_city": { + "name": "address_city", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_state": { + "name": "address_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_zip": { + "name": "address_zip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_country": { + "name": "address_country", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "three_d_secure_supported": { + "name": "three_d_secure_supported", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "funding": { + "name": "funding", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "regulated_status": { + "name": "regulated_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "address_line1_check_status": { + "name": "address_line1_check_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "postal_code_check_status": { + "name": "postal_code_check_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_forwarded_for": { + "name": "http_x_forwarded_for", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_city": { + "name": "http_x_vercel_ip_city", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_country": { + "name": "http_x_vercel_ip_country", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_latitude": { + "name": "http_x_vercel_ip_latitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_longitude": { + "name": "http_x_vercel_ip_longitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ja4_digest": { + "name": "http_x_vercel_ja4_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "eligible_for_free_credits": { + "name": "eligible_for_free_credits", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "stripe_data": { + "name": "stripe_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_d7d7fb15569674aaadcfbc0428": { + "name": "IDX_d7d7fb15569674aaadcfbc0428", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_e1feb919d0ab8a36381d5d5138": { + "name": "IDX_e1feb919d0ab8a36381d5d5138", + "columns": [ + { + "expression": "stripe_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_payment_methods_organization_id": { + "name": "IDX_payment_methods_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_29df1b0403df5792c96bbbfdbe6": { + "name": "UQ_29df1b0403df5792c96bbbfdbe6", + "columns": [ + "user_id", + "stripe_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.pending_impact_sale_reversals": { + "name": "pending_impact_sale_reversals", + "schema": "", + "columns": { + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "dispute_id": { + "name": "dispute_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "real", + "primaryKey": false, + "notNull": true + }, + "currency": { + "name": "currency", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_date": { + "name": "event_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "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 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "pending_impact_sale_reversals_attempt_count_non_negative_check": { + "name": "pending_impact_sale_reversals_attempt_count_non_negative_check", + "value": "\"pending_impact_sale_reversals\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.platform_access_token_credentials": { + "name": "platform_access_token_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "integration_type": { + "name": "integration_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_encrypted": { + "name": "token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "provider_credential_type": { + "name": "provider_credential_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_resource_id": { + "name": "provider_resource_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_base_url": { + "name": "provider_base_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorized_by_user_id": { + "name": "authorized_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "provider_scopes": { + "name": "provider_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "provider_verified_at": { + "name": "provider_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "credential_version": { + "name": "credential_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "last_validated_at": { + "name": "last_validated_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 + }, + "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": { + "UQ_platform_access_token_credentials_integration_level": { + "name": "UQ_platform_access_token_credentials_integration_level", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_access_token_credentials\".\"provider_resource_id\" is null", + "concurrently": false + }, + "UQ_platform_access_token_credentials_resource": { + "name": "UQ_platform_access_token_credentials_resource", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_credential_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_access_token_credentials\".\"provider_resource_id\" is not null", + "concurrently": false + }, + "IDX_platform_access_token_credentials_authorized_by_user_id": { + "name": "IDX_platform_access_token_credentials_authorized_by_user_id", + "columns": [ + { + "expression": "authorized_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "platform_access_token_credentials_authorized_by_user_id_kilocode_users_id_fk": { + "name": "platform_access_token_credentials_authorized_by_user_id_kilocode_users_id_fk", + "tableFrom": "platform_access_token_credentials", + "columnsFrom": [ + "authorized_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "FK_platform_access_token_credentials_parent": { + "name": "FK_platform_access_token_credentials_parent", + "tableFrom": "platform_access_token_credentials", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_access_token_credentials_credential_version_check": { + "name": "platform_access_token_credentials_credential_version_check", + "value": "\"platform_access_token_credentials\".\"credential_version\" > 0" + }, + "platform_access_token_credentials_resource_id_check": { + "name": "platform_access_token_credentials_resource_id_check", + "value": "\"platform_access_token_credentials\".\"provider_resource_id\" IS NULL OR \"platform_access_token_credentials\".\"provider_resource_id\" <> ''" + } + }, + "isRLSEnabled": false + }, + "public.platform_integrations": { + "name": "platform_integrations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "integration_type": { + "name": "integration_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform_installation_id": { + "name": "platform_installation_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_account_id": { + "name": "platform_account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_account_login": { + "name": "platform_account_login", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "permissions": { + "name": "permissions", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "repository_access": { + "name": "repository_access", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repositories": { + "name": "repositories", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "repositories_synced_at": { + "name": "repositories_synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auth_invalid_at": { + "name": "auth_invalid_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "auth_invalid_reason": { + "name": "auth_invalid_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "kilo_requester_user_id": { + "name": "kilo_requester_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_requester_account_id": { + "name": "platform_requester_account_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "integration_status": { + "name": "integration_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suspended_at": { + "name": "suspended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "suspended_by": { + "name": "suspended_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "github_app_type": { + "name": "github_app_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'standard'" + }, + "installed_at": { + "name": "installed_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": { + "UQ_platform_integrations_owned_by_org_platform_inst": { + "name": "UQ_platform_integrations_owned_by_org_platform_inst", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"owned_by_organization_id\" is not null", + "concurrently": false + }, + "UQ_platform_integrations_owned_by_user_platform_inst": { + "name": "UQ_platform_integrations_owned_by_user_platform_inst", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"owned_by_user_id\" is not null", + "concurrently": false + }, + "UQ_platform_integrations_slack_platform_inst": { + "name": "UQ_platform_integrations_slack_platform_inst", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"platform\" = 'slack' AND \"platform_integrations\".\"platform_installation_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_platform_integrations_linear_platform_inst": { + "name": "UQ_platform_integrations_linear_platform_inst", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"platform\" = 'linear' AND \"platform_integrations\".\"platform_installation_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_platform_integrations_github_platform_inst": { + "name": "UQ_platform_integrations_github_platform_inst", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_app_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"platform\" = 'github' AND \"platform_integrations\".\"platform_installation_id\" IS NOT NULL", + "concurrently": true + }, + "UQ_platform_integrations_user_bitbucket": { + "name": "UQ_platform_integrations_user_bitbucket", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"platform\" = 'bitbucket' AND \"platform_integrations\".\"owned_by_user_id\" IS NOT NULL", + "concurrently": false + }, + "UQ_platform_integrations_org_bitbucket": { + "name": "UQ_platform_integrations_org_bitbucket", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"platform_integrations\".\"platform\" = 'bitbucket' AND \"platform_integrations\".\"owned_by_organization_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_platform_integrations_owned_by_org_id": { + "name": "IDX_platform_integrations_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_owned_by_user_id": { + "name": "IDX_platform_integrations_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_platform_inst_id": { + "name": "IDX_platform_integrations_platform_inst_id", + "columns": [ + { + "expression": "platform_installation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_platform": { + "name": "IDX_platform_integrations_platform", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_owned_by_org_platform": { + "name": "IDX_platform_integrations_owned_by_org_platform", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_owned_by_user_platform": { + "name": "IDX_platform_integrations_owned_by_user_platform", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_integration_status": { + "name": "IDX_platform_integrations_integration_status", + "columns": [ + { + "expression": "integration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_kilo_requester": { + "name": "IDX_platform_integrations_kilo_requester", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kilo_requester_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "integration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_integrations_platform_requester": { + "name": "IDX_platform_integrations_platform_requester", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "platform_requester_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "integration_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "platform_integrations_owned_by_organization_id_organizations_id_fk": { + "name": "platform_integrations_owned_by_organization_id_organizations_id_fk", + "tableFrom": "platform_integrations", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "platform_integrations_owned_by_user_id_kilocode_users_id_fk": { + "name": "platform_integrations_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "platform_integrations", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_integrations_owner_check": { + "name": "platform_integrations_owner_check", + "value": "(\n (\"platform_integrations\".\"owned_by_user_id\" IS NOT NULL AND \"platform_integrations\".\"owned_by_organization_id\" IS NULL) OR\n (\"platform_integrations\".\"owned_by_user_id\" IS NULL AND \"platform_integrations\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.platform_oauth_credentials": { + "name": "platform_oauth_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "authorized_by_user_id": { + "name": "authorized_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider_subject_id": { + "name": "provider_subject_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_subject_login": { + "name": "provider_subject_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_base_url": { + "name": "provider_base_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_encrypted": { + "name": "access_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_encrypted": { + "name": "refresh_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "oauth_client_secret_encrypted": { + "name": "oauth_client_secret_encrypted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "credential_version": { + "name": "credential_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_reason": { + "name": "revocation_reason", + "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": { + "UQ_platform_oauth_credentials_platform_integration_id": { + "name": "UQ_platform_oauth_credentials_platform_integration_id", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_platform_oauth_credentials_authorized_by_user_id": { + "name": "IDX_platform_oauth_credentials_authorized_by_user_id", + "columns": [ + { + "expression": "authorized_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "platform_oauth_credentials_platform_integration_id_platform_integrations_id_fk": { + "name": "platform_oauth_credentials_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "platform_oauth_credentials", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "platform_oauth_credentials_authorized_by_user_id_kilocode_users_id_fk": { + "name": "platform_oauth_credentials_authorized_by_user_id_kilocode_users_id_fk", + "tableFrom": "platform_oauth_credentials", + "columnsFrom": [ + "authorized_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "platform_oauth_credentials_credential_version_check": { + "name": "platform_oauth_credentials_credential_version_check", + "value": "\"platform_oauth_credentials\".\"credential_version\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.referral_code_usages": { + "name": "referral_code_usages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "referring_kilo_user_id": { + "name": "referring_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redeeming_kilo_user_id": { + "name": "redeeming_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_usd": { + "name": "amount_usd", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "paid_at": { + "name": "paid_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": { + "IDX_referral_code_usages_redeeming_kilo_user_id": { + "name": "IDX_referral_code_usages_redeeming_kilo_user_id", + "columns": [ + { + "expression": "redeeming_kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_referral_code_usages_redeeming_user_id_code": { + "name": "UQ_referral_code_usages_redeeming_user_id_code", + "columns": [ + "redeeming_kilo_user_id", + "referring_kilo_user_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.referral_codes": { + "name": "referral_codes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code": { + "name": "code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "max_redemptions": { + "name": "max_redemptions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 10 + }, + "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": { + "UQ_referral_codes_kilo_user_id": { + "name": "UQ_referral_codes_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_referral_codes_code": { + "name": "IDX_referral_codes_code", + "columns": [ + { + "expression": "code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_advisor_check_catalog": { + "name": "security_advisor_check_catalog", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "check_id": { + "name": "check_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "explanation": { + "name": "explanation", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "risk": { + "name": "risk", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "security_advisor_check_catalog_check_id_unique": { + "name": "security_advisor_check_catalog_check_id_unique", + "columns": [ + "check_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "security_advisor_check_catalog_severity_check": { + "name": "security_advisor_check_catalog_severity_check", + "value": "\"security_advisor_check_catalog\".\"severity\" in ('critical', 'warn', 'info')" + } + }, + "isRLSEnabled": false + }, + "public.security_advisor_content": { + "name": "security_advisor_content", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "security_advisor_content_key_unique": { + "name": "security_advisor_content_key_unique", + "columns": [ + "key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_advisor_kiloclaw_coverage": { + "name": "security_advisor_kiloclaw_coverage", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "area": { + "name": "area", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "match_check_ids": { + "name": "match_check_ids", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "is_active": { + "name": "is_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "security_advisor_kiloclaw_coverage_area_unique": { + "name": "security_advisor_kiloclaw_coverage_area_unique", + "columns": [ + "area" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_advisor_scans": { + "name": "security_advisor_scans", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_platform": { + "name": "source_platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_method": { + "name": "source_method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "plugin_version": { + "name": "plugin_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "openclaw_version": { + "name": "openclaw_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "public_ip": { + "name": "public_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "findings_critical": { + "name": "findings_critical", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "findings_warn": { + "name": "findings_warn", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "findings_info": { + "name": "findings_info", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_security_advisor_scans_user_created_at": { + "name": "idx_security_advisor_scans_user_created_at", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_advisor_scans_created_at": { + "name": "idx_security_advisor_scans_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_advisor_scans_platform": { + "name": "idx_security_advisor_scans_platform", + "columns": [ + { + "expression": "source_platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_agent_commands": { + "name": "security_agent_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "command_type": { + "name": "command_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "operation_key": { + "name": "operation_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'accepted'" + }, + "result_code": { + "name": "result_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_metadata": { + "name": "result_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "last_error_redacted": { + "name": "last_error_redacted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_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": 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": { + "idx_security_agent_commands_org_created": { + "name": "idx_security_agent_commands_org_created", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_agent_commands_user_created": { + "name": "idx_security_agent_commands_user_created", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_agent_commands_status_updated": { + "name": "idx_security_agent_commands_status_updated", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_agent_commands_finding_created": { + "name": "idx_security_agent_commands_finding_created", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_security_agent_commands_org_operation_key": { + "name": "UQ_security_agent_commands_org_operation_key", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "operation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_agent_commands\".\"owned_by_organization_id\" IS NOT NULL AND \"security_agent_commands\".\"operation_key\" IS NOT NULL", + "concurrently": true + }, + "UQ_security_agent_commands_user_operation_key": { + "name": "UQ_security_agent_commands_user_operation_key", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "operation_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_agent_commands\".\"owned_by_user_id\" IS NOT NULL AND \"security_agent_commands\".\"operation_key\" IS NOT NULL", + "concurrently": true + } + }, + "foreignKeys": { + "security_agent_commands_owned_by_organization_id_organizations_id_fk": { + "name": "security_agent_commands_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_agent_commands", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_agent_commands_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_agent_commands_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_agent_commands", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_agent_commands_finding_id_security_findings_id_fk": { + "name": "security_agent_commands_finding_id_security_findings_id_fk", + "tableFrom": "security_agent_commands", + "columnsFrom": [ + "finding_id" + ], + "tableTo": "security_findings", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_agent_commands_owner_check": { + "name": "security_agent_commands_owner_check", + "value": "(\n (\"security_agent_commands\".\"owned_by_user_id\" IS NOT NULL AND \"security_agent_commands\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_agent_commands\".\"owned_by_user_id\" IS NULL AND \"security_agent_commands\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "security_agent_commands_type_check": { + "name": "security_agent_commands_type_check", + "value": "\"security_agent_commands\".\"command_type\" IN ('sync', 'dismiss_finding', 'start_analysis', 'apply_auto_remediation')" + }, + "security_agent_commands_origin_check": { + "name": "security_agent_commands_origin_check", + "value": "\"security_agent_commands\".\"origin\" IN ('manual', 'dashboard_refresh', 'enable_initial_sync', 'settings_include_existing')" + }, + "security_agent_commands_status_check": { + "name": "security_agent_commands_status_check", + "value": "\"security_agent_commands\".\"status\" IN ('accepted', 'running', 'succeeded', 'failed', 'no_op')" + } + }, + "isRLSEnabled": false + }, + "public.security_agent_repository_sync_state": { + "name": "security_agent_repository_sync_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_attempted_at": { + "name": "last_attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_succeeded_at": { + "name": "last_succeeded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_failure_code": { + "name": "last_failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_security_agent_repository_sync_state_org_repo": { + "name": "UQ_security_agent_repository_sync_state_org_repo", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_agent_repository_sync_state\".\"owned_by_organization_id\" is not null", + "concurrently": false + }, + "UQ_security_agent_repository_sync_state_user_repo": { + "name": "UQ_security_agent_repository_sync_state_user_repo", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_agent_repository_sync_state\".\"owned_by_user_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "security_agent_repository_sync_state_owned_by_organization_id_organizations_id_fk": { + "name": "security_agent_repository_sync_state_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_agent_repository_sync_state", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_agent_repository_sync_state_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_agent_repository_sync_state_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_agent_repository_sync_state", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_agent_repository_sync_state_owner_check": { + "name": "security_agent_repository_sync_state_owner_check", + "value": "(\n (\"security_agent_repository_sync_state\".\"owned_by_user_id\" IS NOT NULL AND \"security_agent_repository_sync_state\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_agent_repository_sync_state\".\"owned_by_user_id\" IS NULL AND \"security_agent_repository_sync_state\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.security_analysis_owner_state": { + "name": "security_analysis_owner_state", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auto_analysis_enabled_at": { + "name": "auto_analysis_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "blocked_until": { + "name": "blocked_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "block_reason": { + "name": "block_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "consecutive_actor_resolution_failures": { + "name": "consecutive_actor_resolution_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "last_actor_resolution_failure_at": { + "name": "last_actor_resolution_failure_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": { + "UQ_security_analysis_owner_state_org_owner": { + "name": "UQ_security_analysis_owner_state_org_owner", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_analysis_owner_state\".\"owned_by_organization_id\" is not null", + "concurrently": false + }, + "UQ_security_analysis_owner_state_user_owner": { + "name": "UQ_security_analysis_owner_state_user_owner", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_analysis_owner_state\".\"owned_by_user_id\" is not null", + "concurrently": false + } + }, + "foreignKeys": { + "security_analysis_owner_state_owned_by_organization_id_organizations_id_fk": { + "name": "security_analysis_owner_state_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_analysis_owner_state", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_analysis_owner_state_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_analysis_owner_state_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_analysis_owner_state", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_analysis_owner_state_owner_check": { + "name": "security_analysis_owner_state_owner_check", + "value": "(\n (\"security_analysis_owner_state\".\"owned_by_user_id\" IS NOT NULL AND \"security_analysis_owner_state\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_analysis_owner_state\".\"owned_by_user_id\" IS NULL AND \"security_analysis_owner_state\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "security_analysis_owner_state_block_reason_check": { + "name": "security_analysis_owner_state_block_reason_check", + "value": "\"security_analysis_owner_state\".\"block_reason\" IS NULL OR \"security_analysis_owner_state\".\"block_reason\" IN ('INSUFFICIENT_CREDITS', 'ACTOR_RESOLUTION_FAILED', 'OPERATOR_PAUSE')" + } + }, + "isRLSEnabled": false + }, + "public.security_analysis_queue": { + "name": "security_analysis_queue", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "queue_status": { + "name": "queue_status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "severity_rank": { + "name": "severity_rank", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "admitted_config_revision": { + "name": "admitted_config_revision", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_by_job_id": { + "name": "claimed_by_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_token": { + "name": "claim_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "reopen_requeue_count": { + "name": "reopen_requeue_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error_redacted": { + "name": "last_error_redacted", + "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": { + "UQ_security_analysis_queue_finding_id": { + "name": "UQ_security_analysis_queue_finding_id", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_analysis_queue_claim_path_org": { + "name": "idx_security_analysis_queue_claim_path_org", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "severity_rank", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" = 'queued'", + "concurrently": false + }, + "idx_security_analysis_queue_claim_path_user": { + "name": "idx_security_analysis_queue_claim_path_user", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "severity_rank", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" = 'queued'", + "concurrently": false + }, + "idx_security_analysis_queue_in_flight_org": { + "name": "idx_security_analysis_queue_in_flight_org", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queue_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" IN ('pending', 'running')", + "concurrently": false + }, + "idx_security_analysis_queue_in_flight_user": { + "name": "idx_security_analysis_queue_in_flight_user", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queue_status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" IN ('pending', 'running')", + "concurrently": false + }, + "idx_security_analysis_queue_lag_dashboards": { + "name": "idx_security_analysis_queue_lag_dashboards", + "columns": [ + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" = 'queued'", + "concurrently": false + }, + "idx_security_analysis_queue_pending_reconciliation": { + "name": "idx_security_analysis_queue_pending_reconciliation", + "columns": [ + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" = 'pending'", + "concurrently": false + }, + "idx_security_analysis_queue_running_reconciliation": { + "name": "idx_security_analysis_queue_running_reconciliation", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"queue_status\" = 'running'", + "concurrently": false + }, + "idx_security_analysis_queue_failure_trend": { + "name": "idx_security_analysis_queue_failure_trend", + "columns": [ + { + "expression": "failure_code", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_analysis_queue\".\"failure_code\" IS NOT NULL", + "concurrently": false + } + }, + "foreignKeys": { + "security_analysis_queue_finding_id_security_findings_id_fk": { + "name": "security_analysis_queue_finding_id_security_findings_id_fk", + "tableFrom": "security_analysis_queue", + "columnsFrom": [ + "finding_id" + ], + "tableTo": "security_findings", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_analysis_queue_owned_by_organization_id_organizations_id_fk": { + "name": "security_analysis_queue_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_analysis_queue", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_analysis_queue_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_analysis_queue_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_analysis_queue", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_analysis_queue_owner_check": { + "name": "security_analysis_queue_owner_check", + "value": "(\n (\"security_analysis_queue\".\"owned_by_user_id\" IS NOT NULL AND \"security_analysis_queue\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_analysis_queue\".\"owned_by_user_id\" IS NULL AND \"security_analysis_queue\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "security_analysis_queue_status_check": { + "name": "security_analysis_queue_status_check", + "value": "\"security_analysis_queue\".\"queue_status\" IN ('queued', 'pending', 'running', 'failed', 'completed')" + }, + "security_analysis_queue_claim_token_required_check": { + "name": "security_analysis_queue_claim_token_required_check", + "value": "\"security_analysis_queue\".\"queue_status\" NOT IN ('pending', 'running') OR \"security_analysis_queue\".\"claim_token\" IS NOT NULL" + }, + "security_analysis_queue_attempt_count_non_negative_check": { + "name": "security_analysis_queue_attempt_count_non_negative_check", + "value": "\"security_analysis_queue\".\"attempt_count\" >= 0" + }, + "security_analysis_queue_reopen_requeue_count_non_negative_check": { + "name": "security_analysis_queue_reopen_requeue_count_non_negative_check", + "value": "\"security_analysis_queue\".\"reopen_requeue_count\" >= 0" + }, + "security_analysis_queue_severity_rank_check": { + "name": "security_analysis_queue_severity_rank_check", + "value": "\"security_analysis_queue\".\"severity_rank\" IN (0, 1, 2, 3)" + }, + "security_analysis_queue_failure_code_check": { + "name": "security_analysis_queue_failure_code_check", + "value": "\"security_analysis_queue\".\"failure_code\" IS NULL OR \"security_analysis_queue\".\"failure_code\" IN (\n 'NETWORK_TIMEOUT',\n 'UPSTREAM_5XX',\n 'TEMP_TOKEN_FAILURE',\n 'START_CALL_AMBIGUOUS',\n 'REQUEUE_TEMPORARY_PRECONDITION',\n 'ACTOR_RESOLUTION_FAILED',\n 'GITHUB_TOKEN_UNAVAILABLE',\n 'INVALID_CONFIG',\n 'MISSING_OWNERSHIP',\n 'PERMISSION_DENIED_PERMANENT',\n 'UNSUPPORTED_SEVERITY',\n 'INSUFFICIENT_CREDITS',\n 'STATE_GUARD_REJECTED',\n 'SKIPPED_ALREADY_IN_PROGRESS',\n 'SKIPPED_NO_LONGER_ELIGIBLE',\n 'REOPEN_LOOP_GUARD',\n 'RUN_LOST'\n )" + } + }, + "isRLSEnabled": false + }, + "public.security_audit_log": { + "name": "security_audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_email": { + "name": "actor_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_type": { + "name": "resource_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_id": { + "name": "resource_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "before_state": { + "name": "before_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "after_state": { + "name": "after_state", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "source_occurred_at": { + "name": "source_occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "event_key": { + "name": "event_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schema_version": { + "name": "schema_version", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "finding_snapshot": { + "name": "finding_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "source_context": { + "name": "source_context", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_security_audit_log_org_created": { + "name": "IDX_security_audit_log_org_created", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_security_audit_log_user_created": { + "name": "IDX_security_audit_log_user_created", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_security_audit_log_resource": { + "name": "IDX_security_audit_log_resource", + "columns": [ + { + "expression": "resource_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "resource_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_security_audit_log_actor": { + "name": "IDX_security_audit_log_actor", + "columns": [ + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_security_audit_log_action": { + "name": "IDX_security_audit_log_action", + "columns": [ + { + "expression": "action", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_security_audit_log_org_event_key": { + "name": "UQ_security_audit_log_org_event_key", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_audit_log\".\"owned_by_organization_id\" IS NOT NULL AND \"security_audit_log\".\"event_key\" IS NOT NULL", + "concurrently": false + }, + "UQ_security_audit_log_user_event_key": { + "name": "UQ_security_audit_log_user_event_key", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_audit_log\".\"owned_by_user_id\" IS NOT NULL AND \"security_audit_log\".\"event_key\" IS NOT NULL", + "concurrently": false + }, + "IDX_security_audit_log_org_occurred": { + "name": "IDX_security_audit_log_org_occurred", + "columns": [ + { + "expression": "owned_by_organization_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, + "with": {}, + "method": "btree", + "where": "\"security_audit_log\".\"owned_by_organization_id\" IS NOT NULL AND \"security_audit_log\".\"occurred_at\" IS NOT NULL", + "concurrently": false + }, + "IDX_security_audit_log_user_occurred": { + "name": "IDX_security_audit_log_user_occurred", + "columns": [ + { + "expression": "owned_by_user_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, + "with": {}, + "method": "btree", + "where": "\"security_audit_log\".\"owned_by_user_id\" IS NOT NULL AND \"security_audit_log\".\"occurred_at\" IS NOT NULL", + "concurrently": false + } + }, + "foreignKeys": { + "security_audit_log_owned_by_organization_id_organizations_id_fk": { + "name": "security_audit_log_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_audit_log", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_audit_log_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_audit_log_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_audit_log", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_audit_log_owner_check": { + "name": "security_audit_log_owner_check", + "value": "(\"security_audit_log\".\"owned_by_user_id\" IS NOT NULL AND \"security_audit_log\".\"owned_by_organization_id\" IS NULL) OR (\"security_audit_log\".\"owned_by_user_id\" IS NULL AND \"security_audit_log\".\"owned_by_organization_id\" IS NOT NULL)" + }, + "security_audit_log_action_check": { + "name": "security_audit_log_action_check", + "value": "\"security_audit_log\".\"action\" IN ('security.finding.created', 'security.finding.severity_changed', 'security.finding.status_change', 'security.finding.dismissed', 'security.finding.auto_dismissed', 'security.finding.superseded', 'security.finding.analysis_started', 'security.finding.analysis_completed', 'security.finding.analysis_failed', 'security.remediation.queued', 'security.remediation.started', 'security.remediation.pr_opened', 'security.remediation.failed', 'security.remediation.blocked', 'security.remediation.no_changes_needed', 'security.remediation.cancelled', 'security.remediation.retried', 'security.finding.deleted', 'security.config.enabled', 'security.config.disabled', 'security.config.updated', 'security.sync.triggered', 'security.sync.completed', 'security.audit_log.exported', 'security.audit_report.generated')" + }, + "security_audit_log_actor_type_check": { + "name": "security_audit_log_actor_type_check", + "value": "\"security_audit_log\".\"actor_type\" IN ('customer_user', 'kilo_admin', 'system')" + }, + "security_audit_log_source_context_check": { + "name": "security_audit_log_source_context_check", + "value": "\"security_audit_log\".\"source_context\" IN ('security_sync', 'web', 'analysis_worker', 'remediation_callback', 'rollout_baseline')" + } + }, + "isRLSEnabled": false + }, + "public.security_finding_notifications": { + "name": "security_finding_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recipient_user_id": { + "name": "recipient_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'staged'" + }, + "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": true, + "default": "now()" + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "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()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "uq_security_finding_notifications_finding_recipient_kind": { + "name": "uq_security_finding_notifications_finding_recipient_kind", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recipient_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_finding_notifications_pending": { + "name": "idx_security_finding_notifications_pending", + "columns": [ + { + "expression": "next_attempt_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_finding_notifications\".\"status\" = 'pending'", + "concurrently": false + }, + "idx_security_finding_notifications_staged": { + "name": "idx_security_finding_notifications_staged", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_finding_notifications\".\"status\" = 'staged'", + "concurrently": false + }, + "idx_security_finding_notifications_finding_id": { + "name": "idx_security_finding_notifications_finding_id", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_finding_notifications_recipient_user_id": { + "name": "idx_security_finding_notifications_recipient_user_id", + "columns": [ + { + "expression": "recipient_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "security_finding_notifications_finding_fk": { + "name": "security_finding_notifications_finding_fk", + "tableFrom": "security_finding_notifications", + "columnsFrom": [ + "finding_id" + ], + "tableTo": "security_findings", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_finding_notifications_recipient_fk": { + "name": "security_finding_notifications_recipient_fk", + "tableFrom": "security_finding_notifications", + "columnsFrom": [ + "recipient_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_finding_notifications_kind_check": { + "name": "security_finding_notifications_kind_check", + "value": "\"security_finding_notifications\".\"kind\" IN ('new_finding', 'sla_warning', 'sla_breach')" + }, + "security_finding_notifications_status_check": { + "name": "security_finding_notifications_status_check", + "value": "\"security_finding_notifications\".\"status\" IN ('staged', 'pending', 'sending', 'sent', 'failed', 'cancelled')" + }, + "security_finding_notifications_attempt_count_check": { + "name": "security_finding_notifications_attempt_count_check", + "value": "\"security_finding_notifications\".\"attempt_count\" >= 0" + }, + "security_finding_notifications_claimed_at_check": { + "name": "security_finding_notifications_claimed_at_check", + "value": "(\n (\"security_finding_notifications\".\"status\" = 'sending' AND \"security_finding_notifications\".\"claimed_at\" IS NOT NULL) OR\n (\"security_finding_notifications\".\"status\" <> 'sending' AND \"security_finding_notifications\".\"claimed_at\" IS NULL)\n )" + }, + "security_finding_notifications_sent_at_check": { + "name": "security_finding_notifications_sent_at_check", + "value": "(\n (\"security_finding_notifications\".\"status\" = 'sent' AND \"security_finding_notifications\".\"sent_at\" IS NOT NULL) OR\n (\"security_finding_notifications\".\"status\" <> 'sent' AND \"security_finding_notifications\".\"sent_at\" IS NULL)\n )" + }, + "security_finding_notifications_error_message_length_check": { + "name": "security_finding_notifications_error_message_length_check", + "value": "\"security_finding_notifications\".\"error_message\" IS NULL OR length(\"security_finding_notifications\".\"error_message\") <= 500" + } + }, + "isRLSEnabled": false + }, + "public.security_findings": { + "name": "security_findings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ghsa_id": { + "name": "ghsa_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cve_id": { + "name": "cve_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "package_name": { + "name": "package_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "package_ecosystem": { + "name": "package_ecosystem", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "vulnerable_version_range": { + "name": "vulnerable_version_range", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "patched_version": { + "name": "patched_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "manifest_path": { + "name": "manifest_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "ignored_reason": { + "name": "ignored_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ignored_by": { + "name": "ignored_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fixed_at": { + "name": "fixed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sla_due_at": { + "name": "sla_due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "dependabot_html_url": { + "name": "dependabot_html_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cwe_ids": { + "name": "cwe_ids", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "cvss_score": { + "name": "cvss_score", + "type": "numeric(3, 1)", + "primaryKey": false, + "notNull": false + }, + "dependency_scope": { + "name": "dependency_scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cli_session_id": { + "name": "cli_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analysis_status": { + "name": "analysis_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analysis_started_at": { + "name": "analysis_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "analysis_completed_at": { + "name": "analysis_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "analysis_error": { + "name": "analysis_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analysis": { + "name": "analysis", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "raw_data": { + "name": "raw_data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "first_detected_at": { + "name": "first_detected_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_synced_at": { + "name": "last_synced_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": { + "uq_security_findings_user_source": { + "name": "uq_security_findings_user_source", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_findings\".\"owned_by_user_id\" IS NOT NULL", + "concurrently": false + }, + "uq_security_findings_org_source": { + "name": "uq_security_findings_org_source", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_findings\".\"owned_by_organization_id\" IS NOT NULL", + "concurrently": false + }, + "idx_security_findings_org_id": { + "name": "idx_security_findings_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_user_id": { + "name": "idx_security_findings_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_repo": { + "name": "idx_security_findings_repo", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_severity": { + "name": "idx_security_findings_severity", + "columns": [ + { + "expression": "severity", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_status": { + "name": "idx_security_findings_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_package": { + "name": "idx_security_findings_package", + "columns": [ + { + "expression": "package_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_sla_due_at": { + "name": "idx_security_findings_sla_due_at", + "columns": [ + { + "expression": "sla_due_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_session_id": { + "name": "idx_security_findings_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_cli_session_id": { + "name": "idx_security_findings_cli_session_id", + "columns": [ + { + "expression": "cli_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_analysis_status": { + "name": "idx_security_findings_analysis_status", + "columns": [ + { + "expression": "analysis_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_findings_org_analysis_in_flight": { + "name": "idx_security_findings_org_analysis_in_flight", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "analysis_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_findings\".\"analysis_status\" IN ('pending', 'running')", + "concurrently": false + }, + "idx_security_findings_user_analysis_in_flight": { + "name": "idx_security_findings_user_analysis_in_flight", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "analysis_status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_findings\".\"analysis_status\" IN ('pending', 'running')", + "concurrently": false + } + }, + "foreignKeys": { + "security_findings_owned_by_organization_id_organizations_id_fk": { + "name": "security_findings_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_findings", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_findings_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_findings_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_findings", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_findings_platform_integration_id_platform_integrations_id_fk": { + "name": "security_findings_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "security_findings", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_findings_owner_check": { + "name": "security_findings_owner_check", + "value": "(\n (\"security_findings\".\"owned_by_user_id\" IS NOT NULL AND \"security_findings\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_findings\".\"owned_by_user_id\" IS NULL AND \"security_findings\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.security_remediation_attempts": { + "name": "security_remediation_attempts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "remediation_id": { + "name": "remediation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "attempt_number": { + "name": "attempt_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "retry_of_attempt_id": { + "name": "retry_of_attempt_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "requested_by_user_id": { + "name": "requested_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "analysis_fingerprint": { + "name": "analysis_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "analysis_completed_at": { + "name": "analysis_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "remediation_model_slug": { + "name": "remediation_model_slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "branch_name": { + "name": "branch_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kilo_session_id": { + "name": "kilo_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "execution_id": { + "name": "execution_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "priority": { + "name": "priority", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 50 + }, + "claim_token": { + "name": "claim_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_by_job_id": { + "name": "claimed_by_job_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "launch_attempt_count": { + "name": "launch_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "callback_attempt_token_hash": { + "name": "callback_attempt_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blocked_reason": { + "name": "blocked_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error_redacted": { + "name": "last_error_redacted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "structured_result": { + "name": "structured_result", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "final_assistant_message": { + "name": "final_assistant_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "validation_evidence": { + "name": "validation_evidence", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "risk_notes": { + "name": "risk_notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "draft_reason": { + "name": "draft_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "pr_draft": { + "name": "pr_draft", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "pr_head_branch": { + "name": "pr_head_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_base_branch": { + "name": "pr_base_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cancellation_requested_at": { + "name": "cancellation_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_requested_by_user_id": { + "name": "cancellation_requested_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "queued_at": { + "name": "queued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "launched_at": { + "name": "launched_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": { + "UQ_security_remediation_attempts_number": { + "name": "UQ_security_remediation_attempts_number", + "columns": [ + { + "expression": "remediation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "attempt_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_security_remediation_attempts_active_finding": { + "name": "UQ_security_remediation_attempts_active_finding", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('queued', 'launching', 'running')", + "concurrently": false + }, + "UQ_security_remediation_attempts_active_remediation": { + "name": "UQ_security_remediation_attempts_active_remediation", + "columns": [ + { + "expression": "remediation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('queued', 'launching', 'running')", + "concurrently": false + }, + "UQ_security_remediation_attempts_finding_fingerprint_terminal": { + "name": "UQ_security_remediation_attempts_finding_fingerprint_terminal", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "analysis_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('queued', 'launching', 'running', 'pr_opened')", + "concurrently": false + }, + "idx_security_remediation_attempts_org_claim": { + "name": "idx_security_remediation_attempts_org_claim", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" = 'queued'", + "concurrently": false + }, + "idx_security_remediation_attempts_user_claim": { + "name": "idx_security_remediation_attempts_user_claim", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" = 'queued'", + "concurrently": false + }, + "idx_security_remediation_attempts_repo_claim": { + "name": "idx_security_remediation_attempts_repo_claim", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "queued_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" = 'queued'", + "concurrently": false + }, + "idx_security_remediation_attempts_org_inflight": { + "name": "idx_security_remediation_attempts_org_inflight", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('launching', 'running')", + "concurrently": false + }, + "idx_security_remediation_attempts_user_inflight": { + "name": "idx_security_remediation_attempts_user_inflight", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('launching', 'running')", + "concurrently": false + }, + "idx_security_remediation_attempts_repo_inflight": { + "name": "idx_security_remediation_attempts_repo_inflight", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "claimed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"security_remediation_attempts\".\"status\" IN ('launching', 'running')", + "concurrently": false + }, + "idx_security_remediation_attempts_cloud_agent_session": { + "name": "idx_security_remediation_attempts_cloud_agent_session", + "columns": [ + { + "expression": "cloud_agent_session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_remediation_attempts_finding_fingerprint": { + "name": "idx_security_remediation_attempts_finding_fingerprint", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "analysis_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "security_remediation_attempts_remediation_id_security_remediations_id_fk": { + "name": "security_remediation_attempts_remediation_id_security_remediations_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "remediation_id" + ], + "tableTo": "security_remediations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediation_attempts_finding_id_security_findings_id_fk": { + "name": "security_remediation_attempts_finding_id_security_findings_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "finding_id" + ], + "tableTo": "security_findings", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediation_attempts_owned_by_organization_id_organizations_id_fk": { + "name": "security_remediation_attempts_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediation_attempts_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_remediation_attempts_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediation_attempts_requested_by_user_id_kilocode_users_id_fk": { + "name": "security_remediation_attempts_requested_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "requested_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "security_remediation_attempts_cancellation_requested_by_user_id_kilocode_users_id_fk": { + "name": "security_remediation_attempts_cancellation_requested_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_remediation_attempts", + "columnsFrom": [ + "cancellation_requested_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_remediation_attempts_owner_check": { + "name": "security_remediation_attempts_owner_check", + "value": "(\n (\"security_remediation_attempts\".\"owned_by_user_id\" IS NOT NULL AND \"security_remediation_attempts\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_remediation_attempts\".\"owned_by_user_id\" IS NULL AND \"security_remediation_attempts\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "security_remediation_attempts_status_check": { + "name": "security_remediation_attempts_status_check", + "value": "\"security_remediation_attempts\".\"status\" IN ('queued', 'launching', 'running', 'pr_opened', 'failed', 'blocked', 'no_changes_needed', 'cancelled')" + }, + "security_remediation_attempts_origin_check": { + "name": "security_remediation_attempts_origin_check", + "value": "\"security_remediation_attempts\".\"origin\" IN ('auto_policy', 'bulk_existing', 'manual')" + }, + "security_remediation_attempts_attempt_number_check": { + "name": "security_remediation_attempts_attempt_number_check", + "value": "\"security_remediation_attempts\".\"attempt_number\" >= 1" + }, + "security_remediation_attempts_launch_attempt_count_check": { + "name": "security_remediation_attempts_launch_attempt_count_check", + "value": "\"security_remediation_attempts\".\"launch_attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.security_remediations": { + "name": "security_remediations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "finding_id": { + "name": "finding_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "repo_full_name": { + "name": "repo_full_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "latest_attempt_id": { + "name": "latest_attempt_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "latest_analysis_fingerprint": { + "name": "latest_analysis_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "latest_analysis_completed_at": { + "name": "latest_analysis_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "pr_draft": { + "name": "pr_draft", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "pr_head_branch": { + "name": "pr_head_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_base_branch": { + "name": "pr_base_branch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "blocked_reason": { + "name": "blocked_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outcome_summary": { + "name": "outcome_summary", + "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": { + "UQ_security_remediations_finding_id": { + "name": "UQ_security_remediations_finding_id", + "columns": [ + { + "expression": "finding_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_remediations_org_status": { + "name": "idx_security_remediations_org_status", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_remediations_user_status": { + "name": "idx_security_remediations_user_status", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_remediations_repo_status": { + "name": "idx_security_remediations_repo_status", + "columns": [ + { + "expression": "repo_full_name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_security_remediations_latest_attempt": { + "name": "idx_security_remediations_latest_attempt", + "columns": [ + { + "expression": "latest_attempt_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "security_remediations_owned_by_organization_id_organizations_id_fk": { + "name": "security_remediations_owned_by_organization_id_organizations_id_fk", + "tableFrom": "security_remediations", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediations_owned_by_user_id_kilocode_users_id_fk": { + "name": "security_remediations_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "security_remediations", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "security_remediations_finding_id_security_findings_id_fk": { + "name": "security_remediations_finding_id_security_findings_id_fk", + "tableFrom": "security_remediations", + "columnsFrom": [ + "finding_id" + ], + "tableTo": "security_findings", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "security_remediations_owner_check": { + "name": "security_remediations_owner_check", + "value": "(\n (\"security_remediations\".\"owned_by_user_id\" IS NOT NULL AND \"security_remediations\".\"owned_by_organization_id\" IS NULL) OR\n (\"security_remediations\".\"owned_by_user_id\" IS NULL AND \"security_remediations\".\"owned_by_organization_id\" IS NOT NULL)\n )" + }, + "security_remediations_status_check": { + "name": "security_remediations_status_check", + "value": "\"security_remediations\".\"status\" IN ('queued', 'running', 'pr_opened', 'failed', 'blocked', 'no_changes_needed', 'cancelled')" + } + }, + "isRLSEnabled": false + }, + "public.shared_cli_sessions": { + "name": "shared_cli_sessions", + "schema": "", + "columns": { + "share_id": { + "name": "share_id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "session_id": { + "name": "session_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "shared_state": { + "name": "shared_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'public'" + }, + "api_conversation_history_blob_url": { + "name": "api_conversation_history_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "task_metadata_blob_url": { + "name": "task_metadata_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ui_messages_blob_url": { + "name": "ui_messages_blob_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "git_state_blob_url": { + "name": "git_state_blob_url", + "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": { + "IDX_shared_cli_sessions_session_id": { + "name": "IDX_shared_cli_sessions_session_id", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_shared_cli_sessions_created_at": { + "name": "IDX_shared_cli_sessions_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "shared_cli_sessions_session_id_cli_sessions_session_id_fk": { + "name": "shared_cli_sessions_session_id_cli_sessions_session_id_fk", + "tableFrom": "shared_cli_sessions", + "columnsFrom": [ + "session_id" + ], + "tableTo": "cli_sessions", + "columnsTo": [ + "session_id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "shared_cli_sessions_kilo_user_id_kilocode_users_id_fk": { + "name": "shared_cli_sessions_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "shared_cli_sessions", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "shared_cli_sessions_shared_state_check": { + "name": "shared_cli_sessions_shared_state_check", + "value": "\"shared_cli_sessions\".\"shared_state\" IN ('public', 'organization')" + } + }, + "isRLSEnabled": false + }, + "public.slack_bot_requests": { + "name": "slack_bot_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "slack_team_id": { + "name": "slack_team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_team_name": { + "name": "slack_team_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_channel_id": { + "name": "slack_channel_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_user_id": { + "name": "slack_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_thread_ts": { + "name": "slack_thread_ts", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_message": { + "name": "user_message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_message_truncated": { + "name": "user_message_truncated", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_time_ms": { + "name": "response_time_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "model_used": { + "name": "model_used", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tool_calls_made": { + "name": "tool_calls_made", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "cloud_agent_session_id": { + "name": "cloud_agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_slack_bot_requests_created_at": { + "name": "idx_slack_bot_requests_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_slack_team_id": { + "name": "idx_slack_bot_requests_slack_team_id", + "columns": [ + { + "expression": "slack_team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_owned_by_org_id": { + "name": "idx_slack_bot_requests_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_owned_by_user_id": { + "name": "idx_slack_bot_requests_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_status": { + "name": "idx_slack_bot_requests_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_event_type": { + "name": "idx_slack_bot_requests_event_type", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_slack_bot_requests_team_created": { + "name": "idx_slack_bot_requests_team_created", + "columns": [ + { + "expression": "slack_team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "slack_bot_requests_owned_by_organization_id_organizations_id_fk": { + "name": "slack_bot_requests_owned_by_organization_id_organizations_id_fk", + "tableFrom": "slack_bot_requests", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "slack_bot_requests_owned_by_user_id_kilocode_users_id_fk": { + "name": "slack_bot_requests_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "slack_bot_requests", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "slack_bot_requests_platform_integration_id_platform_integrations_id_fk": { + "name": "slack_bot_requests_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "slack_bot_requests", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_bot_requests_owner_check": { + "name": "slack_bot_requests_owner_check", + "value": "(\n (\"slack_bot_requests\".\"owned_by_user_id\" IS NOT NULL AND \"slack_bot_requests\".\"owned_by_organization_id\" IS NULL) OR\n (\"slack_bot_requests\".\"owned_by_user_id\" IS NULL AND \"slack_bot_requests\".\"owned_by_organization_id\" IS NOT NULL) OR\n (\"slack_bot_requests\".\"owned_by_user_id\" IS NULL AND \"slack_bot_requests\".\"owned_by_organization_id\" IS NULL)\n )" + } + }, + "isRLSEnabled": false + }, + "public.slack_oauth_credentials": { + "name": "slack_oauth_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "platform_integration_id": { + "name": "platform_integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "slack_team_id": { + "name": "slack_team_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slack_enterprise_id": { + "name": "slack_enterprise_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_enterprise_install": { + "name": "is_enterprise_install", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_encrypted": { + "name": "access_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_encrypted": { + "name": "refresh_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_scopes": { + "name": "granted_scopes", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "credential_version": { + "name": "credential_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "refresh_claimed_at": { + "name": "refresh_claimed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_attempt_count": { + "name": "refresh_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_refresh_attempt_at": { + "name": "next_refresh_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_refreshed_at": { + "name": "last_refreshed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_reason": { + "name": "revocation_reason", + "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": { + "UQ_slack_oauth_credentials_platform_integration_id": { + "name": "UQ_slack_oauth_credentials_platform_integration_id", + "columns": [ + { + "expression": "platform_integration_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_slack_oauth_credentials_slack_team_id": { + "name": "IDX_slack_oauth_credentials_slack_team_id", + "columns": [ + { + "expression": "slack_team_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_slack_oauth_credentials_refresh_due": { + "name": "IDX_slack_oauth_credentials_refresh_due", + "columns": [ + { + "expression": "access_token_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"slack_oauth_credentials\".\"revoked_at\" is null", + "concurrently": false + } + }, + "foreignKeys": { + "slack_oauth_credentials_platform_integration_id_platform_integrations_id_fk": { + "name": "slack_oauth_credentials_platform_integration_id_platform_integrations_id_fk", + "tableFrom": "slack_oauth_credentials", + "columnsFrom": [ + "platform_integration_id" + ], + "tableTo": "platform_integrations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "slack_oauth_credentials_credential_version_check": { + "name": "slack_oauth_credentials_credential_version_check", + "value": "\"slack_oauth_credentials\".\"credential_version\" > 0" + }, + "slack_oauth_credentials_refresh_attempt_count_check": { + "name": "slack_oauth_credentials_refresh_attempt_count_check", + "value": "\"slack_oauth_credentials\".\"refresh_attempt_count\" >= 0" + }, + "slack_oauth_credentials_slack_team_id_check": { + "name": "slack_oauth_credentials_slack_team_id_check", + "value": "\"slack_oauth_credentials\".\"slack_team_id\" <> ''" + } + }, + "isRLSEnabled": false + }, + "public.source_embeddings": { + "name": "source_embeddings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "embedding": { + "name": "embedding", + "type": "vector(1536)", + "primaryKey": false, + "notNull": true + }, + "file_path": { + "name": "file_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_hash": { + "name": "file_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_line": { + "name": "start_line", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "end_line": { + "name": "end_line", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "git_branch": { + "name": "git_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "is_base_branch": { + "name": "is_base_branch", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": { + "IDX_source_embeddings_organization_id": { + "name": "IDX_source_embeddings_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_kilo_user_id": { + "name": "IDX_source_embeddings_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_project_id": { + "name": "IDX_source_embeddings_project_id", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_created_at": { + "name": "IDX_source_embeddings_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_updated_at": { + "name": "IDX_source_embeddings_updated_at", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_file_path_lower": { + "name": "IDX_source_embeddings_file_path_lower", + "columns": [ + { + "expression": "LOWER(\"file_path\")", + "isExpression": true, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_git_branch": { + "name": "IDX_source_embeddings_git_branch", + "columns": [ + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_source_embeddings_org_project_branch": { + "name": "IDX_source_embeddings_org_project_branch", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "git_branch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "source_embeddings_organization_id_organizations_id_fk": { + "name": "source_embeddings_organization_id_organizations_id_fk", + "tableFrom": "source_embeddings", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "source_embeddings_kilo_user_id_kilocode_users_id_fk": { + "name": "source_embeddings_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "source_embeddings", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_source_embeddings_org_project_branch_file_lines": { + "name": "UQ_source_embeddings_org_project_branch_file_lines", + "columns": [ + "organization_id", + "project_id", + "git_branch", + "file_path", + "start_line", + "end_line" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.stripe_dispute_actions": { + "name": "stripe_dispute_actions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "case_id": { + "name": "case_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "action_type": { + "name": "action_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_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 + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "terminal_at": { + "name": "terminal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "result_code": { + "name": "result_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_reference_id": { + "name": "result_reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_context": { + "name": "failure_context", + "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": { + "IDX_stripe_dispute_actions_case_id": { + "name": "IDX_stripe_dispute_actions_case_id", + "columns": [ + { + "expression": "case_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_actions_claim_path": { + "name": "IDX_stripe_dispute_actions_claim_path", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "stripe_dispute_actions_case_id_stripe_dispute_cases_id_fk": { + "name": "stripe_dispute_actions_case_id_stripe_dispute_cases_id_fk", + "tableFrom": "stripe_dispute_actions", + "columnsFrom": [ + "case_id" + ], + "tableTo": "stripe_dispute_cases", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_stripe_dispute_actions_case_type_target": { + "name": "UQ_stripe_dispute_actions_case_type_target", + "columns": [ + "case_id", + "action_type", + "target_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "stripe_dispute_actions_action_type_check": { + "name": "stripe_dispute_actions_action_type_check", + "value": "\"stripe_dispute_actions\".\"action_type\" IN ('stripe_acceptance', 'user_block', 'auto_top_up_disable', 'credit_balance_reset', 'subscription_cancellation', 'access_termination', 'kiloclaw_suspension')" + }, + "stripe_dispute_actions_status_check": { + "name": "stripe_dispute_actions_status_check", + "value": "\"stripe_dispute_actions\".\"status\" IN ('queued', 'processing', 'completed', 'failed', 'skipped')" + }, + "stripe_dispute_actions_attempt_count_non_negative_check": { + "name": "stripe_dispute_actions_attempt_count_non_negative_check", + "value": "\"stripe_dispute_actions\".\"attempt_count\" >= 0" + }, + "stripe_dispute_actions_target_key_not_empty_check": { + "name": "stripe_dispute_actions_target_key_not_empty_check", + "value": "length(\"stripe_dispute_actions\".\"target_key\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.stripe_dispute_cases": { + "name": "stripe_dispute_cases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "stripe_dispute_id": { + "name": "stripe_dispute_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_event_id": { + "name": "stripe_event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_event_created_at": { + "name": "stripe_event_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_payment_intent_id": { + "name": "stripe_payment_intent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "amount_minor_units": { + "name": "amount_minor_units", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "currency": { + "name": "currency", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dispute_reason": { + "name": "dispute_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_status": { + "name": "stripe_status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_classification": { + "name": "owner_classification", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'needs_action'" + }, + "status_reason": { + "name": "status_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_context": { + "name": "failure_context", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_created_at": { + "name": "stripe_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "evidence_due_by": { + "name": "evidence_due_by", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "synced_at": { + "name": "synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_by_kilo_user_id": { + "name": "accepted_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "acceptance_started_at": { + "name": "acceptance_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "enforcement_completed_at": { + "name": "enforcement_completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "review_required_at": { + "name": "review_required_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "closed_at": { + "name": "closed_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": { + "IDX_stripe_dispute_cases_event_id": { + "name": "IDX_stripe_dispute_cases_event_id", + "columns": [ + { + "expression": "stripe_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_charge_id": { + "name": "IDX_stripe_dispute_cases_charge_id", + "columns": [ + { + "expression": "stripe_charge_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_payment_intent_id": { + "name": "IDX_stripe_dispute_cases_payment_intent_id", + "columns": [ + { + "expression": "stripe_payment_intent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_customer_id": { + "name": "IDX_stripe_dispute_cases_customer_id", + "columns": [ + { + "expression": "stripe_customer_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_kilo_user_id": { + "name": "IDX_stripe_dispute_cases_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_organization_id": { + "name": "IDX_stripe_dispute_cases_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_dispute_cases_status_due_by": { + "name": "IDX_stripe_dispute_cases_status_due_by", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "evidence_due_by", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stripe_created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "stripe_dispute_cases_kilo_user_id_kilocode_users_id_fk": { + "name": "stripe_dispute_cases_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "stripe_dispute_cases", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "stripe_dispute_cases_organization_id_organizations_id_fk": { + "name": "stripe_dispute_cases_organization_id_organizations_id_fk", + "tableFrom": "stripe_dispute_cases", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "stripe_dispute_cases_accepted_by_kilo_user_id_kilocode_users_id_fk": { + "name": "stripe_dispute_cases_accepted_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "stripe_dispute_cases", + "columnsFrom": [ + "accepted_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_stripe_dispute_cases_dispute_id": { + "name": "UQ_stripe_dispute_cases_dispute_id", + "columns": [ + "stripe_dispute_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "stripe_dispute_cases_owner_classification_check": { + "name": "stripe_dispute_cases_owner_classification_check", + "value": "\"stripe_dispute_cases\".\"owner_classification\" IN ('personal', 'organization', 'ambiguous', 'unmatched')" + }, + "stripe_dispute_cases_status_check": { + "name": "stripe_dispute_cases_status_check", + "value": "\"stripe_dispute_cases\".\"status\" IN ('needs_action', 'processing', 'accepted', 'acceptance_failed', 'enforcement_failed', 'review_required', 'closed')" + }, + "stripe_dispute_cases_amount_minor_units_non_negative_check": { + "name": "stripe_dispute_cases_amount_minor_units_non_negative_check", + "value": "\"stripe_dispute_cases\".\"amount_minor_units\" IS NULL OR \"stripe_dispute_cases\".\"amount_minor_units\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.stripe_early_fraud_warning_actions": { + "name": "stripe_early_fraud_warning_actions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "case_id": { + "name": "case_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "action_type": { + "name": "action_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_key": { + "name": "target_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_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 + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "terminal_at": { + "name": "terminal_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "result_code": { + "name": "result_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "result_reference_id": { + "name": "result_reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_context": { + "name": "failure_context", + "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": { + "IDX_stripe_early_fraud_warning_actions_case_id": { + "name": "IDX_stripe_early_fraud_warning_actions_case_id", + "columns": [ + { + "expression": "case_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_actions_claim_path": { + "name": "IDX_stripe_early_fraud_warning_actions_claim_path", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "stripe_early_fraud_warning_actions_case_id_stripe_early_fraud_warning_cases_id_fk": { + "name": "stripe_early_fraud_warning_actions_case_id_stripe_early_fraud_warning_cases_id_fk", + "tableFrom": "stripe_early_fraud_warning_actions", + "columnsFrom": [ + "case_id" + ], + "tableTo": "stripe_early_fraud_warning_cases", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_stripe_early_fraud_warning_actions_case_type_target": { + "name": "UQ_stripe_early_fraud_warning_actions_case_type_target", + "columns": [ + "case_id", + "action_type", + "target_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "stripe_early_fraud_warning_actions_action_type_check": { + "name": "stripe_early_fraud_warning_actions_action_type_check", + "value": "\"stripe_early_fraud_warning_actions\".\"action_type\" IN ('containment', 'refund', 'payment_value_clawback', 'subscription_termination', 'access_termination', 'kiloclaw_suspension', 'affiliate_payout_reversal', 'referral_reward_reversal', 'user_notice')" + }, + "stripe_early_fraud_warning_actions_status_check": { + "name": "stripe_early_fraud_warning_actions_status_check", + "value": "\"stripe_early_fraud_warning_actions\".\"status\" IN ('queued', 'processing', 'completed', 'failed', 'review_required', 'dismissed')" + }, + "stripe_early_fraud_warning_actions_attempt_count_non_negative_check": { + "name": "stripe_early_fraud_warning_actions_attempt_count_non_negative_check", + "value": "\"stripe_early_fraud_warning_actions\".\"attempt_count\" >= 0" + }, + "stripe_early_fraud_warning_actions_target_key_not_empty_check": { + "name": "stripe_early_fraud_warning_actions_target_key_not_empty_check", + "value": "length(\"stripe_early_fraud_warning_actions\".\"target_key\") > 0" + } + }, + "isRLSEnabled": false + }, + "public.stripe_early_fraud_warning_cases": { + "name": "stripe_early_fraud_warning_cases", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "stripe_early_fraud_warning_id": { + "name": "stripe_early_fraud_warning_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_event_id": { + "name": "stripe_event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_payment_intent_id": { + "name": "stripe_payment_intent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "amount_minor_units": { + "name": "amount_minor_units", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "currency": { + "name": "currency", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "owner_classification": { + "name": "owner_classification", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_context": { + "name": "failure_context", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "warning_created_at": { + "name": "warning_created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "contained_at": { + "name": "contained_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "processing_started_at": { + "name": "processing_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 + }, + "review_required_at": { + "name": "review_required_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "remediated_at": { + "name": "remediated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "dismissed_at": { + "name": "dismissed_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": { + "IDX_stripe_early_fraud_warning_cases_event_id": { + "name": "IDX_stripe_early_fraud_warning_cases_event_id", + "columns": [ + { + "expression": "stripe_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_charge_id": { + "name": "IDX_stripe_early_fraud_warning_cases_charge_id", + "columns": [ + { + "expression": "stripe_charge_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_payment_intent_id": { + "name": "IDX_stripe_early_fraud_warning_cases_payment_intent_id", + "columns": [ + { + "expression": "stripe_payment_intent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_customer_id": { + "name": "IDX_stripe_early_fraud_warning_cases_customer_id", + "columns": [ + { + "expression": "stripe_customer_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_kilo_user_id": { + "name": "IDX_stripe_early_fraud_warning_cases_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_organization_id": { + "name": "IDX_stripe_early_fraud_warning_cases_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_stripe_early_fraud_warning_cases_status_created_at": { + "name": "IDX_stripe_early_fraud_warning_cases_status_created_at", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "stripe_early_fraud_warning_cases_kilo_user_id_kilocode_users_id_fk": { + "name": "stripe_early_fraud_warning_cases_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "stripe_early_fraud_warning_cases", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + }, + "stripe_early_fraud_warning_cases_organization_id_organizations_id_fk": { + "name": "stripe_early_fraud_warning_cases_organization_id_organizations_id_fk", + "tableFrom": "stripe_early_fraud_warning_cases", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_stripe_early_fraud_warning_cases_warning_id": { + "name": "UQ_stripe_early_fraud_warning_cases_warning_id", + "columns": [ + "stripe_early_fraud_warning_id" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "stripe_early_fraud_warning_cases_owner_classification_check": { + "name": "stripe_early_fraud_warning_cases_owner_classification_check", + "value": "\"stripe_early_fraud_warning_cases\".\"owner_classification\" IN ('personal', 'organization', 'ambiguous', 'unmatched')" + }, + "stripe_early_fraud_warning_cases_status_check": { + "name": "stripe_early_fraud_warning_cases_status_check", + "value": "\"stripe_early_fraud_warning_cases\".\"status\" IN ('queued', 'contained', 'processing', 'completed', 'review_required', 'failed', 'remediated', 'dismissed')" + }, + "stripe_early_fraud_warning_cases_amount_minor_units_non_negative_check": { + "name": "stripe_early_fraud_warning_cases_amount_minor_units_non_negative_check", + "value": "\"stripe_early_fraud_warning_cases\".\"amount_minor_units\" IS NULL OR \"stripe_early_fraud_warning_cases\".\"amount_minor_units\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.stytch_fingerprints": { + "name": "stytch_fingerprints", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visitor_fingerprint": { + "name": "visitor_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "browser_fingerprint": { + "name": "browser_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "browser_id": { + "name": "browser_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hardware_fingerprint": { + "name": "hardware_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "network_fingerprint": { + "name": "network_fingerprint", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "visitor_id": { + "name": "visitor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verdict_action": { + "name": "verdict_action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "detected_device_type": { + "name": "detected_device_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "is_authentic_device": { + "name": "is_authentic_device", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "reasons": { + "name": "reasons", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{\"\"}'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "status_code": { + "name": "status_code", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fingerprint_data": { + "name": "fingerprint_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "kilo_free_tier_allowed": { + "name": "kilo_free_tier_allowed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "http_x_forwarded_for": { + "name": "http_x_forwarded_for", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_city": { + "name": "http_x_vercel_ip_city", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_country": { + "name": "http_x_vercel_ip_country", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_latitude": { + "name": "http_x_vercel_ip_latitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_longitude": { + "name": "http_x_vercel_ip_longitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ja4_digest": { + "name": "http_x_vercel_ja4_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_user_agent": { + "name": "http_user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_hardware_fingerprint": { + "name": "idx_hardware_fingerprint", + "columns": [ + { + "expression": "hardware_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_kilo_user_id": { + "name": "idx_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_stytch_fingerprints_reasons_gin": { + "name": "idx_stytch_fingerprints_reasons_gin", + "columns": [ + { + "expression": "reasons", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "gin", + "concurrently": false + }, + "idx_verdict_action": { + "name": "idx_verdict_action", + "columns": [ + { + "expression": "verdict_action", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "idx_visitor_fingerprint": { + "name": "idx_visitor_fingerprint", + "columns": [ + { + "expression": "visitor_fingerprint", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.system_prompt_prefix": { + "name": "system_prompt_prefix", + "schema": "", + "columns": { + "system_prompt_prefix_id": { + "name": "system_prompt_prefix_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "system_prompt_prefix": { + "name": "system_prompt_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_system_prompt_prefix": { + "name": "UQ_system_prompt_prefix", + "columns": [ + { + "expression": "system_prompt_prefix", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.transactional_email_log": { + "name": "transactional_email_log", + "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": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_type": { + "name": "email_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_transactional_email_log_type_idempotency_key": { + "name": "UQ_transactional_email_log_type_idempotency_key", + "columns": [ + { + "expression": "email_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_transactional_email_log_user_id": { + "name": "IDX_transactional_email_log_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_transactional_email_log_organization_id": { + "name": "IDX_transactional_email_log_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "transactional_email_log_user_id_kilocode_users_id_fk": { + "name": "transactional_email_log_user_id_kilocode_users_id_fk", + "tableFrom": "transactional_email_log", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "no action" + }, + "transactional_email_log_organization_id_organizations_id_fk": { + "name": "transactional_email_log_organization_id_organizations_id_fk", + "tableFrom": "transactional_email_log", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "CHK_transactional_email_log_owner": { + "name": "CHK_transactional_email_log_owner", + "value": "\"transactional_email_log\".\"user_id\" IS NOT NULL OR \"transactional_email_log\".\"organization_id\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.user_admin_notes": { + "name": "user_admin_notes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note_content": { + "name": "note_content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "admin_kilo_user_id": { + "name": "admin_kilo_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": { + "IDX_34517df0b385234babc38fe81b": { + "name": "IDX_34517df0b385234babc38fe81b", + "columns": [ + { + "expression": "admin_kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_ccbde98c4c14046daa5682ec4f": { + "name": "IDX_ccbde98c4c14046daa5682ec4f", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_d0270eb24ef6442d65a0b7853c": { + "name": "IDX_d0270eb24ef6442d65a0b7853c", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_affiliate_attributions": { + "name": "user_affiliate_attributions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tracking_id": { + "name": "tracking_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_user_affiliate_attributions_user_id": { + "name": "IDX_user_affiliate_attributions_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_affiliate_attributions_user_id_kilocode_users_id_fk": { + "name": "user_affiliate_attributions_user_id_kilocode_users_id_fk", + "tableFrom": "user_affiliate_attributions", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_user_affiliate_attributions_user_provider": { + "name": "UQ_user_affiliate_attributions_user_provider", + "columns": [ + "user_id", + "provider" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "user_affiliate_attributions_provider_check": { + "name": "user_affiliate_attributions_provider_check", + "value": "\"user_affiliate_attributions\".\"provider\" IN ('impact')" + } + }, + "isRLSEnabled": false + }, + "public.user_affiliate_events": { + "name": "user_affiliate_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_event_id": { + "name": "parent_event_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "delivery_state": { + "name": "delivery_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "payload_json": { + "name": "payload_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impact_action_id": { + "name": "impact_action_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impact_submission_uri": { + "name": "impact_submission_uri", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claimed_at": { + "name": "claimed_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": { + "IDX_user_affiliate_events_claim_path": { + "name": "IDX_user_affiliate_events_claim_path", + "columns": [ + { + "expression": "delivery_state", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"next_retry_at\", '-infinity'::timestamptz)", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_affiliate_events_parent_event_id": { + "name": "IDX_user_affiliate_events_parent_event_id", + "columns": [ + { + "expression": "parent_event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_affiliate_events_provider_event_type_charge": { + "name": "IDX_user_affiliate_events_provider_event_type_charge", + "columns": [ + { + "expression": "provider", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stripe_charge_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_affiliate_events_user_id_kilocode_users_id_fk": { + "name": "user_affiliate_events_user_id_kilocode_users_id_fk", + "tableFrom": "user_affiliate_events", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + }, + "user_affiliate_events_parent_event_id_fk": { + "name": "user_affiliate_events_parent_event_id_fk", + "tableFrom": "user_affiliate_events", + "columnsFrom": [ + "parent_event_id" + ], + "tableTo": "user_affiliate_events", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_user_affiliate_events_dedupe_key": { + "name": "UQ_user_affiliate_events_dedupe_key", + "columns": [ + "dedupe_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "user_affiliate_events_provider_check": { + "name": "user_affiliate_events_provider_check", + "value": "\"user_affiliate_events\".\"provider\" IN ('impact')" + }, + "user_affiliate_events_event_type_check": { + "name": "user_affiliate_events_event_type_check", + "value": "\"user_affiliate_events\".\"event_type\" IN ('signup', 'trial_start', 'trial_end', 'sale', 'sale_reversal')" + }, + "user_affiliate_events_delivery_state_check": { + "name": "user_affiliate_events_delivery_state_check", + "value": "\"user_affiliate_events\".\"delivery_state\" IN ('queued', 'blocked', 'sending', 'delivered', 'failed')" + }, + "user_affiliate_events_attempt_count_non_negative_check": { + "name": "user_affiliate_events_attempt_count_non_negative_check", + "value": "\"user_affiliate_events\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.user_auth_provider": { + "name": "user_auth_provider", + "schema": "", + "columns": { + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "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 + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "hosted_domain": { + "name": "hosted_domain", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_user_auth_provider_kilo_user_id": { + "name": "IDX_user_auth_provider_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_auth_provider_hosted_domain": { + "name": "IDX_user_auth_provider_hosted_domain", + "columns": [ + { + "expression": "hosted_domain", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "user_auth_provider_provider_provider_account_id_pk": { + "name": "user_auth_provider_provider_provider_account_id_pk", + "columns": [ + "provider", + "provider_account_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_data_export_object_deletions": { + "name": "user_data_export_object_deletions", + "schema": "", + "columns": { + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "multipart_upload_id": { + "name": "multipart_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'account_deletion'" + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "available_at": { + "name": "available_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": { + "IDX_user_data_export_object_deletions_ready": { + "name": "IDX_user_data_export_object_deletions_ready", + "columns": [ + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "object_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_data_export_object_deletions_reason_check": { + "name": "user_data_export_object_deletions_reason_check", + "value": "\"user_data_export_object_deletions\".\"reason\" IN ('account_deletion', 'admin_cancel', 'admin_replace')" + }, + "user_data_export_object_deletions_attempt_count_nonnegative": { + "name": "user_data_export_object_deletions_attempt_count_nonnegative", + "value": "\"user_data_export_object_deletions\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.user_data_export_outbox": { + "name": "user_data_export_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "export_id": { + "name": "export_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'generate'" + }, + "available_at": { + "name": "available_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "sent_at": { + "name": "sent_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": { + "IDX_user_data_export_outbox_pending": { + "name": "IDX_user_data_export_outbox_pending", + "columns": [ + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_export_outbox\".\"sent_at\" IS NULL", + "concurrently": false + } + }, + "foreignKeys": { + "user_data_export_outbox_export_id_user_data_exports_id_fk": { + "name": "user_data_export_outbox_export_id_user_data_exports_id_fk", + "tableFrom": "user_data_export_outbox", + "columnsFrom": [ + "export_id" + ], + "tableTo": "user_data_exports", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_user_data_export_outbox_generation_operation": { + "name": "UQ_user_data_export_outbox_generation_operation", + "columns": [ + "export_id", + "generation", + "operation" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "user_data_export_outbox_operation_check": { + "name": "user_data_export_outbox_operation_check", + "value": "\"user_data_export_outbox\".\"operation\" = 'generate'" + }, + "user_data_export_outbox_generation_nonnegative": { + "name": "user_data_export_outbox_generation_nonnegative", + "value": "\"user_data_export_outbox\".\"generation\" >= 0" + }, + "user_data_export_outbox_attempt_count_nonnegative": { + "name": "user_data_export_outbox_attempt_count_nonnegative", + "value": "\"user_data_export_outbox\".\"attempt_count\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.user_data_export_parts": { + "name": "user_data_export_parts", + "schema": "", + "columns": { + "export_id": { + "name": "export_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "part_number": { + "name": "part_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "etag": { + "name": "etag", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "user_data_export_parts_export_id_user_data_exports_id_fk": { + "name": "user_data_export_parts_export_id_user_data_exports_id_fk", + "tableFrom": "user_data_export_parts", + "columnsFrom": [ + "export_id" + ], + "tableTo": "user_data_exports", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "user_data_export_parts_export_id_part_number_pk": { + "name": "user_data_export_parts_export_id_part_number_pk", + "columns": [ + "export_id", + "part_number" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_data_export_parts_part_number_positive": { + "name": "user_data_export_parts_part_number_positive", + "value": "\"user_data_export_parts\".\"part_number\" > 0" + }, + "user_data_export_parts_size_bytes_nonnegative": { + "name": "user_data_export_parts_size_bytes_nonnegative", + "value": "\"user_data_export_parts\".\"size_bytes\" >= 0" + } + }, + "isRLSEnabled": false + }, + "public.user_data_exports": { + "name": "user_data_exports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'user'" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'queued'" + }, + "schema_version": { + "name": "schema_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "snapshot_at": { + "name": "snapshot_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "current_source": { + "name": "current_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source_cursor": { + "name": "source_cursor", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "multipart_upload_id": { + "name": "multipart_upload_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "next_part_number": { + "name": "next_part_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "dispatch_generation": { + "name": "dispatch_generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "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 + }, + "attempt_count": { + "name": "attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "row_count": { + "name": "row_count", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "size_bytes": { + "name": "size_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "r2_object_key": { + "name": "r2_object_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "r2_etag": { + "name": "r2_etag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "failure_code": { + "name": "failure_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_error_redacted": { + "name": "last_error_redacted", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_at": { + "name": "requested_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": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "email_status": { + "name": "email_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "email_attempt_count": { + "name": "email_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "email_lease_token": { + "name": "email_lease_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_lease_expires_at": { + "name": "email_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "email_sent_at": { + "name": "email_sent_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": { + "UQ_user_data_exports_single_active": { + "name": "UQ_user_data_exports_single_active", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"status\" IN ('queued', 'processing', 'finalizing') AND \"user_data_exports\".\"subject_type\" = 'user'", + "concurrently": false + }, + "UQ_user_data_exports_single_active_org": { + "name": "UQ_user_data_exports_single_active_org", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"status\" IN ('queued', 'processing', 'finalizing') AND \"user_data_exports\".\"subject_type\" = 'organization'", + "concurrently": false + }, + "IDX_user_data_exports_user_created": { + "name": "IDX_user_data_exports_user_created", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_data_exports_org_created": { + "name": "IDX_user_data_exports_org_created", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"organization_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_user_data_exports_lease_expiry": { + "name": "IDX_user_data_exports_lease_expiry", + "columns": [ + { + "expression": "lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"status\" IN ('processing', 'finalizing')", + "concurrently": false + }, + "IDX_user_data_exports_ready_expiry": { + "name": "IDX_user_data_exports_ready_expiry", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"status\" = 'ready'", + "concurrently": false + }, + "IDX_user_data_exports_failed_multipart": { + "name": "IDX_user_data_exports_failed_multipart", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"status\" = 'failed' AND \"user_data_exports\".\"multipart_upload_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_user_data_exports_email_lease_expiry": { + "name": "IDX_user_data_exports_email_lease_expiry", + "columns": [ + { + "expression": "email_lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_data_exports\".\"email_status\" = 'sending'", + "concurrently": false + } + }, + "foreignKeys": { + "user_data_exports_kilo_user_id_kilocode_users_id_fk": { + "name": "user_data_exports_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_data_exports", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + }, + "user_data_exports_organization_id_organizations_id_fk": { + "name": "user_data_exports_organization_id_organizations_id_fk", + "tableFrom": "user_data_exports", + "columnsFrom": [ + "organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "restrict" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_data_exports_status_check": { + "name": "user_data_exports_status_check", + "value": "\"user_data_exports\".\"status\" IN ('queued', 'processing', 'finalizing', 'ready', 'failed', 'expired')" + }, + "user_data_exports_subject_type_check": { + "name": "user_data_exports_subject_type_check", + "value": "\"user_data_exports\".\"subject_type\" IN ('user', 'organization')" + }, + "user_data_exports_subject_shape": { + "name": "user_data_exports_subject_shape", + "value": "(\"user_data_exports\".\"subject_type\" = 'user' AND \"user_data_exports\".\"organization_id\" IS NULL)\n OR (\"user_data_exports\".\"subject_type\" = 'organization' AND \"user_data_exports\".\"organization_id\" IS NOT NULL)" + }, + "user_data_exports_schema_version_positive": { + "name": "user_data_exports_schema_version_positive", + "value": "\"user_data_exports\".\"schema_version\" > 0" + }, + "user_data_exports_next_part_number_positive": { + "name": "user_data_exports_next_part_number_positive", + "value": "\"user_data_exports\".\"next_part_number\" > 0" + }, + "user_data_exports_dispatch_generation_nonnegative": { + "name": "user_data_exports_dispatch_generation_nonnegative", + "value": "\"user_data_exports\".\"dispatch_generation\" >= 0" + }, + "user_data_exports_attempt_count_nonnegative": { + "name": "user_data_exports_attempt_count_nonnegative", + "value": "\"user_data_exports\".\"attempt_count\" >= 0" + }, + "user_data_exports_row_count_nonnegative": { + "name": "user_data_exports_row_count_nonnegative", + "value": "\"user_data_exports\".\"row_count\" >= 0" + }, + "user_data_exports_size_bytes_nonnegative": { + "name": "user_data_exports_size_bytes_nonnegative", + "value": "\"user_data_exports\".\"size_bytes\" IS NULL OR \"user_data_exports\".\"size_bytes\" >= 0" + }, + "user_data_exports_lease_shape": { + "name": "user_data_exports_lease_shape", + "value": "(\"user_data_exports\".\"lease_token\" IS NULL) = (\"user_data_exports\".\"lease_expires_at\" IS NULL)" + }, + "user_data_exports_ready_shape": { + "name": "user_data_exports_ready_shape", + "value": "\"user_data_exports\".\"status\" <> 'ready' OR (\"user_data_exports\".\"r2_object_key\" IS NOT NULL AND \"user_data_exports\".\"size_bytes\" IS NOT NULL AND \"user_data_exports\".\"completed_at\" IS NOT NULL AND \"user_data_exports\".\"expires_at\" IS NOT NULL)" + }, + "user_data_exports_last_error_redacted_length": { + "name": "user_data_exports_last_error_redacted_length", + "value": "\"user_data_exports\".\"last_error_redacted\" IS NULL OR length(\"user_data_exports\".\"last_error_redacted\") <= 500" + }, + "user_data_exports_email_attempt_count_nonnegative": { + "name": "user_data_exports_email_attempt_count_nonnegative", + "value": "\"user_data_exports\".\"email_attempt_count\" >= 0" + }, + "user_data_exports_email_status_check": { + "name": "user_data_exports_email_status_check", + "value": "\"user_data_exports\".\"email_status\" IN ('pending', 'sending', 'sent', 'failed')" + }, + "user_data_exports_email_lease_shape": { + "name": "user_data_exports_email_lease_shape", + "value": "(\"user_data_exports\".\"email_status\" = 'sending') = (\"user_data_exports\".\"email_lease_token\" IS NOT NULL AND \"user_data_exports\".\"email_lease_expires_at\" IS NOT NULL)" + }, + "user_data_exports_email_sent_shape": { + "name": "user_data_exports_email_sent_shape", + "value": "(\"user_data_exports\".\"email_status\" = 'sent') = (\"user_data_exports\".\"email_sent_at\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.user_deletion_activity": { + "name": "user_deletion_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "step_key": { + "name": "step_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "details_json": { + "name": "details_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()" + } + }, + "indexes": { + "IDX_user_deletion_activity_request_created": { + "name": "IDX_user_deletion_activity_request_created", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_deletion_activity_request_id_user_deletion_requests_id_fk": { + "name": "user_deletion_activity_request_id_user_deletion_requests_id_fk", + "tableFrom": "user_deletion_activity", + "columnsFrom": [ + "request_id" + ], + "tableTo": "user_deletion_requests", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_deletion_audit_events": { + "name": "user_deletion_audit_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_kilo_user_id": { + "name": "actor_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_email_hmac": { + "name": "target_email_hmac", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_key": { + "name": "subject_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "details_json": { + "name": "details_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()" + } + }, + "indexes": { + "UQ_user_deletion_audit_events_idempotent": { + "name": "UQ_user_deletion_audit_events_idempotent", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_deletion_audit_events\".\"request_id\" IS NOT NULL", + "concurrently": false + }, + "IDX_user_deletion_audit_events_request_id": { + "name": "IDX_user_deletion_audit_events_request_id", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_deletion_audit_events_hmac": { + "name": "IDX_user_deletion_audit_events_hmac", + "columns": [ + { + "expression": "target_email_hmac", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_deletion_audit_events_request_id_user_deletion_requests_id_fk": { + "name": "user_deletion_audit_events_request_id_user_deletion_requests_id_fk", + "tableFrom": "user_deletion_audit_events", + "columnsFrom": [ + "request_id" + ], + "tableTo": "user_deletion_requests", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_deletion_audit_events_event_type_check": { + "name": "user_deletion_audit_events_event_type_check", + "value": "\"user_deletion_audit_events\".\"event_type\" IN ('request_created', 'intake_refused', 'access_disabled', 'access_absent', 'preflight_disposition', 'task_disposition', 'manual_retry', 'manual_action', 'anonymized', 'deletion_ready_for_customer_reply', 'cancelled', 'completed')" + } + }, + "isRLSEnabled": false + }, + "public.user_deletion_provider_credentials": { + "name": "user_deletion_provider_credentials", + "schema": "", + "columns": { + "provider_scope": { + "name": "provider_scope", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "encrypted_material": { + "name": "encrypted_material", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_by_kilo_user_id": { + "name": "updated_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "user_deletion_provider_credentials_updated_by_kilo_user_id_kilocode_users_id_fk": { + "name": "user_deletion_provider_credentials_updated_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_deletion_provider_credentials", + "columnsFrom": [ + "updated_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_deletion_provider_credentials_scope_check": { + "name": "user_deletion_provider_credentials_scope_check", + "value": "\"user_deletion_provider_credentials\".\"provider_scope\" IN ('kiloclaw', 'customerio', 'cloud_storage', 'session_ingest', 'posthog', 'substack', 'pylon')" + } + }, + "isRLSEnabled": false + }, + "public.user_deletion_requests": { + "name": "user_deletion_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "catalog_version": { + "name": "catalog_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "requested_by_kilo_user_id": { + "name": "requested_by_kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_email": { + "name": "target_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "target_email_hmac": { + "name": "target_email_hmac", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pylon_ticket_ref": { + "name": "pylon_ticket_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cloud_subject_resolution": { + "name": "cloud_subject_resolution", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cloud_subject_proof_ref": { + "name": "cloud_subject_proof_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "preflight_attention_code": { + "name": "preflight_attention_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_progress_at": { + "name": "last_progress_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "anonymized_at": { + "name": "anonymized_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 + } + }, + "indexes": { + "UQ_user_deletion_requests_active_email_hmac": { + "name": "UQ_user_deletion_requests_active_email_hmac", + "columns": [ + { + "expression": "target_email_hmac", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing')", + "concurrently": false + }, + "UQ_user_deletion_requests_active_user_id": { + "name": "UQ_user_deletion_requests_active_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_deletion_requests\".\"user_id\" IS NOT NULL AND \"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing')", + "concurrently": false + }, + "UQ_user_deletion_requests_active_pylon_ticket": { + "name": "UQ_user_deletion_requests_active_pylon_ticket", + "columns": [ + { + "expression": "regexp_replace(\"pylon_ticket_ref\", '^#', '')", + "isExpression": true, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_deletion_requests\".\"pylon_ticket_ref\" IS NOT NULL AND \"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing')", + "concurrently": false + }, + "IDX_user_deletion_requests_fairness": { + "name": "IDX_user_deletion_requests_fairness", + "columns": [ + { + "expression": "last_progress_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing')", + "concurrently": false + }, + "IDX_user_deletion_requests_email_hmac": { + "name": "IDX_user_deletion_requests_email_hmac", + "columns": [ + { + "expression": "target_email_hmac", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_deletion_requests_user_id": { + "name": "IDX_user_deletion_requests_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_deletion_requests_user_id_kilocode_users_id_fk": { + "name": "user_deletion_requests_user_id_kilocode_users_id_fk", + "tableFrom": "user_deletion_requests", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + }, + "user_deletion_requests_requested_by_kilo_user_id_kilocode_users_id_fk": { + "name": "user_deletion_requests_requested_by_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_deletion_requests", + "columnsFrom": [ + "requested_by_kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_deletion_requests_status_check": { + "name": "user_deletion_requests_status_check", + "value": "\"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing', 'completed', 'cancelled')" + }, + "user_deletion_requests_cloud_subject_resolution_check": { + "name": "user_deletion_requests_cloud_subject_resolution_check", + "value": "\"user_deletion_requests\".\"cloud_subject_resolution\" IN ('current_user', 'authoritative_absence', 'prior_queue_cleanup', 'legacy_identity_unresolved')" + }, + "user_deletion_requests_catalog_version_positive": { + "name": "user_deletion_requests_catalog_version_positive", + "value": "\"user_deletion_requests\".\"catalog_version\" >= 1" + }, + "user_deletion_requests_completed_at_check": { + "name": "user_deletion_requests_completed_at_check", + "value": "(\"user_deletion_requests\".\"status\" = 'completed') = (\"user_deletion_requests\".\"completed_at\" IS NOT NULL)" + }, + "user_deletion_requests_cancelled_at_check": { + "name": "user_deletion_requests_cancelled_at_check", + "value": "(\"user_deletion_requests\".\"status\" = 'cancelled') = (\"user_deletion_requests\".\"cancelled_at\" IS NOT NULL)" + }, + "user_deletion_requests_active_email_check": { + "name": "user_deletion_requests_active_email_check", + "value": "(\"user_deletion_requests\".\"status\" IN ('pending', 'in_progress', 'finalizing')) = (\"user_deletion_requests\".\"target_email\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.user_deletion_steps": { + "name": "user_deletion_steps", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "step_key": { + "name": "step_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "available_at": { + "name": "available_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "claim_token": { + "name": "claim_token", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "claimed_until": { + "name": "claimed_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "window_attempt_count": { + "name": "window_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "lifetime_attempt_count": { + "name": "lifetime_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "progress_json": { + "name": "progress_json", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_error_code": { + "name": "last_error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rate_limited_since": { + "name": "rate_limited_since", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "manual_evidence_json": { + "name": "manual_evidence_json", + "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": { + "IDX_user_deletion_steps_due": { + "name": "IDX_user_deletion_steps_due", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "where": "\"user_deletion_steps\".\"status\" IN ('pending', 'retry_wait', 'running')", + "concurrently": false + }, + "IDX_user_deletion_steps_request_id": { + "name": "IDX_user_deletion_steps_request_id", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_deletion_steps_request_id_user_deletion_requests_id_fk": { + "name": "user_deletion_steps_request_id_user_deletion_requests_id_fk", + "tableFrom": "user_deletion_steps", + "columnsFrom": [ + "request_id" + ], + "tableTo": "user_deletion_requests", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_user_deletion_steps_request_step": { + "name": "UQ_user_deletion_steps_request_step", + "columns": [ + "request_id", + "step_key" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "user_deletion_steps_step_key_check": { + "name": "user_deletion_steps_step_key_check", + "value": "\"user_deletion_steps\".\"step_key\" IN ('kiloclaw_destroy', 'customerio', 'cli_v1_blobs', 'cli_v2_sessions', 'usage_prompt_prefixes', 'posthog', 'substack', 'anonymize', 'pylon_reply', 'pylon_contact')" + }, + "user_deletion_steps_status_check": { + "name": "user_deletion_steps_status_check", + "value": "\"user_deletion_steps\".\"status\" IN ('pending', 'running', 'retry_wait', 'needs_attention', 'manual_action_required', 'succeeded', 'not_applicable', 'manually_verified')" + }, + "user_deletion_steps_window_attempt_count_nonnegative": { + "name": "user_deletion_steps_window_attempt_count_nonnegative", + "value": "\"user_deletion_steps\".\"window_attempt_count\" >= 0" + }, + "user_deletion_steps_lifetime_attempt_count_nonnegative": { + "name": "user_deletion_steps_lifetime_attempt_count_nonnegative", + "value": "\"user_deletion_steps\".\"lifetime_attempt_count\" >= 0" + }, + "user_deletion_steps_claim_fields_check": { + "name": "user_deletion_steps_claim_fields_check", + "value": "(\"user_deletion_steps\".\"claim_token\" IS NULL) = (\"user_deletion_steps\".\"claimed_until\" IS NULL)" + }, + "user_deletion_steps_manual_evidence_check": { + "name": "user_deletion_steps_manual_evidence_check", + "value": "(\"user_deletion_steps\".\"status\" = 'manually_verified') = (\"user_deletion_steps\".\"manual_evidence_json\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.user_feedback": { + "name": "user_feedback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "feedback_text": { + "name": "feedback_text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "feedback_for": { + "name": "feedback_for", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "feedback_batch": { + "name": "feedback_batch", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'unknown'" + }, + "context_json": { + "name": "context_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()" + } + }, + "indexes": { + "IDX_user_feedback_created_at": { + "name": "IDX_user_feedback_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_feedback_kilo_user_id": { + "name": "IDX_user_feedback_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_feedback_feedback_for": { + "name": "IDX_user_feedback_feedback_for", + "columns": [ + { + "expression": "feedback_for", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_feedback_feedback_batch": { + "name": "IDX_user_feedback_feedback_batch", + "columns": [ + { + "expression": "feedback_batch", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_feedback_source": { + "name": "IDX_user_feedback_source", + "columns": [ + { + "expression": "source", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_feedback_kilo_user_id_kilocode_users_id_fk": { + "name": "user_feedback_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_feedback", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "set null" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_github_app_tokens": { + "name": "user_github_app_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_app_type": { + "name": "github_app_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'standard'" + }, + "github_user_id": { + "name": "github_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "github_login": { + "name": "github_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_encrypted": { + "name": "access_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "refresh_token_encrypted": { + "name": "refresh_token_encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "credential_version": { + "name": "credential_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "revocation_reason": { + "name": "revocation_reason", + "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": { + "UQ_user_github_app_tokens_user_app": { + "name": "UQ_user_github_app_tokens_user_app", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_app_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_user_github_app_tokens_github_user_app": { + "name": "UQ_user_github_app_tokens_github_user_app", + "columns": [ + { + "expression": "github_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "github_app_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_github_app_tokens_kilo_user_id_kilocode_users_id_fk": { + "name": "user_github_app_tokens_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_github_app_tokens", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_github_app_tokens_app_type_check": { + "name": "user_github_app_tokens_app_type_check", + "value": "\"user_github_app_tokens\".\"github_app_type\" IN ('standard', 'lite')" + } + }, + "isRLSEnabled": false + }, + "public.user_model_preferences": { + "name": "user_model_preferences", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "favorites": { + "name": "favorites", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "last_selected": { + "name": "last_selected", + "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": { + "UQ_user_model_preferences_user_id": { + "name": "UQ_user_model_preferences_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_model_preferences_user_id_kilocode_users_id_fk": { + "name": "user_model_preferences_user_id_kilocode_users_id_fk", + "tableFrom": "user_model_preferences", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "cascade", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_moderation_blocks": { + "name": "user_moderation_blocks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "blocker_user_id": { + "name": "blocker_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "blocked_github_login": { + "name": "blocked_github_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_user_moderation_blocks_blocker_login": { + "name": "UQ_user_moderation_blocks_blocker_login", + "columns": [ + { + "expression": "blocker_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "blocked_github_login", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_moderation_mutes": { + "name": "user_moderation_mutes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "blocker_user_id": { + "name": "blocker_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "muted_github_login": { + "name": "muted_github_login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_user_moderation_mutes_blocker_login": { + "name": "UQ_user_moderation_mutes_blocker_login", + "columns": [ + { + "expression": "blocker_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "muted_github_login", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_notification_preferences": { + "name": "user_notification_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "agent_push_enabled": { + "name": "agent_push_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "chat_messages_enabled": { + "name": "chat_messages_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "agent_attention_enabled": { + "name": "agent_attention_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "session_status_enabled": { + "name": "session_status_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "kiloclaw_activity_enabled": { + "name": "kiloclaw_activity_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "balance_alerts_enabled": { + "name": "balance_alerts_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "security_findings_enabled": { + "name": "security_findings_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": 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": { + "user_notification_preferences_user_id_kilocode_users_id_fk": { + "name": "user_notification_preferences_user_id_kilocode_users_id_fk", + "tableFrom": "user_notification_preferences", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_period_cache": { + "name": "user_period_cache", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cache_type": { + "name": "cache_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_type": { + "name": "period_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "period_key": { + "name": "period_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "computed_at": { + "name": "computed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "shared_url_token": { + "name": "shared_url_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "shared_at": { + "name": "shared_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "IDX_user_period_cache_kilo_user_id": { + "name": "IDX_user_period_cache_kilo_user_id", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_user_period_cache": { + "name": "UQ_user_period_cache", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "cache_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_period_cache_lookup": { + "name": "IDX_user_period_cache_lookup", + "columns": [ + { + "expression": "cache_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "UQ_user_period_cache_share_token": { + "name": "UQ_user_period_cache_share_token", + "columns": [ + { + "expression": "shared_url_token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "where": "\"user_period_cache\".\"shared_url_token\" IS NOT NULL", + "concurrently": false + } + }, + "foreignKeys": { + "user_period_cache_kilo_user_id_kilocode_users_id_fk": { + "name": "user_period_cache_kilo_user_id_kilocode_users_id_fk", + "tableFrom": "user_period_cache", + "columnsFrom": [ + "kilo_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "user_period_cache_period_type_check": { + "name": "user_period_cache_period_type_check", + "value": "\"user_period_cache\".\"period_type\" IN ('year', 'quarter', 'month', 'week', 'custom')" + } + }, + "isRLSEnabled": false + }, + "public.user_push_tokens": { + "name": "user_push_tokens", + "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 + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "platform": { + "name": "platform", + "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": { + "UQ_user_push_tokens_token": { + "name": "UQ_user_push_tokens_token", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_user_push_tokens_user_id": { + "name": "IDX_user_push_tokens_user_id", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "user_push_tokens_user_id_kilocode_users_id_fk": { + "name": "user_push_tokens_user_id_kilocode_users_id_fk", + "tableFrom": "user_push_tokens", + "columnsFrom": [ + "user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_terms_acceptances": { + "name": "user_terms_acceptances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "terms_version": { + "name": "terms_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "age_posture": { + "name": "age_posture", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'13_plus'" + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "UQ_user_terms_acceptances_user_version": { + "name": "UQ_user_terms_acceptances_user_version", + "columns": [ + { + "expression": "kilo_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "terms_version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vercel_ip_city": { + "name": "vercel_ip_city", + "schema": "", + "columns": { + "vercel_ip_city_id": { + "name": "vercel_ip_city_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "vercel_ip_city": { + "name": "vercel_ip_city", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_vercel_ip_city": { + "name": "UQ_vercel_ip_city", + "columns": [ + { + "expression": "vercel_ip_city", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vercel_ip_country": { + "name": "vercel_ip_country", + "schema": "", + "columns": { + "vercel_ip_country_id": { + "name": "vercel_ip_country_id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "vercel_ip_country": { + "name": "vercel_ip_country", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "UQ_vercel_ip_country": { + "name": "UQ_vercel_ip_country", + "columns": [ + { + "expression": "vercel_ip_country", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.webhook_events": { + "name": "webhook_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "pg_catalog.gen_random_uuid()" + }, + "owned_by_organization_id": { + "name": "owned_by_organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "owned_by_user_id": { + "name": "owned_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event_action": { + "name": "event_action", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "headers": { + "name": "headers", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "processed": { + "name": "processed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "handlers_triggered": { + "name": "handlers_triggered", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'" + }, + "errors": { + "name": "errors", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "event_signature": { + "name": "event_signature", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "IDX_webhook_events_owned_by_org_id": { + "name": "IDX_webhook_events_owned_by_org_id", + "columns": [ + { + "expression": "owned_by_organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_webhook_events_owned_by_user_id": { + "name": "IDX_webhook_events_owned_by_user_id", + "columns": [ + { + "expression": "owned_by_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_webhook_events_platform": { + "name": "IDX_webhook_events_platform", + "columns": [ + { + "expression": "platform", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_webhook_events_event_type": { + "name": "IDX_webhook_events_event_type", + "columns": [ + { + "expression": "event_type", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "IDX_webhook_events_created_at": { + "name": "IDX_webhook_events_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "webhook_events_owned_by_organization_id_organizations_id_fk": { + "name": "webhook_events_owned_by_organization_id_organizations_id_fk", + "tableFrom": "webhook_events", + "columnsFrom": [ + "owned_by_organization_id" + ], + "tableTo": "organizations", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "webhook_events_owned_by_user_id_kilocode_users_id_fk": { + "name": "webhook_events_owned_by_user_id_kilocode_users_id_fk", + "tableFrom": "webhook_events", + "columnsFrom": [ + "owned_by_user_id" + ], + "tableTo": "kilocode_users", + "columnsTo": [ + "id" + ], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "UQ_webhook_events_signature": { + "name": "UQ_webhook_events_signature", + "columns": [ + "event_signature" + ], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": { + "webhook_events_owner_check": { + "name": "webhook_events_owner_check", + "value": "(\n (\"webhook_events\".\"owned_by_user_id\" IS NOT NULL AND \"webhook_events\".\"owned_by_organization_id\" IS NULL) OR\n (\"webhook_events\".\"owned_by_user_id\" IS NULL AND \"webhook_events\".\"owned_by_organization_id\" IS NOT NULL)\n )" + } + }, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "views": { + "public.microdollar_usage_view": { + "name": "microdollar_usage_view", + "schema": "public", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kilo_user_id": { + "name": "kilo_user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cost": { + "name": "cost", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "input_tokens": { + "name": "input_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "output_tokens": { + "name": "output_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "cache_write_tokens": { + "name": "cache_write_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "cache_hit_tokens": { + "name": "cache_hit_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "http_x_forwarded_for": { + "name": "http_x_forwarded_for", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_city": { + "name": "http_x_vercel_ip_city", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_country": { + "name": "http_x_vercel_ip_country", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_latitude": { + "name": "http_x_vercel_ip_latitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ip_longitude": { + "name": "http_x_vercel_ip_longitude", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "http_x_vercel_ja4_digest": { + "name": "http_x_vercel_ja4_digest", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_model": { + "name": "requested_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_prompt_prefix": { + "name": "user_prompt_prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_prompt_prefix": { + "name": "system_prompt_prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_prompt_length": { + "name": "system_prompt_length", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "http_user_agent": { + "name": "http_user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cache_discount": { + "name": "cache_discount", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "max_tokens": { + "name": "max_tokens", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "has_middle_out_transform": { + "name": "has_middle_out_transform", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "has_error": { + "name": "has_error", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "abuse_classification": { + "name": "abuse_classification", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "inference_provider": { + "name": "inference_provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status_code": { + "name": "status_code", + "type": "smallint", + "primaryKey": false, + "notNull": false + }, + "upstream_id": { + "name": "upstream_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "finish_reason": { + "name": "finish_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "latency": { + "name": "latency", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "moderation_latency": { + "name": "moderation_latency", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "generation_time": { + "name": "generation_time", + "type": "real", + "primaryKey": false, + "notNull": false + }, + "is_byok": { + "name": "is_byok", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "is_user_byok": { + "name": "is_user_byok", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "streamed": { + "name": "streamed", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "cancelled": { + "name": "cancelled", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "editor_name": { + "name": "editor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "api_kind": { + "name": "api_kind", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "has_tools": { + "name": "has_tools", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "machine_id": { + "name": "machine_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "feature": { + "name": "feature", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "auto_model": { + "name": "auto_model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "market_cost": { + "name": "market_cost", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "is_free": { + "name": "is_free", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "abuse_delay": { + "name": "abuse_delay", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "abuse_downgraded_from": { + "name": "abuse_downgraded_from", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "definition": "\n SELECT\n mu.id,\n mu.kilo_user_id,\n meta.message_id,\n mu.cost,\n mu.input_tokens,\n mu.output_tokens,\n mu.cache_write_tokens,\n mu.cache_hit_tokens,\n mu.created_at,\n ip.http_ip AS http_x_forwarded_for,\n city.vercel_ip_city AS http_x_vercel_ip_city,\n country.vercel_ip_country AS http_x_vercel_ip_country,\n meta.vercel_ip_latitude AS http_x_vercel_ip_latitude,\n meta.vercel_ip_longitude AS http_x_vercel_ip_longitude,\n ja4.ja4_digest AS http_x_vercel_ja4_digest,\n mu.provider,\n mu.model,\n mu.requested_model,\n meta.user_prompt_prefix,\n spp.system_prompt_prefix,\n meta.system_prompt_length,\n ua.http_user_agent,\n mu.cache_discount,\n meta.max_tokens,\n meta.has_middle_out_transform,\n mu.has_error,\n mu.abuse_classification,\n mu.organization_id,\n mu.inference_provider,\n mu.project_id,\n meta.status_code,\n meta.upstream_id,\n frfr.finish_reason,\n meta.latency,\n meta.moderation_latency,\n meta.generation_time,\n meta.is_byok,\n meta.is_user_byok,\n meta.streamed,\n meta.cancelled,\n edit.editor_name,\n ak.api_kind,\n meta.has_tools,\n meta.machine_id,\n feat.feature,\n meta.session_id,\n md.mode,\n am.auto_model,\n meta.market_cost,\n meta.is_free,\n meta.abuse_delay,\n meta.abuse_downgraded_from\n FROM \"microdollar_usage\" mu\n LEFT JOIN \"microdollar_usage_metadata\" meta ON mu.id = meta.id\n LEFT JOIN \"http_ip\" ip ON meta.http_ip_id = ip.http_ip_id\n LEFT JOIN \"vercel_ip_city\" city ON meta.vercel_ip_city_id = city.vercel_ip_city_id\n LEFT JOIN \"vercel_ip_country\" country ON meta.vercel_ip_country_id = country.vercel_ip_country_id\n LEFT JOIN \"ja4_digest\" ja4 ON meta.ja4_digest_id = ja4.ja4_digest_id\n LEFT JOIN \"system_prompt_prefix\" spp ON meta.system_prompt_prefix_id = spp.system_prompt_prefix_id\n LEFT JOIN \"http_user_agent\" ua ON meta.http_user_agent_id = ua.http_user_agent_id\n LEFT JOIN \"finish_reason\" frfr ON meta.finish_reason_id = frfr.finish_reason_id\n LEFT JOIN \"editor_name\" edit ON meta.editor_name_id = edit.editor_name_id\n LEFT JOIN \"api_kind\" ak ON meta.api_kind_id = ak.api_kind_id\n LEFT JOIN \"feature\" feat ON meta.feature_id = feat.feature_id\n LEFT JOIN \"mode\" md ON meta.mode_id = md.mode_id\n LEFT JOIN \"auto_model\" am ON meta.auto_model_id = am.auto_model_id\n", + "materialized": false, + "isExisting": false + } + }, + "sequences": {}, + "roles": {}, + "policies": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 06253dc90b..92db81198b 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -1548,6 +1548,13 @@ "when": 1787082936083, "tag": "0220_faulty_the_hand", "breakpoints": true + }, + { + "idx": 221, + "version": "7", + "when": 1787159953982, + "tag": "0221_retire_kiloclaw_referral_rewards", + "breakpoints": true } ] } \ No newline at end of file diff --git a/services/kiloclaw-billing/src/lifecycle.test.ts b/services/kiloclaw-billing/src/lifecycle.test.ts index ed3dc3a627..a962e768ad 100644 --- a/services/kiloclaw-billing/src/lifecycle.test.ts +++ b/services/kiloclaw-billing/src/lifecycle.test.ts @@ -4396,19 +4396,11 @@ describe('credit renewal Kilo Pass bonus projection', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -4683,19 +4675,11 @@ describe('credit renewal Kilo Pass bonus projection', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -4727,7 +4711,7 @@ describe('credit renewal Kilo Pass bonus projection', () => { expect(sideEffectActions).toEqual([ 'issue_kilo_pass_bonus_from_usage_threshold', - 'process_paid_conversion', + 'enqueue_affiliate_event', ]); }); @@ -4928,19 +4912,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -4971,7 +4947,7 @@ describe('credit renewal sweep affiliate tracking', () => { ]) ); - const paidConversionCalls = fetch.mock.calls + const affiliateSaleCalls = fetch.mock.calls .map( ([, init]) => JSON.parse(typeof init?.body === 'string' ? init.body : '{}') as { @@ -4979,9 +4955,9 @@ describe('credit renewal sweep affiliate tracking', () => { input: Record; } ) - .filter(call => call.action === 'process_paid_conversion'); - const paidConversionInputs = paidConversionCalls.map(call => call.input); - expect(paidConversionInputs).toEqual( + .filter(call => call.action === 'enqueue_affiliate_event'); + const affiliateSaleInputs = affiliateSaleCalls.map(call => call.input); + expect(affiliateSaleInputs).toEqual( expect.arrayContaining([ expect.objectContaining({ userId: 'legacy-user', @@ -5143,19 +5119,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -5365,19 +5333,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -5654,19 +5614,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -5716,7 +5668,7 @@ describe('credit renewal sweep affiliate tracking', () => { expect(deletes).toHaveLength(0); }); - it('normalizes Postgres renewal timestamps before paid-conversion side effects', async () => { + it('normalizes Postgres renewal timestamps before affiliate sale side effects', async () => { const postgresRenewalAt = '2026-04-29 01:16:12.945+00'; const renewalAtIso = '2026-04-29T01:16:12.945Z'; const { db } = createMockDb([ @@ -5745,13 +5697,8 @@ describe('credit renewal sweep affiliate tracking', () => { return Response.json({ projectedBonusMicrodollars: 0 }); case 'issue_kilo_pass_bonus_from_usage_threshold': return Response.json({ ok: true }); - case 'process_paid_conversion': - return Response.json({ - affiliateSaleEnqueued: false, - winningTouchType: 'none', - conversionId: null, - disqualificationReason: null, - }); + case 'enqueue_affiliate_event': + return Response.json({ ok: true }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -5776,7 +5723,7 @@ describe('credit renewal sweep affiliate tracking', () => { input: Record; } ) - .find(call => call.action === 'process_paid_conversion'); + .find(call => call.action === 'enqueue_affiliate_event'); expect(saleCall?.input.eventDateIso).toBe(renewalAtIso); }); @@ -5900,19 +5847,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -5965,12 +5904,14 @@ describe('credit renewal sweep affiliate tracking', () => { input: Record; } ) - .find(call => call.action === 'process_paid_conversion'); + .find(call => call.action === 'enqueue_affiliate_event'); expect(saleCall).toEqual({ - action: 'process_paid_conversion', + action: 'enqueue_affiliate_event', input: { userId: 'user-1', + provider: 'impact', + eventType: 'sale', dedupeKey: 'affiliate:impact:sale:kiloclaw-subscription:instance-1:2026-04', eventDateIso: renewalAt, orderId: 'kiloclaw-subscription:instance-1:2026-04', @@ -5983,7 +5924,7 @@ describe('credit renewal sweep affiliate tracking', () => { }); }); - it('does not roll back or fail renewal when paid conversion side effect fails', async () => { + it('does not roll back or fail renewal when the affiliate sale side effect fails', async () => { const renewalAt = '2026-04-09T10:00:00.000Z'; const { db, txUpdates } = createMockDb([ [ @@ -6035,7 +5976,7 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': + case 'enqueue_affiliate_event': return new Response(JSON.stringify({ error: 'temporarily unavailable' }), { status: 503, headers: { 'content-type': 'application/json' }, @@ -6114,19 +6055,11 @@ describe('credit renewal sweep affiliate tracking', () => { status: 200, headers: { 'content-type': 'application/json' }, }); - case 'process_paid_conversion': - return new Response( - JSON.stringify({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }), - { - status: 200, - headers: { 'content-type': 'application/json' }, - } - ); + case 'enqueue_affiliate_event': + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -6182,9 +6115,11 @@ describe('credit renewal sweep affiliate tracking', () => { expect(sideEffectCalls).toEqual([ { - action: 'process_paid_conversion', + action: 'enqueue_affiliate_event', input: { userId: 'user-1', + provider: 'impact', + eventType: 'sale', dedupeKey: 'affiliate:impact:sale:kiloclaw-subscription:instance-1:2026-04', eventDateIso: renewalAt, orderId: 'kiloclaw-subscription:instance-1:2026-04', @@ -6495,13 +6430,8 @@ describe('credit renewal sweep affiliate tracking', () => { return Response.json({ projectedBonusMicrodollars: 0 }); case 'issue_kilo_pass_bonus_from_usage_threshold': return Response.json({ ok: true }); - case 'process_paid_conversion': - return Response.json({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }); + case 'enqueue_affiliate_event': + return Response.json({ ok: true }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } @@ -6593,13 +6523,8 @@ describe('credit renewal sweep affiliate tracking', () => { return Response.json({ projectedBonusMicrodollars: 0 }); case 'issue_kilo_pass_bonus_from_usage_threshold': return Response.json({ ok: true }); - case 'process_paid_conversion': - return Response.json({ - affiliateSaleEnqueued: true, - winningTouchType: 'affiliate', - conversionId: null, - disqualificationReason: null, - }); + case 'enqueue_affiliate_event': + return Response.json({ ok: true }); default: throw new Error(`Unexpected side effect action: ${body.action}`); } diff --git a/services/kiloclaw-billing/src/lifecycle.ts b/services/kiloclaw-billing/src/lifecycle.ts index 58232dc0c5..12b4facfb0 100644 --- a/services/kiloclaw-billing/src/lifecycle.ts +++ b/services/kiloclaw-billing/src/lifecycle.ts @@ -365,20 +365,6 @@ type SideEffectRequest = subscriptionId: string; }; } - | { - action: 'process_paid_conversion'; - input: { - userId: string; - dedupeKey: string; - eventDateIso: string; - orderId: string; - amount: number; - currencyCode: string; - itemCategory: string; - itemName: string; - itemSku?: string; - }; - } | { action: 'issue_kilo_pass_bonus_from_usage_threshold'; input: { userId: string; nowIso: string }; @@ -396,14 +382,7 @@ type SideEffectResponse = T['action'] extends 'send ? { guarded: boolean } : T['action'] extends 'report_commit_retirement_anomaly' ? { ok: true } - : T['action'] extends 'process_paid_conversion' - ? { - affiliateSaleEnqueued: boolean; - winningTouchType: 'referral' | 'affiliate' | 'none'; - conversionId: string | null; - disqualificationReason: string | null; - } - : { ok: true }; + : { ok: true }; export class KiloClawApiError extends Error { readonly statusCode: number; @@ -1514,7 +1493,7 @@ async function enqueueAffiliateEvent( ); } -type PaidConversionParams = { +type CreditRenewalSaleParams = { userId: string; dedupeKey: string; eventDateIso: string; @@ -1526,31 +1505,23 @@ type PaidConversionParams = { itemSku?: string; }; -async function processPaidConversion( - env: BillingWorkerEnv, - context: SweepExecutionContext, - params: PaidConversionParams -): Promise { - await callBillingSideEffect( - env, - context, - { - action: 'process_paid_conversion', - input: params, - }, - { userId: params.userId } - ); -} - -async function processPaidConversionBestEffort( +/** + * Affiliate SALE reporting for a settled credit renewal. Reporting must never + * fail a renewal, so delivery problems are logged and swallowed. + */ +async function enqueueCreditRenewalSaleBestEffort( env: BillingWorkerEnv, context: SweepExecutionContext, - params: PaidConversionParams + params: CreditRenewalSaleParams ): Promise { try { - await processPaidConversion(env, context, params); + await enqueueAffiliateEvent(env, context, { + ...params, + provider: 'impact', + eventType: 'sale', + }); } catch (error) { - log('error', 'Paid conversion side effect failed after credit renewal', { + log('error', 'Affiliate sale side effect failed after credit renewal', { userId: params.userId, dedupeKey: params.dedupeKey, error: error instanceof Error ? error.message : String(error), @@ -2203,7 +2174,7 @@ async function processCreditRenewalRow( outcome.wasPastDue ); - await processPaidConversionBestEffort(env, context, { + await enqueueCreditRenewalSaleBestEffort(env, context, { userId: outcome.userId, dedupeKey: `affiliate:impact:sale:${outcome.deductionCategory}`, eventDateIso: serializeBillingTimestamp(outcome.renewalAt), @@ -2256,7 +2227,7 @@ async function processCreditRenewalRow( outcome.wasPastDue ); - await processPaidConversionBestEffort(env, context, { + await enqueueCreditRenewalSaleBestEffort(env, context, { userId: outcome.userId, dedupeKey: `affiliate:impact:sale:${outcome.deductionCategory}`, eventDateIso: serializeBillingTimestamp(outcome.renewalAt),