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
+408
View File
@@ -0,0 +1,408 @@
/**
* Quarters, and the one shape everything dated turns into.
*
* PIG's argument is that one ledger answers the question, so the calendar is a
* PROJECTION over records that already carry dates — contracts, obligations,
* deals, commitments, allocations, compliance artefacts — not a second store
* that would immediately drift from them. The only rows that live in their own
* table are the ones with no other home: a meeting, a QBR, a reminder.
*
* Kept in @pig/core because the browser and the API must agree on the event
* shape and on where a quarter begins.
*
* Two decisions are load-bearing here and are pinned by tests.
*
* **A quarter is half-open, [from, to).** Every temporal column in PIG is
* `timestamp with time zone`; there is not a single `date` column. So a
* quarter is an interval of instants, and consecutive quarters must tile
* without overlapping. An inclusive upper bound puts a contract expiring at
* exactly midnight on 1 October into both Q3 and Q4, and a GTM lead adding up
* two quarters then counts it twice.
*
* **A fiscal year is named for the calendar year it ENDS in.** This is the
* dominant convention among the companies whose paper PIG holds — a fiscal
* year beginning April 2026 and ending March 2027 is FY2027. The alternative
* (naming for the starting year) is also in use, which is exactly why the
* choice is stated here once rather than assumed at each call site.
*/
export type QuarterNumber = 1 | 2 | 3 | 4;
/** A fiscal or calendar quarter label, e.g. `2026-Q3`. */
export type Quarter = `${number}-Q${QuarterNumber}`;
/** Half-open interval of instants: `from` is included, `to` is not. */
export interface QuarterBounds {
from: Date;
to: Date;
quarter: Quarter;
}
/**
* Kinds of dated thing the projection can emit.
*
* Every one of these is derived from a record that already carries the date,
* except `calendar_entry`, which is the only row type the calendar owns.
*/
export const CALENDAR_EVENT_KINDS = [
'expected_close',
'contract_effective',
'contract_expiry',
'contract_executed',
'renewal_notice',
'obligation_due',
'capacity_window',
'allocation_window',
'hold_expiry',
'supply_available_from',
'authorization_expiry',
'artifact_expiry',
'calendar_entry',
] as const;
export type CalendarEventKind = (typeof CALENDAR_EVENT_KINDS)[number];
export function isCalendarEventKind(value: string): value is CalendarEventKind {
return (CALENDAR_EVENT_KINDS as readonly string[]).includes(value);
}
/** The kinds a human-owned `calendar_entries` row may take. */
export const CALENDAR_ENTRY_KINDS = [
'meeting',
'qbr',
'reminder',
'campaign',
'internal',
] as const;
export type CalendarEntryKind = (typeof CALENDAR_ENTRY_KINDS)[number];
/**
* `done` is set by a completion column, never by the clock — an obligation
* whose due date has passed is `overdue`, not finished, and conflating the two
* is how a missed renewal notice disappears from a screen.
*/
export type CalendarEventState = 'upcoming' | 'due' | 'overdue' | 'done';
export interface CalendarEvent {
/**
* `${recordType}:${recordId}:${field}` — synthesised, never stored. A
* derived projection has no primary key of its own, and inventing one in a
* table would mean the same expiry date living in two places.
*/
id: string;
kind: CalendarEventKind;
title: string;
/**
* ISO-8601. Strings rather than `Date` because this interface crosses the
* wire: the browser receives JSON, and a shape that only typechecks before
* serialisation is a shape the front end cannot honestly claim to hold.
*/
startsAt: string;
/** Null for a point in time. */
endsAt: string | null;
isSpan: boolean;
state: CalendarEventState;
accountId: string | null;
accountName: string | null;
ownerUserId: string | null;
/** Integer cents, per the money rule. Null where the event has no value. */
amountCents: number | null;
currency: string | null;
/** The table the event was derived from, e.g. `contract`. */
recordType: string;
recordId: string;
href: string;
meta: Record<string, unknown>;
}
/** Stable, storage-free identity for a projected event. */
export function calendarEventId(
recordType: string,
recordId: string,
field: string,
): string {
return `${recordType}:${recordId}:${field}`;
}
/**
* How soon before its date an event counts as `due` rather than `upcoming`.
* Seven days is the shortest horizon in which a renewal notice or an export
* authorisation can still realistically be acted on.
*/
export const CALENDAR_DUE_HORIZON_DAYS = 7;
const DAY_MS = 86_400_000;
export function eventState(input: {
at: Date;
now: Date;
completedAt?: Date | null;
dueWithinDays?: number;
}): CalendarEventState {
if (input.completedAt) return 'done';
const at = input.at.getTime();
const now = input.now.getTime();
if (at < now) return 'overdue';
const horizon = (input.dueWithinDays ?? CALENDAR_DUE_HORIZON_DAYS) * DAY_MS;
return at - now <= horizon ? 'due' : 'upcoming';
}
/**
* A span's state reads from its END, because a window that has started is not
* late — it is running. Only a window that has closed is behind us.
*
* `done` is right here only because these spans have no completion column: a
* capacity or allocation window IS the fact, and it is over when the clock says
* so. A span nobody could fail to do cannot be overdue. For anything a person
* was supposed to do inside the window, use `completableSpanState`.
*/
export function spanState(input: {
startsAt: Date;
endsAt: Date;
now: Date;
}): CalendarEventState {
if (input.endsAt.getTime() < input.now.getTime()) return 'done';
if (input.startsAt.getTime() <= input.now.getTime()) return 'due';
return eventState({ at: input.startsAt, now: input.now });
}
/**
* The same reading of a span for a row that CAN record completion — today only
* `calendar_entries`, which carries `completed_at`.
*
* The end still decides running versus past, but a closed window with nothing
* in the completion column is `overdue`, not `done`. Reusing `spanState` here
* made a missed QBR read as finished purely because its author had typed an end
* time — the byte-identical entry without one read `overdue` — which is exactly
* the conflation the note above `CalendarEventState` forbids.
*/
export function completableSpanState(input: {
startsAt: Date;
endsAt: Date;
now: Date;
completedAt?: Date | null;
}): CalendarEventState {
if (input.completedAt) return 'done';
if (input.endsAt.getTime() < input.now.getTime()) return 'overdue';
if (input.startsAt.getTime() <= input.now.getTime()) return 'due';
return eventState({ at: input.startsAt, now: input.now });
}
// ---------------------------------------------------------------- time zones
interface ZonedParts {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
}
/**
* Constructing an `Intl.DateTimeFormat` is expensive enough to be worth
* keeping, but the key is a caller-supplied string that reaches here from a
* query parameter, so the map is capped: an unbounded one lets a loop over
* distinct values grow a long-lived API process without limit. The IANA
* database has well under 500 zones, so a real deployment never evicts;
* insertion-order eviction only ever bites junk.
*/
const FORMATTER_CACHE_LIMIT = 512;
const formatterCache = new Map<string, Intl.DateTimeFormat>();
/** Whether the runtime's ICU data recognises `timeZone` as an IANA zone. */
export function isValidTimeZone(timeZone: string): boolean {
try {
new Intl.DateTimeFormat('en-US', { timeZone });
return true;
} catch {
return false;
}
}
/**
* Falls back to UTC rather than throwing. `users.timezone` is free text set
* through a preferences endpoint that does not validate it, so a stale or
* mistyped zone must degrade to a defensible answer instead of 500ing the
* whole calendar. Request-supplied zones are rejected at the route boundary
* instead, where a 400 can still tell the caller what was wrong.
*/
function formatterFor(timeZone: string): Intl.DateTimeFormat {
const cached = formatterCache.get(timeZone);
if (cached) return cached;
let formatter: Intl.DateTimeFormat;
try {
formatter = new Intl.DateTimeFormat('en-US', {
timeZone,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
} catch {
formatter = formatterFor('UTC');
}
if (formatterCache.size >= FORMATTER_CACHE_LIMIT) {
const oldest = formatterCache.keys().next();
if (!oldest.done) formatterCache.delete(oldest.value);
}
formatterCache.set(timeZone, formatter);
return formatter;
}
function zonedParts(instant: Date, timeZone: string): ZonedParts {
const parts = formatterFor(timeZone).formatToParts(instant);
const read = (type: Intl.DateTimeFormatPartTypes): number =>
Number(parts.find((part) => part.type === type)?.value ?? '0');
return {
year: read('year'),
month: read('month'),
day: read('day'),
hour: read('hour'),
minute: read('minute'),
second: read('second'),
};
}
function offsetMsAt(instant: Date, timeZone: string): number {
const parts = zonedParts(instant, timeZone);
const asIfUtc = Date.UTC(
parts.year,
parts.month - 1,
parts.day,
parts.hour,
parts.minute,
parts.second,
);
return asIfUtc - instant.getTime();
}
/**
* The instant at which local midnight begins on a given day in a given zone.
*
* Iterated rather than solved because the offset depends on the instant we are
* trying to find. Two passes settle every real zone including the daylight
* transitions; the third is insurance and costs nothing.
*/
function startOfZonedDay(
year: number,
month: number,
day: number,
timeZone: string,
): Date {
const wallClock = Date.UTC(year, month - 1, day);
let instant = wallClock;
for (let pass = 0; pass < 3; pass += 1) {
instant = wallClock - offsetMsAt(new Date(instant), timeZone);
}
return new Date(instant);
}
// ------------------------------------------------------------------ quarters
function assertFiscalStart(fiscalYearStartMonth: number): void {
if (
!Number.isInteger(fiscalYearStartMonth) ||
fiscalYearStartMonth < 0 ||
fiscalYearStartMonth > 11
) {
throw new RangeError(
`fiscalYearStartMonth must be an integer month index 011, got ${fiscalYearStartMonth}.`,
);
}
}
/**
* Which quarter an instant falls in.
*
* `fiscalYearStartMonth` is a zero-based month index: 0 for calendar quarters
* (the default), 3 for an April start, 9 for an October start. `timeZone`
* decides the boundary, and it matters: 31 December 23:00 in New York is
* already Q1 in London.
*/
export function quarterOf(
date: Date,
fiscalYearStartMonth = 0,
timeZone = 'UTC',
): Quarter {
assertFiscalStart(fiscalYearStartMonth);
const local = zonedParts(date, timeZone);
const monthIndex = local.month - 1;
// Months elapsed since the fiscal year began, 011.
const sinceStart = (monthIndex - fiscalYearStartMonth + 12) % 12;
const quarter = (Math.floor(sinceStart / 3) + 1) as QuarterNumber;
// Named for the year the fiscal year ends in — see the note at the top.
const startedThisCalendarYear = monthIndex >= fiscalYearStartMonth;
const fiscalYear =
fiscalYearStartMonth === 0
? local.year
: startedThisCalendarYear
? local.year + 1
: local.year;
return `${fiscalYear}-Q${quarter}`;
}
/**
* The half-open bounds of a quarter, as instants.
*
* `year` is the fiscal year label, not the calendar year in which the quarter
* starts — those differ for every non-calendar fiscal offset, which is the
* mistake this signature exists to make hard to write.
*/
export function quarterBounds(
year: number,
quarter: QuarterNumber,
fiscalYearStartMonth = 0,
timeZone = 'UTC',
): QuarterBounds {
assertFiscalStart(fiscalYearStartMonth);
if (!Number.isInteger(quarter) || quarter < 1 || quarter > 4) {
throw new RangeError(`quarter must be 14, got ${quarter}.`);
}
// Inverse of the labelling rule in quarterOf: a non-calendar fiscal year
// labelled `year` began in the previous calendar year.
const fiscalStartCalendarYear = fiscalYearStartMonth === 0 ? year : year - 1;
const startMonthIndex = fiscalYearStartMonth + (quarter - 1) * 3;
const from = startOfZonedDay(
fiscalStartCalendarYear + Math.floor(startMonthIndex / 12),
(startMonthIndex % 12) + 1,
1,
timeZone,
);
const endMonthIndex = startMonthIndex + 3;
const to = startOfZonedDay(
fiscalStartCalendarYear + Math.floor(endMonthIndex / 12),
(endMonthIndex % 12) + 1,
1,
timeZone,
);
return { from, to, quarter: `${year}-Q${quarter}` };
}
/** Splits `2026-Q3` back into its parts. Null when the label is malformed. */
export function parseQuarter(
label: string,
): { year: number; quarter: QuarterNumber } | null {
const match = /^(\d{4})-Q([1-4])$/.exec(label);
if (!match) return null;
return {
year: Number(match[1]),
quarter: Number(match[2]) as QuarterNumber,
};
}
/** The bounds of the quarter containing `date`. */
export function quarterBoundsFor(
date: Date,
fiscalYearStartMonth = 0,
timeZone = 'UTC',
): QuarterBounds {
const parsed = parseQuarter(quarterOf(date, fiscalYearStartMonth, timeZone));
if (!parsed) throw new Error('quarterOf produced an unparseable label.');
return quarterBounds(parsed.year, parsed.quarter, fiscalYearStartMonth, timeZone);
}
+3
View File
@@ -1,6 +1,9 @@
export * from './ontology';
export * from './calendar';
export * from './learn';
export * from './margin';
export * from './permissions';
export * from './piggy-context';
export * from './theme';
export * from './imports';
export * from './lifecycle';
+307
View File
@@ -0,0 +1,307 @@
/**
* Learn — the two tracks, and the host allowlist that turns a pasted link into
* an iframe source.
*
* **Two tracks, and they are not the same kind of thing.** `supply` and
* `demand` are CONCEPT material: how this market actually works, taught to the
* GTM team that runs that side. `platform` is PIG itself — onboarding, feature
* walkthroughs, demos. The distinction is load-bearing rather than cosmetic,
* because the access code unlocks exactly one of them.
*
* **Only the platform track may be visible to a code-holder.** Someone holding
* the share code has no account and no principal; they may see how the product
* works, because that is a sales asset. They may not see how we source and
* price capacity. This predicate is enforced three times on purpose — here, in
* the API write path, and in a database CHECK constraint — because a concept
* video becoming anon-visible through a mistake in a form is the failure that
* matters, and a UI-only rule does not survive an API caller.
*
* **The allowlist is the whole XSS surface of the feature.** A learn resource
* is a URL somebody pasted, and it ends up as an `iframe src`. So a pasted URL
* is never stored as a source and never rendered as one: it is resolved
* through the table below into a *provider* and an *external id*, and every
* embed URL is rebuilt from a hardcoded template and a pattern-checked id.
* Anything the table does not match is rejected at the write path, so a row
* that cannot be rendered safely cannot exist.
*
* Adding a provider is one row here plus one host in the proxy's `frame-src`
* (see `LEARN_FRAME_SRC_HOSTS`). Do not add a row whose URL shape has not been
* checked against the running service — the id extraction is what decides
* whether a hostile path becomes a trusted embed.
*/
// ---------------------------------------------------------------------------
// Tracks and visibility
// ---------------------------------------------------------------------------
export const LEARN_TRACKS = ['supply', 'demand', 'platform'] as const;
export type LearnTrack = (typeof LEARN_TRACKS)[number];
/** The tracks that teach the market rather than the product. Members only. */
export const LEARN_CONCEPT_TRACKS = ['supply', 'demand'] as const satisfies readonly LearnTrack[];
export type LearnConceptTrack = (typeof LEARN_CONCEPT_TRACKS)[number];
/** The one track a code-holder may reach. Named once; referenced everywhere. */
export const LEARN_CODE_TRACK = 'platform' as const satisfies LearnTrack;
export const LEARN_TRACK_LABELS: Record<LearnTrack, string> = {
supply: 'Supply',
demand: 'Demand',
platform: 'Platform',
};
export const LEARN_TRACK_DESCRIPTIONS: Record<LearnTrack, string> = {
supply: 'How capacity is sourced, qualified, priced and contracted.',
demand: 'How compute is sold, renewed and expanded.',
platform: 'Onboarding, feature walkthroughs and product demos of PIG itself.',
};
export const LEARN_VISIBILITIES = ['members', 'code'] as const;
export type LearnVisibility = (typeof LEARN_VISIBILITIES)[number];
export function isLearnTrack(value: string): value is LearnTrack {
return (LEARN_TRACKS as readonly string[]).includes(value);
}
export function isLearnVisibility(value: string): value is LearnVisibility {
return (LEARN_VISIBILITIES as readonly string[]).includes(value);
}
/**
* May this track carry this visibility?
*
* Phrased as a predicate over the pair rather than "is this track public", so
* that the check reads the same in the write path and in the CHECK constraint
* and neither can drift into asking a subtly different question.
*/
export function learnVisibilityPermitted(track: LearnTrack, visibility: LearnVisibility): boolean {
return visibility !== 'code' || track === LEARN_CODE_TRACK;
}
// ---------------------------------------------------------------------------
// The provider allowlist
// ---------------------------------------------------------------------------
export const LEARN_PROVIDERS = ['cap', 'loom', 'youtube_nocookie'] as const;
export type LearnProvider = (typeof LEARN_PROVIDERS)[number];
export interface LearnProviderDefinition {
provider: LearnProvider;
label: string;
/**
* Disabled providers are inert: a pasted link matching one is rejected, so a
* row can never be created and nothing can ever be framed from it. They are
* listed so that turning one on is a flag and a CSP host rather than a
* design exercise under time pressure.
*/
enabled: boolean;
/** Exact hostnames. Never a suffix match — `evil-loom.com` ends in loom.com. */
hosts: readonly string[];
/** Path prefixes whose NEXT segment is the id, and nothing after it. */
idSegmentPrefixes: readonly string[];
/** The id charset, anchored. Everything downstream trusts this. */
idPattern: RegExp;
embed(externalId: string): string;
watch(externalId: string): string;
/** What the proxy's `frame-src` needs before this provider can render. */
frameSrc: string;
}
/**
* Cap (cap.so) self-hosted at video.karti.ai.
*
* Verified against the running instance rather than assumed: the Next.js app
* carries `app/s/[videoId]` and `app/embed/[videoId]`, both of which answer 404
* for an unknown id — which is how we know the routes exist at all, since
* every unrouted path there answers 307 instead. Ids observed in that
* instance's database are lowercase alphanumeric, 15 characters; the pattern
* is deliberately a little wider than that and no wider.
*
* HyperFrames (app.heygen.com) is the next one wanted. It is absent rather
* than disabled because its share/embed path shape has not been checked
* against the live service, and guessing that is precisely how an id
* extraction ends up accepting a path it should not.
*/
export const LEARN_PROVIDER_TABLE: readonly LearnProviderDefinition[] = [
{
provider: 'cap',
label: 'Cap',
enabled: true,
hosts: ['video.karti.ai'],
idSegmentPrefixes: ['s', 'embed'],
idPattern: /^[a-z0-9]{8,32}$/,
embed: (id) => `https://video.karti.ai/embed/${id}`,
watch: (id) => `https://video.karti.ai/s/${id}`,
frameSrc: 'https://video.karti.ai',
},
{
provider: 'loom',
label: 'Loom',
enabled: false,
hosts: ['www.loom.com', 'loom.com'],
idSegmentPrefixes: ['share', 'embed'],
idPattern: /^[a-f0-9]{16,64}$/,
embed: (id) => `https://www.loom.com/embed/${id}`,
watch: (id) => `https://www.loom.com/share/${id}`,
frameSrc: 'https://www.loom.com',
},
{
provider: 'youtube_nocookie',
label: 'YouTube',
enabled: false,
// The nocookie host only, never youtube.com: the point of listing YouTube
// at all is the privacy-preserving embed, and accepting the ordinary host
// would quietly reintroduce the tracking this avoids.
hosts: ['www.youtube-nocookie.com', 'youtube-nocookie.com'],
idSegmentPrefixes: ['embed'],
idPattern: /^[A-Za-z0-9_-]{11}$/,
embed: (id) => `https://www.youtube-nocookie.com/embed/${id}`,
watch: (id) => `https://www.youtube-nocookie.com/embed/${id}`,
frameSrc: 'https://www.youtube-nocookie.com',
},
];
/** Hosts the proxy must allow in `frame-src` for the enabled providers. */
export const LEARN_FRAME_SRC_HOSTS: readonly string[] = LEARN_PROVIDER_TABLE.filter(
(definition) => definition.enabled,
).map((definition) => definition.frameSrc);
export function learnProviderDefinition(
provider: LearnProvider,
): LearnProviderDefinition | undefined {
return LEARN_PROVIDER_TABLE.find((definition) => definition.provider === provider);
}
export const LEARN_EMBED_REJECTIONS = [
'malformed_url',
'insecure_scheme',
'unknown_host',
'provider_disabled',
'unrecognised_path',
'malformed_id',
] as const;
export type LearnEmbedRejection = (typeof LEARN_EMBED_REJECTIONS)[number];
export type LearnEmbedResolution =
| {
ok: true;
provider: LearnProvider;
externalId: string;
/** Canonical share link. Safe to show a human; never an iframe source. */
watchUrl: string;
embedUrl: string;
}
| { ok: false; reason: LearnEmbedRejection };
export const LEARN_EMBED_REJECTION_MESSAGES: Record<LearnEmbedRejection, string> = {
malformed_url: 'That is not a URL.',
insecure_scheme: 'Only https links can be embedded.',
unknown_host: `Links from that host are not allowed. Allowed: ${LEARN_PROVIDER_TABLE.filter((d) => d.enabled).map((d) => d.hosts[0]).join(', ')}.`,
provider_disabled: 'That provider is recognised but not enabled yet.',
unrecognised_path: 'That looks like the right host but not a share link.',
malformed_id: 'The video id in that link is not a shape we recognise.',
};
/**
* Extract the id from a path, or null.
*
* The segment must be the LAST one. `/s/<id>/../../anything` and
* `/s/<id>/edit` are both rejected rather than silently truncated to `<id>`,
* because "close enough to a share link" is not a category this function is
* allowed to have.
*/
function externalIdFromPath(definition: LearnProviderDefinition, pathname: string): string | null {
const segments = pathname.split('/').filter(Boolean);
if (segments.length !== 2) return null;
const [prefix, candidate] = segments;
if (!prefix || !candidate) return null;
if (!definition.idSegmentPrefixes.includes(prefix)) return null;
return candidate;
}
/**
* Turn a pasted URL into a provider and an id, or say why not.
*
* Everything a caller may render is rebuilt from the template in the table.
* The input string itself is never returned as a URL, so a resolution result
* cannot carry an attacker's bytes into an attribute.
*/
export function resolveLearnEmbed(raw: string): LearnEmbedResolution {
let parsed: URL;
try {
parsed = new URL(raw.trim());
} catch {
return { ok: false, reason: 'malformed_url' };
}
// `javascript:` and `data:` are the obvious ones; `http:` matters too,
// because framing it from an https page is blocked anyway and storing it
// produces a resource that silently never plays.
if (parsed.protocol !== 'https:') return { ok: false, reason: 'insecure_scheme' };
// `https://video.karti.ai@evil.example/` parses with hostname `evil.example`
// and reads to a human as the trusted host. Never legitimate here.
if (parsed.username || parsed.password) return { ok: false, reason: 'malformed_url' };
// A trusted hostname on an unexpected port is a different service.
if (parsed.port) return { ok: false, reason: 'malformed_url' };
const host = parsed.hostname.toLowerCase();
const definition = LEARN_PROVIDER_TABLE.find((candidate) => candidate.hosts.includes(host));
if (!definition) return { ok: false, reason: 'unknown_host' };
if (!definition.enabled) return { ok: false, reason: 'provider_disabled' };
const externalId = externalIdFromPath(definition, parsed.pathname);
if (externalId === null) return { ok: false, reason: 'unrecognised_path' };
if (!definition.idPattern.test(externalId)) return { ok: false, reason: 'malformed_id' };
return {
ok: true,
provider: definition.provider,
externalId,
watchUrl: definition.watch(externalId),
embedUrl: definition.embed(externalId),
};
}
/**
* Rebuild an embed source from stored columns.
*
* Re-validates the id rather than trusting the database. A row written before
* a pattern was tightened, or by a future code path that skipped the resolver,
* must not be framed on the strength of having been persisted once.
*/
export function learnEmbedUrl(provider: LearnProvider, externalId: string): string | null {
const definition = learnProviderDefinition(provider);
if (!definition || !definition.enabled) return null;
if (!definition.idPattern.test(externalId)) return null;
return definition.embed(externalId);
}
/** The human-facing share link, on the same terms. */
export function learnWatchUrl(provider: LearnProvider, externalId: string): string | null {
const definition = learnProviderDefinition(provider);
if (!definition || !definition.enabled) return null;
if (!definition.idPattern.test(externalId)) return null;
return definition.watch(externalId);
}
// ---------------------------------------------------------------------------
// Presentation helpers
// ---------------------------------------------------------------------------
/**
* `4:32`, or `1:04:12` past the hour.
*
* Here rather than in the web app because the duration is also rendered by the
* public code-holder view, and two formatters would eventually disagree about
* whether a 61-minute video is `61:00` or `1:01:00`.
*/
export function formatLearnDuration(seconds: number | null | undefined): string | null {
if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return null;
const whole = Math.round(seconds);
const hours = Math.floor(whole / 3600);
const minutes = Math.floor((whole % 3600) / 60);
const secs = whole % 60;
const pad = (value: number) => String(value).padStart(2, '0');
return hours > 0 ? `${hours}:${pad(minutes)}:${pad(secs)}` : `${minutes}:${pad(secs)}`;
}
+11 -2
View File
@@ -36,8 +36,17 @@ export const TEAM_DESCRIPTIONS: Record<Team, string> = {
research: 'Consumes capacity internally. Real burn, no revenue.',
};
/** Role within a team. Authorization is team-scoped, never global by default. */
export const TEAM_ROLES = ['member', 'lead', 'admin'] as const;
/**
* Role within a team. Authorization is team-scoped, never global by default.
*
* Listed in ascending rank, matching the Postgres enum's sort order — see
* `ROLE_RANK` in permissions.ts, which is the authority. `viewer` exists for
* the analyst, the executive and the outside contractor: people who must read
* the book and must never write to it. It sits below `member` precisely so
* that introducing it grants nothing, every existing rule requiring `member`
* or higher.
*/
export const TEAM_ROLES = ['viewer', 'member', 'lead', 'admin'] as const;
export type TeamRole = (typeof TEAM_ROLES)[number];
// ---------------------------------------------------------------------------
+121 -8
View File
@@ -8,19 +8,57 @@ export const CAPABILITIES = [
'deal:write',
'commitment:write',
'contract:sign',
'activity:write',
'data:import',
'fact:review',
'integration:connect',
'settings:admin',
'book:read',
'economics:read',
'team:read',
] as const;
export type Capability = (typeof CAPABILITIES)[number];
/**
* Writes, authorised per team.
*
* `data:import`, `fact:review` and `integration:connect` were one capability
* until an audit pointed out they are three different authorities: rewriting
* five thousand rows, accepting an agent's claim about a named person, and
* handing PIG a third party's OAuth token. Someone trusted with the third is
* not thereby trusted with the first.
*/
export const TEAM_CAPABILITIES = [
'deal:write',
'commitment:write',
'contract:sign',
'activity:write',
'data:import',
'fact:review',
'integration:connect',
] as const satisfies readonly Capability[];
export type TeamCapability = (typeof TEAM_CAPABILITIES)[number];
export type GlobalCapability = Exclude<Capability, TeamCapability>;
/**
* Reads, authorised platform-wide.
*
* Deliberately NOT team-scoped, and the distinction is load-bearing. Every read
* endpoint returns the whole book — every account, every contract, every
* block — because no row-level team filter exists anywhere in the query layer.
* A team-scoped read grant would therefore be a lie the guard could not
* enforce: it would say "demand only" while the handler returned supply too.
* The honest model is that a read capability is held or it is not, and the
* *role* required to hold it is what separates the roster from the cost book.
*/
export const READ_CAPABILITIES = [
'book:read',
'economics:read',
'team:read',
] as const satisfies readonly Capability[];
export type ReadCapability = (typeof READ_CAPABILITIES)[number];
export type GlobalCapability = Exclude<Capability, TeamCapability | ReadCapability>;
export type WriteCapability = TeamCapability | GlobalCapability;
export interface PermissionSubject {
isPlatformAdmin: boolean;
@@ -33,7 +71,7 @@ export interface PermissionGrant {
team: Team | null;
}
interface TeamCapabilityRule {
interface CapabilityRule {
teams: readonly Team[];
minimumRole: TeamRole;
}
@@ -42,22 +80,85 @@ interface TeamCapabilityRule {
* The role policy is shared by API and browser code so controls cannot drift
* from server enforcement as new write paths are added.
*/
export const TEAM_CAPABILITY_RULES: Readonly<Record<TeamCapability, TeamCapabilityRule>> = {
export const TEAM_CAPABILITY_RULES: Readonly<Record<TeamCapability, CapabilityRule>> = {
'deal:write': { teams: ['supply', 'demand'], minimumRole: 'member' },
'commitment:write': { teams: ['supply'], minimumRole: 'lead' },
'contract:sign': { teams: ['supply', 'demand'], minimumRole: 'admin' },
// Logging a call is the lightest write in the product and every member does
// it, but it still moves `accounts.lastActivityAt`, which drives the account
// list ordering — so a viewer must not be able to reorder someone's day.
'activity:write': { teams: TEAMS, minimumRole: 'member' },
'data:import': { teams: TEAMS, minimumRole: 'admin' },
// Unchanged from when this was `data:import` on research: fact review is the
// research team's judgement about evidence, not a commercial authority.
'fact:review': { teams: ['research'], minimumRole: 'admin' },
'integration:connect': { teams: TEAMS, minimumRole: 'admin' },
};
/**
* `economics:read` is the one that matters. Supplier cost per GPU-hour and the
* break-even price ARE the business; a research contractor consuming capacity
* internally has no reason to see what we pay for it, and neither has an
* analyst hired to read the book. Commercial members do: you cannot price a
* deal without knowing what the block cost.
*/
export const READ_CAPABILITY_RULES: Readonly<Record<ReadCapability, CapabilityRule>> = {
'book:read': { teams: TEAMS, minimumRole: 'viewer' },
'economics:read': { teams: ['supply', 'demand'], minimumRole: 'member' },
'team:read': { teams: TEAMS, minimumRole: 'viewer' },
};
/**
* Rank, not identity: every rule is "at or above". `viewer` is deliberately
* below `member` so that adding it grants nothing that was not already
* granted — every existing rule starts at `member` or higher.
*/
const ROLE_RANK: Readonly<Record<TeamRole, number>> = {
member: 0,
lead: 1,
admin: 2,
viewer: 0,
member: 1,
lead: 2,
admin: 3,
};
export function resolvePermissionGrants(subject: PermissionSubject): PermissionGrant[] {
/**
* Rank comparison, exported because it was duplicated in `hasTeamAccess` and
* the copy went stale the moment `viewer` was added — silently ranking an
* unknown role as `undefined >= n`, which is `false` for every threshold and
* would have locked viewers out of nothing while looking correct.
*/
export function roleMeets(role: TeamRole, minimumRole: TeamRole): boolean {
return ROLE_RANK[role] >= ROLE_RANK[minimumRole];
}
export function isTeamCapability(capability: Capability): capability is TeamCapability {
return (TEAM_CAPABILITIES as readonly Capability[]).includes(capability);
}
export function isReadCapability(capability: Capability): capability is ReadCapability {
return (READ_CAPABILITIES as readonly Capability[]).includes(capability);
}
/** Capabilities that are neither team-scoped nor reads: platform administration. */
export const GLOBAL_CAPABILITIES = CAPABILITIES.filter(
(capability): capability is GlobalCapability =>
!isTeamCapability(capability) && !isReadCapability(capability),
);
function meetsRule(subject: PermissionSubject, rule: CapabilityRule): boolean {
return subject.teams.some(
(membership) =>
rule.teams.includes(membership.team) &&
ROLE_RANK[membership.role] >= ROLE_RANK[rule.minimumRole],
);
}
/** Team-scoped write grants. One entry per (capability, team) that qualifies. */
export function resolveWritePermissionGrants(subject: PermissionSubject): PermissionGrant[] {
if (subject.isPlatformAdmin) {
return CAPABILITIES.map((capability) => ({ capability, team: null }));
return [...TEAM_CAPABILITIES, ...GLOBAL_CAPABILITIES].map((capability) => ({
capability,
team: null,
}));
}
const grants: PermissionGrant[] = [];
@@ -75,6 +176,18 @@ export function resolvePermissionGrants(subject: PermissionSubject): PermissionG
return grants;
}
/** Read grants, always platform-wide — see `READ_CAPABILITIES`. */
export function resolveReadPermissionGrants(subject: PermissionSubject): PermissionGrant[] {
return READ_CAPABILITIES.filter(
(capability) =>
subject.isPlatformAdmin || meetsRule(subject, READ_CAPABILITY_RULES[capability]),
).map((capability) => ({ capability, team: null }));
}
export function resolvePermissionGrants(subject: PermissionSubject): PermissionGrant[] {
return [...resolveReadPermissionGrants(subject), ...resolveWritePermissionGrants(subject)];
}
export function permissionGranted(
grants: readonly PermissionGrant[],
capability: Capability,
+84
View File
@@ -0,0 +1,84 @@
/**
* What Piggy is looking at.
*
* This type crosses four process boundaries — the browser, the API relay, the
* Piggy chat server and the model prompt — and both server-side zod schemas
* are `.strict()`. Widening it in one place and not the others does not fail
* loudly; it produces a 400 `invalid_request` at whichever hop was missed. So
* the shape lives here, once, and every hop derives from it.
*
* Two kinds of context, deliberately distinguished:
*
* record — the user opened Piggy from a specific row. Piggy gets a tool that
* reads exactly that record and cannot pivot to another, which is
* why the tool's input schema is empty rather than taking an id.
* page — Piggy is docked and the user is simply on a page. There is no id.
* The route is what Piggy knows, and it selects which read tool it
* is given.
*
* `route` is a closed set rather than free text. A docked panel publishes the
* route on every navigation, so free text would put arbitrary client-supplied
* strings into a model prompt on every page change.
*/
/** Record types Piggy can be pointed at. Each maps to a `pig_get_record` read. */
export const PIGGY_RECORD_TYPES = [
'account',
'contact',
'demand_deal',
'supply_deal',
'contract',
'commitment',
] as const;
export type PiggyRecordType = (typeof PIGGY_RECORD_TYPES)[number];
/**
* Routes the dock may report. Kept in step with the NAV table in Shell.tsx.
* A route absent from this list is reported as `/` rather than rejected —
* a new page should never break the dock.
*/
export const PIGGY_PAGE_ROUTES = [
'/',
'/growth',
'/margin',
'/calendar',
'/capacity',
'/demand',
'/supply',
'/accounts',
'/contracts',
'/imports',
'/team',
'/facts',
'/learn',
'/settings',
'/piggy',
] as const;
export type PiggyPageRoute = (typeof PIGGY_PAGE_ROUTES)[number];
export type PiggyChatContext =
| { type: PiggyRecordType; id: string; label?: string }
| { type: 'page'; route: PiggyPageRoute; label?: string };
/** Narrowing helper, so callers do not re-derive the discriminant test. */
export function isPageContext(
context: PiggyChatContext | undefined,
): context is Extract<PiggyChatContext, { type: 'page' }> {
return context?.type === 'page';
}
/**
* Coerce an arbitrary router pathname to a route the dock may publish.
*
* Falls back to '/' rather than throwing: an unknown route means a page was
* added without updating this list, and the correct behaviour there is a
* slightly less specific Piggy, not a broken one.
*/
export function toPiggyPageRoute(pathname: string): PiggyPageRoute {
const match = PIGGY_PAGE_ROUTES.find(
(route) => route === pathname || (route !== '/' && pathname.startsWith(`${route}/`)),
);
return match ?? '/';
}
+245
View File
@@ -0,0 +1,245 @@
/**
* Tests for quarter arithmetic and the projected event shape.
*
* The calendar has no storage of its own, so there is nothing to inspect when
* a bucket is wrong — a deal simply appears under the wrong heading and the
* quarterly number is quietly off. The cases below therefore pin the two
* decisions that a plausible-but-wrong implementation gets backwards: which
* calendar year names a fiscal year, and whether the upper bound is inclusive.
*/
import { strict as assert } from 'node:assert';
import { describe, it } from 'node:test';
import {
CALENDAR_EVENT_KINDS,
calendarEventId,
completableSpanState,
eventState,
isCalendarEventKind,
isValidTimeZone,
parseQuarter,
quarterBounds,
quarterBoundsFor,
quarterOf,
spanState,
} from '../src/calendar';
describe('quarterOf', () => {
it('buckets calendar quarters', () => {
assert.equal(quarterOf(new Date('2026-01-01T00:00:00.000Z')), '2026-Q1');
assert.equal(quarterOf(new Date('2026-08-13T12:00:00.000Z')), '2026-Q3');
assert.equal(quarterOf(new Date('2026-12-31T23:59:59.999Z')), '2026-Q4');
});
it('names a fiscal year for the calendar year it ENDS in', () => {
// The decision. A fiscal year starting April 2026 runs to March 2027 and
// is FY2027 — the convention used by the companies whose paper PIG holds.
// Naming it FY2026 instead is the plausible-but-wrong version: it puts
// every April-to-December deal a year early, and the error is invisible
// because the quarter number is right.
assert.equal(quarterOf(new Date('2026-04-01T00:00:00.000Z'), 3), '2027-Q1');
assert.equal(quarterOf(new Date('2026-08-13T00:00:00.000Z'), 3), '2027-Q2');
assert.equal(quarterOf(new Date('2027-03-31T23:00:00.000Z'), 3), '2027-Q4');
// The next fiscal year begins the following day, and the label advances.
assert.equal(quarterOf(new Date('2027-04-01T00:00:00.000Z'), 3), '2028-Q1');
});
it('handles the year boundary under an October fiscal start', () => {
// A US-federal-style year: October 2026 is already FY2027 Q1, while
// September 2026 is still FY2026 Q4. A naive implementation that derives
// the label from the calendar year alone puts these in the same year.
assert.equal(quarterOf(new Date('2026-09-30T23:59:59.999Z'), 9), '2026-Q4');
assert.equal(quarterOf(new Date('2026-10-01T00:00:00.000Z'), 9), '2027-Q1');
assert.equal(quarterOf(new Date('2026-12-31T23:59:59.999Z'), 9), '2027-Q1');
assert.equal(quarterOf(new Date('2027-01-01T00:00:00.000Z'), 9), '2027-Q2');
});
it('buckets by the reader time zone, not by UTC', () => {
// Every temporal column in PIG is `timestamp with time zone`, so a
// quarter boundary is a local-midnight question. This instant is already
// Q1 in London and still Q4 in New York; bucketing everything in UTC
// silently reports one of the two readers a wrong quarterly total.
const newYearInLondon = new Date('2027-01-01T00:30:00.000Z');
assert.equal(quarterOf(newYearInLondon, 0, 'Europe/London'), '2027-Q1');
assert.equal(quarterOf(newYearInLondon, 0, 'America/New_York'), '2026-Q4');
});
it('falls back to UTC rather than throwing on an unusable zone', () => {
// `users.timezone` is free text and nothing validates it on write.
assert.equal(quarterOf(new Date('2026-08-13T12:00:00.000Z'), 0, 'Mars/Olympus'), '2026-Q3');
});
it('rejects a fiscal start that is not a month index', () => {
assert.throws(() => quarterOf(new Date(), 12), RangeError);
assert.throws(() => quarterOf(new Date(), -1), RangeError);
});
});
describe('quarterBounds', () => {
it('is half-open, so consecutive quarters tile without overlapping', () => {
// An inclusive upper bound files a contract expiring at exactly midnight
// on 1 October into both Q3 and Q4, and adding the two quarters together
// then counts its value twice.
const q3 = quarterBounds(2026, 3);
const q4 = quarterBounds(2026, 4);
assert.equal(q3.from.toISOString(), '2026-07-01T00:00:00.000Z');
assert.equal(q3.to.toISOString(), '2026-10-01T00:00:00.000Z');
assert.equal(q3.to.getTime(), q4.from.getTime());
assert.equal(quarterOf(q3.to), '2026-Q4', 'the upper bound belongs to the NEXT quarter');
});
it('rolls into the following calendar year for a fiscal offset', () => {
// FY2027 under an April start began in April 2026, so its Q4 is the first
// calendar quarter of 2027. Reading `year` as the starting calendar year
// puts this a whole year out.
const q1 = quarterBounds(2027, 1, 3);
const q4 = quarterBounds(2027, 4, 3);
assert.equal(q1.from.toISOString(), '2026-04-01T00:00:00.000Z');
assert.equal(q4.from.toISOString(), '2027-01-01T00:00:00.000Z');
assert.equal(q4.to.toISOString(), '2027-04-01T00:00:00.000Z');
assert.equal(q4.quarter, '2027-Q4');
});
it('round-trips with quarterOf at both ends of every fiscal offset', () => {
for (const fiscalStart of [0, 1, 3, 6, 9, 11]) {
for (const quarter of [1, 2, 3, 4] as const) {
const bounds = quarterBounds(2027, quarter, fiscalStart);
assert.equal(quarterOf(bounds.from, fiscalStart), bounds.quarter);
assert.equal(
quarterOf(new Date(bounds.to.getTime() - 1), fiscalStart),
bounds.quarter,
`last instant of ${bounds.quarter} at fiscal start ${fiscalStart}`,
);
}
}
});
it('anchors on local midnight, not on UTC midnight', () => {
// New York is five hours behind in January, so its Q1 opens at 05:00Z.
const q1 = quarterBounds(2026, 1, 0, 'America/New_York');
assert.equal(q1.from.toISOString(), '2026-01-01T05:00:00.000Z');
});
it('survives a quarter that opens across a daylight-saving transition', () => {
// Sydney's Q4 opens on the morning clocks go forward; a fixed-offset
// implementation lands an hour out and mis-buckets everything on 1 October.
const q4 = quarterBounds(2026, 4, 0, 'Australia/Sydney');
assert.equal(quarterOf(q4.from, 0, 'Australia/Sydney'), '2026-Q4');
assert.equal(
quarterOf(new Date(q4.from.getTime() - 1), 0, 'Australia/Sydney'),
'2026-Q3',
);
});
it('rejects a quarter outside 14', () => {
assert.throws(() => quarterBounds(2026, 0 as 1), RangeError);
assert.throws(() => quarterBounds(2026, 5 as 1), RangeError);
});
});
describe('quarterBoundsFor and parseQuarter', () => {
it('contains the instant it was derived from', () => {
const date = new Date('2026-08-13T12:00:00.000Z');
const bounds = quarterBoundsFor(date, 3, 'Europe/London');
assert.equal(bounds.quarter, '2027-Q2');
assert.ok(bounds.from <= date && date < bounds.to);
});
it('rejects a malformed label rather than guessing', () => {
assert.deepEqual(parseQuarter('2026-Q3'), { year: 2026, quarter: 3 });
assert.equal(parseQuarter('2026-Q5'), null);
assert.equal(parseQuarter('26-Q3'), null);
assert.equal(parseQuarter('2026Q3'), null);
});
});
describe('event state', () => {
const now = new Date('2026-08-13T12:00:00.000Z');
const inDays = (days: number) => new Date(now.getTime() + days * 86_400_000);
it('reads completion from the column, never from the clock', () => {
// A renewal notice whose date has passed is overdue, not finished.
assert.equal(eventState({ at: inDays(-3), now }), 'overdue');
assert.equal(
eventState({ at: inDays(-3), now, completedAt: inDays(-4) }),
'done',
'only a completion timestamp closes an event',
);
});
it('separates due from upcoming on the action horizon', () => {
assert.equal(eventState({ at: inDays(3), now }), 'due');
assert.equal(eventState({ at: inDays(30), now }), 'upcoming');
});
it('judges a span by its end, because a running window is not late', () => {
assert.equal(spanState({ startsAt: inDays(-10), endsAt: inDays(10), now }), 'due');
assert.equal(spanState({ startsAt: inDays(-30), endsAt: inDays(-1), now }), 'done');
assert.equal(spanState({ startsAt: inDays(60), endsAt: inDays(90), now }), 'upcoming');
});
it('never lets a clock close a span that has a completion column', () => {
// The defect this pins: a QBR scheduled last week and never held read
// `done` under `spanState`, while the same QBR entered with no end time
// read `overdue`. Whether a missed human commitment is flagged then
// depends on nothing but whether its author typed an end time.
const missed = { startsAt: inDays(-30), endsAt: inDays(-1), now };
assert.equal(completableSpanState(missed), 'overdue');
assert.equal(eventState({ at: missed.startsAt, now }), 'overdue', 'and agrees with a point');
assert.equal(completableSpanState({ ...missed, completedAt: inDays(-2) }), 'done');
assert.equal(spanState(missed), 'done', 'the windowed reading is still right for windows');
});
it('still reads a running or future completable span from its end and start', () => {
assert.equal(
completableSpanState({ startsAt: inDays(-10), endsAt: inDays(10), now }),
'due',
);
assert.equal(
completableSpanState({ startsAt: inDays(60), endsAt: inDays(90), now }),
'upcoming',
);
assert.equal(
completableSpanState({ startsAt: inDays(60), endsAt: inDays(90), now, completedAt: now }),
'done',
'completion outranks the clock in both directions',
);
});
});
describe('time zone validation', () => {
it('separates a real zone from a plausible-looking string', () => {
// The projection falls back to UTC for a stored zone it cannot use, which
// is right for `users.timezone` and wrong for a query parameter: a caller
// asking for a zone that does not exist should be told, not quietly
// answered in UTC, and the formatter cache is keyed on this string.
assert.equal(isValidTimeZone('Europe/London'), true);
assert.equal(isValidTimeZone('UTC'), true);
assert.equal(isValidTimeZone('Mars/Olympus'), false);
assert.equal(isValidTimeZone(''), false);
});
it('does not grow the formatter cache without bound', () => {
// A loop over distinct values used to add one entry per value, for the
// life of the process. Nothing observable should change from running it.
for (let index = 0; index < 2000; index += 1) {
quarterOf(new Date('2026-08-13T12:00:00.000Z'), 0, `Junk/Zone${index}`);
}
assert.equal(
quarterOf(new Date('2027-01-01T00:30:00.000Z'), 0, 'America/New_York'),
'2026-Q4',
);
});
});
describe('event identity', () => {
it('is stable without storage, and distinguishes fields on one record', () => {
const id = calendarEventId('contract', 'c1', 'expiresAt');
assert.equal(id, 'contract:c1:expiresAt');
assert.notEqual(id, calendarEventId('contract', 'c1', 'effectiveAt'));
});
it('exposes every kind through the guard', () => {
for (const kind of CALENDAR_EVENT_KINDS) assert.ok(isCalendarEventKind(kind));
assert.equal(isCalendarEventKind('renewal'), false);
});
});
+171 -1
View File
@@ -1,6 +1,16 @@
import { strict as assert } from 'node:assert';
import { describe, it } from 'node:test';
import { permissionGranted, resolvePermissionGrants } from '../src/permissions';
import { TEAM_ROLES, TEAMS, type Team, type TeamRole } from '../src/ontology';
import {
CAPABILITIES,
permissionGranted,
resolvePermissionGrants,
resolveReadPermissionGrants,
resolveWritePermissionGrants,
roleMeets,
type Capability,
type PermissionSubject,
} from '../src/permissions';
describe('role permissions', () => {
it('keeps deal writes on the side where the person is a member', () => {
@@ -46,3 +56,163 @@ describe('role permissions', () => {
assert.equal(permissionGranted(grants, 'settings:admin'), true);
});
});
describe('the three authorities that used to be data:import', () => {
it('does not let a research admin rewrite a commercial book', () => {
const grants = resolvePermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'research', role: 'admin' }],
});
assert.equal(permissionGranted(grants, 'fact:review', 'research'), true);
assert.equal(permissionGranted(grants, 'data:import', 'demand'), false);
assert.equal(permissionGranted(grants, 'data:import', 'supply'), false);
});
it('does not let a commercial admin approve a claim about a person', () => {
const grants = resolvePermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'supply', role: 'admin' }],
});
assert.equal(permissionGranted(grants, 'data:import', 'supply'), true);
assert.equal(permissionGranted(grants, 'integration:connect', 'supply'), true);
// Fact review lives on research alone; being a supply admin buys nothing.
assert.equal(permissionGranted(grants, 'fact:review', 'research'), false);
});
});
describe('reads', () => {
it('resolves read grants platform-wide, never per team', () => {
const grants = resolveReadPermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'demand', role: 'member' }],
});
// A team-scoped read grant would be a promise the query layer does not
// keep: `/api/contracts` returns supply paper to a demand reader either
// way. See READ_CAPABILITIES.
assert.deepEqual(
grants,
[
{ capability: 'book:read', team: null },
{ capability: 'economics:read', team: null },
{ capability: 'team:read', team: null },
],
);
});
it('shows a research contractor the book but not what we pay for capacity', () => {
const grants = resolveReadPermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'research', role: 'lead' }],
});
assert.equal(permissionGranted(grants, 'book:read'), true);
assert.equal(permissionGranted(grants, 'team:read'), true);
assert.equal(permissionGranted(grants, 'economics:read'), false);
});
it('gives a viewer reads and no writes at all', () => {
const subject: PermissionSubject = {
isPlatformAdmin: false,
teams: [{ team: 'demand', role: 'viewer' }],
};
assert.deepEqual(resolveWritePermissionGrants(subject), []);
assert.equal(permissionGranted(resolveReadPermissionGrants(subject), 'book:read'), true);
// Cost economics are a commercial member's tool, not a reader's.
assert.equal(permissionGranted(resolveReadPermissionGrants(subject), 'economics:read'), false);
});
});
/**
* The matrix is pure data, so pinning every cell is cheap — and it is the only
* way a role added later cannot quietly inherit an authority nobody chose to
* give it. Change a rule and this table tells you exactly which cells moved.
*/
describe('the whole role × capability matrix', () => {
const EXPECTED: Readonly<Record<TeamRole, readonly Capability[]>> = {
viewer: ['book:read', 'team:read'],
member: ['book:read', 'economics:read', 'team:read', 'deal:write', 'activity:write'],
lead: [
'book:read',
'economics:read',
'team:read',
'deal:write',
'activity:write',
'commitment:write',
],
admin: [
'book:read',
'economics:read',
'team:read',
'deal:write',
'activity:write',
'commitment:write',
'contract:sign',
'data:import',
'integration:connect',
],
};
/** Held on the supply team, whose rules exercise every rank threshold. */
for (const role of TEAM_ROLES) {
it(`grants a supply ${role} exactly the expected set`, () => {
const grants = resolvePermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'supply', role }],
});
const held = CAPABILITIES.filter((capability) =>
grants.some((grant) => grant.capability === capability),
);
assert.deepEqual(new Set(held), new Set(EXPECTED[role]));
});
}
it('gives research its own shape — evidence review, no commercial reach', () => {
const grants = resolvePermissionGrants({
isPlatformAdmin: false,
teams: [{ team: 'research', role: 'admin' }],
});
const held = CAPABILITIES.filter((capability) =>
grants.some((grant) => grant.capability === capability),
);
assert.deepEqual(
new Set(held),
new Set([
'book:read',
'team:read',
'activity:write',
'data:import',
'fact:review',
'integration:connect',
]),
);
});
it('never grants a lower rank something a higher rank on the same team lacks', () => {
for (const team of TEAMS as readonly Team[]) {
let previous = new Set<Capability>();
for (const role of TEAM_ROLES) {
const held = new Set<Capability>(
resolvePermissionGrants({ isPlatformAdmin: false, teams: [{ team, role }] }).map(
(grant) => grant.capability,
),
);
for (const capability of previous) {
assert.ok(held.has(capability), `${team}/${role} lost ${capability} by promotion`);
}
previous = held;
}
}
});
it('ranks viewer below member, which is what makes it safe to add', () => {
assert.equal(roleMeets('viewer', 'member'), false);
assert.equal(roleMeets('member', 'viewer'), true);
assert.equal(roleMeets('admin', 'admin'), true);
assert.equal(TEAM_ROLES[0], 'viewer');
});
});
@@ -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({