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
+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({