Files
CatoandClaude f41fca0617 Stammtisch: learners talk to each other in Zurich German; chat explains in the language you write in (#466)
* Stammtisch: learners talk to each other in Zurich German

A table for two to six signed-in adults, about a situation they have
learned or a topic of their own, with Heidi between them. The more
situations somebody can follow, the more they can do there: topics, own
topics, group tables and messages a day.

- One pipeline per message: read with the deterministic gate, plan, one
  model call that screens and renders, decide, and a view per reader. A
  rendering is used only after the gate passed or repaired it.
- Two filters per person (what I send, what I read); the reader's wins,
  and threats and hate are filtered whatever the switches say. A flagged
  line is replaced for readers by a line of the topic and marked as
  filtered; its sender sees their own words.
- A waiting open table is the queue. Heidi sits down with somebody
  waiting alone, on their poll; nothing runs on a timer.
- Every rule is data (rulebook.ts), edited on /manage/stammtisch in an
  editor drawn from the rule fields, with a dry run of a message against
  unsaved rules.
- Metrics on the same screen: good tables a week, four drivers, four
  guardrails, each with a target and the rules that move it, counted
  from events that carry no text.

Migration 0037. Words in all seven languages; privacy flow, HEIDI.md,
roadmap and changelog updated.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrrxMUHD988kZLaApG

* Stammtisch: deleting an account erases its tables, seats and lines

What somebody said at a table, their seats, their adult confirmation
and counts, their blocks and any report by or about them go with the
account; events stay as counts with nobody's id. The course guard now
knows which Stammtisch tables belong to a course.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrrxMUHD988kZLaApG

* Stammtisch: the variety is named by the pack, not by the code

Heidi's answer about a message's language is "variety", "bridge" or
"other"; the prompt takes both names from the pack, and the table
screen takes the language tag from it.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmrrxMUHD988kZLaApG

* feat(chat): explain in the language of the learner's latest message; trim history context

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(stammtisch): seat race, blocks by link, refund unread lines, suspended speakers, erase audience, no paid fallback for free tables; multi-user tests

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-04 19:16:57 +01:00

1340 lines
58 KiB
TypeScript

// Accounts: the same tables in every fleet product (@bitbaum/accountkit/auth).
export * from "@bitbaum/accountkit/auth/schema";
import { createManagerTables } from "@bitbaum/accountkit/auth/schema";
import { bigint, boolean, customType, date, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { DEFAULT_COURSE } from "../course/registry.ts";
/**
* Which course a row is about (`lib/course/registry.ts`).
*
* The default is the course every row written before the column existed
* belongs to, so adding it changed nothing about them. Code that writes a row
* names the course itself rather than leaning on the default.
*/
const course = () => text("course").notNull().default(DEFAULT_COURSE.id);
/**
* Study groups — the first thing in Heidi that outlives a browser tab.
*
* WHO A ROW BELONGS TO. `created_by`, `actor_id` and `author_id` hold the
* person's actor id, as text, with no foreign key: the account id for someone
* who registered here, or the OrangeCat actor id for someone whose first way
* in was OrangeCat (lib/auth — that keeps every row written before Heidi had
* accounts theirs). The account tables themselves come from
* @bitbaum/accountkit/auth, re-exported above.
*
* The consequence is that a display name has to be DENORMALISED onto the
* membership row. There is nothing to join to. It is captured at join time
* from the OIDC profile and may drift if someone renames themselves upstream;
* that is a real cost, accepted knowingly, and much cheaper than mirroring an
* identity provider.
*
* Heidi herself is NOT a member row. She participates in every group by
* construction, so storing her would be a row that must be written correctly
* for every group forever and can only ever say the same thing. She is
* composed into the threadkit participant list at read time instead.
*/
export const studyGroups = pgTable("study_groups", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
/** OIDC `sub` of whoever made it. They see the thread from its start. */
createdBy: text("created_by").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* The invite link's secret. Unguessable and rotatable — knowing a group's
* id must never be enough to join it, because ids travel in URLs and logs.
* Unique so a link resolves to exactly one group.
*/
inviteToken: text("invite_token").notNull().unique(),
/**
* The situation domain a TEAM works on (`care`, `everyday`, …), set by its
* organiser. Null for an ordinary study group. With a focus, members may
* choose to show the organiser their standing in those situations — see
* `lib/domain/teams/overview.ts`.
*/
focus: text("focus"),
});
export const groupMembers = pgTable(
"group_members",
{
groupId: uuid("group_id")
.notNull()
.references(() => studyGroups.id, { onDelete: "cascade" }),
/** OIDC `sub`. No foreign key: the person lives in OrangeCat, not here. */
actorId: text("actor_id").notNull(),
/** Denormalised from the OIDC profile — see the note above. */
displayName: text("display_name").notNull(),
joinedAt: timestamp("joined_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Set rather than deleted. threadkit gates visibility on `leftAt`, so a
* departure has to be a fact with a time on it; a deleted row would make
* the messages they wrote authorless.
*/
leftAt: timestamp("left_at", { withTimezone: true }),
/**
* Whether this member shows the organiser their situation standings. OFF
* until they turn it on, per team, and only ever standings — never which
* lines or answers.
*/
sharesProgress: boolean("shares_progress").notNull().default(false),
},
(t) => [
primaryKey({ columns: [t.groupId, t.actorId] }),
// "Which groups am I in" is the portal's first query on every page load.
index("group_members_actor_idx").on(t.actorId),
],
);
export const groupMessages = pgTable(
"group_messages",
{
id: uuid("id").primaryKey().defaultRandom(),
groupId: uuid("group_id")
.notNull()
.references(() => studyGroups.id, { onDelete: "cascade" }),
/** An OIDC `sub`, or the assistant's fixed id. */
authorId: text("author_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Heidi's structured answer — glosses, suggestions, the model that wrote
* it — kept whole rather than shredded into columns.
*
* It is a rendering detail of one message, never queried across rows, and
* its shape is owned by `lib/domain/chat/types.ts`, which changes when the
* prompt changes. Columns would turn every prompt revision into a
* migration. Null for anything a human wrote.
*/
answer: jsonb("answer"),
},
// Every read is "this group's messages, oldest first".
(t) => [index("group_messages_group_created_idx").on(t.groupId, t.createdAt)],
);
/**
* A private conversation with Heidi, and its messages.
*
* NOT the group tables with one member. That was the tempting reuse and it
* fails on the two things that matter: `study_groups.invite_token` is
* `NOT NULL UNIQUE` and is a CREDENTIAL, so every private chat would mint a
* joinable room key nobody asked for — and deletion means the opposite in each
* case. A group departure sets `left_at` precisely so the messages someone
* wrote keep an author; deleting a conversation means destroying the text. One
* table cannot honour both.
*
* Same identity rule as everywhere else here: `actor_id` is the OIDC `sub`,
* stored as bare text with no foreign key, because the row it would point at
* lives in OrangeCat.
*/
export const conversations = pgTable(
"conversations",
{
id: uuid("id").primaryKey().defaultRandom(),
actorId: text("actor_id").notNull(),
/**
* Derived from the first message, never asked for. Every product that asks
* collects a thousand "Untitled"; what someone pasted is also the best
* possible label, because it is how they will recognise the thread later.
*/
title: text("title").notNull().default(""),
/**
* Which language Heidi explained in.
*
* On the conversation rather than the request: re-opening a six-month-old
* thread from a browser negotiated to French and having Heidi continue in
* French mid-conversation is a bug you only find in production.
*/
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/** Bumped on every message. The sidebar's sort key. */
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
/**
* A tombstone, and the messages are GONE.
*
* Deleting sets this and hard-deletes every `conversation_messages` row in
* the same transaction. A `deleted_at` that leaves the text sitting in the
* table forever is exactly the lie the privacy section would then have to
* tell. What the tombstone buys is worth keeping: a deleted id answers a
* stable 404 rather than one that might be a permissions bug, and the
* per-actor count survives a delete loop.
*/
deletedAt: timestamp("deleted_at", { withTimezone: true }),
},
(t) => [index("conversations_actor_updated_idx").on(t.actorId, t.updatedAt)],
);
export const conversationMessages = pgTable(
"conversation_messages",
{
id: uuid("id").primaryKey().defaultRandom(),
conversationId: uuid("conversation_id")
.notNull()
.references(() => conversations.id, { onDelete: "cascade" }),
/** An OIDC `sub`, or the assistant's fixed id. */
authorId: text("author_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/** Heidi's structured answer, kept whole. Null for anything a human wrote. */
answer: jsonb("answer"),
/**
* HOW MANY pictures rode along, never the pictures.
*
* Attachments are downscaled data URLs: they would be the largest rows in
* this database and the single most private artefact the product touches.
* The count is enough for a re-opened thread to say "2 pictures" honestly
* without Heidi holding them, and it is what keeps the privacy section
* short.
*/
imageCount: integer("image_count").notNull().default(0),
},
(t) => [index("conversation_messages_conversation_created_idx").on(t.conversationId, t.createdAt)],
);
/**
* Speaking rounds: the topics people propose, and the sittings they become.
*
* WHAT IS NOT HERE IS THE POINT.
*
* There is no audio table and no table of anybody's takes. A recording is
* measured in the browser (`domain/speaking/delivery.ts`); the numbers, and
* the learner's own write-up of what they said, are kept in their own
* localStorage. Neither the sound nor the text ever reaches this database. §10
* calls voice notes among the most private things a person owns, and the
* cheapest way to honour that is to never hold one. It is the call
* `image_count` already made for pictures, taken one step further because
* there is not even a count worth keeping.
*
* So what is stored here is only the SOCIAL half — who proposed what, who is
* coming, and when it sits. All of it is meant to be seen by the other people
* in the round, which is exactly the property the private half does not have.
*
* Same identity rule as everywhere else: an actor id is the OIDC `sub`, bare
* text, no foreign key, with the display name denormalised at write time.
*/
export const speakingTopics = pgTable(
"speaking_topics",
{
id: uuid("id").primaryKey().defaultRandom(),
title: text("title").notNull(),
/** One line of why it is worth an hour. */
pitch: text("pitch").notNull(),
proposedBy: text("proposed_by").notNull(),
proposerName: text("proposer_name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("speaking_topics_created_idx").on(t.createdAt)],
);
/**
* "I would come to that."
*
* A row rather than a counter on the topic, because a count cannot answer the
* question the page actually asks — whether YOU already said yes — and a
* counter with no rows behind it can only ever go up.
*/
export const topicInterest = pgTable(
"topic_interest",
{
topicId: uuid("topic_id")
.notNull()
.references(() => speakingTopics.id, { onDelete: "cascade" }),
actorId: text("actor_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.topicId, t.actorId] })],
);
export const speakingRounds = pgTable(
"speaking_rounds",
{
id: uuid("id").primaryKey().defaultRandom(),
/**
* The proposal it came from. Nullable, and `set null` on delete: a round
* people are coming to is a fact, and removing the topic it grew out of
* must not remove the meeting.
*/
topicId: uuid("topic_id").references(() => speakingTopics.id, { onDelete: "set null" }),
title: text("title").notNull(),
/** `webinar` or `circle` — see domain/speaking/types.ts. */
format: text("format").notNull(),
hostId: text("host_id").notNull(),
hostName: text("host_name").notNull(),
/**
* The first sitting, absolute. Every later one is COMPUTED from this plus
* the cadence and the zone, never stored — see domain/speaking/schedule.ts.
* A table of generated occurrences would have to be extended by a job
* nobody would notice had stopped.
*/
startsAt: timestamp("starts_at", { withTimezone: true }).notNull(),
durationMinutes: integer("duration_minutes").notNull(),
/** `once`, `weekly` or `fortnightly`. */
cadence: text("cadence").notNull(),
/**
* The zone the repeat is anchored in. Kept even though `starts_at` is
* absolute: "every Tuesday at 19:00" survives a daylight-saving change and
* an instant plus seven days does not.
*/
timeZone: text("time_zone").notNull(),
/** An https room somewhere else. Heidi carries no video. Validated on write. */
meetingUrl: text("meeting_url"),
capacity: integer("capacity").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Called off, rather than deleted. People have it in their calendar; a row
* that vanishes tells them nothing and a row that says cancelled does.
*/
cancelledAt: timestamp("cancelled_at", { withTimezone: true }),
},
(t) => [index("speaking_rounds_starts_idx").on(t.startsAt)],
);
export const roundAttendance = pgTable(
"round_attendance",
{
roundId: uuid("round_id")
.notNull()
.references(() => speakingRounds.id, { onDelete: "cascade" }),
actorId: text("actor_id").notNull(),
/** Denormalised from the OIDC profile, like every other name here. */
displayName: text("display_name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.roundId, t.actorId] }), index("round_attendance_actor_idx").on(t.actorId)],
);
/**
* Feedback on the roadmap and the changelog — the storage behind bip-kit's
* `FeedbackStore` contract (`lib/feedback/store.ts`).
*
* `voter` is NOT an identity. It is the random key the reader's browser keeps
* (bip-kit's `x-bip-voter`), so a vote needs no sign-in and says nothing about
* who cast it. `target_id` is a bip-kit id (`roadmap:teams`,
* `changelog:2026-09-25:1`), validated against the published roadmap and
* changelog by the route before anything is written.
*/
export const feedbackStances = pgTable(
"feedback_stances",
{
targetId: text("target_id").notNull(),
voter: text("voter").notNull(),
/** `needed` | `not-needed`. Withdrawing a stance deletes the row. */
stance: text("stance").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.targetId, t.voter] })],
);
export const feedbackComments = pgTable(
"feedback_comments",
{
id: uuid("id").primaryKey().defaultRandom(),
targetId: text("target_id").notNull(),
voter: text("voter").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("feedback_comments_target_idx").on(t.targetId, t.createdAt)],
);
export const feedbackSuggestions = pgTable("feedback_suggestions", {
id: uuid("id").primaryKey().defaultRandom(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
/** One row per voter who asked for a suggestion, its author included. */
export const feedbackSupport = pgTable(
"feedback_support",
{
suggestionId: uuid("suggestion_id")
.notNull()
.references(() => feedbackSuggestions.id, { onDelete: "cascade" }),
voter: text("voter").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.suggestionId, t.voter] })],
);
/**
* Progress synced between a learner's devices — OPT-IN, signed in, off by
* default (settings). One row per device per record kind; see
* `lib/domain/progress/sync.ts` for why devices are kept apart rather than
* merged into one row: a page adds them up when it shows them, and nothing is
* ever counted twice.
*
* `device_id` is random and names only "a browser"; `actor_id` is the OIDC
* subject, like everywhere else here. Turning sync off deletes this device's
* rows; "delete synced progress" deletes all of them.
*/
export const progressDevices = pgTable(
"progress_devices",
{
actorId: text("actor_id").notNull(),
deviceId: text("device_id").notNull(),
/** `model` | `history` | `streak` | `saved`. */
key: text("key").notNull(),
value: jsonb("value").notNull(),
/**
* The course the record is about. Not part of the primary key: a second
* course needs the key widened to include it, in its own migration, and
* until one exists every row is the same course.
*/
course: course(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.actorId, t.deviceId, t.key] })],
);
/**
* A certificate for one situation, issued by the SERVER from the learner's
* synced progress — never from a browser's say-so, which is what makes the
* public page worth showing to somebody else.
*
* It records what was measured when it was issued (`askable`, `held`,
* `stuck`), because situations grow: a certificate from a 10-line scene says
* 10, and stays true about what it certified after the scene has 20.
* No name: the page is public, and a name there would be a directory of who
* is learning Swiss German. The learner may type one for printing; it is not
* stored.
*/
export const certificates = pgTable(
"certificates",
{
id: uuid("id").primaryKey().defaultRandom(),
actorId: text("actor_id").notNull(),
sceneId: text("scene_id").notNull(),
/** Scene ids are unique within a course, not across them. */
course: course(),
askable: integer("askable").notNull(),
held: integer("held").notNull(),
stuck: integer("stuck").notNull(),
issuedAt: timestamp("issued_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("certificates_actor_scene_idx").on(t.actorId, t.sceneId)],
);
/**
* What a signed-in learner chose for themselves, so a new device starts from
* it instead of from German.
*
* Only the site language today. The `heidi_locale` cookie already remembers a
* choice per browser; this row is what lets it follow the PERSON — somebody
* who reads the site in Züridütsch should not be handed Hochdeutsch again on
* every phone they sign in on. Written only when they pick a language while
* signed in (or sign in from a page that is not the German default), read
* only on the way back from signing in. See `lib/domain/preferences/`.
*/
export const preferences = pgTable("preferences", {
/** OIDC `sub`. No foreign key: the person lives in OrangeCat, not here. */
actorId: text("actor_id").primaryKey(),
/** One of `LOCALES`; checked on write and again on read. */
locale: text("locale").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* What a signed-in learner has agreed to be written to about — one row, one
* switch. Off until they turn it on (`reminders`); the sweep that sends
* (`lib/mail/reminder-sweep.ts`) reads only rows where it is on, and the rules
* for when it may actually write live in `lib/mail/reminder-policy.ts`.
*
* `tz` is the browser's IANA zone at the moment they switched it on, so the
* mail arrives in their evening and not the server's. `ignored` counts
* reminders in a row that were not followed by practice; three and it goes
* quiet by itself.
*/
export const mailPreferences = pgTable("mail_preferences", {
actorId: text("actor_id").primaryKey(),
reminders: boolean("reminders").notNull().default(false),
tz: text("tz"),
lastReminderAt: timestamp("last_reminder_at", { withTimezone: true }),
ignored: integer("ignored").notNull().default(0),
/**
* The weekly mail to admins (`lib/mail/digest-sweep.ts`). On unless somebody
* turned it off: null and true send, false does not. Only read for a user
* whose role is `admin`.
*/
digest: boolean("digest"),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Channels a learner follows, and what came out on them.
*
* WHY THIS IS ON THE SERVER AT ALL, when the learner model, the saved words
* and the streak are deliberately in the browser. Following a channel means
* being told when it publishes, and a browser that is closed cannot poll
* YouTube. So the follow is a row, the sweep that reads the feeds runs here,
* and the thing we keep about the person is exactly one fact: which channels.
* What they answered about a video stays in their browser
* (`heidi.videos.v1`), like every other measurement of them.
*
* `channels.id` is the platform's own channel id (the `UC…` string), so two
* learners following the same channel share one row and one feed read. The
* transcript and the questions are per VIDEO and shared the same way: a
* transcript is the publisher's text and the questions are ours about it —
* neither is about a learner.
*/
export const channels = pgTable("channels", {
/**
* The platform's channel id (`UC…` on YouTube), or for a podcast an id
* derived from its feed URL (`f` + 24 hex — `lib/channels/rss.ts`).
*/
id: text("id").primaryKey(),
/** `youtube` | `podcast`. A "channel" here is anything with a feed of episodes. */
kind: text("kind").notNull().default("youtube"),
name: text("name").notNull(),
/** The `@handle`, when the channel was added by one; for the link we show. */
handle: text("handle"),
url: text("url").notNull(),
/** The feed the sweep reads: YouTube's Atom feed or the podcast's RSS. */
feedUrl: text("feed_url").notNull().default(""),
/** What is spoken, when the register knows the source (`dialect` | `standard` | `mixed`). */
spoken: text("spoken"),
/** The podcast's artwork; null for a YouTube channel (each video has its own). */
imageUrl: text("image_url"),
/** When the feed was last read. Null until the first sweep. */
checkedAt: timestamp("checked_at", { withTimezone: true }),
/** Why the last read failed, in a word; null after a good one. */
lastError: text("last_error"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const channelVideos = pgTable(
"channel_videos",
{
/** The platform's video id. */
id: text("id").primaryKey(),
channelId: text("channel_id")
.notNull()
.references(() => channels.id, { onDelete: "cascade" }),
title: text("title").notNull(),
publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
thumbnailUrl: text("thumbnail_url"),
description: text("description"),
/** A podcast episode's audio (the enclosure); null for a YouTube video. */
mediaUrl: text("media_url"),
mediaType: text("media_type"),
durationSeconds: integer("duration_seconds"),
/** A transcript the publisher linked (`<podcast:transcript>`), and its MIME type. */
transcriptUrl: text("transcript_url"),
transcriptType: text("transcript_type"),
/**
* `{ lines, source, lang }` — see `lib/channels/transcript.ts`. Null until
* somebody opened the video and it could be fetched or was pasted.
*/
transcript: jsonb("transcript"),
/**
* `unknown` | `ready` | `none` | `blocked`. `none` is the platform saying
* there are no captions; `blocked` is the platform refusing to tell us —
* which is what sends the learner to the paste path.
*/
transcriptState: text("transcript_state").notNull().default("unknown"),
/** The generated question set, once a learner asked for one. */
questions: jsonb("questions"),
/** When followers were told about it. Null until the sweep sends. */
notifiedAt: timestamp("notified_at", { withTimezone: true }),
fetchedAt: timestamp("fetched_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("channel_videos_channel_published_idx").on(t.channelId, t.publishedAt)],
);
export const channelFollows = pgTable(
"channel_follows",
{
actorId: text("actor_id").notNull(),
channelId: text("channel_id")
.notNull()
.references(() => channels.id, { onDelete: "cascade" }),
followedAt: timestamp("followed_at", { withTimezone: true }).notNull().defaultNow(),
/** The last time this learner looked at the channel's videos — what "new" means. */
seenAt: timestamp("seen_at", { withTimezone: true }),
},
(t) => [primaryKey({ columns: [t.actorId, t.channelId] }), index("channel_follows_channel_idx").on(t.channelId)],
);
/**
* A browser that asked to be told. The endpoint is the push service's URL for
* that one browser and is the identity: re-subscribing from the same browser
* replaces the row rather than adding one. Deleted when the push service
* answers 404 or 410, which is how a browser that forgot us tells us so.
*/
export const pushSubscriptions = pgTable(
"push_subscriptions",
{
endpoint: text("endpoint").primaryKey(),
actorId: text("actor_id").notNull(),
p256dh: text("p256dh").notNull(),
auth: text("auth").notNull(),
/** The site language the browser was in, so the notification is in it. */
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("push_subscriptions_actor_idx").on(t.actorId)],
);
/**
* A thumb under one of Heidi's answers — the reader's half of the fleet's
* chat-review loop (chatkit 0.14, `AnswerFeedback`).
*
* `conversation_id` is TEXT and carries no foreign key, on purpose. A signed-in
* conversation's id is a `conversations` row; a signed-out one has no row at
* all (nothing anonymous reaches the database — §10) and files its thumb under
* the literal `draft`, so a bad answer in the browser-only chat is still
* counted, even though no transcript can ever be joined to it. `message_id` is
* likewise the product's own id — a `conversation_messages` row, or the
* client's local id for a draft — and never a person.
*
* Nothing here names who pressed it. The nightly review (`/api/chat/
* review-export`) reads these beside the conversation they belong to; a thumb
* with no owner is exactly as useful to it and exactly as private as the
* conversation row already is.
*/
export const chatFeedback = pgTable(
"chat_feedback",
{
id: uuid("id").primaryKey().defaultRandom(),
conversationId: text("conversation_id").notNull(),
messageId: text("message_id").notNull(),
/** `up` | `down`. */
verdict: text("verdict").notNull(),
/** One of chatkit's `FEEDBACK_REASONS`, when the person picked one. */
reason: text("reason"),
/** Their own words, at most 1000 characters, when they typed any. */
text: text("text"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
// The export joins thumbs to the conversations it is about to ship.
(t) => [index("chat_feedback_conversation_idx").on(t.conversationId, t.createdAt)],
);
/**
* Passes: what was offered for payment, and what access it bought.
*
* `pay_checkouts` is one row per invoice Heidi asked OrangeCat for. It is the
* only link from a settled payment back to a person: OrangeCat's
* `payment.settled` names the payment and nothing else. `handle` is the token
* that reads the payment's status and never leaves the server. `settled_at`
* is the idempotency mark: a payment grants its days once, however often the
* webhook is delivered and however the status poll races it.
*
* `entitlements` is one row per person: the pass they hold and when it ends.
*/
export const payCheckouts = pgTable(
"pay_checkouts",
{
id: text("id").primaryKey(),
actorId: text("actor_id").notNull(),
provider: text("provider").notNull(),
planId: text("plan_id").notNull(),
amount: integer("amount").notNull(),
currency: text("currency").notNull(),
invoice: text("invoice"),
payUrl: text("pay_url"),
handle: text("handle"),
expiresAt: timestamp("expires_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
settledAt: timestamp("settled_at", { withTimezone: true }),
},
(t) => [index("pay_checkouts_actor_idx").on(t.actorId, t.createdAt)],
);
export const entitlements = pgTable("entitlements", {
actorId: text("actor_id").primaryKey(),
planId: text("plan_id").notNull(),
/** The course the pass was bought for. Recorded by the column's default. */
course: course(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Heidi Plus: the subscription a person holds at Stripe, as paykit's
* `SubscriptionRecord` (`applySubscriptionEvent` keeps it).
*
* One row per person. `subscription_id` and `customer_id` are Stripe's ids:
* the first is how a renewal (`invoice.paid`) finds the person, the second is
* what opens Stripe's portal to manage or cancel, and is reused when the same
* person subscribes again. No card, no address, no name: those stay at Stripe.
* `period_end` is the end of the latest paid period, and access runs to it;
* the pass in `entitlements` is moved to it on every paid invoice.
* `event_at` is the newest Stripe event folded in, so an older one arriving
* late cannot undo a newer one.
*
* Erased with the account (`eraseActorData`). Cancelling at Stripe is the
* person's own step in the portal; erasing here does not cancel there.
*/
export const paySubscriptions = pgTable(
"pay_subscriptions",
{
actorId: text("actor_id").primaryKey(),
provider: text("provider").notNull(),
subscriptionId: text("subscription_id").notNull(),
customerId: text("customer_id"),
planId: text("plan_id"),
status: text("status").notNull(),
periodEnd: timestamp("period_end", { withTimezone: true }),
cancelAtPeriodEnd: boolean("cancel_at_period_end").notNull().default(false),
paymentFailed: boolean("payment_failed").notNull().default(false),
eventAt: timestamp("event_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [uniqueIndex("pay_subscriptions_subscription_idx").on(t.subscriptionId)],
);
/**
* Provider events already handled, by the provider's own event id: a
* webhook delivered twice is acknowledged the second time and does nothing.
* Only ids, types and times; no payload.
*/
export const payEvents = pgTable("pay_events", {
id: text("id").primaryKey(),
provider: text("provider").notNull(),
type: text("type").notNull(),
receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* How Heidi is paid, as the owner set it in the back office (Money →
* «Zahlungen», `lib/pay/settings.ts`), so the owner never edits a file on
* the server: the subscription prices, the sales switch, the Stripe key and
* webhook secret, and what «Stripe einrichten» made at Stripe (the ids of
* the prices, the portal configuration and the webhook endpoint).
*
* `name` is the environment variable it stands for: a row here wins over
* the variable, no row leaves the variable in charge. A secret is stored
* sealed (`sealed`: AES-256-GCM under the session secret, `@bitbaum/ai-kit/seal`)
* and never sent back to a page. Nothing about a person is in this table.
*/
export const paySettings = pgTable("pay_settings", {
name: text("name").primaryKey(),
value: text("value").notNull(),
sealed: boolean("sealed").notNull().default(false),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Pass codes: a pass that was paid for somewhere Heidi cannot see.
*
* An organisation pays for its people in francs, by bank transfer, and there
* is no invoice of OrangeCat's to settle. So the owner issues one code per
* person and the person redeems it: the same `entitlements` row a Bitcoin
* payment writes, through the same arithmetic (`lib/pay/codes.ts`).
*
* `id` is the SHA-256 of the code. The code itself is shown once, to the
* owner who issued it, and is stored nowhere: a copy of this table is not a
* list of passes anybody can take. `hint` is its last four characters, so the
* owner can tell which of a batch has been used. `label` is who the batch was
* issued for, in the owner's words. `redeemed_at` is the idempotency mark, as
* `settled_at` is on a checkout: a code grants its days once.
*/
export const passCodes = pgTable(
"pass_codes",
{
id: text("id").primaryKey(),
hint: text("hint").notNull(),
days: integer("days").notNull(),
label: text("label").notNull(),
/** The course the pass is for. Recorded by the column's default. */
course: course(),
createdBy: text("created_by").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
redeemedBy: text("redeemed_by"),
redeemedAt: timestamp("redeemed_at", { withTimezone: true }),
},
(t) => [index("pass_codes_label_idx").on(t.label, t.createdAt)],
);
/**
* Who asked to be told when a language Heidi does not teach yet is ready.
*
* WHAT IT IS FOR, AND NOTHING ELSE: to learn which language to build next,
* and to write to that address once when it exists. It is a list of
* addresses and a wish each — never an account, never a subscription to
* anything else, and no page may call it a waiting list for a product that
* has a date. `lib/config/languages.ts` holds which languages can be asked
* for; `lib/config/privacy.ts` states this table on the privacy page.
*
* The person is the `email`: there is no `actor_id`, because the form works
* signed out. Deleting an account deletes the rows with that account's
* address (`eraseActorData`). One row per address and language, so asking
* twice changes nothing but the region.
*
* `region` is their own words for the canton or region they live in or are
* moving to, when they gave one. `locale` is the interface language they
* asked in, so the one mail can be written in it.
*/
export const languageInterest = pgTable(
"language_interest",
{
id: uuid("id").primaryKey().defaultRandom(),
email: text("email").notNull(),
/** A `PlannedLanguageId` from `lib/config/languages.ts`. */
language: text("language").notNull(),
region: text("region"),
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Double opt-in (2026-11-25). `confirmedAt` is when the person opened the
* link in the one confirmation mail; null on every row from before, and
* on a row whose mail was never opened. `confirmToken` is the SHA-256 of
* the link's token while one is outstanding, never the token itself;
* `confirmSentAt` is when that mail last went out, so an address is not
* mailed again and again by whoever types it into the form.
*/
confirmedAt: timestamp("confirmed_at", { withTimezone: true }),
confirmToken: text("confirm_token"),
confirmSentAt: timestamp("confirm_sent_at", { withTimezone: true }),
},
(t) => [
uniqueIndex("language_interest_email_language_idx").on(t.email, t.language),
uniqueIndex("language_interest_confirm_token_idx").on(t.confirmToken),
],
);
/**
* Addresses that asked on /plans to be told when passes go on sale
* (`lib/pay/pass-notify.ts`). An address, the page's language and the time:
* nothing about the browser, no account. Written once per address, used once,
* and deleted with the account whose address it is (`eraseActorData`).
*/
export const passInterest = pgTable("pass_interest", {
email: text("email").primaryKey(),
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Rate-limit counters for signed-in callers (`lib/domain/limit-counter.ts`).
*
* One row per key and time bucket; a key is `<purpose>:<course>:<account>`
* and has at most two live rows. Nothing here says what anybody did: a
* purpose is the name of a limit ("chat", "speak"), the count is how many
* requests were allowed in that bucket, and rows older than a day are
* removed. Anonymous callers are counted in memory and never reach this
* table, so it holds no address.
*/
export const rateLimits = pgTable(
"rate_limits",
{
key: text("key").notNull(),
/** The start of the bucket, in epoch milliseconds. */
bucket: bigint("bucket", { mode: "number" }).notNull(),
count: integer("count").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.key, t.bucket] }), index("rate_limits_bucket_idx").on(t.bucket)],
);
/**
* What one person has used of a pass period's allowance
* (`lib/domain/usage-meter.ts`): seconds of server voice, dictation clips.
*
* One row per person, kind and period, holding the running total. The period
* is a string the caller derives (the 30-day block of the pass the person
* holds), so a new period is a new row and nothing is ever reset in place.
* Unlike `rate_limits` these survive any restart and are not swept: a row is
* a few bytes and a pass holder is a person who paid.
*/
export const usageMeter = pgTable(
"usage_meter",
{
actorId: text("actor_id").notNull(),
kind: text("kind").notNull(),
period: text("period").notNull(),
amount: integer("amount").notNull().default(0),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.actorId, t.kind, t.period] })],
);
/**
* Server errors, grouped (`lib/domain/errors/sink.ts`).
*
* One row per KIND of error, not per occurrence: the route pattern it
* happened in (`/api/chat`, `/[locale]/practice`: the file's path, never the
* address that was requested), the error's name and a message with
* addresses, ids and long tokens removed, how often, and when first and
* last. No request, no body, no header, no account. Capped at a few hundred
* rows; a row not seen for thirty days is removed.
*/
export const errorEvents = pgTable(
"error_events",
{
/** sha-256 of route, name and scrubbed message: what makes two errors "the same". */
hash: text("hash").primaryKey(),
route: text("route").notNull(),
name: text("name").notNull(),
message: text("message").notNull(),
count: integer("count").notNull().default(1),
firstSeen: timestamp("first_seen", { withTimezone: true }).notNull().defaultNow(),
lastSeen: timestamp("last_seen", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("error_events_last_seen_idx").on(t.lastSeen)],
);
/**
* Anonymous totals: how often something happened on a day, and nothing about
* who did it.
*
* WHY. Practice lives in the browser, so nobody — the owner included — could
* say whether people finish a situation, which question everybody gets
* wrong, or whether an exercise is used at all. A product that cannot see
* that cannot be made better on purpose. Decided by the owner on 2026-11-28.
*
* WHAT A ROW IS. A day, a key from a closed vocabulary (`usage/keys.ts`:
* «a run of this situation was started», «this question was answered
* wrong») and a count. No account, no visitor id, no address, no time of
* day, no text anybody typed. Two people cannot be told apart in it, and one
* person cannot be followed through it; that is the design, not a setting.
*/
export const usageCounts = pgTable(
"usage_counts",
{
day: date("day").notNull(),
key: text("key").notNull(),
count: integer("count").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.day, t.key] })],
);
/**
* What a native speaker said about a line of a situation.
*
* WHY. On 2026-11-28 none of the 793 lines of the situations had been read
* by anybody who speaks the variety, and the pages say so. That is the first
* thing a care home's own staff would notice. A reader goes through a scene
* line by line and says "that is how we say it", "not like this" (with how
* they would say it) or "not sure"; the owner reads the verdicts and corrects
* the pack, and only then is a line marked reviewed (`Provenance`).
*
* NO ACCOUNT. The reader is a nurse who was sent a link; an account between
* her and the first line is the end of the review. `reader` is a random id
* her browser made up (`heidi.review.reader.v1`), which says only that two
* verdicts came from the same browser. One row per reader and line: a reader
* who changes their mind replaces their verdict.
*
* The line is stored AS IT WAS SHOWN, so a verdict on a line that has since
* been corrected is not mistaken for one on the new wording.
*/
export const lineReviews = pgTable(
"line_reviews",
{
reader: text("reader").notNull(),
scene: text("scene").notNull(),
line: integer("line").notNull(),
/** `ok` | `other` (fine, but I say it differently) | `wrong` | `unsure`. */
verdict: text("verdict").notNull(),
/** How the reader would say it; only with `wrong` or `unsure`. */
suggestion: text("suggestion"),
/** Where the reader's own dialect is from, in their words, if they said. */
origin: text("origin"),
/**
* Which invitation the reader came through (`?via=` on the link), so the
* owner can tell a care home's own staff from a link passed round among
* friends. A short code the sender chose, never a name.
*/
via: text("via"),
/** The line as the reader saw it. */
shown: text("shown").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.reader, t.scene, t.line] }), index("line_reviews_scene_idx").on(t.scene, t.line)],
);
/** Raw bytes. Drizzle has no built-in column for them. */
const bytea = customType<{ data: Uint8Array }>({ dataType: () => "bytea" });
/**
* A native speaker saying one line of a situation (`lib/domain/review/recordings.ts`
* for why, for what consent means here, and for why the bytes are in the row).
*
* The same `reader` as `line_reviews`: a random id from the browser, no
* account, no name. One row per reader and line; saying it again replaces the
* take and puts it back to `new`. `status` is `new` until a person in the back
* office has listened: only `approved` rows are ever served to learners.
* `shown` is the line as it was said, so a recording of a wording corrected
* since is not offered under the new one.
*/
export const lineRecordings = pgTable(
"line_recordings",
{
id: uuid("id").primaryKey(),
reader: text("reader").notNull(),
scene: text("scene").notNull(),
line: integer("line").notNull(),
shown: text("shown").notNull(),
mime: text("mime").notNull(),
bytes: integer("bytes").notNull(),
durationMs: integer("duration_ms").notNull(),
audio: bytea("audio").notNull(),
origin: text("origin"),
via: text("via"),
/** `new` | `approved` | `rejected`. */
status: text("status").notNull().default("new"),
decidedAt: timestamp("decided_at", { withTimezone: true }),
/** The actor id of whoever listened and decided. */
decidedBy: text("decided_by"),
/** When the reader agreed that learners may hear it: the moment they sent it. */
consentAt: timestamp("consent_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [
uniqueIndex("line_recordings_reader_line_idx").on(t.reader, t.scene, t.line),
index("line_recordings_scene_idx").on(t.scene, t.status),
],
);
/**
* The daily chat benchmark (`lib/domain/bench`): a fixed set of messages sent
* through the real chat, and the translations also sent to the same models
* WITHOUT Heidi's prompt or check, so the page can show what the check is
* worth. One row per run; nothing in it is about a person.
*/
export const benchRuns = pgTable("bench_runs", {
ranAt: timestamp("ran_at", { withTimezone: true }).primaryKey(),
results: jsonb("results").notNull(),
});
/**
* An account the owner linked by mail (`lib/domain/owner/link.ts`): somebody
* who signs in through OrangeCat has no real address here, so `OWNER_EMAILS`
* can never match them. A link mailed to the owner address and opened makes
* that account an owner, with no change on the server.
*/
export const ownerLinks = pgTable("owner_links", {
actorId: text("actor_id").primaryKey(),
/** Which owner address the confirming mail went to. */
confirmedBy: text("confirmed_by").notNull(),
linkedAt: timestamp("linked_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* A run of the understanding test (`bench/understand.ts`): course lines the
* chat was asked to explain with the line itself held back, each judged
* against the line's known meaning. Started by hand; holds no person.
*/
export const understandRuns = pgTable("understand_runs", {
ranAt: timestamp("ran_at", { withTimezone: true }).primaryKey(),
results: jsonb("results").notNull(),
});
/**
* A pilot asked for on a sector page (`/organisations/<sector>`): who, from
* where, how to reach them, and what they wrote. The owner reads them at
* `/api/owner/requests` and gets a mail for each when mail is set up.
*/
export const orgRequests = pgTable("org_requests", {
id: uuid("id").primaryKey().defaultRandom(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
sector: text("sector").notNull(),
locale: text("locale").notNull(),
name: text("name").notNull(),
organisation: text("organisation").notNull(),
role: text("role"),
email: text("email").notNull(),
people: text("people"),
message: text("message"),
/** When somebody in the back office marked it done (`/manage/inbox`). */
handledAt: timestamp("handled_at", { withTimezone: true }),
/** What was answered from the back office, and when; the mail itself went to `email`. */
replyText: text("reply_text"),
repliedAt: timestamp("replied_at", { withTimezone: true }),
});
/**
* The back office's own two tables, defined by the package that owns the
* rules (`@bitbaum/accountkit/auth/managers`, used in
* `lib/domain/admin/people.ts`). `admin_invites`: a single-use link carrying
* a role; only the hash of the link is kept. `admin_events`: who was let in,
* by whom, and who was taken out, an append-only history written in the same
* statement as the change itself; an account that is deleted stays in it as
* nobody (`account/erase.ts`). Column for column what migrations 0028 and
* 0030 created.
*/
export const { adminInvites, adminEvents } = createManagerTables();
/**
* Practising together (`lib/domain/play/`): a challenge behind a link, and a
* live round with a six-digit code. Nicknames and scores, nothing else about
* a person: no account, no address, no device id. A challenge and its players
* go 30 days after it was made; a room and everything in it 2 hours after
* anybody last touched it. Both are swept when somebody next opens or makes
* one, never by a timer.
*
* `item_ids` are question ids of the course (`PACK_ITEMS`), in the order they
* are asked; with `seed` they fix the questions and the order of every
* question's options for every player.
*/
export const playChallenges = pgTable(
"play_challenges",
{
id: text("id").primaryKey(),
course: course(),
/** What it is about: `all`, `area:<domain>` or `scene:<id>` (`play/subject.ts`). */
subject: text("subject").notNull(),
itemIds: jsonb("item_ids").$type<string[]>().notNull(),
seed: integer("seed").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("play_challenges_created_idx").on(t.createdAt)],
);
export const playChallengePlayers = pgTable(
"play_challenge_players",
{
id: uuid("id").primaryKey().defaultRandom(),
challengeId: text("challenge_id")
.notNull()
.references(() => playChallenges.id, { onDelete: "cascade" }),
nickname: text("nickname").notNull(),
/** Right or wrong, per question, in the challenge's order. */
answers: jsonb("answers").$type<boolean[]>().notNull(),
right: integer("right").notNull(),
/** How long the whole challenge took, as the player's browser measured it. */
ms: integer("ms").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("play_challenge_players_challenge_idx").on(t.challengeId)],
);
/**
* A live room. The one row every phone polls: `version` goes up whenever
* something everybody must see changes (a player joins, a question opens or
* closes), so a phone that is up to date is answered from this row alone.
*/
export const playRooms = pgTable(
"play_rooms",
{
code: text("code").primaryKey(),
course: course(),
subject: text("subject").notNull(),
itemIds: jsonb("item_ids").$type<string[]>().notNull(),
seed: integer("seed").notNull(),
/** sha256 of the host's secret, which only the host's browser holds. */
hostHash: text("host_hash").notNull(),
phase: text("phase").notNull().default("lobby"),
q: integer("q").notNull().default(0),
openedAt: timestamp("opened_at", { withTimezone: true }),
version: integer("version").notNull().default(1),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
touchedAt: timestamp("touched_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("play_rooms_touched_idx").on(t.touchedAt)],
);
export const playRoomPlayers = pgTable(
"play_room_players",
{
id: uuid("id").primaryKey().defaultRandom(),
roomCode: text("room_code")
.notNull()
.references(() => playRooms.code, { onDelete: "cascade" }),
/** sha256 of the player's secret, which only their browser holds. */
tokenHash: text("token_hash").notNull(),
nickname: text("nickname").notNull(),
score: integer("score").notNull().default(0),
joinedAt: timestamp("joined_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [uniqueIndex("play_room_players_name_idx").on(t.roomCode, t.nickname)],
);
/** One answer per player per question: the key is what makes a second tap count nothing. */
export const playRoomAnswers = pgTable(
"play_room_answers",
{
roomCode: text("room_code")
.notNull()
.references(() => playRooms.code, { onDelete: "cascade" }),
q: integer("q").notNull(),
playerId: uuid("player_id")
.notNull()
.references(() => playRoomPlayers.id, { onDelete: "cascade" }),
choice: integer("choice").notNull(),
right: boolean("right").notNull(),
points: integer("points").notNull(),
ms: integer("ms").notNull(),
},
(t) => [primaryKey({ columns: [t.roomCode, t.q, t.playerId] })],
);
/**
* The Stammtisch (`lib/domain/stammtisch/`): people who are learning talk to
* each other in Zurich German, two at a table or a few, with Heidi between
* them. Every statement is in `stammtisch/store.ts`.
*
* WHAT IS KEPT, AND FOR HOW LONG. A table, its seats and its messages go
* together, `idleMinutes` (the rulebook) after anybody last touched the
* table; they are swept when somebody next asks for a table, never by a
* timer. What outlives a table: a person's standing (`stammtisch_people`),
* who they blocked, a report with the lines it is about, and the events the
* numbers are counted from, which hold no text.
*/
export const stammtischTables = pgTable(
"stammtisch_tables",
{
/** Random, and for a private table the link is the key (like a group's invite). */
id: text("id").primaryKey(),
course: course(),
/** `pair` or `group` (`stammtisch/table.ts`). */
kind: text("kind").notNull(),
seats: integer("seats").notNull(),
/** Strangers may be seated here. False for a table made to be shared by link. */
open: boolean("open").notNull().default(true),
/** `{ kind: "scene", id }` or `{ kind: "own", text }` (`stammtisch/topics.ts`). */
topic: jsonb("topic").$type<{ kind: "scene"; id: string } | { kind: "own"; text: string }>().notNull(),
/** Heidi sits at the table: she answers while one person is alone at it. */
heidi: boolean("heidi").notNull().default(false),
/** Lines in Zurich German so far, everybody's together: the table's shared goal. */
meter: integer("meter").notNull().default(0),
/** Goes up with everything a phone must see; an up-to-date phone is answered from this row. */
version: integer("version").notNull().default(1),
lastSeq: integer("last_seq").notNull().default(0),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
touchedAt: timestamp("touched_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("stammtisch_tables_touched_idx").on(t.touchedAt), index("stammtisch_tables_open_idx").on(t.open, t.kind)],
);
export const stammtischSeats = pgTable(
"stammtisch_seats",
{
tableId: text("table_id")
.notNull()
.references(() => stammtischTables.id, { onDelete: "cascade" }),
actorId: text("actor_id").notNull(),
/** The seat's number at this table: what other phones name a person by, never the account id. */
n: integer("n").notNull(),
name: text("name").notNull(),
/** The mouth filter: Heidi helps what this person sends into Zurich German. */
mouth: boolean("mouth").notNull().default(true),
/** The ear filter: Heidi screens what this person receives. */
ears: boolean("ears").notNull().default(true),
/** Set when this person was moved away from the others: the last line of the table they still share. */
shadowSeq: integer("shadow_seq"),
/** Flagged messages at this table; confident misses of the dialect in a row. */
flagged: integer("flagged").notNull().default(0),
misses: integer("misses").notNull().default(0),
mutedUntil: timestamp("muted_until", { withTimezone: true }),
/** Lines written in Zurich German unaided; lines sent the way Heidi suggested; points. */
own: integer("own").notNull().default(0),
helped: integer("helped").notNull().default(0),
points: integer("points").notNull().default(0),
joinedAt: timestamp("joined_at", { withTimezone: true }).notNull().defaultNow(),
seenAt: timestamp("seen_at", { withTimezone: true }).notNull().defaultNow(),
leftAt: timestamp("left_at", { withTimezone: true }),
},
(t) => [
primaryKey({ columns: [t.tableId, t.actorId] }),
index("stammtisch_seats_actor_idx").on(t.actorId),
// Two people sitting down at the same instant cannot both be seat n: the second statement fails and `sit` asks again.
uniqueIndex("stammtisch_seats_table_n_idx").on(t.tableId, t.n),
],
);
export const stammtischMessages = pgTable(
"stammtisch_messages",
{
tableId: text("table_id")
.notNull()
.references(() => stammtischTables.id, { onDelete: "cascade" }),
seq: integer("seq").notNull(),
/** An account id, or `heidi`. */
authorId: text("author_id").notNull(),
/** What was written. */
body: text("body").notNull(),
/** What a filtered reader gets, where it differs: Heidi's Zurich German, or the line put in a flagged message's place. Null with `filtered` means nothing is shown. */
shown: text("shown"),
/** `own` | `suggested` | `auto` | `plain` | `filtered` (`stammtisch/decide.ts`). */
treatment: text("treatment").notNull(),
flag: text("flag").notNull().default("ok"),
/** Sent with the sender's mouth filter off: a reader whose ear filter is off too reads it as written. */
unhelped: boolean("unhelped").notNull().default(false),
/** `all`, or the one account that sees it (a person moved away, and what is answered to them). */
audience: text("audience").notNull().default("all"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.tableId, t.seq] })],
);
/** One row per person who has opened the Stammtisch: their standing, their day, their totals. */
export const stammtischPeople = pgTable("stammtisch_people", {
actorId: text("actor_id").primaryKey(),
/** When they said they are an adult. Without it, no table. */
adultAt: timestamp("adult_at", { withTimezone: true }),
strikes: integer("strikes").notNull().default(0),
strikesAt: timestamp("strikes_at", { withTimezone: true }),
suspendedUntil: timestamp("suspended_until", { withTimezone: true }),
/** How many situations their browser said they can follow, last time they asked for a table. */
learned: integer("learned").notNull().default(0),
/** The day `used` counts (UTC, `YYYY-MM-DD`), and the messages sent on it that cost a model call. */
day: text("day"),
used: integer("used").notNull().default(0),
tables: integer("tables").notNull().default(0),
goals: integer("goals").notNull().default(0),
own: integer("own").notNull().default(0),
helped: integer("helped").notNull().default(0),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/** Somebody a person does not want to be seated with again. Either way round keeps them apart. */
export const stammtischBlocks = pgTable(
"stammtisch_blocks",
{
actorId: text("actor_id").notNull(),
blockedId: text("blocked_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.actorId, t.blockedId] })],
);
/**
* A report. It keeps the reported person's last lines as they were written,
* because a report with nothing to read cannot be judged; that is the one
* place a table's words outlive the table.
*/
export const stammtischReports = pgTable(
"stammtisch_reports",
{
id: uuid("id").primaryKey().defaultRandom(),
tableId: text("table_id").notNull(),
reporterId: text("reporter_id").notNull(),
reportedId: text("reported_id").notNull(),
reportedName: text("reported_name").notNull(),
reason: text("reason").notNull(),
excerpt: jsonb("excerpt").$type<{ body: string; flag: string; at: string }[]>().notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
resolvedAt: timestamp("resolved_at", { withTimezone: true }),
/** `dismissed` | `suspended`. */
resolution: text("resolution"),
},
(t) => [index("stammtisch_reports_open_idx").on(t.resolvedAt, t.createdAt)],
);
/** What happened, without what was said: the rows the Stammtisch's numbers are counted from (`stammtisch/metrics.ts`). */
export const stammtischEvents = pgTable(
"stammtisch_events",
{
id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
at: timestamp("at", { withTimezone: true }).notNull().defaultNow(),
name: text("name").notNull(),
detail: text("detail"),
actorId: text("actor_id"),
tableId: text("table_id"),
n: integer("n"),
},
(t) => [index("stammtisch_events_name_at_idx").on(t.name, t.at)],
);
/** The rulebook as the owner set it (`stammtisch/rulebook.ts`); no row means the defaults. */
export const stammtischRules = pgTable("stammtisch_rules", {
course: text("course").primaryKey(),
rules: jsonb("rules").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
updatedBy: text("updated_by"),
});