Rebuild the shell, add Calendar and Learn, and govern reads
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:
@@ -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;
|
||||
@@ -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';
|
||||
|
||||
@@ -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;
|
||||
@@ -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',
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user