Rebuild the shell, add Calendar and Learn, and govern reads
CI / verify (push) Successful in 3m45s
CI / publish (push) Has been skipped

Seven parallel agents and an adversarial verification pass. The three things
worth knowing before reading the diff:

RBAC WAS ALREADY BUILT. docs/build-plan.md marks F2 and F3 outstanding and is
stale — packages/core/src/permissions.ts and lib/mutation.ts shipped long ago.
So this does not rebuild them; it closes the gaps an audit found. The big one
is that reads were entirely ungoverned: every GET was "any authenticated
member", so a junior demand rep and a research contractor could both pull
per-block supplier cost and break-even prices from /api/capacity/margin, and
every contract's negotiated terms. For a company whose margin is the business,
that was the hole that mattered. Adds book:read / economics:read / team:read,
a readGuard middleware, and a `viewer` role below member.

THE BUTTON AND THE 403 DISAGREED — the exact thing F3 said must never happen.
Contracts.tsx never called can() at all, so its save button was always enabled
against a server requiring contract:sign; Capacity.tsx gated commitment
creation on deal:write/demand while the server wanted commitment:write/supply.

POST /api/activities was the one write bypassing executeMutation: no capability
check, and any member could mutate accounts.lastActivityAt as a side effect.
It is now a proper mutation() behind activity:write.

The shell becomes three panes — a collapsible shadcn sidebar with an account
switcher on the Piggy accent, a header with real search, and Piggy docked to
the right, page-aware and persistent across navigation. The phone keeps its
bottom tab bar, which is the thing this product already beat trycompai/crm on,
and gains the sidebar as a sheet.

Calendar is a projection over thirteen dated sources rather than a new table,
because a table would duplicate dates that already live on contracts, deals and
commitments and would drift — and one ledger answering the question is the
whole argument. It surfaces export_authorizations and compliance_artifacts,
which had indexed expires_at columns, schema comments saying they must be
alerted on, and no read endpoint or UI anywhere.

Learn carries two tracks. Concepts are members-only; the platform track can be
opened with a share code by someone with no account. The code mints a scoped
learn-only token and never a Principal — every route here resolves a principal
and then checks capabilities, so a principal-minting code would be one missing
check away from leaking the book. "Only platform-track rows may be code-visible"
is a database CHECK constraint as well as a write-path rule, and a test asserts
a valid learn token still gets 401 on /api/dashboard, /api/accounts and
/api/contracts — the same invariant scripts/deploy.sh refuses to ship without.

CD becomes tag-to-ship. CI publishes an image to the Gitea registry on a
release-* tag and cloud-2 pulls it, so no credential on the shared runner can
execute anything on production — by construction rather than by policy. Both
halves of deploy.sh's original rule survive: nothing on the runner reaches the
host, and a human still decides when it ships. deploy.sh gains a rollback and a
public-origin check, and PIG_IMAGE now reaches compose through `sudo env`,
without which sudo's env_reset silently resolved every release to pig:local.

Tests 141 -> 261.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-13 15:02:48 -07:00
parent 6cf80747cc
commit 13dec6b4b8
102 changed files with 28638 additions and 913 deletions
@@ -0,0 +1,26 @@
CREATE TABLE "calendar_entries" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"title" text NOT NULL,
"description" text,
"kind" text DEFAULT 'meeting' NOT NULL,
"starts_at" timestamp with time zone NOT NULL,
"ends_at" timestamp with time zone,
"all_day" boolean DEFAULT false NOT NULL,
"owner_user_id" uuid,
"account_id" uuid,
"demand_deal_id" uuid,
"supply_deal_id" uuid,
"completed_at" timestamp with time zone,
"created_by_user_id" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "calendar_entries" ADD CONSTRAINT "calendar_entries_owner_user_id_users_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "calendar_entries" ADD CONSTRAINT "calendar_entries_account_id_accounts_id_fk" FOREIGN KEY ("account_id") REFERENCES "public"."accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "calendar_entries" ADD CONSTRAINT "calendar_entries_demand_deal_id_demand_deals_id_fk" FOREIGN KEY ("demand_deal_id") REFERENCES "public"."demand_deals"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "calendar_entries" ADD CONSTRAINT "calendar_entries_supply_deal_id_supply_deals_id_fk" FOREIGN KEY ("supply_deal_id") REFERENCES "public"."supply_deals"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "calendar_entries" ADD CONSTRAINT "calendar_entries_created_by_user_id_users_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "calendar_entries_starts_idx" ON "calendar_entries" USING btree ("starts_at");--> statement-breakpoint
CREATE INDEX "calendar_entries_owner_idx" ON "calendar_entries" USING btree ("owner_user_id");--> statement-breakpoint
CREATE INDEX "calendar_entries_account_idx" ON "calendar_entries" USING btree ("account_id");
@@ -0,0 +1,29 @@
CREATE TABLE "learn_resources" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"track" text NOT NULL,
"title" text NOT NULL,
"summary" text,
"url" text NOT NULL,
"provider" text NOT NULL,
"external_id" text NOT NULL,
"visibility" text DEFAULT 'members' NOT NULL,
"duration_seconds" integer,
"sort_order" integer DEFAULT 100 NOT NULL,
"published_at" timestamp with time zone DEFAULT now() NOT NULL,
"added_by_user_id" uuid,
"archived_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "learn_resources_track_provider_external_key" UNIQUE("track","provider","external_id"),
CONSTRAINT "learn_resources_track_check" CHECK ("learn_resources"."track" IN ('supply', 'demand', 'platform')),
CONSTRAINT "learn_resources_visibility_check" CHECK ("learn_resources"."visibility" IN ('members', 'code')),
CONSTRAINT "learn_resources_provider_check" CHECK ("learn_resources"."provider" IN ('cap', 'loom', 'youtube_nocookie')),
CONSTRAINT "learn_resources_code_is_platform_only_check" CHECK ("learn_resources"."visibility" <> 'code' OR "learn_resources"."track" = 'platform'),
CONSTRAINT "learn_resources_duration_check" CHECK ("learn_resources"."duration_seconds" IS NULL OR "learn_resources"."duration_seconds" > 0)
);
--> statement-breakpoint
ALTER TABLE "platform_settings" ADD COLUMN "learn_access_code" text DEFAULT 'carlthefog' NOT NULL;--> statement-breakpoint
ALTER TABLE "platform_settings" ADD COLUMN "learn_access_code_updated_at" timestamp with time zone;--> statement-breakpoint
ALTER TABLE "learn_resources" ADD CONSTRAINT "learn_resources_added_by_user_id_users_id_fk" FOREIGN KEY ("added_by_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "learn_resources_track_order_idx" ON "learn_resources" USING btree ("track","sort_order");--> statement-breakpoint
CREATE INDEX "learn_resources_visibility_idx" ON "learn_resources" USING btree ("visibility","track");
@@ -0,0 +1,16 @@
-- Hand-written, like 0005, because drizzle-kit cannot express this safely.
--
-- Two traps live in these three lines.
--
-- First, `ALTER TYPE ... ADD VALUE` could not run inside a transaction block
-- before Postgres 12, and the drizzle migrator wraps every migration in one.
-- PIG targets Postgres 16, where it is permitted; what remains forbidden even
-- on 16 is *using* the new value in the same transaction, so nothing here may
-- reference 'viewer' — no backfill, no default change, no CHECK. Adding one
-- later means its own migration.
--
-- Second, `BEFORE 'member'` is not cosmetic. `viewer` outranks nobody, and the
-- enum's sort order is what `ORDER BY role` and any future comparison would
-- use. Appending it to the end would silently make the least privileged role
-- sort as the most senior.
ALTER TYPE "public"."pig_team_role" ADD VALUE IF NOT EXISTS 'viewer' BEFORE 'member';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+22 -1
View File
@@ -71,6 +71,27 @@
"when": 1786612000000,
"tag": "0009_warm_metal_master",
"breakpoints": true
},
{
"idx": 10,
"version": "7",
"when": 1786651559230,
"tag": "0010_calendar_entries",
"breakpoints": true
},
{
"idx": 11,
"version": "7",
"when": 1786655711401,
"tag": "0011_learn_resources",
"breakpoints": true
},
{
"idx": 12,
"version": "7",
"when": 1786655800000,
"tag": "0012_viewer_team_role",
"breakpoints": true
}
]
}
}
+83
View File
@@ -0,0 +1,83 @@
/**
* The one dated thing that has no other home.
*
* Everything else on the quarterly calendar is a PROJECTION: a contract
* expiry, an obligation due date, a commitment window, a hold expiring, an
* export authorisation lapsing. Those dates already live on the records that
* own them, and copying them into a calendar table would guarantee drift —
* two answers to "when does this expire?", with nothing to say which is right.
* PIG's whole argument is that one ledger answers the question.
*
* What genuinely has nowhere to live is a human-owned dated item: the QBR, the
* renewal check-in, the campaign week. So exactly one table, for exactly that.
*
* **No recurrence in v1, deliberately.** A recurrence rule is worthless
* without an expansion strategy — do you materialise occurrences, expand at
* read time, and where does an edited single occurrence live? Every calendar
* table that grew an `rrule` column before answering those questions ended up
* with orphaned exceptions nobody could delete. When recurrence is needed it
* should arrive with its expansion, not before it.
*/
import { boolean, index, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
import { CALENDAR_ENTRY_KINDS } from '@pig/core';
import { accounts } from './crm';
import { demandDeals } from './demand';
import { supplyDeals } from './supply';
import { users } from './identity';
export const calendarEntries = pgTable(
'calendar_entries',
{
id: uuid('id').primaryKey().defaultRandom(),
title: text('title').notNull(),
description: text('description'),
kind: text('kind', { enum: CALENDAR_ENTRY_KINDS }).notNull().default('meeting'),
startsAt: timestamp('starts_at', { withTimezone: true }).notNull(),
/** Null for a point in time — a reminder is not a window. */
endsAt: timestamp('ends_at', { withTimezone: true }),
/**
* An all-day entry still stores instants, because every temporal column in
* PIG does and a mixed representation would need a special case in every
* date predicate. The flag records the author's intent so the front end
* can render "12 August" rather than "12 August, 00:00".
*/
allDay: boolean('all_day').notNull().default(false),
ownerUserId: uuid('owner_user_id').references(() => users.id, { onDelete: 'set null' }),
/**
* Polymorphic by nullable FK, the same idiom `activities` uses. A junction
* table would be more general and would also make "what is on the calendar
* for this account?" a three-way join for no benefit — an entry is about
* at most one of these things in practice.
*/
accountId: uuid('account_id').references(() => accounts.id, { onDelete: 'cascade' }),
demandDealId: uuid('demand_deal_id').references(() => demandDeals.id, {
onDelete: 'cascade',
}),
supplyDealId: uuid('supply_deal_id').references(() => supplyDeals.id, {
onDelete: 'cascade',
}),
/** Completion is a timestamp, never a boolean: when matters as much as whether. */
completedAt: timestamp('completed_at', { withTimezone: true }),
createdByUserId: uuid('created_by_user_id').references(() => users.id, {
onDelete: 'set null',
}),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
/** The quarter query scans by date; the "my calendar" view scans by owner. */
index('calendar_entries_starts_idx').on(t.startsAt),
index('calendar_entries_owner_idx').on(t.ownerUserId),
index('calendar_entries_account_idx').on(t.accountId),
],
);
export type CalendarEntry = typeof calendarEntries.$inferSelect;
export type NewCalendarEntry = typeof calendarEntries.$inferInsert;
+3
View File
@@ -11,6 +11,7 @@
* allocations the join between the two. The reason PIG exists.
* contracts MSA, DPA, SLA, order forms, obligations
* compliance export control as a predicate on the match
* calendar the one dated row type nothing else owns
* agent the leased task queue and evidence-bearing facts
* fields user-defined fields
*/
@@ -23,6 +24,8 @@ export * from './demand';
export * from './allocations';
export * from './contracts';
export * from './compliance';
export * from './calendar';
export * from './learn';
export * from './agent';
export * from './fields';
export * from './integrations';
+117
View File
@@ -0,0 +1,117 @@
/**
* Learn resources — shared videos, in two kinds of track.
*
* The table is ordinary. One column pair on it is not, and it is the reason
* this file carries a comment at all:
*
* **`visibility = 'code'` is only legal on the platform track**, and that is a
* CHECK constraint rather than a convention. A resource marked `code` is
* readable by someone holding the share code, who has no account, no principal
* and no capability of any kind. Concept material about how we source and
* price capacity must never enter that set. The API write path refuses it too,
* but a constraint is what makes it true of rows that arrive any other way —
* a seed, a repair script, a psql session at midnight.
*
* **No raw URL is ever framed.** `url` is the canonical share link, kept for a
* human to click and for provenance; `provider` and `external_id` are what the
* embed is rebuilt from, through the allowlist in `@pig/core`. The read paths
* deliberately do not select `url` at all, so a poisoned value in that column
* cannot reach an `iframe src` even by accident.
*
* The unique key on (track, provider, external_id) is load-bearing for the
* seed: `onConflictDoNothing()` is a silent no-op without a constraint to
* conflict on, and it has already duplicated seed data twice in this codebase.
*/
import { sql } from 'drizzle-orm';
import {
check,
index,
integer,
pgTable,
text,
timestamp,
unique,
uuid,
} from 'drizzle-orm/pg-core';
import {
LEARN_CODE_TRACK,
LEARN_PROVIDERS,
LEARN_TRACKS,
LEARN_VISIBILITIES,
} from '@pig/core';
import { users } from './identity';
/**
* Render a value set as a SQL `IN` list from the ontology constant.
*
* Typing the values into the migration by hand is what lets the database and
* the application disagree about the vocabulary; deriving them means removing
* a value stops validating rather than silently persisting. The values are
* compile-time literal constants from `@pig/core`, never input.
*/
const inList = (values: readonly string[]) =>
sql.raw(values.map((value) => `'${value}'`).join(', '));
export const learnResources = pgTable(
'learn_resources',
{
id: uuid('id').primaryKey().defaultRandom(),
track: text('track', { enum: LEARN_TRACKS }).notNull(),
title: text('title').notNull(),
summary: text('summary'),
/** The canonical share link. Shown to a human, never used as a frame src. */
url: text('url').notNull(),
/** Resolved from the host by the allowlist — never supplied by a client. */
provider: text('provider', { enum: LEARN_PROVIDERS }).notNull(),
externalId: text('external_id').notNull(),
visibility: text('visibility', { enum: LEARN_VISIBILITIES }).notNull().default('members'),
durationSeconds: integer('duration_seconds'),
/** Ascending. Ties break on published_at, so a default is fine. */
sortOrder: integer('sort_order').notNull().default(100),
publishedAt: timestamp('published_at', { withTimezone: true }).notNull().defaultNow(),
addedByUserId: uuid('added_by_user_id').references(() => users.id, {
onDelete: 'set null',
}),
/**
* Archive rather than delete, as everywhere else in PIG: a video pulled
* from the curriculum is still the answer to "what did onboarding say in
* March?", and the activity log references it.
*/
archivedAt: timestamp('archived_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
check('learn_resources_track_check', sql`${t.track} IN (${inList(LEARN_TRACKS)})`),
check(
'learn_resources_visibility_check',
sql`${t.visibility} IN (${inList(LEARN_VISIBILITIES)})`,
),
check('learn_resources_provider_check', sql`${t.provider} IN (${inList(LEARN_PROVIDERS)})`),
/**
* THE constraint. Written as an implication rather than an equality so it
* reads as the rule it encodes: code-visible implies platform track.
*/
check(
'learn_resources_code_is_platform_only_check',
sql`${t.visibility} <> 'code' OR ${t.track} = ${sql.raw(`'${LEARN_CODE_TRACK}'`)}`,
),
check('learn_resources_duration_check', sql`${t.durationSeconds} IS NULL OR ${t.durationSeconds} > 0`),
unique('learn_resources_track_provider_external_key').on(t.track, t.provider, t.externalId),
/** Both list queries are "one track, in order". */
index('learn_resources_track_order_idx').on(t.track, t.sortOrder),
/** The public route filters on this pair and nothing else. */
index('learn_resources_visibility_idx').on(t.visibility, t.track),
],
);
export type LearnResource = typeof learnResources.$inferSelect;
export type NewLearnResource = typeof learnResources.$inferInsert;
+15
View File
@@ -25,6 +25,21 @@ export const platformSettings = pgTable(
primeApiKeyUpdatedAt: timestamp('prime_api_key_updated_at', { withTimezone: true }),
primeSyncEnabled: boolean('prime_sync_enabled').notNull().default(false),
primeSyncIntervalMinutes: integer('prime_sync_interval_minutes').notNull().default(30),
/**
* The Learn share code, in the database because it is rotatable.
*
* Not an env var and not a constant: rotating it must be something an
* administrator does at 11pm when it has been forwarded outside the
* company, without a redeploy. Stored in clear rather than hashed because
* it is a passphrase a human reads aloud and an admin has to be able to
* see it to share it — and because it grants nothing but the platform
* track, which is marketing material. It is compared in constant time all
* the same; the timing of a wrong answer should not narrow the guess.
*
* The initial value is a column default so the row is never without one.
*/
learnAccessCode: text('learn_access_code').notNull().default('carlthefog'),
learnAccessCodeUpdatedAt: timestamp('learn_access_code_updated_at', { withTimezone: true }),
updatedByUserId: uuid('updated_by_user_id').references(() => users.id, {
onDelete: 'set null',
}),
+386 -15
View File
@@ -35,7 +35,7 @@
* is more useful than one that opens on a loss, which reads as a broken
* product rather than an under-utilised book.
*/
import { ALLOCATION_STATUSES, type AllocationStatus } from '@pig/core';
import { ALLOCATION_STATUSES, quarterBoundsFor, type AllocationStatus } from '@pig/core';
import { and, eq, like, or } from 'drizzle-orm';
import { createDatabase } from '../client';
import {
@@ -43,16 +43,21 @@ import {
activities,
facts,
allocations,
calendarEntries,
capacityCommitments,
capacityRequests,
complianceArtifacts,
contacts,
contracts,
contractObligations,
demandDeals,
exportAuthorizations,
learnResources,
type NewAllocation,
sites,
slaTerms,
supplyDeals,
users,
} from '../schema/index';
const db = createDatabase();
@@ -66,6 +71,31 @@ function isAllocationStatus(value: string): value is AllocationStatus {
return (ALLOCATION_STATUSES as readonly string[]).includes(value);
}
/**
* Dates are placed by QUARTER, and deterministically.
*
* This file used to scatter close dates with `at(20 + Math.random() * 60)`,
* which put the whole book in one arbitrary bucket, differently on every run —
* so the quarterly view could not be demonstrated and the CI seed-idempotency
* gate was one unlucky reseed away from a false failure. Placement is now
* deliberate: something in the quarter just gone, several in the one we are
* in, and a couple in the next, so the calendar has all three states to show.
*/
const thisQuarter = quarterBoundsFor(new Date(now));
function quarterAt(offset: -1 | 0 | 1, fraction: number): Date {
const bounds =
offset === 0
? thisQuarter
: quarterBoundsFor(
new Date(
offset < 0 ? thisQuarter.from.getTime() - 1 : thisQuarter.to.getTime(),
),
);
const span = bounds.to.getTime() - bounds.from.getTime();
return new Date(bounds.from.getTime() + Math.round(span * fraction));
}
/** GPU-hours for a block, allowing for a maintenance/ramp haircut. */
const hours = (gpus: number, days: number, efficiency = 0.94) =>
String(Math.round(gpus * 24 * days * efficiency));
@@ -136,6 +166,69 @@ const SUPPLY = [
},
];
/**
* Dated obligations per supplier, spread deliberately across the year.
*
* `kind` is one of the five the schema allows. The near-term Nebius notice is
* kept so the renewal alarm still has something to fire on today.
*/
const OBLIGATION_SCHEDULE: Record<
string,
{ title: string; kind: 'renewal_notice' | 'payment' | 'true_up'; inDays: number; description: string }[]
> = {
'nebius.com': [
{
title: 'Renewal notice',
kind: 'renewal_notice',
inDays: 21,
description: '90 days notice required to prevent auto-renewal.',
},
{
title: 'Quarterly instalment',
kind: 'payment',
inDays: 75,
description: 'Committed spend invoiced quarterly in arrears.',
},
],
'coreweave.com': [
{
title: 'Renewal notice',
kind: 'renewal_notice',
inDays: 95,
description: '90 days notice required to prevent auto-renewal.',
},
{
title: 'Prepayment drawdown reconciliation',
kind: 'payment',
inDays: 40,
description: 'Reconcile the 25% prepayment against hours actually drawn.',
},
{
title: 'Take-or-pay true-up',
kind: 'true_up',
inDays: 130,
// The obligation that turns idle capacity from a metric into an invoice.
description: 'Shortfall against the 100% floor becomes payable at the true-up date.',
},
],
'crusoe.ai': [
{
title: 'Renewal notice',
kind: 'renewal_notice',
inDays: 160,
description: '90 days notice required to prevent auto-renewal.',
},
],
'runpod.io': [
{
title: 'Renewal notice',
kind: 'renewal_notice',
inDays: 250,
description: '90 days notice required to prevent auto-renewal.',
},
],
};
/**
* Fictional customers.
*
@@ -158,6 +251,9 @@ const DEMAND = [
msaExecuted: true,
dpaExecuted: true,
},
// Slipped: the close date is in the quarter just gone while the deal is
// still open, so the calendar has a genuinely overdue item to render.
close: { quarter: -1 as const, fraction: 0.62 },
request: { gpuType: 'H200', gpuCount: 256, fastFabric: true, maxPriceCents: 285 },
// Draws from the CoreWeave block.
allocation: {
@@ -181,6 +277,7 @@ const DEMAND = [
msaExecuted: true,
dpaExecuted: false,
},
close: { quarter: 0 as const, fraction: 0.55 },
// Data residency: must land in the EU. Drives the Nebius block.
request: {
gpuType: 'H100_80GB',
@@ -211,6 +308,7 @@ const DEMAND = [
msaExecuted: true,
dpaExecuted: true,
},
close: { quarter: 0 as const, fraction: 0.82 },
request: { gpuType: 'B200', gpuCount: 32, fastFabric: true, maxPriceCents: 460 },
allocation: {
supplier: 'crusoe.ai',
@@ -233,6 +331,7 @@ const DEMAND = [
msaExecuted: false,
dpaExecuted: false,
},
close: { quarter: 0 as const, fraction: 0.34 },
request: { gpuType: 'A100_80GB', gpuCount: 16, fastFabric: false, maxPriceCents: 175 },
// A HOLD, not a sale. The deal has not closed, so this reserves capacity
// without counting as revenue — the distinction the capacity view exists
@@ -259,6 +358,7 @@ const DEMAND = [
msaExecuted: false,
dpaExecuted: false,
},
close: { quarter: 1 as const, fraction: 0.38 },
request: { gpuType: 'H200', gpuCount: 128, fastFabric: true, maxPriceCents: 265 },
allocation: null, // Still in legal. Nothing reserved yet — correctly.
},
@@ -276,6 +376,7 @@ const DEMAND = [
msaExecuted: false,
dpaExecuted: false,
},
close: { quarter: 1 as const, fraction: 0.74 },
request: null,
allocation: null,
},
@@ -290,6 +391,8 @@ async function clear() {
.where(like(accounts.name, `${PREFIX}%`));
const ids = demoAccounts.map((a) => a.id);
await db.delete(calendarEntries).where(like(calendarEntries.title, `${PREFIX}%`));
await db.delete(learnResources).where(like(learnResources.title, `${PREFIX}%`));
await db.delete(allocations).where(like(allocations.notes, `${PREFIX}%`));
await db.delete(contractObligations);
await db.delete(slaTerms);
@@ -300,6 +403,10 @@ async function clear() {
await db.delete(capacityCommitments).where(like(capacityCommitments.name, `${PREFIX}%`));
await db.delete(activities).where(like(activities.subject, `${PREFIX}%`));
for (const id of ids) {
// Compliance rows cascade on the account anyway; deleted explicitly so the
// order of removal stays readable rather than relying on the constraint.
await db.delete(exportAuthorizations).where(eq(exportAuthorizations.accountId, id));
await db.delete(complianceArtifacts).where(eq(complianceArtifacts.accountId, id));
await db.delete(contacts).where(eq(contacts.accountId, id));
}
await db.delete(accounts).where(like(accounts.name, `${PREFIX}%`));
@@ -390,7 +497,10 @@ async function seedDemo() {
side: 'supply',
title: `${PREFIX}MSA — ${supplier.domain}`,
capacityCommitmentId: commitment?.id,
effectiveAt: at(-60),
// The anchor tenant's paper predates the block by months. Without one
// contract genuinely in the past, every `contract_effective` event on
// the calendar sits in the same fortnight and the view teaches nothing.
effectiveAt: supplier.domain === 'coreweave.com' ? at(-150) : at(-60),
expiresAt: at(c.days + 60),
isAutoRenew: true,
noticeDays: 90,
@@ -441,15 +551,26 @@ async function seedDemo() {
});
}
await db.insert(contractObligations).values({
contractId: msa.id,
title: `${PREFIX}Renewal notice — ${supplier.domain}`,
kind: 'renewal_notice',
// Deliberately near-term on one supplier so the renewal alarm has
// something real to fire on.
dueAt: at(supplier.domain === 'nebius.com' ? 21 : 200),
description: '90 days notice required to prevent auto-renewal.',
});
/*
* Obligations spread across the year rather than bunched.
*
* Three of the four used to fall on the same day at +200, which made
* every quarter after this one look empty and the current one look
* uneventful. They are the dated things most likely to be missed, so a
* demo that cannot show one falling due in each quarter is not showing
* the feature at all. Payment and true-up dates are here for the same
* reason: a renewal notice is not the only deadline that costs money.
*/
const obligationsFor = OBLIGATION_SCHEDULE[supplier.domain] ?? [];
for (const obligation of obligationsFor) {
await db.insert(contractObligations).values({
contractId: msa.id,
title: `${PREFIX}${obligation.title}${supplier.domain}`,
kind: obligation.kind,
dueAt: at(obligation.inDays),
description: obligation.description,
});
}
}
await db.insert(supplyDeals).values({
@@ -518,7 +639,7 @@ async function seedDemo() {
description: 'Fictional company, for demonstration only.',
source: 'seed',
confidence: 'confirmed',
lastActivityAt: at(-Math.random() * 10),
lastActivityAt: at(-2 - (DEMAND.indexOf(d) % 5)),
})
.returning();
if (!account) continue;
@@ -550,13 +671,13 @@ async function seedDemo() {
msaExecuted: d.deal.msaExecuted,
dpaExecuted: d.deal.dpaExecuted,
primaryContactId: contact?.id,
expectedCloseDate: at(20 + Math.round(Math.random() * 60)),
expectedCloseDate: quarterAt(d.close.quarter, d.close.fraction),
probability: String(
{ qualification: 0.1, legal: 0.35, proposal: 0.45, procurement: 0.6, poc: 0.7, deployment: 0.9 }[
d.deal.stage
] ?? 0.5,
),
lastActivityAt: at(-Math.random() * 8),
lastActivityAt: at(-1 - (DEMAND.indexOf(d) % 6)),
})
.returning();
if (!deal) continue;
@@ -666,6 +787,246 @@ async function seedDemo() {
}
}
// ------------------------------------------------ compliance deadlines
//
// Both of these columns are indexed, both carry a schema comment saying they
// MUST be alerted on, and until the calendar existed neither was read by a
// single endpoint or shown on a single screen. An export authorisation that
// lapses unnoticed converts lawful business into unlawful business; a SOC 2
// report that expires mid-procurement stalls the deal it was gating. Seeding
// one of each means the quarterly view opens with both visible.
const [verity] = await db
.select({ id: accounts.id })
.from(accounts)
.where(eq(accounts.name, `${PREFIX}Verity Health AI`))
.limit(1);
if (verity) {
const AUTHORIZATION_REFERENCE = `${PREFIX}DC-VEU-2026-0417`;
const [existingAuthorization] = await db
.select({ id: exportAuthorizations.id })
.from(exportAuthorizations)
.where(eq(exportAuthorizations.reference, AUTHORIZATION_REFERENCE))
.limit(1);
if (!existingAuthorization) {
await db.insert(exportAuthorizations).values({
accountId: verity.id,
authorizationType: 'dc_veu',
reference: AUTHORIZATION_REFERENCE,
scopeNotes:
'Illustrative demo record. Covers EU-resident training workloads only; ' +
'inference in other regions is out of scope.',
issuedAt: at(-320),
// Inside the current quarter on almost any day of the year, and close
// enough that it reads as urgent rather than as a diary note.
expiresAt: at(45),
evidenceUrl: 'https://example.invalid/demo-authorisation',
// Rules in flux for this counterparty: re-verify, do not trust the date.
volatile: true,
});
}
const ARTIFACT_SCOPE = `${PREFIX}EU training platform`;
const [existingArtifact] = await db
.select({ id: complianceArtifacts.id })
.from(complianceArtifacts)
.where(eq(complianceArtifacts.scope, ARTIFACT_SCOPE))
.limit(1);
if (!existingArtifact) {
await db.insert(complianceArtifacts).values({
accountId: verity.id,
claim: 'soc2',
scope: ARTIFACT_SCOPE,
// A true certification, not an alignment claim — the distinction the
// column exists for, and the one procurement actually gates on.
isCertified: true,
soc2Type: 'type_ii',
observationWindowStart: at(-365),
observationWindowEnd: at(-10),
auditFirm: 'Demo Assurance LLP',
carveOutMethod: 'carve_out',
productsInScope: ['training', 'managed inference'],
evidenceUrl: 'https://example.invalid/demo-soc2',
expiresAt: quarterAt(1, 0.5),
});
}
}
// ------------------------------------------------------- calendar entries
//
// The only rows the calendar owns. Everything else on it is projected from
// a record that already carries the date; these are the human-owned items
// that have nowhere else to live.
const [owner] = await db.select({ id: users.id }).from(users).limit(1);
const [halcyon] = await db
.select({ id: accounts.id })
.from(accounts)
.where(eq(accounts.name, `${PREFIX}Halcyon Research`))
.limit(1);
const CALENDAR_ENTRIES = [
{
title: `${PREFIX}Q business review — Halcyon Research`,
kind: 'qbr' as const,
description: 'Utilisation against the reserved block, and the expansion case.',
startsAt: quarterAt(0, 0.7),
durationMinutes: 90,
accountId: halcyon?.id ?? null,
},
{
title: `${PREFIX}Renewal check-in — Nebius`,
kind: 'meeting' as const,
// A fortnight ahead of the +21 renewal notice obligation, which is the
// point: the reminder has to land before the deadline, not on it.
description: 'Decide whether to give notice before the 90-day window closes.',
startsAt: at(7),
durationMinutes: 45,
accountId: null,
},
{
title: `${PREFIX}Pipeline review — next quarter commit`,
kind: 'internal' as const,
description: 'Weighted pipeline against the number, before the quarter opens.',
startsAt: quarterAt(1, 0.02),
durationMinutes: 60,
accountId: null,
},
{
title: `${PREFIX}Blackwell availability campaign`,
kind: 'campaign' as const,
description: 'Outbound week against accounts waiting on B200 capacity.',
startsAt: quarterAt(0, 0.45),
// A span, not a point — the calendar must render both.
durationMinutes: 5 * 24 * 60,
accountId: null,
},
];
let entriesAdded = 0;
for (const entry of CALENDAR_ENTRIES) {
const [existingEntry] = await db
.select({ id: calendarEntries.id })
.from(calendarEntries)
.where(eq(calendarEntries.title, entry.title))
.limit(1);
if (existingEntry) continue;
await db.insert(calendarEntries).values({
title: entry.title,
description: entry.description,
kind: entry.kind,
startsAt: entry.startsAt,
endsAt: new Date(entry.startsAt.getTime() + entry.durationMinutes * 60_000),
allDay: entry.durationMinutes >= 24 * 60,
accountId: entry.accountId,
ownerUserId: owner?.id ?? null,
createdByUserId: owner?.id ?? null,
});
entriesAdded += 1;
}
// ------------------------------------------------------------- learn
//
// Every id below is a REAL public recording on the Cap instance at
// video.karti.ai, checked against its database rather than invented. A demo
// row whose embed 404s teaches nothing and reads as a broken feature, which
// is the opposite of what a demo seed is for — so the titles are illustrative
// and prefixed, and the videos behind them are whatever is actually there.
//
// The platform rows are `code`-visible: they are what a code-holder with no
// account sees. The concept rows are `members`, and the CHECK constraint on
// the table would refuse them any other way round.
const LEARN_RESOURCES = [
{
track: 'platform' as const,
title: `${PREFIX}Your first hour in PIG`,
summary: 'Signing in, finding your pipeline, and what the Overview numbers mean.',
externalId: '0n6n9p83efnxbs2',
visibility: 'code' as const,
durationSeconds: 8 * 60 + 40,
sortOrder: 10,
},
{
track: 'platform' as const,
title: `${PREFIX}Allocations: joining what we bought to what we sold`,
summary: 'The one table the product is built around, walked through on the demo book.',
externalId: '1rqq9rk4dpp71fd',
visibility: 'code' as const,
durationSeconds: 12 * 60 + 15,
sortOrder: 20,
},
{
track: 'platform' as const,
title: `${PREFIX}Reading the margin report without fooling yourself`,
summary: 'Why cost is charged against the whole commitment, and what idle capacity costs.',
externalId: 'sjqqvthbfma27bm',
visibility: 'code' as const,
durationSeconds: 9 * 60 + 5,
sortOrder: 30,
},
{
track: 'supply' as const,
title: `${PREFIX}How neocloud capacity is actually priced`,
summary: 'Reserved versus on-demand, commitment length, and where the spread comes from.',
externalId: '0n6n9p83efnxbs2',
visibility: 'members' as const,
durationSeconds: 14 * 60 + 30,
sortOrder: 10,
},
{
track: 'supply' as const,
title: `${PREFIX}Qualifying a provider: fabric, tier and paperwork`,
summary: 'Interconnect, security tier and the contract weight each supplier archetype brings.',
externalId: '1rqq9rk4dpp71fd',
visibility: 'members' as const,
durationSeconds: 11 * 60,
sortOrder: 20,
},
{
track: 'demand' as const,
title: `${PREFIX}Discovery for a training run`,
summary: 'The five questions that decide whether a deal is servable before you quote it.',
externalId: 'sjqqvthbfma27bm',
visibility: 'members' as const,
durationSeconds: 16 * 60 + 20,
sortOrder: 10,
},
{
track: 'demand' as const,
title: `${PREFIX}Holds, and why one is not revenue`,
summary: 'What a hold removes from everyone else, and when to let one expire.',
externalId: '0n6n9p83efnxbs2',
visibility: 'members' as const,
durationSeconds: 7 * 60 + 45,
sortOrder: 20,
},
];
let learnAdded = 0;
for (const resource of LEARN_RESOURCES) {
// Idempotent on the unique key rather than an existence check, which is
// the whole reason that constraint exists: onConflictDoNothing without one
// is a silent no-op and has duplicated seed data here twice before.
const inserted = await db
.insert(learnResources)
.values({
track: resource.track,
title: resource.title,
summary: resource.summary,
url: `https://video.karti.ai/s/${resource.externalId}`,
provider: 'cap',
externalId: resource.externalId,
visibility: resource.visibility,
durationSeconds: resource.durationSeconds,
sortOrder: resource.sortOrder,
addedByUserId: owner?.id ?? null,
})
.onConflictDoNothing({
target: [learnResources.track, learnResources.provider, learnResources.externalId],
})
.returning({ id: learnResources.id });
if (inserted.length) learnAdded += 1;
}
// -------------------------------------------------- agent-derived facts
//
// Without these the fact-review queue and every provenance tooltip are
@@ -819,7 +1180,7 @@ async function seedDemo() {
method: seed.method,
sourceUrl: seed.sourceUrl,
evidence: seed.evidence,
observedAt: at(-Math.round(Math.random() * 6) - 1),
observedAt: at(-1 - (factSeeds.indexOf(seed) % 6)),
});
factsAdded += 1;
}
@@ -828,6 +1189,16 @@ async function seedDemo() {
console.log(` ${factSeeds.length} agent-derived facts (${factsAdded} new) — 2 applied, 4 awaiting review`);
console.log(' 6 demand deals across the pipeline, 5 supply deals');
console.log(' Allocations including one unconverted hold and internal research burn');
console.log(
' Close dates placed deliberately in the previous, current and next quarter',
);
console.log(
` 1 export authorisation (45 days), 1 SOC 2 report (next quarter), ` +
`${CALENDAR_ENTRIES.length} calendar entries (${entriesAdded} new)`,
);
console.log(
` ${LEARN_RESOURCES.length} learn resources (${learnAdded} new) — 3 platform walkthroughs behind the share code`,
);
console.log('\nEverything is prefixed "DEMO — ". Remove it with: pnpm db:demo -- --clear');
}
+17
View File
@@ -120,6 +120,23 @@ async function seed() {
// --------------------------------------------------- customer references
for (const reference of PUBLIC_CUSTOMER_REFERENCES) {
/*
* An existence check, not `onConflictDoNothing()`.
*
* These accounts have no domain, and the only unique index on `accounts`
* is on the domain so there was nothing to conflict on and the clause
* was a no-op, exactly as the README warns. Every run added another Ramp
* and another Zapier. Nobody noticed because the CI idempotency gate
* counts `contacts`, and the contact insert below already had its own
* existence check.
*/
const [alreadyPresent] = await db
.select({ id: accounts.id })
.from(accounts)
.where(eq(accounts.name, reference.account))
.limit(1);
if (alreadyPresent) continue;
const [account] = await db
.insert(accounts)
.values({