Skip to content

Latest commit

 

History

History
779 lines (713 loc) · 39 KB

contracts.md

File metadata and controls

779 lines (713 loc) · 39 KB

dialed.run — Contracts

Frozen interfaces between lanes. Phase 0 turns this document into code; after that, changing anything here requires the schema-change protocol in CLAUDE.md (stop, propose in design doc, human review).

Supersedes plan/docs/contracts.md. Key changes from that archive: the garment model is category × layer with typed attributes (not body_part); verdicts are per-run 5-state (not per-item 3-state); likes are reactions (kind useful); entries carry an audience (D-109); users carry onboarding fields; garments link to canonical products with an enrichment pipeline behind them (D-26/D-31). Rationale: docs/decisions.md.

Entity model (dialed-core)

erDiagram
    users ||--o{ wardrobe_items : owns
    users ||--o{ runs : records
    users ||--o{ follows : follows
    users ||--o{ notifications : receives
    runs ||--o| outfit_entries : "has at most one"
    outfit_entries ||--{ outfit_entry_items : contains
    outfit_entries ||--{ entry_tags : tagged
    wardrobe_items ||--o{ outfit_entry_items : "worn in"
    outfit_entries ||--o{ entry_photos : shows
    outfit_entries ||--o{ reactions : gets
    runs ||--o| weather_observations : "occurred during"
    runs ||--o| run_conditions : "copied into"
Loading

users (Better Auth tables + app columns)

Auth tables (users, sessions, accounts, verifications) are owned by Better Auth's Drizzle adapter. App-owned columns added to users (or a 1:1 user_profiles table if the adapter fights column additions — Phase 0 decides, documents, and the choice is invisible behind modules/auth):

display_name     text
city_label       text     -- "Minneapolis, MN"; user-editable
lat, lng         real     -- geocoded home location, nullable
time_zone        text     -- IANA zone of lat/lng (design 142), nullable. Looked up
                          --  from Visual Crossing by the place writer, never
                          --  typed; replaced or cleared with every place
                          --  written. NULL beside lat/lng = lookup owed, which
                          --  the :00 firing re-drives. Read through
                          --  onboarding's runnerTimeZone.
thermal_level    int      -- -2..+2 from onboarding O1 (-2 = runs warm,
                          --  +2 = always freezing); °C mapping lives in code
temp_unit        text     -- 'f' | 'c'; distance_unit 'mi' | 'km'; from locale
default_audience text     -- 'runners' (default) | 'private' | 'groups' | 'world':
                          --  who new entries are for (D-109, design 131).
                          --  Writers store runners | private | world; 'world'
                          --  only while public_profile is on (round 41 #86b).
count_in_totals  int      -- boolean, NOT NULL DEFAULT 1: Settings › Sharing's
                          --  "Count my runs in anonymous totals" (D-108 D).
                          --  Nothing creates a profile row at signup, so a
                          --  runner may have none: the guide job reads the
                          --  runner LEFT JOIN user_profiles and counts
                          --  COALESCE(count_in_totals, 1) = 1. A plain join
                          --  would silently drop every runner without a row.
                          --  The in-app consensus block reads it too (U2's
                          --  pool folded in, owner 2026-10-12): an entry
                          --  counts unless its runner's row says 0 (NOT
                          --  EXISTS on the profile's primary key).
public_profile   int      -- boolean, NOT NULL DEFAULT 0: Settings › Privacy's
                          --  "Public profile" (D-151). Off, /@handle is the
                          --  not-public page to a signed-out visitor; turning
                          --  it off moves a 'world' default_audience to
                          --  'runners' in the same write.
public_closet    int      -- boolean, NOT NULL DEFAULT 0: "Show my closet", the
                          --  rotation on the public profile; read only while
                          --  public_profile is on, and kept while it is off.
theme            text     -- 'system' (default) | 'light' | 'dark', NOT NULL:
                          --  Settings › Display › Theme (R48·133, design
                          --  185). The account's value, which takes over
                          --  from the device's cached one on sign-in; the
                          --  root's signed-in answer carries it. Signed out
                          --  is always 'system'. modules/account/theme.ts
                          --  is the one reader and writer.
system_account   int      -- boolean, NOT NULL DEFAULT 0: an account the
                          --  service runs, not a runner — the production
                          --  smoke account (design 193, #533). Invisible to
                          --  runners: runnerInStanding (search, H, /@handle)
                          --  and the entry rules' author clause (feeds, kits,
                          --  consensus, "worn by N") hide it, and
                          --  confirmedUserId refuses its shared writes. No
                          --  app code writes it; the owner sets it with one
                          --  `wrangler d1 execute` (docs/deployment.md §9).
                          --  test/architecture/system-account.test.ts holds
                          --  both.

wardrobe_items

id               text PK  -- ULID
user_id          text FK
category         text     -- enum: top | bottom | headwear | neckwear | gloves
                          --       | socks | shoes | accessory
type             text     -- NULLABLE. The runner may pick it on F (D-75,
                          -- R-112); a linked product's type fills it only
                          -- where it is blank (on save, on naming, on the
                          -- link a confirmation owes), and the runner's
                          -- pick always wins. Never parsed from a name
                          -- (design screen Z). Null means nobody said:
                          -- a garment with no product may have one, and
                          -- one with a product may not.
                          -- top: singlet|tee|longSleeve|halfZip|jacket|vest
                          --      |sportsBra
                          -- bottom: shorts|halfTights|tights
                          -- headwear: cap|beanie|headband
                          -- neckwear: neckGaiter    gloves: gloves
                          -- socks: socks            shoes: shoes
                          -- accessory: sunglasses|armSleeves
                          -- Not a column enum: the legal values depend on
                          -- the category, which a CHECK cannot express.
                          -- garmentSchema is the gate. Named for the Icon
                          -- Pack's glyphs, so a garment's icon IS its type.
layer            text     -- enum: base | mid | outer, NULLABLE
                          -- (meaningful for top/bottom; a jacket = top+outer)
weight           text     -- enum: light | mid | heavy, NULLABLE
fabric           text     -- enum: synthetic | merino | cotton | blend | down, NULLABLE
wind_resistant   int      -- 0/1, NULLABLE
water_resistant  int      -- 0/1, NULLABLE
est_temp_low_c   real     -- attribute-derived guess, NULLABLE
est_temp_high_c  real     -- NULLABLE
brand            text     -- NULLABLE
name             text     -- required; the only required descriptive field
size, color      text     -- NULLABLE. `color` is the COLOURWAY the runner
                          -- typed ("Obsidian"), free text, never parsed.
color_name       text     -- NULLABLE enum, 13 locked names in two classes
                          -- (AH): black white grey navy brown beige |
                          -- red orange yellow green blue purple pink.
                          -- No "multi", no "other", and hi-viz is NOT one
                          -- of them — it is a reason, not a colour.
color_hex        text     -- NULLABLE '#rrggbb', lowercase. Level 2 of AH;
                          -- optional beside an optional name. Enrichment
                          -- may propose the NAME, never a hex.
visibility_level text     -- NULLABLE enum: plain | reflective | hi_viz.
                          -- **Not `visibility` below.** This is the
                          -- garment property (AH); that one is the
                          -- moderation state. Only hi_viz exempts a
                          -- garment from the colour tiebreak; reflective
                          -- does not, because the base colour still shows.
photo_key        text     -- R2 key, NULLABLE
product_url      text     -- NULLABLE, https-only, user-entered
product_id       text     -- NULLABLE FK -> products; links this garment to a
                          -- canonical product (D-26). Product attributes act
                          -- as defaults; the garment's own columns override.
origin           text     -- enum: manual | taplist  (taplist rows are
                          -- [GENERIC] placeholders until upgraded — D-27)
retired          int      -- 0/1
visibility       text     -- enum: ok | pending | pass | flagged |
                          -- hidden_pending_review (106). 'ok' means never
                          -- screened, which is NOT 'pass'. Same vocabulary
                          -- as entry_photos.screen_status on purpose.
created_at       int

Which attributes apply is enforced by the contract layer, not the table (D1 can't do unions): the zod garment schema is a discriminated union on category, and per-category variants admit only their attributes. The table stays flat/nullable so closet filters (wind, water, temp range) are plain indexed SQL. Closet UI groups are derived, not stored:

UI group (design C) Predicate
Tops category='top' AND (layer IS NULL OR layer != 'outer')
Bottoms category='bottom' AND (layer IS NULL OR layer != 'outer')
Outer layer='outer'
Hands / head category IN ('headwear','neckwear','gloves')
Shoes category='shoes'
Socks / extras category IN ('socks','accessory')

brands (curated seed + user additions — lane 101)

id          text PK
name        text          -- display form ("Janji")
normalized  text UNIQUE   -- casefold/punctuation-fold, autocomplete key
seeded      int           -- 1 = from the curated running-brand seed list

products (canonical product identity — CRUD in 101, enrichment in 107)

id                 text PK
brand_id           text FK -> brands
name               text          -- model name ("Rover Half-Zip")
normalized_name    text          -- UNIQUE(brand_id, normalized_name);
                                 -- create-if-missing dedup key (D-30)
source_url         text          -- NULLABLE; first pasted product URL;
                                 -- cleared when its read lands on a denied
                                 -- site (R-176), so the next paste fills it
category_hint      text          -- NULLABLE garment category enum value
type               text          -- NULLABLE garment type; the source of
                                 -- wardrobe_items.type, filled by enrichment
fabric_composition text          -- NULLABLE; verbatim as published
                                 -- ("Body: 100% recycled polyester;
                                 --   Liner: 88% polyester, 12% spandex")
fabric_parts       text          -- NULLABLE JSON (fabricCompositionSchema.parts):
                                 -- parsed per-part breakdown; garments can be
                                 -- multi-composition (two-layer shorts, lined
                                 -- tights) so composition is a LIST of labeled
                                 -- parts, never a single pair (D-34)
weight             text          -- NULLABLE enum: light | mid | heavy
fabric             text          -- NULLABLE enum (same as garments)
wind_resistant     int           -- NULLABLE 0/1
water_resistant    int           -- NULLABLE 0/1
extracted          text          -- NULLABLE JSON, written only by 107's
                                 -- applyExtraction: { rung, found, written }.
                                 -- `found` is everything the ladder found
                                 -- (D-31 "raw extras"); `written` is what it
                                 -- last put in each typed column, which is
                                 -- how "never overwrite a human edit" is
                                 -- decided without a per-column flag
extraction_status  text          -- enum: none | pending | done | failed
status             text          -- 'active' | 'hidden' (106 moderation —
                                 -- product names are UGC, D-26)
created_by         text FK -> users
created_at         int

Rules: product rows are shared; a user "creating" an existing normalized brand+name gets the existing row. Garments inherit product attributes as defaults where their own columns are NULL (application logic, not triggers). Social-proof counts ("worn by N runners") derive only from shared (runners) outfit_entries — never from closet linkage (D-29).

product_snapshots (retention — lane 107)

id          text PK
product_id  text FK -> products
url         text
r2_key      text     -- raw fetched HTML under products/{productId}/
rung        text     -- the deepest ladder rung that contributed, re-recorded
                     -- on every reextract: jsonld | shopify | og | text | llm | none
fetched_at  int

Snapshots exist so extraction can re-run and improve later; never delete them to save space (they are the un-refetchable archive — D-31).

runs

id           text PK   -- ULID
user_id      text FK
source       text      -- enum: manual | file | garmin   (Strava is NOT a source;
                       -- garmin = fetched through Garmin's API, plan 160)
started_at   int       -- epoch seconds
duration_s   int       -- elapsed: keeps running through a pause (D-111)
distance_m   real
moving_s     int       -- NULLABLE; moving time read from the file (D-111).
                       -- NULL for manual and indoor runs
elevation_gain_m real  -- NULLABLE; metres climbed, from the file (D-111).
                       -- NULL for manual and indoor runs, and no altitude
lat, lng     real      -- NULLABLE
indoor       int       -- 0/1; indoor runs skip conditions entirely
effort       text      -- enum: easy | steady | workout | race, NULLABLE
                       -- (unused by v1 logic; accrues for the call)
title        text
weather_status text    -- enum: none | pending | attached | manual | failed
reminder_matched_at int -- NULLABLE; the Strava reminder this file run answered (127)
rpe          int       -- NULLABLE; the watch's perceived effort 1–10 (FIT workout_rpe ÷ 10)
effort_source text     -- NULLABLE enum: watch | runner — who picked `effort` (G5)
device_name  text      -- NULLABLE; Garmin's name for the device, for attribution (G1)

outfit_entries

id           text PK
run_id       text FK   -- UNIQUE (at most one entry per run)
user_id      text FK   -- denormalized deliberately: backs the feed index
verdict      int       -- -2..+2, NULLABLE until the user answers
                       -- -2 way_cold, -1 bit_cold, 0 dialed, +1 bit_warm, +2 way_warm
audience     text      -- 'private' | 'groups' | 'runners' | 'world' (D-109,
                       -- D-151): who may see it. PRIVATE / SHARED / PUBLIC on
                       -- screen. Seeded from default_audience at log time,
                       -- runner-chosen. DEFAULT 'private' fails closed; every
                       -- app writer sets it. 'runners' and 'world' are shown
                       -- to signed-in strangers; only 'world' to the open web.
caption      text      -- NULLABLE
created_at   int
  • SHARED is visible to any signed-in runner; only PUBLIC reaches the open web (D-58, revised by D-151). A signed-out request gets nothing about a SHARED or PRIVATE entry, or a profile that is not public — not its data, not its photo, not entry-specific head meta. A PUBLIC kit is served at /kit/<id> with the fields D-151 lists, and a public profile at /@handle (design 163); worldVisibleEntry() in modules/safety is the one open-web rule. Link previews use the generic card except a PUBLIC kit's own (D-152).
  • A run appears in the feed only when it has a shared (runners or world) outfit_entry.
  • The shared post shows the 5-state verdict label. What is never public: aggregate verdict history, coverage charts, per-item flags, thermal level.

outfit_entry_items

entry_id   text FK
item_id    text FK
flag       text   -- enum: too_much | not_enough, NULLABLE
PK (entry_id, item_id)

There is no per-item verdict — comfort is judged per-run; flag carries the item-level exception ("gloves too much"). The per-item note is cut for v1 (D-160), and its column was dropped before the baseline (#408).

entry_tags

entry_id   text FK
tag        text   -- from the curated list in contracts.ts (cold_first_mile,
                  -- chafed, perfect_warmup, sleeves_damp, ...); no free text
PK (entry_id, tag)

run_conditions (a copy of each run's judged conditions — D-175, design 189)

run_id               text PK         -- the run; one row per run
user_id              text            -- the runner: the account purge deletes by it
-- weather's half, written in the batch that settles the run (attached or
-- manual), cleared by the hourly retry cron while the run is pending again
feels_like_c         real NULLABLE   -- the starting hour's
min_feels_like_c     real NULLABLE   -- the coldest hour the run reached
max_feels_like_c     real NULLABLE   -- the warmest
precip_class         text NULLABLE   -- dry | damp | wet, the starting hour's
source               text NULLABLE   -- visualcrossing | manual
-- feed's half, written in the batch that writes the entry's verdict or
-- audience, cleared when the entry is retracted
verdict              integer NULLABLE
entry_created_at     integer NULLABLE
entry_shared         integer bool    -- audience is SHARED or PUBLIC
-- generated (virtual)
judged_feels_like_c  real            -- judgedFeelsLikeC: coldest if the verdict
                                     -- is cold, warmest if warm, else the start
judged_bucket        integer         -- floor(judged_feels_like_c)
INDEX run_conditions_band (precip_class, judged_bucket, entry_created_at)
  WHERE entry_shared = 1 AND source != 'manual'
INDEX run_conditions_user (user_id)

A copy, not an authority. The conditions consensus seeks it by band and window instead of reading every shared entry in the window and then each run's weather in the other database. Audience, moderation and the totals opt-out are still read live from outfit_entries and user_profiles in the join. entry_shared only keeps private entries out of the index. It holds no note, photo, place or start time, and the published totals (D-108) do not read it. A run counts once its weather has settled (D-156).

Social + system tables

follows:        follower_id, followee_id, created_at; PK (follower_id, followee_id)
reactions:      entry_id, user_id, kind ('useful'), created_at; PK (entry_id, user_id)
entry_photos:   id, entry_id, photo_key, position (max 4 per entry)
notifications:  id, user_id, kind, subject_id, body, read, created_at,
                link_id NULLABLE -- what the row opens when that is not its
                  -- subject: the filer's garment for a correction's outcome,
                  -- the follower for a follow; null for a grouped follow
                  -- (design 183). `notifications/target.ts` reads it.
                UNIQUE(user_id, kind, subject_id)  -- dedupe key
follow_notices: followee_id, follower_id, notification_id, rung_at;
                UNIQUE(followee_id, follower_id) -- a follower rings a
                  -- runner at most once in 30 days (R48·131e); the row is
                  -- kept when the follow is undone. `notification_id` is
                  -- the bell row the follow joined (grouped while unread).
strava_connections:  user_id PK, athlete_id, refresh_token,
                     connected_at NULLABLE -- when the grant was made (127)
                     -- refresh_token is kept ONLY to revoke the grant (D-54);
                     -- no access token, expiry or status is stored
                     -- webhook reminder flow ONLY; no other module may import it
processed_webhook_events: UNIQUE(object_id, aspect_type, event_time),
                INDEX(event_time) -- pruned after 7 days (127, STR-10)
strava_revocations: id, refresh_token, created_at
                -- the revoke outbox (law 8c); drained with the refresh token
cron_checkpoints: cron_name PK, last_run_at
imports:        id, user_id, r2_key,
                status ('pending'|'processing'|'done'|'failed'|'duplicate'),
                failure_reason, run_id NULLABLE, created_at,
                garmin_activity_id NULLABLE, -- plan 160; UNIQUE(user_id, garmin_activity_id)
                claimed_by NULLABLE  -- #841; the claimId of the queue message that last claimed the row

Task 106 added:

reports:         id, reporter_id, subject_type ('entry'|'photo'|'profile'|
                 'product'), subject_id, reason, note NULLABLE, created_at
                 UNIQUE(reporter_id, subject_type, subject_id)
                   -- NOT a dedupe convenience. "N reports from DISTINCT
                   -- users" is only true under retries if a second report
                   -- cannot become a second row; this is what makes
                   -- COUNT(*) a count of people.
review_queue:    id, subject_type, subject_id, source ('reports'|
                 'classifier'|'fingerprint'|'unscreened'|'missing_file'),
                 status ('pending'|'reviewing'|'approved'|
                 'removed'), resolved_by NULLABLE, resolved_at NULLABLE,
                 created_at; UNIQUE(subject_type, subject_id)
                   -- one row per subject, not per report: three reports
                   -- about one entry are one decision. `status` is the
                   -- claim column (law 2). 'unscreened' and
                   -- 'missing_file': a photo still pending screening a
                   -- day after upload (D-157) — the classifier never
                   -- answered, or storage has no object to screen.
domain_denylist: domain PK (bare registrable host, lowercased, no 'www.'),
                 added_by, reason NULLABLE, created_at. Seeded with link
                   -- shorteners and redirectors, added_by 'seed'
                   -- (R-176, migration 0078); a redirector host such as
                   -- l.facebook.com is a row for that subdomain only.
link_landings:   url PK (a product link as typed), landed_domain (domainOf
                 form), checked_at -- where enrichment's read of the link
                   -- landed, kept only when that is another domain
                   -- (R-176, design 171). A landing, not a verdict: a
                   -- link is denied when its own domain or its landing's
                   -- is, at every read. Read and written only by safety.
photo_screenings: id, photo_scope ('entry'|'garment'), photo_id, model,
                 scores (raw per-category JSON), decision ('pass'|'flag'),
                 created_at -- kept so a threshold can be re-tuned against
                 real scores without re-classifying anything.
blocks:          blocker_id, blocked_id, created_at;
                 UNIQUE(blocker_id, blocked_id) + INDEX(blocked_id)
                   -- read from both ends: W2 promises blocking works in
                   -- both directions. Deliberately NOT read by the
                   -- consensus aggregate — a blocked runner's verdicts
                   -- still count in numbers that name nobody.
user_profiles:   + banned_at NULLABLE, ban_reason NULLABLE
                   -- `banned_at IS NOT NULL` IS the ban: one fact, not a
                   -- boolean and a date that can disagree.
outfit_entries:  + moderation_status ('ok'|'hidden_pending_review'|'removed')
                   -- SEPARATE from audience, which is the runner's own
                   -- sharing choice. A moderator writing audience would
                   -- silently rewrite a preference they set, and approving
                   -- could never restore it correctly.
entry_photos:    + screen_status ('pending'|'pass'|'flagged'|
                 'hidden_pending_review'|'removed'), default 'pending'
                   -- the durable "not finished" marker that lets screening
                   -- retry be a cron rather than a queue (law 8c).
                   -- 'removed' (D-130): a copyright hold's hide, the one
                   -- state the owner's reads skip too. An entry's hold is
                   -- moderation_status 'removed'. Only the hold's restore
                   -- moves either out of it; a report and Approve do not.
copyright_holds: subject (entry|photo), owner, entry, the takedown's
                 moderation_actions row; status hidden|restored|purging|
                 purged; hidden_at, purge_at (+30d); counter_notice_at,
                 restore_at (12th weekday after), court_action_at,
                 case_closed_by.
                   -- D-130, design 149. Strikes = an owner's holds that
                   -- were not restored. A court action is a litigation
                   -- hold (D-146): no purge until the Desk's "Case over".

Design 183 added:

product_corrections: id, product_id, user_id, garment_id, field ('name'|
                 'weight'|'fabric'|'wind'|'water'|'composition'|'link'),
                 value, note NULLABLE, status ('waiting'|'applied'|
                 'declined'), reason NULLABLE, decided_by NULLABLE,
                 decided_at NULLABLE, idempotency_key, created_at
                   -- D-163. UNIQUE(user_id, product_id, field) WHERE
                   -- waiting: a second correction to the field replaces
                   -- the first. `value` is the sheet's input as stored:
                   -- the text, the enum word, or 'yes'/'no'. The fields
                   -- and their rules are lib/contracts/product-corrections.
                   -- Apply writes the product and decides every waiting
                   -- row for the field; Decline only its own value's.
review_audit:    id, actor_id, action ('opened_reporters'), review_id,
                 subject_type, subject_id, created_at
                   -- D-164, R-66: written in the batch that reads a review
                   -- row's reporters, so they cannot be read unrecorded.

One rule for "visible to a stranger". audience IN ('runners', 'world') AND moderation_status = 'ok' and the author not banned, expressed once as publiclyVisibleEntry() in modules/safety and imported by every read that shows entries to someone other than their author. Given the viewer (publiclyVisibleEntry(viewerId), and entryVisibleTo(viewerId) which adds "or it is the viewer's own"), it also drops a blocked pair, either direction, and entries the viewer reported (task 128). The anonymous form — no viewer — is what aggregates use, so blocks and a reporter's own hide move no counts; a ban does. The "stranger" is always a signed-in runner (decision D-58). Five call sites wrote the first half by hand before 106; a second condition would have made five copies of a rule, and the dangerous one is the consensus aggregate, where a missed clause hides nothing visibly and only skews the numbers.

Covering indexes (minimum set; lanes add their own with EXPLAIN proof)

outfit_entries(user_id, created_at DESC)           -- feed + profile
outfit_entries(audience, moderation_status, created_at)          -- consensus window
outfit_entries(user_id, audience, moderation_status, created_at) -- feed + H seek
follows(follower_id, followee_id)
wardrobe_items(user_id, category)
wardrobe_items(product_id)                         -- worn-by counts via entries
products(brand_id, normalized_name)                -- UNIQUE + autocomplete
brands(normalized)                                 -- UNIQUE
runs(user_id, started_at DESC)
notifications(user_id, read)

dialed-weather database

weather_observations: id, run_id (nullable), lat_r, lng_r, hour_bucket,
  temp_c, feels_like_c, humidity, wind_kph, precip_mm, condition,
  source ('visualcrossing'), fetched_at
UNIQUE(lat_r, lng_r, hour_bucket)   -- the cache key: lat/lng rounded to 2dp

manual_conditions: run_id (PK), temp_c, set_at, sky NULLABLE -- R2b's band and sky (dry|damp|rain|snow), one run's own

weather_observations is a shared cache and holds real observations only. A band a runner sets in R2b belongs to that run and lives in manual_conditions, keyed by the run — never in a cache cell, where it would answer for every other runner at that place and hour (PR #103, B1). No source='manual' cache row has ever been deployed, and nothing writes one: the cache's readers no longer step around them (tasks 125 and 129), and 'manual' left the column's enum with the owner's approval (2026-09-26, task 129; a TypeScript enum, so no SQL changed). A band reads back tagged source='manual' — a label on the reading, not a cache row — and is excluded from consensus aggregates and future training queries. Every stored value is metric; display units convert at render from user prefs.

Shared TypeScript contracts (become src/lib/contracts.ts in Phase 0)

import { z } from "zod";

// ---- Garments: discriminated union on category ----------------------------
export const layerSchema = z.enum(["base", "mid", "outer"]);
export const weightSchema = z.enum(["light", "mid", "heavy"]);
export const fabricSchema = z.enum([
  "synthetic",
  "merino",
  "cotton",
  "blend",
  "down",
]);

const garmentBase = z.object({
  name: z.string().min(1).max(80),
  brand: z.string().max(60).optional(),
  size: z.string().max(20).optional(),
  color: z.string().max(30).optional(),
  // AH, additive 2026-09-19. The classes are the source and the enum is
  // derived from them — `colorClass()` reads them rather than restating
  // the split, because the Call's tiebreak keys off the class.
  colorName: colorNameSchema.optional(),
  colorHex: colorHexSchema.optional(),
  visibilityLevel: garmentVisibilitySchema.optional(),
  productUrl: z.string().url().startsWith("https://").optional(),
  productId: z.string().optional(),
  estTempLowC: z.number().optional(),
  estTempHighC: z.number().optional(),
});
const layered = garmentBase.extend({
  layer: layerSchema.optional(),
  weight: weightSchema.optional(),
  fabric: fabricSchema.optional(),
  windResistant: z.boolean().optional(),
  waterResistant: z.boolean().optional(),
});
export const garmentSchema = z.discriminatedUnion("category", [
  layered.extend({ category: z.literal("top") }),
  layered.extend({ category: z.literal("bottom") }),
  garmentBase.extend({
    category: z.literal("headwear"),
    weight: weightSchema.optional(),
    fabric: fabricSchema.optional(),
    windResistant: z.boolean().optional(),
  }),
  garmentBase.extend({
    category: z.literal("neckwear"),
    weight: weightSchema.optional(),
    fabric: fabricSchema.optional(),
  }),
  garmentBase.extend({
    category: z.literal("gloves"),
    weight: weightSchema.optional(),
    windResistant: z.boolean().optional(),
    waterResistant: z.boolean().optional(),
  }),
  garmentBase.extend({
    category: z.literal("socks"),
    weight: weightSchema.optional(),
    fabric: fabricSchema.optional(),
  }),
  garmentBase.extend({
    category: z.literal("shoes"),
    waterResistant: z.boolean().optional(),
  }),
  garmentBase.extend({ category: z.literal("accessory") }),
]);
export type Garment = z.infer<typeof garmentSchema>;

// ---- Products (D-26/D-31) ---------------------------------------------------
export const productDraftSchema = z.object({
  brand: z.string().min(1).max(60),
  name: z.string().min(1).max(120),
  sourceUrl: z.string().url().startsWith("https://").optional(),
});

/** Fabric composition: multi-part by design (D-34) — two-layer shorts,
 *  lined tights, insulated jackets carry per-part compositions. `verbatim`
 *  is always kept exactly as published; `parts` is best-effort parse. */
export const fabricPartSchema = z.object({
  part: z.string().optional(), // "body" | "liner" | "shell" | "panels" ... ; absent when unlabeled
  materials: z
    .array(
      z.object({
        material: z.string(), // "polyester", "merino wool", "elastane"
        pct: z.number().min(0).max(100).optional(),
      }),
    )
    .min(1),
});
export const fabricCompositionSchema = z.object({
  verbatim: z.string(),
  parts: z.array(fabricPartSchema).optional(),
});

/** What the extraction ladder emits; every field independently optional. */
export const extractedProductSchema = z.object({
  name: z.string().optional(),
  brand: z.string().optional(),
  categoryHint: z.string().optional(),
  fabricComposition: fabricCompositionSchema.optional(),
  weight: weightSchema.optional(),
  fabric: fabricSchema.optional(),
  windResistant: z.boolean().optional(),
  waterResistant: z.boolean().optional(),
  imageUrl: z.string().url().optional(),
  extras: z.record(z.string(), z.unknown()).optional(), // preserved verbatim in products.extracted
});
export type ExtractedProduct = z.infer<typeof extractedProductSchema>;

/** Deterministic rungs (JSON-LD, Shopify JSON, OG) implement this per source. */
export interface PageExtractor {
  readonly rung: "jsonld" | "shopify" | "og";
  /**
   * `undefined`, not `null`, for "this rung found nothing" — `unicorn/no-null`
   * is repo policy and `src/` contains no `return null`, so the original
   * signature could not be implemented without a suppression nobody may add.
   * Changed by 107 when the first rung was written; no other lane implements
   * or calls this.
   */
  extract(url: URL, html: string): ExtractedProduct | undefined;
}

/** LLM rung behind an adapter; eval decides the implementation (D-32). */
export interface ExtractionModel {
  extract(pageText: string, hint: { url: string }): Promise<ExtractedProduct>;
}

// ---- Verdicts -------------------------------------------------------------
export const verdictSchema = z.number().int().min(-2).max(2);
export const verdictLabels = {
  "-2": "way_cold",
  "-1": "bit_cold",
  "0": "dialed",
  "1": "bit_warm",
  "2": "way_warm",
} as const;
export const itemFlagSchema = z.enum(["too_much", "not_enough"]);
export const entryTags = [
  "cold_first_mile",
  "cold_throughout",
  "overheated_late",
  "sleeves_damp",
  "chafed",
  "perfect_warmup",
  "wind_cut_through",
  "hands_cold",
  "hands_sweaty",
] as const;
export const entryTagSchema = z.enum(entryTags);

// ---- Runs -----------------------------------------------------------------
export const effortSchema = z.enum(["easy", "steady", "workout", "race"]);
export const runDraftSchema = z.object({
  startedAt: z.number().int().positive(),
  durationS: z.number().int().positive(),
  distanceM: z.number().positive(),
  lat: z.number().min(-90).max(90).optional(),
  lng: z.number().min(-180).max(180).optional(),
  indoor: z.boolean().default(false),
  effort: effortSchema.optional(),
  title: z.string().min(1).max(120),
});
export type RunDraft = z.infer<typeof runDraftSchema>;

/** Every import path (file parser now; Polar/Fitbit later) produces this. */
export interface RunSource {
  readonly kind: "fit" | "gpx" | "tcx";
  parse(bytes: ArrayBuffer): Promise<RunDraft>;
}

// ---- Weather --------------------------------------------------------------
export const weatherObservationSchema = z.object({
  tempC: z.number(),
  feelsLikeC: z.number(),
  humidity: z.number().min(0).max(100),
  windKph: z.number().min(0),
  precipMm: z.number().min(0),
  condition: z.string(),
  // R-96: the IANA zone of the place observed. Optional and additive —
  // manual observations and rows cached before the column have none.
  // Refined by `isTimeZone`, because an invalid zone throws inside `Intl`
  // at render time rather than failing here.
  timeZone: z.string().refine(isTimeZone).optional(),
});
export type WeatherObservation = z.infer<typeof weatherObservationSchema>;

export interface WeatherProvider {
  /** Historical/near-past conditions at a time+place (for imports). */
  observation(lat: number, lng: number, at: Date): Promise<WeatherObservation>;
  /** Forecast at a future time+place (for the call, post-MVP). */
  forecast(lat: number, lng: number, at: Date): Promise<WeatherObservation>;
}

// ---- Onboarding / profile -------------------------------------------------
export const thermalLevelSchema = z.number().int().min(-2).max(2);
/** UI copy maps: +2 "always freezing" ... -2 "sweating in a t-shirt at 40°".
 *  Degree offset mapping (code, not DB): level * 2.2°C. */

Route conventions (TanStack Start)

File-based routes under src/routes/, one directory per lane — ownership is the directory, so route merges are append-only:

src/routes/
  __root.tsx            # Phase 0: shell, tab bar, auth context
  index.tsx             # Phase 0: redirects to feed
  auth/                 # Phase 0 (Better Auth pages)
  closet/               # lane 101
  runs/                 # lane 102 (log flow, imports, notifications)
  feed/                 # lane 104 (feed tabs, entry detail, profiles, search)
  products/             # lane 101 (autocomplete endpoints); 107 adds none
  onboarding/           # lane 105
  call/                 # lane 105 (teaser tab only, until the call epic)
  api/                  # webhook + queue-facing HTTP endpoints, per-lane files
  • Navigation uses typed Link to / navigate only — string URLs are linted.
  • Mutations and loads are server functions exported from modules/<lane>/index.ts; route files stay thin (parse params → call module → render module components).
  • Reserved server-function namespaces mirror modules: auth.*, closet.*, runs.*, weather.* (internal only), feed.*, onboarding.*, products.* (101: CRUD/autocomplete) and enrichment.* (107: internal only).

Component convention

  • Shared primitives live in src/ui/ (Layout, tab bar, sheet, Mono, Bracketed, verdict badge, garment chip — see docs/product.md).
  • Lane components live with the code whose data they show: in modules/<lane>/<sub-module>/components/ when the module is split into sub-modules (design 240 rule 5, e.g. ops/desk/components/), otherwise in modules/<lane>/components/. Pieces with no data of their own that several sub-modules' screens use stay in the parent's components/.
  • A component imports files directly, in its own sub-module or another's, and never a sub-module's index.ts: a door may reach env, which would put server code in the client bundle. A module's index.ts exports a component only where another lane genuinely consumes it (e.g. weather's WeatherAttribution, runs' notification bell slot), and a sub-module's door never does.