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');
});
});