Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

116 KB
Raw Blame
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

/// Explicitly published, portable single-session snapshots. Live shares remain a separate protocol.
model CommunityHarness {
  id            String   @id @default(uuid()) @map("_id")
  autonomousEnv String   @default("prod")
  authorId      String
  authorName    String
  title         String
  description   String
  category      String
  engine        String
  harnessId     String?
  viewerPath    String
  files         Json
  conversation  Json
  cover         String?
  forkedFrom    String?
  credits       Json     @default("[]")
  deletedAt     DateTime?
  createdAt     DateTime @default(now())
  // Set when its author edits it (routes/communityEdit.ts); never on publishing.
  updatedAt     DateTime?
  // Its likes, moved with each one saved (lib/communityLikes.ts) and reconciled at worker boot: what a
  // popular feed orders by, instead of counting every publication's likes for each page.
  likeCount     Int      @default(0)

  @@index([autonomousEnv, deletedAt, createdAt])
  @@index([autonomousEnv, deletedAt, likeCount, createdAt])
  @@index([autonomousEnv, authorId])
  @@index([autonomousEnv, forkedFrom])
  @@index([autonomousEnv, category, deletedAt, createdAt])
  @@map("community_harnesses")
}

model CommunityLike {
  id            String   @id @default(auto()) @map("_id") @db.ObjectId
  autonomousEnv String   @default("prod")
  harnessId     String
  userId        String
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, harnessId, userId])
  @@index([autonomousEnv, harnessId])
  // A trending feed reads only the last week's likes.
  @@index([autonomousEnv, createdAt])
  @@map("community_likes")
}

model CommunityComment {
  id            String   @id @default(uuid()) @map("_id")
  autonomousEnv String   @default("prod")
  harnessId     String
  userId        String
  authorName    String
  body          String
  clientId      String
  parentId      String?
  parentAuthorName String?
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, harnessId, userId, clientId])
  @@index([autonomousEnv, harnessId, createdAt])
  @@index([autonomousEnv, userId, createdAt])
  @@map("community_comments")
}

/// One reader's report of a publication or a comment (lib/communityReports.ts). It hides that one from
/// its reader at once; reports from three readers hide it from everyone (CommunityHidden).
model CommunityReport {
  id            String   @id @default(auto()) @map("_id") @db.ObjectId
  autonomousEnv String   @default("prod")
  targetType    String   // 'harness' | 'comment'
  targetId      String
  harnessId     String   // the publication, or the one the comment is on
  userId        String
  reason        String
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, targetType, targetId, userId])
  @@index([autonomousEnv, userId, targetType])
  @@index([autonomousEnv, targetType, targetId, createdAt])
  @@map("community_reports")
}

/// A publication or comment hidden from everyone after reports, until a reviewer restores it (kept,
/// with `restoredAt`: only reports after that count again) or removes it.
model CommunityHidden {
  id            String    @id @default(auto()) @map("_id") @db.ObjectId
  autonomousEnv String    @default("prod")
  targetType    String
  targetId      String
  harnessId     String
  createdAt     DateTime  @default(now())
  restoredAt    DateTime?

  @@unique([autonomousEnv, targetType, targetId])
  @@index([autonomousEnv, targetType, restoredAt])
  @@map("community_hidden")
}

/// Something that happened to a creator's work on the Hub, for their bell (lib/communityNotifications.ts):
/// a comment on their harness, a reply to their comment, a fork of their harness. It names who did it and
/// where, never what they wrote.
model CommunityNotification {
  id            String    @id @default(auto()) @map("_id") @db.ObjectId
  autonomousEnv String    @default("prod")
  userId        String    // who is told
  kind          String    // 'comment' | 'reply' | 'fork'
  harnessId     String    // the harness commented on, or the one forked
  harnessTitle  String
  actorName     String
  targetId      String    // the comment, or the fork
  createdAt     DateTime  @default(now())
  readAt        DateTime?

  @@index([autonomousEnv, userId, createdAt])
  @@index([autonomousEnv, userId, readAt])
  @@map("community_notifications")
}

model CommunityFollow {
  id            String   @id @default(auto()) @map("_id") @db.ObjectId
  autonomousEnv String   @default("prod")
  authorId      String
  userId        String
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, authorId, userId])
  @@index([autonomousEnv, userId])
  @@map("community_follows")
}

/// A thin MIRROR of a product user. Identity is the normalized email authenticated by Autonomous
/// SSO. The two Autonomous account planes issue different subjects for the same email, so production
/// and staging subjects are stored separately. Lives in the SAME MongoDB the agent-manager uses, but
/// in its own `users` collection — the manager never touches it.
///
/// The production subject (`externalId`) remains unique because SDS stores that value as a device's
/// `customer_id`. A device may connect before its owner has signed in, so that provisional row uses a
/// deterministic non-deliverable email until the first production SSO login claims it.
model User {
  id              String    @id @default(auto()) @map("_id") @db.ObjectId
  email           String    @unique // normalized SSO identity; provisional device rows use @pending.harness.invalid
  externalId      String    @unique // production SSO subject == SDS `customer_id`; local-prod-* until known
  stagExternalId  String? // staging SSO subject; authentication still keys by email
  passwordHash    String? // legacy only; SSO users have none
  name            String? // from SSO once, while empty; later sign-ins never overwrite it (UserService.upsertFromSso)
  role            String    @default("user") // user | admin
  // Which Autonomous account plane this user signs in against. Existing rows are backfilled to
  // staging because they were created while the app used staging globally; new users default prod.
  autonomousEnv   String    @default("prod") // prod | stag
  // The user's private harness grid, minted on first ask and never rewritten (see routes/grid.ts).
  // Deliberately NOT @unique: on MongoDB a unique index counts nulls as values, so every user
  // without a grid would collide with every other. Global uniqueness is the grid control plane's
  // rule to enforce; ours is only one name per user, which the conditional write in the route gives.
  gridName        String?
  // Cloudflare `CF-IPCountry` (ISO-2) of the last control-plane request this user made, stamped by
  // middlewares/authMiddleware.ts through lib/clientGeo.ts (rate-floored, never per request). The
  // REST call always comes from the person's own computer, so this is the "where is the user" answer;
  // `Machine.countryCode` and the machine/device presence rows carry the CONNECTING SOCKET's country
  // instead, which for a remote machine is the VPS, not the person.
  // Null on rows that predate it or when the request did not come through Cloudflare.
  lastCountryCode String?
  lastCountryAt   DateTime?
  // The `utm_*` and `rid` a sign-in arrived with (lib/signInAttribution.ts), recorded by /api/auth/exchange.
  // `signUpAttribution` is the tags the account was created with — how it was acquired — written once,
  // by the sign-in that created the row (or claimed a device's provisional row). Unset for an account
  // created untagged or elsewhere, so a later tagged sign-in never claims the acquisition.
  // `lastAttribution` is the latest tagged sign-in.
  signUpAttribution SignInAttribution?
  lastAttribution   SignInAttribution?
  // The account's Google subject as this backend last read it LIVE from the Autonomous profile
  // (lib/googleSubject.ts, ADR 0046), so `GET /api/grid/profile` can answer for a computer signed in
  // by QR, whose token Autonomous cannot read. `googleSubCheckedAt` unset means never checked — and on
  // MongoDB that is ABSENT on every row written before today as well as null, so a filter on
  // `googleSubCheckedAt: null` alone misses the legacy rows (the trap `Machine.deletedAt` and
  // routes/grid.ts document); `UserService.recordGoogleSubject` adds `isSet: false`. Once checked, a
  // null `googleSub` means "this account has no Google identity".
  // Both are internal: `UserService.toPublic` leaves them out of every user-describing response.
  googleSub          String?
  googleSubCheckedAt DateTime?
  createdAt       DateTime  @default(now())
  updatedAt       DateTime  @updatedAt

  @@index([stagExternalId])
  @@map("users")
}

type SignInAttribution {
  source     String?
  medium     String?
  campaign   String?
  term       String?
  content    String?
  rid        String? // Autonomous referral id
  recordedAt DateTime
}

/// A machine: the unit that groups N agents and the thing a user creates, names, pays for and
/// attaches a device to. Maps a user to their provisioned machine (agent-node) + the per-machine
/// api-key the backend generated for it. The backend injects this key when reverse-proxying the
/// user's data-plane traffic to the manager (the web never sees it). One node per machine.
/// The manager owns the authoritative `machine_nodes` record; this is the backend's routing view
/// (api-key + which manager owns the node).
model Machine {
  id                              String    @id @default(auto()) @map("_id") @db.ObjectId
  userId                          String // owner (User.id); a user may own many machines
  machineId                       String    @unique // sha256(apiKey)[:32] — the routing key, on the wire as `machineId`
  apiKey                          String // per-machine key; the data-plane credential (handed to the owner) + routing/node auth
  managerId                       String // which manager owns the node → its dial-in socket routes this machine's traffic
  workspaceId                     String?
  // Immutable upstream plane copied from the owner when the machine is created. Billing and campaign
  // credentials always resolve from this value, even if an admin later switches the user env.
  autonomousEnv                   String    @default("prod") // prod | stag
  // Subscription plan the machine is on (SubscriptionPlan.id). cpus/memory are resolved THROUGH the
  // plan (the manager reads it), replacing the old per-machine cpus/memory fields. Optional so legacy
  // rows read; set to the default plan on every new create.
  planId                          String?
  // Denormalized from SubscriptionPlan.authMode at creation — IMMUTABLE (set once; there is no
  // plan-switch path). All authMode logic reads THIS field, never the plan (a later plan-doc edit
  // must not flip a live machine's mode). Optional so legacy rows read; backfilled at backend startup.
  authMode                        String?
  // The machine's display name. User-editable (PATCH /api/machines/:id); seeded ONCE from the
  // connecting computer's hostname when still empty, then never overwritten by a connect.
  name                            String?
  // Hostname of the COMPUTER on its LAST adapter-ws connect (remote machines only) — the adapter
  // sends it as `?label=` and it is overwritten every time, so it reflects the most recent computer.
  // Secondary detail only: never used as the machine's name. Null for machines that never connected.
  hostname                        String?
  // The COMPUTER currently bound to this machine — the CLI's per-computer id, normalized
  // (lib/deviceAuth.ts:normalizeComputerId). Stamped when a computer is connected through the
  // device-auth grant and refreshed on every adapter-ws connect, so `harness auth device` on the same
  // box reconnects to THAT machine instead of minting a second one. Null on rows that predate it.
  computerId                      String?
  // How the computer signed in on its LAST adapter-ws connect: `team` for a team session (lib/teamSession.ts),
  // a Mac's team account running teammates' Swarm agents; `computer` for any other sign-in. A `team` row taken
  // over by a normal sign-in is set to `computer` before that socket attaches, so `team` never names a machine a
  // normal sign-in serves. Null on rows that predate it (never a team machine). A team session acts only for a
  // row marked `team`; Swarm routing reads it (Task 3 of docs/plans/2026-10-24-swarm-team-account.md).
  sessionKind                     String?
  // A team machine's Mac: the machineId of the owner's own machine on the computer whose Harness Team account this
  // is, so every list shows that Mac once ("One machine" in docs/plans/2026-10-24-swarm-team-account.md). Copied from
  // the team session (`HarnessSession.hostMachineId`) whenever that session registers its machine; nothing a team
  // session sends sets it. Null for every other machine, a dedicated one (`harness team on`) included.
  hostMachineId                   String?
  // Version string the CLIENT reported on its LAST adapter-ws connect (remote machines only) — the
  // client sends it as `?v=` and it is overwritten every time, so it reflects the most recent connect.
  // Self-declared and sanitized at the upgrade; null for a machine that never connected or a client
  // old enough not to send it.
  clientVersion                   String?
  // Cloudflare `CF-IPCountry` (ISO-2) of the computer on its LAST adapter-ws connect — same
  // overwrite-every-connect rule as `hostname`/`clientVersion`. Null when the upgrade did not come
  // through Cloudflare (local dev) or the row predates the field.
  countryCode                     String?
  // When this machine's daemon was last seen on /api/adapter-ws: stamped on connect, on close, and at most every
  // MACHINE_PRESENCE_WRITE_MS while the socket stays open (adapterWs.ts), so it lags real liveness by at most
  // that. One overwritten value, never a history. Redis `machine:{id}:mgr` is still "online right now"; this
  // answers "since when is it offline". Null on rows that have not connected since the field shipped.
  lastSeenAt                      DateTime?
  // Billing lifecycle for newly-created campaign machines. Missing on old rows means legacy-active.
  // Grandfathered Remote machines are `not_required`; new paid Remote and managed machines move pending -> active only after
  // checkout verification. A cancelled paid subscription stays active until its period end, then
  // the billing worker moves it to `suspended` and the manager stops (but preserves) its node.
  billingStatus                   String?
  externalDeviceId                String?
  externalSubscriptionId          String?
  externalSubscriptionStatus      Int?
  externalSubscriptionEndAt       DateTime?
  externalSubscriptionCancelledAt DateTime?
  billingActivatedAt              DateTime?
  billingError                    String?
  billingErrorAt                  DateTime?
  // AES-256-GCM envelope containing the managed campaign llm_api_key. Always null for Remote.
  llmApiKeyEncrypted              String?
  // authMode 'provider' only. The A2A endpoint this machine is backed by — supplied by the OWNER, so
  // every outbound request to it goes through lib/providerUrl.ts (SSRF guard), never a bare fetch.
  providerUrl                     String?
  // AES-256-GCM envelope (lib/machineCredential.ts) holding the owner's credential FOR THE PROVIDER.
  // Write-only from the client's point of view: never returned by an API, never logged.
  providerCredentialEncrypted     String?
  // Soft-delete marker: destroy() stamps this instead of removing the row (the container/node is
  // still torn down). Every read path treats a stamped row as absent. NOTE (Prisma-Mongo): legacy
  // rows LACK the field entirely and `{deletedAt: null}` does not match absent — filter with the
  // shared `machineAlive` helper (lib/prisma.ts), never an inline `deletedAt: null`.
  deletedAt                       DateTime?
  createdAt                       DateTime  @default(now())

  @@index([userId])
  @@index([userId, computerId])
  /// A computer's rows of every account (superTabs/computerMoves.ts otherAccountsOnComputer): another account's sign-in there
  /// moves the computer's Swarm entries to it (#3122).
  @@index([computerId, userId])
  @@index([managerId, billingStatus])
  @@index([billingStatus, externalSubscriptionStatus, externalSubscriptionEndAt])
  @@map("machines")
}

/// Durable, account-scoped right to use the Free campaign tier. `reserved` prevents two tabs from
/// starting two Free machines; once activation succeeds it becomes `claimed` and is never deleted,
/// even if the machine is later upgraded or removed.
model MachineFreeEntitlement {
  id            String    @id @default(auto()) @map("_id") @db.ObjectId
  userId        String
  autonomousEnv String    @default("prod") // copied from the machine; one lifetime Free grant per env
  machineId     String    @unique
  status        String    @default("reserved") // reserved | claimed
  reservedAt    DateTime  @default(now())
  claimedAt     DateTime?
  updatedAt     DateTime  @updatedAt

  @@unique([userId, autonomousEnv])
  @@map("machine_free_entitlements")
}

/// Subscription package: the per-machine resource tier + price. A machine is assigned a plan at
/// create (the default one); the manager reads cpus/memory THROUGH the machine's plan. The backend
/// owns writes; the manager mirrors this read-only. Exactly one plan should have isDefault=true.
model SubscriptionPlan {
  id                     String    @id @default(auto()) @map("_id") @db.ObjectId
  name                   String
  autonomousEnv          String    @default("prod") // prod | stag; external ids differ between planes
  cpus                   String // docker --cpus, e.g. "1"
  memory                 String // docker --memory, e.g. "2g"
  maxAgents              Int       @default(1) // cap enforced by the backend on agent create
  priceUsd               Float     @default(0)
  // Backend-owned daily voice/STT allowance in seconds. `0` means unlimited; null keeps legacy
  // plans unlimited until the worker backfills their explicit value.
  dailyVoiceLimitSeconds Int?
  // How the agent-node authenticates with Claude:
  //  "self"    → the user logs the in-container `claude` CLI in (creds in ~/.claude), no env injected.
  //  "managed" → the manager injects ANTHROPIC_* creds into the container at start (no user login).
  authMode               String    @default("self")
  isDefault              Boolean   @default(false)
  // Catalog visibility is explicit so legacy Self-Auth/Managed rows remain readable but cannot be
  // selected for new machines. Missing means unavailable. Free/Pro/Max/Remote are synchronized from
  // the environment-specific Autonomous campaign catalog when billing is enabled.
  available              Boolean?
  externalPlanId         Int?
  externalPlanName       String?
  campaignCode           String?
  // Origin that supplied externalPlanId (staging/prod ids are not interchangeable). A cached
  // catalog is reusable only when this matches the current AUTONOMOUS_BFF_URL origin.
  catalogSource          String?
  externalMetadata       Json?
  catalogSyncedAt        DateTime?
  createdAt              DateTime  @default(now())
  updatedAt              DateTime  @updatedAt

  @@unique([autonomousEnv, name])
  @@index([autonomousEnv, externalPlanId])
  @@map("subscription_plans")
}

/// One UTC-day usage bucket per machine. `usedMs` includes pending STT reservations so concurrent
/// devices cannot both pass the same remaining allowance.
model MachineVoiceDailyUsage {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId String
  dayKey    String
  usedMs    Int      @default(0)
  expiresAt DateTime
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@unique([machineId, dayKey])
  @@index([expiresAt])
  @@map("machine_voice_daily_usage")
}

/// Idempotency + crash-recovery record for a completed voice upload. A reservation is created in
/// the same transaction that increments MachineVoiceDailyUsage, committed after STT returns, and
/// released by the worker if STT fails or the process disappears.
model MachineVoiceReservation {
  id          String    @id @default(auto()) @map("_id") @db.ObjectId
  uploadId    String    @unique
  machineId   String
  dayKey      String
  durationMs  Int
  status      String    @default("pending") // pending | committed | released
  releaseAt   DateTime?
  expiresAt   DateTime
  committedAt DateTime?
  releasedAt  DateTime?
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt

  @@index([status, releaseAt])
  @@index([expiresAt])
  @@index([machineId, dayKey])
  @@map("machine_voice_reservations")
}

/// Audit/idempotency record for every hosted checkout attempt. Redirect URLs can contain opaque
/// provider state, so they are owner-only and never logged. Multiple attempts may exist per machine.
model MachineCheckoutAttempt {
  id                String    @id @default(auto()) @map("_id") @db.ObjectId
  machineId         String
  userId            String
  // Snapshot of the machine's immutable upstream plane. Callback completion must not depend on the
  // user's current env because an admin may switch it while Stripe is open.
  autonomousEnv     String    @default("prod")
  externalPlanId    Int
  externalDeviceId  String
  sessionId         String    @unique
  // Stable local operation id embedded in success/failure callback URLs. Hosted checkout operations
  // use this instead of relying on the provider returning a checkout-session id, including Free card setup.
  operationId       String?
  operationType     String? // subscribe | plan_change
  sourcePlanId      String?
  targetPlanId      String?
  providerSessionId String?
  redirectUrl       String?
  // Snapshot of the non-secret checkout request so checkout-complete can resend the exact same
  // fields even if the user's email, WEB_URL, or callback config changes while Stripe is open.
  checkoutEmail     String?
  successUrl        String?
  failureUrl        String?
  webOrigin         String?
  status            String    @default("pending") // pending|completed|failed|cancelled
  error             String?
  completedAt       DateTime?
  createdAt         DateTime  @default(now())
  updatedAt         DateTime  @updatedAt

  @@index([machineId, createdAt])
  @@index([userId])
  // MongoDB unique indexes treat repeated null optional fields as duplicates. sessionId is already
  // unique and equals operationId for every new attempt; keep this nullable legacy field indexed.
  @@index([operationId])
  @@map("machine_checkout_attempts")
}

/// Per-machine agent association (an "agent" = one working unit with its own workspace and engine),
/// populated by the data-plane tap (lib/agentTracker.ts): when a create succeeds we upsert one row;
/// on DELETE we remove it. Lets the backend answer "how many agents does this machine have" without
/// owning contents (the agent-node's SQLite remains the source of truth).
model MachineAgent {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId String // owning machine (matches Machine.machineId)
  agentId   String // the agent unit's UUID, from the create response
  name      String?
  createdAt DateTime @default(now())

  @@unique([machineId, agentId])
  @@index([machineId])
  @@map("machine_agents")
}

/// A device: one COMPUTER running the `harness` daemon, which serves a dial over USB and drives the
/// owner's machines on its behalf. There is no pairing code and no device token — `/api/device-ws`
/// authenticates with the owner's SSO access token plus a `?computer=` id, and this row is
/// resolved-or-created from that. Deleting a row therefore FORGETS a dial (and closes its live socket);
/// it is not a revocation, because the daemon re-creates it on its next connect.
model DeviceBinding {
  id         String    @id @default(auto()) @map("_id") @db.ObjectId
  userId     String // owner (User.id)
  // The COMPUTER this device row belongs to — the `harness` CLI's per-computer id, normalized
  // (lib/deviceAuth.ts:normalizeComputerId). This is the ONLY way a device comes into existence now:
  // `/api/device-ws` authenticates with the owner's SSO token plus `?computer=`, and the row is
  // resolved-or-created from it. Optional only so `prisma db push` reads rows that predate it — those
  // are pruned at boot (pruneLegacyDeviceBindings), since nothing can ever connect as them again.
  computerId String?
  // LEGACY per-machine pairing pinned the device here. NULL for per-user devices — they pick machines at
  // runtime over the commander socket (`machine_select`). Kept only to read a legacy device's origin.
  machineId  String? // (Machine.machineId)
  // Derived, never random: "cmp-" + sha256(userId:autonomousEnv:computerId)[:24]. See
  // DeviceService.resolveOrCreateForComputer for why each ingredient is load-bearing.
  deviceId   String    @unique
  name       String    @default("device")
  lastSeenAt DateTime?
  createdAt  DateTime  @default(now())

  // ── Reported by the device, snapshotted at each `device_hello` (deviceWs handleHello) ──────────
  // These exist so the mobile app can render a device WITHOUT a live socket of its own; the web reads
  // the same facts off the wire instead. All nullable: a device that has never connected on a build
  // that reports them has none of them, and that must read as "unknown", never as a zero value.
  firmwareVersion String?
  chip            String?
  // WiFi as of the last hello. No shipping client reports these since the dial went cable-only, so they
  // stay null — which clients must render as "no data" rather than an empty name or a zero-bar meter.
  ssid            String?
  rssi            Int? // dBm, negative. 0 is never stored — the firmware uses it for "unknown".
  // The machine this device is CURRENTLY attached to (`machine_select` → relay setActiveMachine).
  // Deliberately NOT the legacy `machineId` above: that one is the immutable pairing origin, this one
  // moves every time the user picks a different machine on the device screen. Null while the device is
  // parked on the picker. NOT cleared on socket close — a fast reconnect would race its own teardown —
  // so on an offline device this reads as "last attached to"; clients gate it on liveness.
  activeMachineId String?

  @@index([userId])
  @@index([userId, computerId])
  @@map("device_bindings")
}

/// READ-ONLY view of the agent-manager's `managers` collection (the manager owns writes).
/// The backend reads capacity (maxNodes/nodeCount) to pick a manager on create, and apiKey to
/// authenticate its dial-in socket (/api/manager-ws). No address is needed — the manager dials the
/// backend (inverted transport). The `@unique` on managerId matches the manager's own index so
/// `prisma db push` from both services stays consistent.
model Manager {
  id          String    @id @default(auto()) @map("_id") @db.ObjectId
  managerId   String    @unique
  maxNodes    Int       @default(0)
  nodeCount   Int       @default(0)
  apiKey      String? // this manager's MANAGER_API_KEY (x-api-key on its dial-in socket)
  agentEngine String? // manager AGENT_ENGINE default for machine_nodes without an explicit engine
  lastSeenAt  DateTime?

  @@map("managers")
}

/// Backend-owned routing record for a published app (mirrors Machine's role for machines):
/// answers "which manager owns this subdomain" for the :8087 public app-proxy. The manager owns
/// the parallel `app_deployments` record (subdomain → appPort). Written at register; the subdomain
/// is a random slug (user never picks it). machineId/agentId denormalized for filtered list/get.
model Subdomain {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  subdomain String   @unique
  machineId String // owning machine (Machine.machineId — the data path routes by it)
  agentId   String // the agent unit
  managerId String // which manager serves it (app control RPC target)
  userId    String
  createdAt DateTime @default(now())

  @@index([userId])
  @@index([machineId])
  @@index([machineId, agentId])
  @@map("subdomains")
}

/// Account control only; no report times, usage counters or machine inventory.
model ProductUsagePreference {
  id       String  @id @default(auto()) @map("_id") @db.ObjectId
  userId   String  @unique
  enabled  Boolean
  revision Int     @default(1)

  @@map("product_usage_preferences")
}

/// Only fleet-wide counters. Never add an account, machine, agent, location or event timestamp. So no index on `machineId`
/// either, as the Atlas advisor suggested on 2026-11-04 (task #2841): no row has one, and no backend read asks for it.
model ProductUsageTotal {
  id     String   @id @default(auto()) @map("_id") @db.ObjectId
  dayUtc DateTime
  metric String
  value  Int

  @@unique([dayUtc, metric])
  @@map("product_usage_totals")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Random report receipt, used only to prevent retries counting twice. No identity or report body. Removed at expiresAt by a TTL index
/// (product_usage_expiry); the old 36-day receipts go by 2026-12-04, sooner if the sweep may install its rule (lib/productUsageReceiptSweep.ts).
model ProductUsageReceipt {
  id        String   @id @map("_id")
  expiresAt DateTime
  /// Days the receipt lives past its report day (types/productUsageReceipt.ts). Required by the collection's rule once the
  /// receipt sweep installs it (lib/productUsageReceiptSweep.ts): a server that writes receipts without it cannot count.
  /// Absent on receipts written before 2026-10-29.
  life      Int?

  @@map("product_usage_receipts")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([expiresAt], map: "product_usage_expiry")
}

/// One UTC day a person used Harness while sharing product usage, under a keyed pseudonym
/// (HMAC of the user id; never the id itself). Expires 10 days after the day; the hourly rollup
/// keeps only anonymous `people_*` totals. Deleted at once when the person turns sharing off.
model ProductUsageActivity {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  subject   String
  dayUtc    DateTime
  surfaces  String[]
  worked    Boolean  @default(false)
  /// A Swarm agent's turn ran on this person's Mac that day. Not `worked`, which is only their own sessions' turns. Set only when true;
  /// absent on rows from before 2026-11-04.
  hosting   Boolean?
  signupDay DateTime
  staff     Boolean
  expiresAt DateTime

  @@unique([subject, dayUtc])
  @@map("product_usage_activity")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([expiresAt], map: "product_usage_expiry")
  /// The hourly people rollup reads the marks of its last days (services/ProductUsagePeopleRollupService.ts).
  @@index([dayUtc])
}

/// Legacy individual counters. New ingestion is disabled; dayUtc TTL removes these after 35 days.
model AnalyticsDailyBucket {
  id               String   @id @default(auto()) @map("_id") @db.ObjectId
  userId           String
  machineId        String
  dayUtc           DateTime // midnight UTC of the day these counters belong to
  engine           String
  mode             String // self | managed | remote | provider
  origin           String // human | scheduled | system | api
  schemaVersion    Int
  // Client monotonic stamp, CLAMPED server-side against receivedAt. Ordering key for last-write-wins:
  // each (machine, day, engine, mode, origin) has exactly ONE writer, so no version vector is needed.
  // A client-chosen revision was rejected — a bad or hostile value could pin a record permanently.
  generatedAt      DateTime
  instructions     Int      @default(0)
  turnsStarted     Int      @default(0)
  turnsCompleted   Int      @default(0)
  turnsFailed      Int      @default(0)
  turnsCancelled   Int      @default(0)
  turnsInputNeeded Int      @default(0)
  agentRuntimeMs   BigInt   @default(0) // sum of terminal turn durations; overlaps counted twice by design
  updatedAt        DateTime @updatedAt

  @@unique([userId, machineId, dayUtc, engine, mode, origin, schemaVersion])
  @@index([userId, dayUtc])
  @@map("analytics_daily_buckets")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Legacy, no longer written. Retained only until the 35-day dayUtc expiry.
/// Harness Analytics — NON-ADDITIVE metrics plus the reporting heartbeat. Exactly one row per
/// machine per day. A row with all-zero counters means "the machine was up and idle"; a MISSING row
/// means "we have no data". The UI must never render those two states the same way.
model AnalyticsDailyMachine {
  id                String   @id @default(auto()) @map("_id") @db.ObjectId
  userId            String
  machineId         String
  dayUtc            DateTime
  wallClockActiveMs BigInt   @default(0) // union of turn intervals, computed locally where all are visible
  activeAgents      Int      @default(0) // distinct agents; sums across machines (an agent has one machine)
  uptimeMs          BigInt   @default(0) // denominator for utilization; 0 when not meaningful (provider)
  reported          Boolean  @default(true) // heartbeat: this machine DID report this day
  generatedAt       DateTime
  updatedAt         DateTime @updatedAt

  @@unique([userId, machineId, dayUtc])
  @@index([userId, dayUtc])
  @@map("analytics_daily_machines")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Harness Analytics — per-machine collector control and coverage state. Backs the Coverage panel
/// and the ingest response, which is the ONLY channel a headless collector has for learning that the
/// account turned collection off or deleted its history.
model AnalyticsMachineState {
  id               String    @id @default(auto()) @map("_id") @db.ObjectId
  machineId        String    @unique
  userId           String
  // Collection is ON by default; the owner can switch it off per machine or for the whole account.
  consent          String    @default("on") // on | off
  // Bumped by a user-triggered deletion. Uploads carrying an older epoch are refused, so a collector
  // still holding queued records cannot resurrect erased history.
  epoch            Int       @default(0)
  collectorVersion String?
  engineCoverage   String[] // engines this collector instruments
  // Engines the collector can SEE here (registered agents / discovered binaries). The difference
  // enginesPresent - engineCoverage is what the UI shows as "not instrumented" — coverage alone
  // cannot tell an uninstrumented engine from one that is simply not installed.
  enginesPresent   String[]
  lastReportAt     DateTime?
  clockSkewMs      Int? // receivedAt - generatedAt at the last report; surfaced in Coverage
  updatedAt        DateTime  @updatedAt

  @@index([userId])
  @@map("analytics_machine_states")
}

/// Legacy presence histories: new writes are disabled and dayUtc expires after 35 days.
/// The comments below document old records for historical readers, not current collection.

/// Per-day record of whether a user had the desktop app open, and on which machine. One row per
/// (user, machine, UTC day): "user online that day" is therefore a DISTINCT count of `userId`, while
/// `connections` still sums. The source is the local `harness` daemon reporting its own loopback
/// clients over adapter-ws (`app_presence`, src/lib/adapterWs.ts) — NOT the web-ws upgrade, which
/// the app never performs itself (only the daemon does, per foreign machine it relays) and which
/// therefore missed every single-machine user. `connections` = times a window attached to that
/// daemon that day; a session spanning midnight produces a row for each day it touches with
/// `connections: 0`.
/// Deliberately NO `countryCode` here, unlike the device/machine rows: the signal arrives over the
/// DAEMON's socket, so the country would be the daemon's (a VPS for a remote machine), not the
/// person's. "Where is the user" is `User.lastCountryCode`, stamped from their own REST calls; the
/// machine's own country sits on `machine_daily_presence`, joinable through `machineId`.
model UserDailyPresence {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  userId      String
  // Machine.machineId whose daemon reported the window (the adapter-ws socket the `app_presence`
  // frame came over). Null ONLY on rows that predate the field — those were one per (user, day).
  // Optional rather than required for that reason: Prisma-Mongo refuses to READ a row missing a
  // required field. The old `(userId, dayUtc)` unique index is dropped at worker boot
  // (lib/db/migrate.ts migrateUserPresencePerMachine); the legacy rows stay distinct under the new
  // key because they were already distinct on (userId, dayUtc).
  machineId   String?
  dayUtc      DateTime
  connections Int      @default(0)
  firstSeenAt DateTime
  lastSeenAt  DateTime
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([userId, machineId, dayUtc])
  @@index([userId, dayUtc])
  @@map("user_daily_presence")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Per-day record of a user on a surface other than the desktop app — `UserDailyPresence` stays the
/// desktop app's alone. One row per (user, surface, UTC day); DAU is a distinct `userId`.
/// `surface`: 'tui' (`harness tui`, reported by the local daemon like a desktop window: adapter-ws
/// `app_presence { surface: 'tui' }`, src/lib/adapterWs.ts) — 'harness-os' / 'harness-os-pi' when that
/// TUI is Harness OS on a PC / on an Orange Pi (cli lib/windowSurfaces.ts) —, 'mobile' / 'web' (the app's and the
/// browser's own web-ws sockets, declared with `?client=` — src/lib/webWs.ts; the daemon's relay
/// socket declares nothing and is never counted). `connections` = sessions opened that day (for
/// mobile/web one per machine socket); a session spanning midnight gives the next day `0`.
/// No `machineId`: mobile and web hold a socket per machine they look at, and it is one person.
model UserDailyClientPresence {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  userId      String
  surface     String
  dayUtc      DateTime
  connections Int      @default(0)
  firstSeenAt DateTime
  lastSeenAt  DateTime
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([userId, surface, dayUtc])
  @@index([surface, dayUtc])
  @@map("user_daily_client_presence")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Per-day record of whether a user actually established a remote p2p connection to stream a
/// terminal (signaled by a p2p_offer frame passing through the web-ws relay), scoped to the machine.
model UserDailyRemoteUsage {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  userId      String
  machineId   String
  dayUtc      DateTime
  sessions    Int      @default(0)
  firstSeenAt DateTime
  lastSeenAt  DateTime
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([userId, machineId, dayUtc])
  @@index([userId, dayUtc])
  @@map("user_daily_remote_usage")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Per-day record of whether a user's device was connected to the device-ws relay
/// (src/lib/deviceWs.ts). One row per (user, device, UTC day); a connection spanning midnight
/// produces a row for each day it touches, the later ones with `connections: 0`.
/// `lastSeenAt` is refreshed on connect, on close, and at most every DEVICE_PRESENCE_WRITE_MS while
/// the socket is open, so it lags real liveness by <= that interval — the same rule as
/// MachineDailyPresence. (Before 2026-09-23 it only moved on a RECONNECT, so a device that stayed
/// connected read as last-seen-at-midnight all day; rows older than that cannot be used to measure
/// how long a device was up.) Redis `device:{id}` remains the "online right now" answer.
model UserDailyDevicePresence {
  id          String   @id @default(auto()) @map("_id") @db.ObjectId
  userId      String
  deviceId    String
  dayUtc      DateTime
  connections Int      @default(0)
  countryCode String? // Cloudflare `CF-IPCountry` (ISO-2) at the LAST write that carried one; null = unknown / pre-feature row
  firstSeenAt DateTime
  lastSeenAt  DateTime
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([userId, deviceId, dayUtc])
  @@index([userId, dayUtc])
  @@map("user_daily_device_presence")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Per-day record of whether a MACHINE's `harness` daemon was connected to the adapter-ws relay
/// (src/lib/adapterWs.ts). One row per (machine, UTC day); a connection spanning midnight produces a
/// row for each day it touches. `lastSeenAt` is refreshed on connect, on close, and at most every
/// MACHINE_PRESENCE_WRITE_MS while the socket is open, so it lags real liveness by ≤ that interval.
/// Redis `machine:{id}:mgr` remains the "online right now" answer; this is the history.
/// `turnsStarted` is the usage signal on top of liveness: every `turn_started` up-frame the daemon
/// relays bumps it (adapterWs hub tap). A row can legitimately read `connections: 0, turnsStarted: 0`
/// — a session that spanned midnight and sat idle.
model MachineDailyPresence {
  id           String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId    String // Machine.machineId
  userId       String // owner at connect time (Machine.userId), for per-user rollups
  dayUtc       DateTime
  connections  Int      @default(0)
  turnsStarted Int      @default(0) // `turn_started` up-frames the daemon sent that day (adapterWs tap)
  countryCode  String? // Cloudflare `CF-IPCountry` (ISO-2) at the LAST write that carried one; null = unknown / pre-feature row
  firstSeenAt  DateTime
  lastSeenAt   DateTime
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@unique([machineId, dayUtc])
  @@index([userId, dayUtc])
  @@map("machine_daily_presence")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// Per-day record of an AGENT being driven: one row per (machine, agent, UTC day), created and
/// bumped by every `turn_started` the machine's daemon relays through adapter-ws
/// (src/lib/adapterWs.ts). There is no "connect" for an agent — a turn is the presence signal —
/// so unlike the machine/user/device rows there is no `connections` column. `agentId` is the
/// plaintext correlation id on the frame; the turn's content stays E2EE and is never read here.
model AgentDailyPresence {
  id           String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId    String // Machine.machineId — agentId is only unique within a machine
  agentId      String // MachineAgent.agentId (may be gone from machine_agents later — keep the history)
  userId       String // owner at the time of the turn
  dayUtc       DateTime
  turnsStarted Int      @default(0)
  firstSeenAt  DateTime
  lastSeenAt   DateTime
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@unique([machineId, agentId, dayUtc])
  @@index([machineId, dayUtc])
  @@index([userId, dayUtc])
  @@map("agent_daily_presence")
  /// Expires these rows (lib/productUsage.ts ensureProductUsageExpiry). Declared so db push keeps it; the worker sets its expiry.
  @@index([dayUtc], map: "product_usage_expiry")
}

/// One person's review of one harness in the Harness Store — a star rating and, optionally, a title
/// and some words. One row per (harness, user): writing again replaces it, so a rating cannot be
/// stacked. `harnessId` is the registry id (`owner/name`), never validated against the registry here
/// — the registry lives in the CLI, and a review of a harness the backend has not heard of is still a
/// review. `authorName` is a snapshot of the user's name at write time; the store shows it, never
/// the email.
model HarnessReview {
  id         String   @id @default(auto()) @map("_id") @db.ObjectId
  harnessId  String
  userId     String // User.id
  authorName String
  rating     Int // 1..5
  title      String?
  body       String?
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([harnessId, userId])
  @@index([harnessId])
  @@map("harness_reviews")
}

/// Discovery metadata for one account-bound, view-only invitation. Content remains on the owner
/// daemon, which independently authorizes every observer against its durable local grant list.
model HarnessShare {
  /// A session view derived from this Super Tab; membership is rechecked at admission.
  superTabId     String?
  id             String    @id @map("_id")
  ownerId        String
  machineId      String
  agentId        String
  recipientEmail String
  autonomousEnv  String
  name           String
  engine         String?
  ownerPublicKey String
  expiresAt      DateTime
  revokedAt      DateTime?
  createdAt      DateTime  @default(now())
  updatedAt      DateTime  @updatedAt

  @@unique([machineId, agentId, recipientEmail])
  @@index([recipientEmail, autonomousEnv, expiresAt])
  /// The share list (routes/harnessShares.ts): one recipient's unrevoked shares by createdAt, read without a sort in memory and
  /// without fetching the revoked ones. expiresAt last, so an expired share is dropped from its key before it is fetched.
  @@index([recipientEmail, autonomousEnv, revokedAt, createdAt, expiresAt])
  @@index([ownerId, machineId])
  @@map("harness_shares")
}

/// A whole machine its owner shares with other accounts (docs/plans/2026-10-15-share-machine-plan.md):
/// with these addresses, and with everyone at `domain` when the owner turned that on. Off by default, so
/// a machine with no row is shared with no one. The backend's copy decides who is LISTED the machine and
/// who may select it on the relay; the machine's own daemon keeps the policy it published and trusts
/// only the keys of accounts that policy names (cli services/sharedMachines.ts), as Share's owner does.
model MachineShare {
  id            String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId     String   @unique
  ownerId       String
  autonomousEnv String
  /// Normalized (trimmed, lower case), never the owner's own.
  emails        String[]
  /// The owner's email domain while "Everyone at @domain" is on; null when off. Written by the backend
  /// from the owner's verified address, never taken from the client, and never a public domain.
  domain        String?
  /// Stable while an email/domain grant continues; a removed and restored grant
  /// gets a new version so old Super Tab contributions cannot resume silently.
  grantVersions Json?
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt

  @@index([emails, autonomousEnv])
  @@index([domain, autonomousEnv])
  @@index([ownerId])
  @@map("machine_shares")
}

/// Someone at a machine's domain added it to their machines (a domain share takes one click to add; an
/// address the owner named needs none). Only the accounts that added it are trusted by the machine.
model MachineShareAdd {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  machineId String
  userId    String
  createdAt DateTime @default(now())

  @@unique([machineId, userId])
  @@index([userId])
  @@map("machine_share_adds")
}

/// The account's DESK: its tabs, in order, and the agents each holds — one document per user, the
/// same on every computer the person signs in on (owner, 2026-09-21: "tab là global"). Holds only
/// what the person would call "my tabs": ids, names, order, `(machineId, agentId)` pairs. Nothing
/// about a window — focus, zoom, pane sizes, which tab is on screen — those differ per computer and
/// stay in each app's own state file. Written through `POST /api/desk/ops` (routes/desk.ts): small
/// idempotent operations applied in order under `revision`, so two windows racing merge by rule
/// rather than by whoever saved last. Plaintext, like `Machine.name` and `MachineAgent.name`: the
/// doc adds no class of data the backend does not already hold.
model Desk {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String   @unique
  revision  Int      @default(0)
  tabs      Json     @default("[]")
  updatedAt DateTime @updatedAt

  @@map("desks")
}

/// The account's connected services (Linear, GitHub…), sealed by a daemon for every machine of the account
/// (cli/src/lib/e2ee/connectorVault.ts): only those machines can open it. The backend keeps the latest
/// envelope and a revision for compare-and-set, and tells every computer when it changed.
model ConnectorVault {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String   @unique
  revision  Int      @default(0)
  envelope  Json
  updatedAt DateTime @updatedAt

  @@map("connector_vaults")
}

/// Agent Messages, per tab (docs/design/2026-10-10-agent-messages.md): whether the harnesses in one desk tab
/// may message each other. Absence means off. Kept beside the desk, never in its tab JSON: a backend pod that
/// has not upgraded drops a tab whose JSON it does not know (lib/desk.ts parseTabs). A deterministic _id makes
/// a concurrent first write converge.
model AgentMessageTab {
  id        String   @id @map("_id") @db.ObjectId
  userId    String
  tabId     String
  enabled   Boolean  @default(false)
  /// The tab's leader: a pane of the tab on one of the owner's machines. Written as explicit nulls at create.
  leaderMachineId String?
  leaderAgentId   String?
  revision  Int      @default(0)
  updatedAt DateTime @updatedAt

  @@index([userId])
  @@map("agent_message_tabs")
}

/// A tab its owner shared with other accounts (docs/superpowers/specs/2026-10-15-agent-messages-across-accounts-design.md).
/// `roster` is the owner's signed blob, stored and never read: members verify it against the owner's key.
model AgentMessageShare {
  id             String    @id @map("_id") // sharedTabId: sha256(['amsg-share', ownerUserId, tabId])[:24]
  ownerUserId    String
  ownerMachineId String
  tabId          String
  autonomousEnv  String
  rosterVersion  Int       @default(0)
  roster         Json?
  stoppedAt      DateTime?
  createdAt      DateTime  @default(now())
  updatedAt      DateTime  @updatedAt

  @@unique([ownerUserId, tabId])
  @@map("agent_message_shares")
}

model AgentMessageInvite {
  id             String    @id @map("_id")
  shareId        String
  ownerUserId    String
  ownerMachineId String
  email          String
  autonomousEnv  String
  expiresAt      DateTime
  acceptedBy     String?
  acceptedAt     DateTime?
  revokedAt      DateTime?
  createdAt      DateTime  @default(now())

  @@unique([shareId, email])
  @@index([email, autonomousEnv, expiresAt])
  @@map("agent_message_invites")
}

model AgentMessageMember {
  id         String    @id @map("_id") // sha256(['amsg-member', shareId, userId])[:24]
  shareId    String
  userId     String
  email      String
  inviteId   String
  acceptedAt DateTime  @default(now())
  removedAt  DateTime?

  @@index([userId])
  @@index([shareId])
  @@map("agent_message_members")
}

/// Explicit account opt-ins; missing choices stay off. Each write changes one feature.
// Super Tabs own their roster and history independently of desktop pane layout. Revision writes
// serialize membership changes, commands and delivery claims inside Mongo transactions.
model SuperTab {
  id             String   @id @map("_id")
  ownerId        String
  autonomousEnv  String
  memberIds      String[]
  invitedEmails  String[]
  /// The domain whose people join this Swarm by themselves while its owner has auto-join on (superTabs/autoJoin.ts); absent
  /// otherwise. Derived from the head's sharing in every commit (parts/commit.ts indexesOf).
  autoJoinDomain String?
  /// People who left or were removed: auto-join never adds them again. Cleared by an invitation accepted or a link join.
  autoJoinDeclined String[]
  machineIds     String[]
  /// Machines whose host still has to clean up after their removal: read apart from the 100-Swarm host poll.
  cleanupMachineIds String[] @default([])
  revision       Int      @default(0)
  state          Json
  /// 1: the whole Swarm in `state`. 2: split into the Swarm* part collections (docs/design/2026-10-26-swarm-state-parts.md);
  /// `state` is then `{ version: 2 }`, which every older backend refuses before writing, and the old state is kept in `legacyState`.
  format         Int      @default(1)
  migratedAt     DateTime?
  legacyState    Json?
  /// The Workspace (SwarmWorkspace) it belongs to, also on its head part. Null only on a Swarm from before Workspaces, until migrated.
  workspaceId          String?
  /// When its owner deleted it (superTabs/deletion.ts): from then every read and write answers as for a Swarm that does not
  /// exist, and its owner can restore it until `purgeAt`, when the sweep removes its records and files. Absent on a live Swarm.
  deletedAt      DateTime?
  purgeAt        DateTime?
  /// When the purge may try a deleted Swarm again after a pass could not finish it: newly due ones go first (purge.ts).
  purgeRetryAt   DateTime?
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt

  /// Deleted Swarms whose grace is over, oldest first: the purge sweep's read (superTabs/deletion.ts).
  @@index([purgeAt], map: "swarm_deleted_purge")
  @@index([autonomousEnv, workspaceId])
  /// An owner's Swarms in id order: the grid poll names it (superTabs/parts/indexed.ts NAMED_INDEX.SuperTab.owner).
  @@index([autonomousEnv, ownerId, id])
  /// By id within a member: Swarm lists read 100 at a time in id order, and a Workspace removal finds the person's Swarms
  /// (superTabs/swarmRows.ts).
  @@index([autonomousEnv, memberIds, id])
  /// By id within an address: the invitation list reads the first 100 in id order (superTabs/invitedSwarms.ts).
  @@index([autonomousEnv, invitedEmails, id])
  /// A machine's Swarms, newest first: the host poll's lookup, once a second per host (superTabs/swarmRows.ts machineSwarms).
  @@index([autonomousEnv, machineIds, updatedAt])
  @@index([autonomousEnv, cleanupMachineIds, updatedAt])
  /// The Swarms a person at a domain joins by themselves: one read per person at most every 2 minutes (superTabs/autoJoin.ts).
  @@index([autonomousEnv, autoJoinDomain])
}

// A terminal retains its history when removed from a roster. These bindings
// prevent contributing a private session to another project's audience later.
model SuperTabSessionScope {
  /// Administrative retirement belongs only to the Swarm that withdrew this session.
  releasedTabIds String[] @default([])
  /// A bounded native close may finish after membership is withdrawn.
  closeLeaseId String?
  closeLeaseUntil DateTime?
  closeLeaseGeneration String?
  /// Serializes contribution changes with stop intent across public Swarms.
  stopReleaseId String?
  /// Set when the session first became confidential (a Lead or in a private conversation): the write a concurrent
  /// registration in another Swarm conflicts with, so a confidential session keeps one registration (final review C1).
  confidential Boolean?
  id           String   @id @map("_id")
  scopeIds     String[]
  privateScope String?

  @@index([scopeIds])
}

model SuperTabMessage {
  id              String   @id @map("_id")
  tabId           String
  conversationId  String
  sequence        Int
  author          Json
  source          Json?
  text            String
  /// Files posted with the message (superTabs/attachments.ts); the bytes live in the attachments bucket.
  attachments     Json?
  replyTo         String?
  /// Explicit answer below a message in main chat; kept with the message, without opening a thread (#3609).
  answers         String?
  recipientIds    String[]
  /// People a Lead tagged (superTabs/mentions.ts); absent on older rows.
  mentions        String[]
  /// The thread's root (superTabs/threads.ts): a top-level message's own id, a reply's root. Absent on rows written before
  /// threads, whose replies stay inline quotes.
  thread          String?
  /// A thread reply also shown in the conversation's main stream.
  alsoInChat      Boolean?
  /// A reply in a Buddy thread session's thread (superTabs/buddySessions.ts): the main Buddy never reads it.
  buddySession    Boolean?
  /// The project a row of a person's one Buddy chat belongs to (superTabs/buddySessions.ts lostProjectRow): a project
  /// session's thread and a PM's private line. Hidden once its person no longer reads that project.
  buddyProject    String?
  /// When its author last edited its text (superTabs/messageEdits.ts); no earlier text is kept.
  editedAt        DateTime?
  /// When its author deleted it while replies hung under it: its text is then DELETED_TEXT and its files are gone. A deleted
  /// message with no replies is removed, row and all.
  deletedAt       DateTime?
  createdAt       DateTime @default(now())

  /// Pages read by (sequence, id): older rows of one command share a sequence.
  @@index([tabId, conversationId, sequence, id])
  /// One thread's page, and a page's thread summaries (superTabs/pageReads.ts pageThreads).
  @@index([tabId, conversationId, thread, sequence])
}

/// A Lead's tag of a person, waiting until they reply in that conversation or mark it done (superTabs/mentions.ts).
/// Kept out of the tab state so an older backend still reads it; removed 30 days after createdAt by a TTL index.
model SuperTabMention {
  id             String    @id @map("_id")
  tabId          String
  personId       String
  projectId      String
  conversationId String
  messageId      String
  authorAgentId  String
  createdAt      DateTime
  resolvedAt     DateTime?
  /// reply | done | worker
  resolvedBy     String?
  /// A tag the Lead made about a task with no worker: not listed before this time (superTabs/mentions.ts). Unset on every other tag.
  holdUntil      DateTime?

  @@index([tabId, personId, createdAt])
  @@index([tabId, conversationId, personId])
  /// A tag goes 30 days on (superTabs/mentions.ts ensureMentionExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([createdAt], map: "mention_expiry")
}

/// One reactor's emoji on one message (superTabs/reactions.ts). The id is derived from all four, so adding the same
/// reaction twice keeps one row; message pages count them.
model SuperTabReaction {
  id             String   @id @map("_id")
  tabId          String
  conversationId String
  messageId      String
  /// person | agent
  actorKind      String
  actorId        String
  emoji          String
  createdAt      DateTime @default(now())

  @@index([tabId, messageId])
}

/// How far one person has read one conversation (superTabs/readMarks.ts): the newest message sequence they have seen there.
/// Kept out of the tab state so a read never wakes other readers, and read only by that person's own clients. The id is
/// derived from all three, so one row per person and conversation; it only ever moves forward.
/// A person's Activity row (superTabs/activity.ts): a reply to their message or a reaction to it, for them alone.
model SuperTabActivity {
  id             String    @id @map("_id")
  tabId          String
  /// Whom the row is for: the author of the message replied or reacted to.
  personId       String
  /// reply | reaction
  kind           String
  conversationId String
  /// The reply, or the message reacted to.
  messageId      String
  /// The reply's thread root, or the reacted message's thread.
  threadId       String?
  /// person | agent
  actorKind      String
  actorId        String
  emoji          String?
  createdAt      DateTime
  /// When the person saw it, on any device; unset while unread.
  readAt         DateTime?
  /// A reply's message sequence in its chat, so reading its thread or chat past it marks the row read (activity.ts); unset on a
  /// reaction and on a row written before it was kept, which only opening Activity reads.
  sequence       Int?
  /// A reply also shown in the chat's main stream: the chat mark reads it, as well as its thread's.
  alsoInChat     Boolean?

  /// A person's rows, newest first: the list and the digest.
  @@index([tabId, personId, createdAt])
  /// One thread's or chat's rows of a person, for the read marks that clear them (activity.ts markActivityThreadRead).
  @@index([tabId, personId, conversationId, threadId])
  /// A person's unread rows, newest first: the digest each of their reads asks for (activity.ts activityDigest). Through the
  /// index above it examined every row of 30 days to find the unread (task #3146).
  @@index([tabId, personId, readAt, createdAt])
  /// The sweep's rows past their expiry (activity.ts sweepActivity); no TTL option, which the app user cannot set (#2238).
  @@index([createdAt])
}
/// A person's notification setting for one chat (superTabs/chatSettings.ts): all | mentions | muted. Their own, never shown to others.
model SuperTabChatSetting {
  id             String   @id @map("_id")
  tabId          String
  personId       String
  conversationId String
  /// all | mentions | muted; mentions is the default, kept a week so other devices learn of the change.
  notify         String
  updatedAt      DateTime

  /// A person's settings: every one (a first load) or those moved since a change read's cursor; the cap's count.
  @@index([tabId, personId, updatedAt])
  /// The sweep's default rows untouched for a week (chatSettings.ts sweepChatSettings).
  @@index([updatedAt])
}
model SuperTabReadMark {
  id             String   @id @map("_id")
  tabId          String
  personId       String
  conversationId String
  sequence       Int
  updatedAt      DateTime
  /// When the person's Mark unread moved the mark back (readMarks.ts lowerReadMark); set with updatedAt in that write and
  /// cleared by a read that raises it, so the mark's last move was a Mark unread while the two are equal. Unset otherwise.
  loweredAt      DateTime?

  @@index([tabId, personId, updatedAt])
  /// A mark untouched for 180 days goes: by this index's expiry (superTabs/readMarks.ts ensureReadMarkExpiry), or where the
  /// database refuses it, by the worker's sweep (startReadMarkSweep). Declared so db push keeps the index.
  @@index([updatedAt], map: "read_mark_expiry")
}

/// A person's reminder of one message (superTabs/reminders.ts): bring it back to them at `dueAt`, in Activity's Reminders. Their
/// own, never shown to others. One row per person and message: setting it again replaces its time, and opening it deletes it.
/// At most REMINDER_CAP pending per person and Swarm; the worker's hourly sweep deletes those due more than REMINDER_EXPIRY_MS
/// (30 days) ago, and a Swarm's purge its rows.
model SuperTabReminder {
  /// stableId(tabId, personId, messageId).
  id             String   @id @map("_id")
  tabId          String
  personId       String
  conversationId String
  messageId      String
  dueAt          DateTime
  createdAt      DateTime

  /// A person's reminders: the due list, the next one after now, the digest and the cap's count (parts/indexed.ts NAMED_INDEX).
  @@index([tabId, personId, dueAt])
  /// The sweep's reminders due more than 30 days ago (reminders.ts sweepReminders); no TTL option, which the app user cannot set.
  @@index([dueAt])
}

/// How far a person has read one thread: the newest reply sequence they saw there (superTabs/readMarks.ts). Apart from
/// SuperTabReadMark so a backend without thread marks never reads one as a conversation's mark. At most THREAD_MARK_CAP per
/// person and Swarm; the worker's hourly sweep deletes those untouched for 180 days and those of Swarms and people gone.
model SuperTabThreadMark {
  id             String   @id @map("_id")
  tabId          String
  personId       String
  conversationId String
  /// The thread's root message id.
  threadId       String
  /// 0 on a row a Follow or Unfollow created before the person read the thread anywhere.
  sequence       Int
  /// The person's own choice for the thread (readMarks.ts writeThreadFollow): true Follow, false Unfollow; unset or null
  /// leaves it to whether they started it, replied in it or were tagged in it. Never cleared by a read mark.
  follow         Boolean?
  updatedAt      DateTime

  /// A person's marks: every one (a first load, the inbox, the cap's count and oldest) or those moved since a change read's
  /// cursor, and each Swarm's people with marks (the sweep) (parts/indexed.ts NAMED_INDEX).
  @@index([tabId, personId, updatedAt])
  /// The sweep's marks untouched for 180 days (readMarks.ts sweepThreadMarks); no TTL option, which the app user cannot set.
  @@index([updatedAt])
}

/// A project chat's Buddy proposal roots not yet seen answered (superTabs/proposals.ts), read by the Tasks view's Proposals in place
/// of a walk of the whole chat (task #2777). Written in the transaction that inserts each root (store.ts writeMessages), and by
/// a chat's first reads, which seed it from the chat's rows; a row id `seeded:<tabId>:<conversationId>`, sequence -1, marks a
/// chat seeded. Removed by the read once it finds a root answered or gone, and with its Swarm (purge.ts). Under 10 per project.
/// A root closed by hand (proposal.close, task #2926) stays, with sequence -2 and `closed` { reason, by, at }, out of every
/// read, so no seed opens it again: one row per closed proposal (about 50 per project at first), removed with its Swarm.
model SuperTabOpenProposal {
  /// The root message's id, or the chat's seed mark.
  id             String   @id @map("_id")
  tabId          String
  conversationId String
  /// The root's sequence in its chat; -1 for the seed mark.
  sequence       Int
  createdAt      DateTime @default(now())

  /// A chat's open roots, newest first (proposals.ts databaseProposalReads listed).
  @@index([tabId, conversationId, sequence])
}

/// One thread with at least one reply, summed up as pageThreads' $facet gives it (pageReads.ts refreshThreads): rewritten in the
/// transaction that inserts each reply, and read by root id instead of the $facet once its Swarm is backfilled
/// (SuperTabThreadBackfill). No text; never returned as is. Kept with its messages.
model SuperTabThread {
  /// The root message's id.
  id             String   @id @map("_id")
  tabId          String
  conversationId String
  /// The $facet's `parts` and `mentions` for this thread (pageReads.ts ThreadFacet).
  parts          Json
  mentions       Json
  updatedAt      DateTime

  @@index([tabId, conversationId])
}

/// A Swarm whose thread summaries hold every reply created before `through` (threadBackfill.ts); its pages read them. Written
/// by the singleton worker alone; id = the Swarm's id.
model SuperTabThreadBackfill {
  id      String   @id @map("_id")
  through DateTime
}

/// Where a Swarm sweep reads on from between passes and releases, one row per sweep (readMarks.ts sweepThreadMarks: id
/// "thread-marks", the last Swarm whose people check finished). Written by the singleton worker alone.
model SuperTabSweepCursor {
  id        String   @id @map("_id")
  after     String
  updatedAt DateTime
}

/// A question to one person, with options and a recommendation (backend/src/superTabs/decisions.ts). Kept out of the tab
/// state, as mentions are: an asking agent and the asked person read it, and the person answers it once.
/// writeDecisions removes answered rows older than LEDGER_WEEKS on the next ask; Swarm purge removes all its rows.
model SuperTabDecision {
  id             String    @id @map("_id")
  tabId          String
  /// The ask that put several questions to one person together.
  batchId        String
  projectId      String
  conversationId String
  /// The task whose needs_human asked it, or null for the Lead's decision.ask.
  assignmentId   String?
  personId       String
  askerAgentId   String
  question       String
  options        String[]
  recommended    Int
  /// Optional recommendation deadline; absent on legacy questions, which keep their 24-hour fallback.
  defaultAt      DateTime?
  /// The server applied the recommendation at defaultAt; never a person’s choice or a legacy overdue answer.
  defaulted      Boolean?
  /// A rule says the person must agree (task #3826): no default applies. At defaultAt the PM is told once and defaultAt is
  /// cleared, and the 24-hour sweep never takes it, so it waits for the person. Absent on every other decision.
  mustAgree      Boolean?
  unblocks       String
  createdAt      DateTime
  answeredAt     DateTime?
  choice         Int?
  note           String?
  /// The person asked left it to the PM, who took the recommended option: never shown as their own choice.
  delegated      Boolean?
  /// With `delegated`: the hourly sweep left it to the PM after 24 hours unanswered, not the person (overdueDecisions.ts).
  overdue        Boolean?
  /// "routing-reflection" for a proposal of the nightly routing reflection (costs/reflection.ts): never a Buddy's to read,
  /// and an approved one is kept past the ledger's weeks. Absent on every other decision.
  kind           String?
  /// Closed unanswered because the work it was asked about is over: its task done or cancelled, or its group archived
  /// (decisions.ts withdrawIn; Dee, 10-31). Set with answeredAt and no choice, so it waits no more, is in no list and goes
  /// with the answered ones after the ledger's weeks. Absent on every other decision.
  withdrawn      Boolean?
  /// With kind "buddy-send" (task #4525): the words its owner's Send posts as them, and the proposal's goal, scope, priority
  /// and project (decisions.ts SendPayload), at most a message and a proposal's fields. Absent on every other decision.
  send           Json?

  @@index([tabId, personId, createdAt])
  @@index([tabId, askerAgentId, createdAt])
  @@index([tabId, projectId, createdAt])
  /// The decisions waiting in a conversation whose work ended (decisions.ts withdrawIn).
  @@index([tabId, conversationId])
  /// The hourly overdue sweep reads only the waiting decisions of the last 8 days through it (superTabs/overdueDecisions.ts).
  @@index([answeredAt, createdAt], map: "decision_waiting_created")
  /// Explicit deadlines use their own range so long-lived questions are not missed by the legacy creation window.
  @@index([answeredAt, defaultAt], map: "decision_waiting_default")
}

/// One uploaded file, which one message of the actor that uploaded it can send once.
model SuperTabAttachment {
  id             String   @id @map("_id")
  tabId          String
  conversationId String
  actorKey       String
  name           String
  mime           String
  size           Int
  objectKey      String
  usedBy         String?
  /// The Buddy proposal that carried this file, when its owner sent it in their Buddy chat (superTabs/store.ts proposable):
  /// each file goes with one proposal at most. Their own message keeps it as `usedBy`.
  proposedBy     String?
  /// `avatar` for a profile picture (superTabs/profile.ts), which no message sends; absent on a chat file.
  purpose        String?
  /// A voice message's facts (superTabs/voiceMessages.ts StoredVoice): its length, waveform and words, read once before it is
  /// sent (store.ts readVoice). Absent on any other file. Removed with its row: the unsent-file sweep's, or its message's.
  voice          Json?
  /// A picture's size and its thumbnail (superTabs/thumbnails.ts StoredImage): `{ width, height, thumb?: { url, width, height, size } }`,
  /// made when the picture was uploaded. The thumbnail object sits beside the original (`<objectKey>.thumb.webp`) and goes with
  /// it: the unsent-file sweep (lib/attachmentSweep.ts) and the Swarm purge (superTabs/purge.ts) remove both. Absent on a file
  /// that is not a PNG, JPEG or WebP, on one stored before thumbnails, and on one that would not decode. About 150 bytes.
  image          Json?
  /// When a readVoice call claimed this file to transcribe it; unset once it stored `voice`. A claim older than two minutes
  /// is taken over.
  voiceSince     DateTime?
  createdAt      DateTime @default(now())

  @@index([tabId, actorKey, createdAt])
  /// Unfinished uploads by age, for the pending-upload sweep (lib/pendingUploadSweep.ts).
  @@index([purpose, createdAt])
  /// Unused uploads by age, for the hourly unused-upload sweep (lib/attachmentSweep.ts): its claim (usedBy and proposedBy
  /// null, purpose, createdAt) and its remove step (usedBy alone). Performance Advisor's suggestion of 11-04 with its first
  /// two keys swapped, so the remove step's read is bounded too (#2676). Built by the backend release's schema push: a
  /// production write that needs Ken's go.
  @@index([usedBy, proposedBy, purpose, createdAt])
}

/// One per sender per Swarm while it asks for upload links (superTabs/store.ts uploadLink): each link request writes it in the
/// transaction that counts the sender's last hour and adds the pending upload, so two requests at once conflict and one retries,
/// and the hourly limits hold. The pending-upload sweep (lib/pendingUploadSweep.ts) removes it an hour after its last use.
model SuperTabUploadAllowance {
  id String   @id @map("_id")
  at DateTime
}

/// One command's receipt, so a repeat of the same request gets the same answer. Removed 30 days after createdAt by a TTL index.
model SuperTabOperation {
  id           String   @id @map("_id")
  tabId        String
  actorKey     String
  requestHash  String
  revision     Int
  result       Json
  /// The parts a command wrote, with their versions, returned again on a replay. Absent on receipts from before parts.
  parts        Json?
  createdAt    DateTime @default(now())

  /// A Swarm's receipts, and by date: Atlas's Performance Advisor saw a read scan 107 k rows to return 40 (Ken's plan, 2026-11-04). No
  /// backend read uses the date yet; check on Atlas after the release, and shorten it to tabId if nothing does. It replaces the index on
  /// tabId alone, its prefix, since this collection gets a write on every command.
  @@index([tabId, createdAt])
  /// A receipt goes 30 days after createdAt (superTabs/operations.ts ensureOperationExpiry). Declared so db push keeps the index; the
  /// schema step makes it, with its expiry, before the push.
  @@index([createdAt], map: "operation_expiry")
}

// A conversation-scoped provenance receipt. It grants no terminal access.
// Only the recorded execution host can append observations, and every append
// rechecks the person's membership and both machine grants.
model SuperTabNativeContext {
  id              String   @id @map("_id")
  tabId           String
  conversationId  String
  agentId         String
  userId          String
  binding         Json
  lastEventId     String?
  revoked         Boolean  @default(false)
  createdAt       DateTime @default(now())

  @@index([tabId, revoked])
}

model SuperTabDelivery {
  id                    String   @id @map("_id")
  tabId                 String
  conversationId        String
  messageId             String
  nativeContextId       String?
  assignmentId          String?
  agentId               String
  machineId             String
  machineOwnerId        String?
  membershipGeneration  String
  authorKind            String
  authorId              String
  authorGeneration      String
  status                String   @default("queued")
  claimId               String?
  receipt               String?
  // Optional on older records: backend first, then Desktop's inline receipt.
  holdReason            String?
  holdSince             DateTime?
  // Until when its agent's host holds it while the agent works (turnEnd.ts, task #3403): another agent's post to a crew member.
  // Cleared by the agent's own status change; unset on older rows and on what goes at once.
  waitsUntil            DateTime?
  // A row gathered for its PM's inbox rather than the notice digest (inbox.ts, task #3545): "people" or "crew". At idle the
  // inbox goes at once only for these; unset on notices and on older rows.
  inboxSection          String?
  /// Server-derived proposal priority, 0 first. Absent on rows before proposal cards; retained until existing delivery compaction.
  inputPriority         Int?
  // A queued delivery whose claims keep answering SWARM_BUSY (prod 10-30, v1.3.71): written outside the failed claim, unset by
  // the claim that gets in. The settle pass alarms on them and page reads show the sender (store.ts recordFailedClaim).
  claimFailingSince     DateTime?
  claimFailedAt         DateTime?
  claimFailures         Int?
  claimFailure          String?
  deliveredAt           DateTime?
  answeredAt            DateTime?
  createdAt             DateTime @default(now())
  updatedAt             DateTime @updatedAt

  @@index([tabId, agentId, status, createdAt])
  @@index([tabId, agentId, status, inputPriority, createdAt])
  @@index([machineId, status])
  // A page of messages reads its deliveries by message (pageReads.ts).
  @@index([tabId, messageId])
  // The delivery pass reads only the open ones (superTabs/deliverySettle.ts).
  @@index([status, id])
  /// A Swarm's open deliveries, whoever they are for (the Lead's poll, store.ts fullDeliveries).
  @@index([tabId, status])
  /// An ended task's open deliveries, cancelled with it (store.ts releaseRuns and stopped): by [tabId, status] alone the
  /// planner sometimes walked every delivery of the Swarm (180 read for 1 in the benchmark).
  @@index([tabId, assignmentId])
  /// Finished deliveries by their last change: the hourly compaction reads only those past 14 days (deliveryCompaction.ts).
  @@index([status, updatedAt])
}

// One message's finished deliveries, moved here 14 days after their last change (superTabs/deliveryCompaction.ts): message
// history and its receipts are kept forever, while delivery rows hold only the recent and open ones. Never on the message
// row, never returned whole: a page reads each receipt as a delivery and filters it per reader (pageReads.ts pageDeliveries).
model SuperTabReceipt {
  id             String   @id @map("_id") // the message id
  tabId          String
  conversationId String
  /// By agent id: the delivery row as it was, but for the fields above (pageReads.ts receiptFields).
  receipts       Json
  /// The compacted deliveries' ids, so a host's receipt read finds one by its id (pageReads.ts compactedDelivery).
  deliveryIds    String[]

  @@index([tabId, deliveryIds])
}

// One independent harness owns at most one active assignment across all Super Tabs.
model SuperTabRun {
  id            String   @id @map("_id")
  tabId         String
  assignmentId  String   @unique
  machineId     String
  harnessId     String
  createdAt     DateTime @default(now())

  /// A Swarm's run records (store.ts staleRuns).
  @@index([tabId])
}

// One routing policy document per account and environment (superTabs/routingPolicy.ts).
model RoutingPolicy {
  id            String   @id @map("_id")
  userId        String
  autonomousEnv String
  revision      Int      @default(0)
  policy        Json
  updatedAt     DateTime @updatedAt

  @@unique([userId, autonomousEnv])
}

model SuperTabAttempt {
  id              String   @id @map("_id")
  tabId           String
  conversationId  String
  snapshot        Json
  createdAt       DateTime @default(now())

  @@index([tabId, conversationId, createdAt])
}

/// One `harness super-tab route` decision (superTabs/routeRecord.ts). Deleted 90 days after createdAt on each write (routeDecisions.ts
/// RETENTION_MS; the costs report reads 90 days). Stored trimmed (routeRecord.ts storedRecord).
model SuperTabRouteDecision {
  id             String    @id @map("_id")
  tabId          String
  conversationId String
  record         Json
  final          Json?
  override       Json?
  assignmentId   String?
  outcome        String?
  outcomeAt      DateTime?
  /// Its attempt's run: what it ran on, how it was paid, its session's token totals at start and end (superTabs/costs/attempts.ts).
  run            Json?
  /// What its attempt added to its model's evidence, so a later change adds only the difference (superTabs/evidence/store.ts).
  evidence       Json?
  createdAt      DateTime  @default(now())

  @@index([tabId, createdAt])
  @@index([tabId, conversationId, outcome])
  @@index([tabId, assignmentId])
}

/// One project's scorecard for one local day (superTabs/scorecard): counts and minutes only, never text, names or ids. One row
/// per project and day, about 1 KB; the nightly job deletes a project's rows older than 120 days when it writes (rows.ts
/// SCORECARD_DAYS_KEPT), and a Swarm's go with its purge (purge.ts).
model SuperTabScorecard {
  id         String   @id @map("_id")
  tabId      String
  projectId  String
  /// The local date, YYYY-MM-DD, in timeZone.
  on         String
  timeZone   String
  figures    Json
  computedAt DateTime

  /// A project's days, and the prune of its old ones.
  @@index([tabId, projectId, on])
}

/// How one model did on one kind of job in one week of one project of a Swarm (superTabs/evidence/store.ts): counts and sums
/// only, never a person, an agent or task text. `id` is the hash of the Swarm, project, engine, model, kind and week. Kept 180 days.
model SuperTabModelEvidence {
  id                 String   @id @map("_id")
  tabId              String
  /// The project of the groups its attempts ran in: the report shows a reader only projects they see.
  projectId          String
  engine             String
  model              String
  kind               String
  /// Monday 00:00 UTC of the week its attempts started.
  week               DateTime
  attempts           Float    @default(0)
  firstReviews       Float    @default(0)
  firstReviewPassed  Float    @default(0)
  reworkRounds       Float    @default(0)
  shipped            Float    @default(0)
  minutesToShipSum   Float    @default(0)
  minutesToShipCount Float    @default(0)
  fixesAfterMerge    Float    @default(0)
  tokensInput        Float    @default(0)
  tokensOutput       Float    @default(0)
  tokensCacheRead    Float    @default(0)
  tokensCacheWrite   Float    @default(0)
  tokensKnown        Float    @default(0)
  apiCost            Float    @default(0)
  costKnown          Float    @default(0)
  costUnknown        Float    @default(0)
  spend              Float    @default(0)
  spendKnown         Float    @default(0)
  updatedAt          DateTime

  @@index([tabId, week])
  /// The hourly sweep's prune across every Swarm (superTabs/sweeps.ts).
  @@index([week])
}

/// One model's last ten first-review results on one kind of job in one project of a Swarm, oldest first: [{ a: assignment id, at: its start,
/// passed }] (superTabs/evidence/store.ts). Routing reads it for a model under 50% and its recovery. Kept 180 days after its
/// last change.
model SuperTabModelRecent {
  id        String   @id @map("_id")
  tabId     String
  projectId String
  engine    String
  model     String
  kind      String
  results   Json
  updatedAt DateTime

  @@index([tabId, updatedAt])
  /// The hourly sweep's prune across every Swarm (superTabs/sweeps.ts).
  @@index([updatedAt])
}

model SuperTabStopReceipt {
  id              String   @id @map("_id")
  tabId           String
  assignmentId    String
  machineId       String
  harnessId       String
  machineOwnerId  String
  receipt         String
  createdAt       DateTime @default(now())

  @@unique([tabId, assignmentId])
}

// A custom role's skill text (superTabs/projects.ts ProjectRole), outside the tab snapshot: the snapshot keeps only
// its version, so tab reads and host rosters stay small. Hosts fetch the text when the version changes.
model SuperTabRoleText {
  id        String @id @map("_id")
  tabId     String
  projectId String
  roleId    String
  version   String
  text      String

  @@index([tabId, projectId])
}

// A project's instructions (superTabs/instructions.ts): one Markdown document outside the tab snapshot, as role texts are. The
// snapshot keeps only the project's revision and hash, so reads stay light; hosts and the Instructions panel read the text
// when the revision changes. id = stableId(tabId, projectId). Deleted with the project (store.ts project.delete).
model SuperTabInstructions {
  id        String   @id @map("_id")
  tabId     String
  projectId String
  revision  Int
  hash      String
  text      String
  updatedAt DateTime

  @@index([tabId, projectId])
}

// Every save of a project's instructions, the current one included: its last 50 (instructions.ts MAX_REVISIONS); the save
// that writes the 51st deletes the oldest. `writtenBy` is a person's or the coordinator's id (`writtenByKind`), `askedBy` the
// member whose words it carries. `dropped`: the lines that save dropped, each with its kind and who gave it, for the History
// (superTabs/ruleGuard.ts droppedLines): at most 500 of 400 characters, removed with its revision. id = stableId(tabId,
// projectId, revision).
model SuperTabInstructionsRevision {
  id            String   @id @map("_id")
  tabId         String
  projectId     String
  revision      Int
  hash          String
  text          String
  summary       String
  writtenByKind String
  writtenBy     String
  askedBy       String?
  at            DateTime
  dropped       Json?

  @@index([tabId, projectId, revision])
}

// A project's rules record (superTabs/policy.ts), one row per saved revision: the newest is the record, the rest its history.
// Removed: the save that writes revision N deletes revisions <= N - 50 of its project (policyStore.ts writeRules, MAX_RULES_REVISIONS);
// a deleted project takes its rows; the Swarm purge takes the tab's (purge.ts). A row is at most 16 KB of rules plus its diff.
// `writtenBy` is a person's or the project's PM's id (`writtenByKind`), `askedBy` the person whose words it carries, `askedIn`
// the chat message the PM passed on (null when a person saved). id = stableId(tabId, projectId, revision): two saves of one
// revision collide on it, and one retries into RULES_STALE.
model SuperTabProjectRules {
  id            String   @id @map("_id")
  tabId         String
  projectId     String
  revision      Int
  rules         Json
  diff          Json
  summary       String
  writtenByKind String
  writtenBy     String
  askedBy       String
  askedIn       Json?
  at            DateTime

  @@index([tabId, projectId, revision])
}

// The small things a member tells a project's coordinator, kept beside its instructions so they survive a restart or a move
// (instructions.ts): at most 100 live per project, each up to 300 characters. An expired one is never read and is deleted
// by the next note write of its project; all go with the project.
model SuperTabPmNote {
  id        String    @id @map("_id")
  tabId     String
  projectId String
  text      String
  askedBy   String
  at        DateTime
  expiresAt DateTime?

  @@index([tabId, projectId])
}

// Configuration observations stay outside the tab snapshot so a long-running
// assignment keeps its complete history without making every tab read grow.
model SuperTabConfiguration {
  id             String   @id @map("_id")
  tabId          String
  agentId        String
  revision       Int
  configuration  Json
  assignmentIds  String[]
  actorKey       String
  observedAt     DateTime

  @@index([tabId, agentId, revision])
}

// A Lead's read of, or input to, an agent's terminal, relayed to the host of the agent's machine
// (backend/src/superTabs/terminal.ts). Outside the tab snapshot and history: a screen can show secrets,
// so its text is kept only until the requester reads it.
model SuperTabTerminalRequest {
  id             String    @id @map("_id")
  tabId          String
  agentId        String
  machineId      String
  machineOwnerId String
  harnessId      String
  requesterKey   String
  kind           String
  scrollback     Int?
  text           String?
  keys           String[]  @default([])
  /// pending -> claimed (handed to the host once) -> done
  status         String    @default("pending")
  ok             Boolean?
  result         String?
  error          String?
  createdAt      DateTime
  claimedAt      DateTime?

  @@index([machineId, status])
  @@index([tabId, createdAt])
  /// An unread answer goes after two minutes (superTabs/terminal.ts ensureTerminalExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([createdAt], map: "terminal_request_expiry")
}

// Swarm state by parts (docs/design/2026-10-26-swarm-state-parts.md). Each part is one record of a Swarm, written only
// by the commands that change it. `version` moves on every write and every guarded touch and never resets; `changedAt`
// moves only when `data` changes, and is what readers ask for changes by. A removed part stays as a tombstone
// (`deleted`) until `purgeAt`, so readers learn it is gone. `data` keeps the record's shape from `SuperTab.state`.

/// The Swarm's scalars and settings: projects (without progress), rules, invitations, sharing, routing, Local models.
/// A Workspace: Swarms and the people who may be in them (docs/plans/2026-10-27-swarm-workspaces.md). Not the Harness Team
/// account. It never grants reading a Swarm: that needs the Swarm's own membership too.
model SwarmWorkspace {
  id            String    @id @map("_id")
  autonomousEnv String
  name          String
  ownerId       String
  revision      Int       @default(0)
  createdAt     DateTime  @default(now())
  deletedAt     DateTime?
  purgeAt       DateTime?
  /// People this Workspace removed, whom Swarm auto-join never adds again (superTabs/autoJoin.ts). Kept past the purge of their
  /// member row; cleared when they are added back on purpose (workspaceStore.ts addMember).
  autoJoinDeclined String[]

  /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "workspace_purge")
}

/// One person of a Workspace. A removal keeps the row with `removedAt` until it is purged; a rejoin writes a new generation.
model SwarmWorkspaceMember {
  /// `workspaceId:userId`
  id         String    @id @map("_id")
  workspaceId      String
  userId     String
  email      String
  role       String
  generation String
  version    Int       @default(1)
  addedBy    String
  addedAt    DateTime  @default(now())
  removedAt  DateTime?
  removedBy  String?
  purgeAt    DateTime?

  @@index([workspaceId, removedAt])
  @@index([userId, removedAt])
  /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "workspace_purge")
}

/// One removal of one Workspace membership, open until the person has left every Swarm of the Workspace. While one is open the
/// person cannot be brought back into the Workspace; the hourly sweep finishes them in order (superTabs/workspaceStore.ts).
model SwarmWorkspaceRemoval {
  /// `workspaceId:userId:generation`: the membership generation that was removed.
  id            String    @id @map("_id")
  workspaceId         String
  userId        String
  email         String
  generation    String
  autonomousEnv String
  removedAt     DateTime
  removedBy     String
  finishedAt    DateTime?
  purgeAt       DateTime?

  @@index([finishedAt, id])
  @@index([workspaceId, userId, finishedAt])
  /// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "workspace_purge")
}

/// An invitation to a Workspace, by email; deleted when accepted or revoked, purged when it expires.
model SwarmWorkspaceInvitation {
  /// `workspaceId:email`
  id        String   @id @map("_id")
  workspaceId     String
  email     String
  role      String
  invitedBy String
  expiresAt DateTime

  @@index([email, expiresAt])
  @@index([workspaceId])
  /// An invitation goes when it expires (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([expiresAt], map: "workspace_invitation_expiry")
}

model SwarmHead {
  id              String    @id @map("_id")
  tabId           String
  key             String
  version         Int
  changedAt       DateTime
  deleted         Boolean   @default(false)
  purgeAt         DateTime?
  ordinal         Float
  data            Json
  /// Workgroup numbers are never given twice, whatever was deleted or went dormant.
  groupCounter    Int       @default(0)
  /// Moves when who may see what changes; a reader with an older epoch loads in full.
  visibilityEpoch Int       @default(1)
  /// The tab revision when it was split into parts (0 for a Swarm born in parts). Every later message sequence is above it.
  sequenceBase    Int       @default(0)
  /// The highest version of any agent tombstone the sweep purged (superTabs/agentTombstones.ts): an agent added with no
  /// tombstone starts above it, so its versions never go back. Missing until the first purge.
  agentFloor      Int?

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  /// Removed parts go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "part_purge")
}

/// One person in the Swarm. Every command of theirs touches it, so removing them and their in-flight action cannot both win.
model SwarmMember {
  id        String    @id @map("_id")
  tabId     String
  key       String
  version   Int
  changedAt DateTime
  deleted   Boolean   @default(false)
  purgeAt   DateTime?
  ordinal   Float
  data      Json

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
  @@index([tabId, deleted, key, version, changedAt])
  /// Tombstones past their purge time, compacted by the hourly sweep (superTabs/sweeps.ts compactTombstones). Not a TTL: the tombstone stays.
  @@index([purgeAt])
}

/// One conversation: its work, checks, assignment, members and message counter.
model SwarmGroup {
  id                 String    @id @map("_id")
  tabId              String
  key                String
  version            Int
  changedAt          DateTime
  deleted            Boolean   @default(false)
  purgeAt            DateTime?
  ordinal            Float
  data               Json
  projectId          String?
  kind               String?
  archived           Boolean   @default(false)
  /// Out of first loads and changes: work done or cancelled and quiet for a day, or archived by hand. A message wakes it.
  dormant            Boolean   @default(false)
  agentIds           String[]
  /// The people and agents whose Tasks feed lists it (read/feedIds.ts); [] for a conversation that is no task. Set on every
  /// write; parts written before it are set at worker startup (markFeedIds).
  feedIds            String[]  @default([])
  /// The machine running its active assignment, for the host's change read.
  executionMachineId String?
  messageSeq         Int       @default(0)
  reportSeq          Int       @default(0)
  lastActivityAt     DateTime
  /// Next proposal deadline/revisit; null once none is due. Existing card history lives until project/Swarm deletion.
  proposalDueAt      DateTime?
  /// The machines whose hosts this group's last write concerned: its agents' and its work's, before and after (host reads).
  hostMachineIds     String[]  @default([])
  /// A short hash of the fields host rows read (read/hostRows.ts); a post leaves it. Missing on a part written before it.
  hostDigest         String?
  /// Its task is done or cancelled: all the archive pass reads (superTabs/archive.ts). Marked at worker startup on a part
  /// written before it (markFinishedGroups).
  workFinished       Boolean   @default(false)

  /// Not indexed on `data.kind` (Atlas advisor, 2026-11-04, task #2841): no backend read filters by it, the only one that
  /// does is the rollback script scripts/buddy-sessions/end-all.ts, across every Swarm; and every hot read keeps its plan
  /// with such an index (the numbers are in task #2841's pull request). The top-level `kind` holds the same value.
  @@index([deleted, proposalDueAt, tabId, key])
  @@unique([tabId, key])
  @@index([tabId, changedAt])
  @@index([tabId, dormant, changedAt])
  @@index([tabId, agentIds])
  /// A person's Tasks feed, newest activity first, then by key (read/personalTasks.ts): the person and their own agents.
  @@index([tabId, feedIds, lastActivityAt, key])
  /// A project's quiet conversations by activity (leaderboard, digest), and their pages newest first, then by key (parts/load.ts loadDormant).
  @@index([tabId, projectId, dormant, lastActivityAt, key])
  @@index([tabId, projectId, dormant, reportSeq])
  @@index([dormant, lastActivityAt])
  @@index([workFinished, archived, lastActivityAt])
  /// A host's wake check (read/host.ts woken): the conversations its last writes concerned, by Swarm, since its cursor.
  @@index([hostMachineIds, tabId, changedAt])
  /// A Swarm's running work (parts/light.ts, the host's light load).
  @@index([tabId, executionMachineId])
  /// The host signature (read/host.ts inputs) reads every conversation's digest and dormancy from this index alone.
  @@index([tabId, deleted, key, hostDigest, dormant])
  /// A command's awake conversations, listed by the columns it compares with what it holds (parts/held.ts) from this index alone:
  /// each command read every awake one whole before (task #3146).
  @@index([tabId, dormant, deleted, key, version, changedAt])
  /// Removed parts go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "part_purge")
}

model SwarmAgent {
  id             String    @id @map("_id")
  tabId          String
  key            String
  version        Int
  changedAt      DateTime
  deleted        Boolean   @default(false)
  purgeAt        DateTime?
  ordinal        Float
  data           Json
  machineId      String
  machineOwnerId String
  contributorId  String

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  /// A Swarm's live agents (parts/light.ts, load.ts, read/host.ts): without it the read planned on [tabId, changedAt] and
  /// examined every tombstone too (prod 2026-11-02: 1,070 examined for 40 returned). The held index below has it as its prefix;
  /// it stays until a prod scan shows that one in use (task #4368).
  @@index([tabId, deleted])
  /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
  @@index([tabId, deleted, key, version, changedAt])
  @@index([machineId, deleted])
  @@index([tabId, contributorId])
  /// One agent's registrations in every Swarm (confidential.ts, sessionScope.ts): host rows read them on every changed tab.
  @@index([key, deleted])
  /// Tombstones past their purge time, compacted by the hourly sweep (superTabs/sweeps.ts compactTombstones). Not a TTL: the tombstone stays.
  @@index([purgeAt])
}

/// One machine the Swarm references, contributed or not: its contribution and observation, and its slot ledger.
model SwarmMachine {
  id              String    @id @map("_id")
  tabId           String
  key             String
  version         Int
  changedAt       DateTime
  deleted         Boolean   @default(false)
  purgeAt         DateTime?
  ordinal         Float
  data            Json
  machineId       String
  contributed     Boolean   @default(false)
  cleanupOwnerIds String[]
  /// The last change to its settings or ledger, never its own reading (host reads wake on this, not on changedAt).
  hostChangedAt   DateTime?
  /// The last write of its own reading alone (a report every 15 s): readers of changes see it, while `changedAt`, and so the
  /// Swarm's newest change, stays at the last change of anything else (Stability Roadmap 2.2).
  readAt          DateTime?
  /// The last reading that changed more than its volatile fields (parts/commit.ts machineContentChanged): a client that asks gets
  /// a line for any other reading, not the part (read/changes.ts). Overwritten in place, and gone with its row. Absent before 2026-11-04.
  contentAt       DateTime?

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  @@index([tabId, readAt])
  /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
  @@index([tabId, deleted, key, version, changedAt, readAt])
  @@index([machineId, deleted])
  /// Machines whose settings changed since a host's cursor (read/host.ts woken).
  @@index([tabId, hostChangedAt])
  /// Tombstones past their purge time, compacted by the hourly sweep (superTabs/sweeps.ts compactTombstones). Not a TTL: the tombstone stays.
  @@index([purgeAt])
}

model SwarmStart {
  id             String    @id @map("_id")
  tabId          String
  key            String
  version        Int
  changedAt      DateTime
  deleted        Boolean   @default(false)
  purgeAt        DateTime?
  ordinal        Float
  data           Json
  machineId      String
  conversationId String
  /// The agent it started, once it has a harness: an agent's own removal and a routed assignment find it by this.
  agentId        String?
  /// Failed, or started and settled: out of command state, still loadable by key or agent until it expires 7 days later.
  finishedAt     DateTime?

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  @@index([tabId, finishedAt])
  @@index([machineId, finishedAt])
  @@index([tabId, agentId])
  /// Removed parts go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "part_purge")
  /// Live starts by finish time: the hourly sweep expires those finished 7 days ago (superTabs/sweeps.ts expireStarts).
  @@index([deleted, finishedAt])
}

/// One project's report watermark, and the fence a Lead's worker decisions serialize on.
model SwarmProgress {
  id        String    @id @map("_id")
  tabId     String
  key       String
  version   Int
  changedAt DateTime
  deleted   Boolean   @default(false)
  purgeAt   DateTime?
  ordinal   Float
  data      Json

  @@unique([tabId, key])
  @@index([tabId, changedAt])
  /// A command's live parts by the columns a held part is compared by (parts/held.ts): the listing reads no document (task #4368).
  @@index([tabId, deleted, key, version, changedAt])
  /// Removed parts go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([purgeAt], map: "part_purge")
}

model ExperimentalSettings {
  id               String  @id @map("_id") @db.ObjectId
  userId           String
  focusBarCreature Boolean @default(false)
  shareButton      Boolean @default(false)
  devicesTab       Boolean @default(false)
  /// What agents may do with Harness, per account (owner, 2026-10-12): each computer's daemon keeps a copy
  /// it reads at every launch (cli/src/lib/agentSettings.ts). Off until the person turns one on.
  agentsStartAgents    Boolean @default(false)
  agentPullRequestLine Boolean @default(false)
  agentMessages        Boolean @default(false)
  /// Inverted on purpose: off shares a one-line summary of what each harness does with the shared tab's other accounts.
  agentMessagesHideSummary Boolean @default(false)
  /// An agent may give more work to a harness it started (`harness tell`, cli/src/messages/tell.ts). Off by default.
  agentsTellAgents     Boolean @default(false)
  /// A program acting for the person (a lamp's lamp-tasks, not an agent) may give more work to an idle harness of
  /// theirs in a pane (`harness reply`, cli/src/messages/replyLocal.ts, #1628). Off by default.
  programsReply        Boolean @default(false)
  revision         Int     @default(0)

  @@index([userId])
  @@map("experimental_settings")
}

/// The account's ZOO: the daemons it hatched, the eggs waiting, which one is paired, and the
/// first-egg habits done so far — one document per user, the same on every client, like the desk
/// but separate from it (daemons/README.md, "The zoo"). Written through `POST /api/zoo/ops`
/// (routes/zoo.ts): idempotent ops applied in order under `revision`, the draw made here and only
/// here (lib/zoo.ts). `state` is validated shape by shape on every read; what does not parse is
/// dropped rather than served.
model Zoo {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String   @unique
  revision  Int      @default(0)
  state     Json     @default("{}")
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@map("zoos")
}

/// Serial numbers for hatched daemons: one counter per roster id, across every account. Each server
/// hatch of a daemon the account did not own takes the next one with an atomic increment
/// (routes/zoo.ts), and the daemon keeps it as `serial` in its zoo: the card's `#0042`. A duplicate
/// merges into the daemon you have and takes none; a guest's daemons, hatched on a client, have none.
/// Numbers are never given twice; a hatch whose write never landed leaves a gap.
model DaemonMint {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  daemonId  String   @unique
  count     Int      @default(0)
  updatedAt DateTime @updatedAt

  @@map("daemon_mints")
}

/// A sign-in Harness issued ITSELF rather than through the Autonomous account service — today only
/// to a phone that scanned a signed-in computer's Add Phone QR (lib/harnessSession.ts). The account
/// service has no way for one signed-in device to sign in another, so the computer asks for a
/// one-time handoff code, the QR carries it, and the phone trades it for this session.
///
/// Only a HASH of the refresh token is stored: a dump of this collection must not be a key store.
/// The access token lives in Redis beside it, an hour at a time. Revoking is setting `revokedAt`;
/// every request reads it, so it takes effect at once.
model HarnessSession {
  id          String    @id @default(auto()) @map("_id") @db.ObjectId
  userId      String
  refreshHash String    @unique
  /// What the device calls itself ("Dee's iPhone"), for a list of signed-in devices.
  label       String
  /// `computer` — a computer signed in by a phone scanning its QR (lib/harnessSession.ts): it may
  /// connect AS a machine. Absent (every older row) or `viewer` — an app, which may not.
  /// `team` — the daemon of a Mac's team account, minted by one of the account's computers
  /// (lib/teamSession.ts): it may connect only as the machine of `computerId`, and do less than a computer.
  kind        String?
  /// With `kind: team`: the computer it is bound to (normalized, lib/deviceAuth.ts:normalizeComputerId).
  computerId  String?
  /// With `kind: team`: the machine of the Mac whose team account this is, recorded when the code was minted
  /// (routes/auth.ts) and copied onto the team machine (`Machine.hostMachineId`). Null for a dedicated machine.
  hostMachineId String?
  createdAt   DateTime  @default(now())
  lastUsedAt  DateTime  @default(now())
  /// Slides forward on every refresh: a phone in use stays signed in, one left in a drawer does not.
  expiresAt   DateTime
  revokedAt   DateTime?
  /// A session an SSO sign-in backs (lib/ssoSession.ts): the CLI or Desktop signed in through SSO and traded it for this
  /// session. The person's SSO refresh token, and the last access token it gave, encrypted (lib/machineCredential.ts);
  /// cleared when the session ends. Absent on a session a QR or a handoff made.
  ssoRefresh         String?
  ssoAccess          String?
  ssoAccessExpiresAt DateTime?
  /// The account plane and auth-service client the SSO tokens were issued on: a renewal must name the same.
  ssoEnv             String?
  ssoClientId        String?
  /// The last time SSO accepted the sign-in: re-checked hourly, and the outage grace runs from it.
  ssoCheckedAt       DateTime?
  /// Set before a renewal asks SSO, cleared once its answer is saved. Left set, a renewal was lost on the way — its
  /// rotated refresh token may never have been saved — so a refusal of the stored one is no proof of a sign-out.
  ssoRenewingAt      DateTime?

  @@index([userId])
  @@map("harness_sessions")
  /// Ended and idle-expired sessions go 30 days on (lib/ssoSession.ts ensureHarnessSessionExpiry). Declared so db push keeps the index; the worker sets its expiry.
  @@index([expiresAt], map: "harness_session_expiry")
}

/// One entry of an account's device key log (lib/deviceKeyLog.ts): the identity keys its machines and
/// viewer apps hold, append-only and hash-chained. Every device trusts the keys the log leaves active,
/// so signing in is enough for an account's devices to reach each other end to end.
///
/// `entry` is the JSON the device sent, kept verbatim; its signature and hash cover a binary encoding
/// of its fields, so nothing here depends on how Mongo orders keys. The unique `(userId, seq)` is what
/// makes appending atomic: two devices appending at one head cannot both win.
model DeviceKeyLogEntry {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String
  seq       Int
  hash      String
  entry     String
  /// The Harness session (a phone signed in by a QR) that added this key, so removing the key signs
  /// that session out too. Null for anything else.
  sessionId String?
  createdAt DateTime @default(now())

  @@unique([userId, seq])
  @@map("device_key_log")
}

/// The account's device key log as of entry `seq` (lib/deviceKeyLog.ts), so an append does not verify
/// the whole log again. Only a cache of `device_key_log`: it is checked against the log's real head on
/// every read, a log that moved on is replayed from here, and one that does not fit is replayed from
/// the start. Devices never see it.
model DeviceKeyLogState {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String   @unique
  seq       Int
  hash      String
  /// Active keys by pub, as `DevLogState.active`.
  active    Json
  /// Pubs a `remove` took out, as `DevLogState.removed`.
  removed   Json
  /// pub → the Harness session that added that key (`DeviceKeyLogEntry.sessionId`), for active keys.
  sessions  Json
  updatedAt DateTime @updatedAt

  @@map("device_key_log_state")
}

/// A device's signed "It's mine" for another key on the account's device key log (lib/deviceAckCore.ts):
/// once one trusted device confirms a new one, the account's other devices stop showing it as New.
/// Kept beside `device_key_log` and never in its chain — an op the chain does not know would make every
/// older client freeze the whole log — so a client that predates it never sees one.
///
/// `ack` is the JSON the device sent, kept verbatim; its signature covers a binary encoding of its
/// fields, and every device checks it against its own verified log, never this table's word. The unique
/// `(userId, pub, signer)` makes appending idempotent: one acknowledgement per key per signer.
model DeviceKeyAck {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  userId    String
  /// The acknowledged key, and the seq of the log entry that added it.
  pub       String
  addSeq    Int
  /// The key that acknowledged it (and signed `ack`).
  signer    String
  ack       String
  createdAt DateTime @default(now())

  @@unique([userId, pub, signer])
  @@index([userId, addSeq])
  @@map("device_key_acks")
}

/// Public/private link metadata only. The owner daemon keeps the final policy and encrypted discussion.
model HarnessLink {
  id             String    @id @map("_id")
  ownerId        String
  machineId      String
  agentId        String
  autonomousEnv  String
  name           String
  engine         String?
  ownerPublicKey String
  visibility     String
  revokedAt      DateTime?
  createdAt      DateTime  @default(now())
  updatedAt      DateTime  @updatedAt

  @@unique([machineId, agentId])
  @@index([ownerId, machineId])
  @@map("harness_links")
}

/// One account's sign-in to a service through the connector gateway (lib/connectorGateway.ts), as the
/// Grid control plane keeps it: the provider's tokens, so the gateway can renew them for any of the
/// account's computers. Kept as they came (this database is private). Disconnecting deletes the row.
model ConnectorCredential {
  id           String   @id @default(uuid()) @map("_id")
  userId       String
  connector    String
  accessToken  String
  refreshToken String   @default("")
  tokenType    String   @default("Bearer")
  scope        String   @default("")
  accountName  String   @default("")
  expiresAt   Int      @default(0)
  connectedAt DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@unique([userId, connector])
  @@map("connector_credentials")
}

/// A service the connector gateway signs in to (lib/connectorGateway.ts): the OAuth app Autonomous
/// registered with it, in the Grid control plane's config-connector-auth.json fields, kept as they are
/// (this database is private). Edited directly (Compass) or written by `npm run connectors:import`;
/// read by the gateway, a minute at a time. `enabled: false` switches a service off.
model ConnectorApp {
  id           String   @id @default(uuid()) @map("_id")
  code         String   @unique
  enabled      Boolean  @default(true)
  label        String   @default("")
  description  String   @default("")
  imageUrl     String   @default("")
  clientId     String
  /// Empty for a public client using PKCE.
  clientSecret String   @default("")
  authUrl      String
  tokenUrl     String
  refreshUrl   String   @default("")
  userinfoUrl  String   @default("")
  scopes       String[]
  authStyle    String   @default("")
  pkce         Boolean  @default(false)
  refresh      Boolean  @default(false)
  /// Extra consent-URL parameters (Google's access_type=offline).
  authParams   Json?
  /// Grid's `extra`: mcp_url, mcp_auth_header, token_field.
  extra        Json?
  updatedAt    DateTime @updatedAt

  @@map("connector_apps")
}

/// A Swarm's approval to use a GitHub repository for teammates' work (docs/plans/2026-10-28-swarm-project-github-access.md):
/// someone GitHub says can push to it approved it, signed in to GitHub through the Harness GitHub App. Without one, the
/// app gives no token for the repository, so a project cannot name a repository its people cannot push to and borrow the
/// app's access to it. `projectId` "*": every project of the Swarm.
model GitHubRepositoryApproval {
  id            String   @id @map("_id")
  autonomousEnv String
  tabId         String
  projectId     String
  /// owner/name, lower case, as the project names it.
  repository    String
  approvedBy    String
  githubLogin   String
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, tabId, repository, projectId])
  @@index([tabId])
  /// Whether the reader allowed a repository before, in any Swarm (github/approvals.ts `reader`).
  @@index([autonomousEnv, approvedBy, repository])
}

/// A person GitHub said cannot push to a project's repository when they tried to allow it (github/approvals.ts): the app
/// then asks them to send it to someone who can, instead of offering the same sign-in again. One per person, project and
/// repository; removed when the repository is allowed for the project.
model GitHubApprovalRefusal {
  id            String   @id @map("_id")
  autonomousEnv String
  tabId         String
  projectId     String
  /// owner/name, lower case, as the project names it.
  repository    String
  userId        String
  githubLogin   String
  createdAt     DateTime @default(now())

  @@unique([autonomousEnv, tabId, repository, projectId, userId])
  @@index([tabId])
}

/// A phone's push token (task #2905): where the server sends a thread reply or a tag for its person while the app is closed
/// (push/devices.ts). One row per token, `_id` the SHA-256 of platform and token, so a phone signed in as someone else moves
/// to them. Removed: by the phone at sign-out, when Apple or Google call the token dead, past the 10 newest of a person, and by
/// the TTL index 90 days after `seenAt` (push_device_expiry); a signed-in phone registers again at every launch. About 300 bytes
/// a row, at most 10 a person.
model PushDevice {
  id       String   @id @map("_id")
  userId   String
  /// ios | android
  platform String
  token    String
  /// An iOS token from a development build, which only Apple's sandbox host accepts (push/apns.ts).
  sandbox  Boolean  @default(false)
  seenAt   DateTime

  /// A command's told people's phones (devicesOf), and a person's newest ten.
  @@index([userId])
  /// Expires these rows (push/devices.ts ensurePushDeviceExpiry, made before the push). Declared so db push keeps it.
  @@index([seenAt], map: "push_device_expiry")
  @@map("push_devices")
}