# Kilter — the state machine Derived by reading the code, not the docs. Every guard below names the function and line that implements it, and every invariant says which line enforces it — so when the two disagree, the code is right and this file is stale. There are six machines. Four are persisted (groups, waitlist entries, actors, notifications); one is a *driven* transition (the waitlist tick); one is a pure function with no state at all (the match read), included because its output is an enum people act on. --- ## M1 — Application lifecycle (one machine per applicant per group) States: `none` · `admitted` · `waitlisted` · `not_a_fit` · `dropped` · `left` Note the pre-state: `none` is the applicant who has not applied. There is no row for them anywhere, which is why `not_a_fit` also leaves no row — a refusal is returned to the caller and discarded (`apply_to_group`, app.py:886-888). | From | Event | Guard | To | Code | |---|---|---|---|---| | `none` | `Apply` | bouncer allows (not throttled; dump ≥ 40 chars) | evaluate | `bounce("apply", …)` app.py:846 | | evaluate | — | rules pass **and** seat free **and** owner under budget | `admitted` | app.py:873-876 | | evaluate | — | rules pass **and** owner over budget | `waitlisted` | app.py:877-882 | | evaluate | — | rules pass **and** no seat | `waitlisted` | app.py:883-885 | | evaluate | — | rules fail | `not_a_fit` (no row kept) | app.py:886-888 | | `waitlisted` | `Tick` | rules still pass **and** seat now free **and** owner under budget | `admitted` | `check_waitlist` app.py:938-944 | | `waitlisted` | `Tick` | otherwise | `waitlisted` (stays, gains `blocked_by`) | app.py:945-947 | | `waitlisted` | `Tick` | owning group no longer exists | `dropped` (row deleted, **no notice**) | app.py:929-931 | | `admitted` | `Leave` | — | `left` (seat freed) | `leave_group` | **The decision is a priority ladder, and order matters.** `apply_to_group` tests `ok and has_room and not over_budget` first; the `over_budget` branch is tested *before* `not has_room`, so an applicant into a group that is both full and over-budget is told about the budget. That is deliberate: the budget is the owner's limit, the seat count is transient, and telling someone "the group is full" when it will never have room is the less honest of the two messages. **Two different waiting reasons, one state.** `waitlisted` covers "no seat yet" and "the owner's people budget is spent". They are distinguished by `why`, not by state, because the transition out of both is the same tick. ## M2 — Group lifecycle States: `open` · `full` · `deleted` | From | Event | Guard | To | |---|---|---|---| | `none` | `Create` | bouncer allows; a name exists; a goal or description exists; capacity 0 or 1..10000; owner under budget | `open` | | `open` | `Apply` admitted | `len(members) == capacity` (capacity > 0) | `full` | | `open`/`full` | `Leave` | — | `open` if a seat freed | | `open`/`full` | `Delete` | — | `deleted` (members and its waitlist rows removed) | `capacity == 0` means unlimited and can never reach `full` — but it is still bounded by the owner's people budget, which is why `full` is not the only way to stop admitting (app.py:866-871). `open`/`full` are **derived, never stored**: nothing writes a status field. The state is `capacity == 0 or len(members) < capacity`. That is a deliberate choice — a stored flag would be a second source of truth that drifts from the member list. ## M3 — Actor / bouncer State is **derived from an append-only event log** per actor, never stored as a status: ``` actor = { events: {kind: [timestamps]}, groups: [ids], people: int } ``` | Derived state | Condition | Effect | |---|---|---| | `clear` | every window under its limit and `people < PEOPLE_BUDGET` | creation allowed | | `throttled` | `hour ≥ per_hour` or `day ≥ per_day` for that kind | **429** + `retry_after_s` | | `stale request` | a structural guard fails (no name, thin dump, no goal, bad capacity) | **403** + every reason | | `budget_spent` | `people ≥ PEOPLE_BUDGET` | new groups refused; new applicants waitlisted | Limits: group_create 3/h 20/d · apply 10/h 60/d · reach 60/h · image 2/h 10/d · people budget 50. Windows are sliding, computed at read time by filtering the event list (app.py:1116-1130), so there is no reset job to forget to run. **`throttled` is checked before the structural guards**, and the two produce different status codes, because they mean different things: one is "you are going too fast" and the other is "this request cannot be processed at all". ## M4 — Notification States: `queued` · `sent` · `undeliverable` | From | Event | To | |---|---|---| | `none` | a promotion queues a notice | `queued` (`sent: false`, `created_at`) | | `queued` | `POST /api/notify/mark-sent {ids}` after an actual delivery | `sent` | | `queued` | the `to` field is empty | `undeliverable` (reported, never silently dropped) | **Nothing in this system sends an email.** There is no mail channel on the host. `sent` is set only by an explicit call after somebody delivers the notice, so the queue is a record of what was really delivered rather than what was intended. Any surface that claims otherwise is lying, and `llms.txt` says so in the contract. ## M5 — The waitlist tick (a driven transition, not a user event) `POST /api/waitlist/check` is the only thing that moves anyone off the waiting list. It runs from a Hermes cron job every two hours. For each waiting entry, in file order: 1. group gone → `dropped` 2. re-evaluate the **frozen profile** captured at apply time (`entity["profile"]`) 3. seat free **and** owner under budget → `admitted`, row removed, notice queued 4. otherwise → stays `waitlisted` with `blocked_by` updated ```python if ok and has_room: # admitted else: # still waiting, blocked_by = reasons or "no seat yet (N left)" ``` Order matters and is fair: the list is processed in submission order, so when one seat frees and two people qualify, the one who applied first takes it and the second re-reads `seats_left = 0` and stays. **The profile is frozen at apply time.** The tick re-runs the *rules* against the *original evidence* — it never re-labels anyone. Without that, a model rerun could change whether a person was ever eligible, and the same application would give two different answers on two days. ## M6 — The match read (stateless) A pure function over two labelled profiles. No state, but its output enum is what people act on: ``` balanced trade · mildly uneven · asymmetric, one side carries it · charity-shaped ``` Both directions are computed independently (`a_to_b`, `b_to_a`) and the gap is carried in `_math`. There is deliberately no single score: the gap *is* the answer. --- ## Invariants The rules a reader would agree to hold, and what enforces each. | # | Invariant | Enforced by | |---|---|---| | 1 | **Capacity is never exceeded.** `len(members) ≤ capacity` whenever capacity > 0. | seat check inside the same `_LOCK` as the append (app.py:865-874) | | 2 | **The owner's people budget is never exceeded**, including in capacity-0 groups. | `_actor_people(owner) >= PEOPLE_BUDGET` tested at admission (app.py:868-871, 935-937) | | 3 | **Every admitted member passed the rules at some point.** | `admitted` only from the `ok` branch | | 4 | **A person is never evaluated on evidence that changed after they applied.** | the tick reads `entity["profile"]`, frozen at apply (app.py:932) | | 5 | **A promotion always queues exactly one notice.** | `queue_notification` on every promote (app.py:943) | | 6 | **No notice is ever marked sent without a delivery.** | `sent` only via explicit `mark-sent` | | 7 | **A refusal carries its reasons.** | `not_a_fit` stores `reasons`; 403 carries every reason | | 8 | **Only one caller can decide a seat at a time.** | every read-modify-write of groups/waitlist inside `_LOCK` | | 9 | **Agency never affects eligibility.** `ok` comes from the rules alone; agency is not an input to the gate. | `evaluate_gate(group, profile)` takes no agency (app.py:833); it is attached afterwards as `detail["agency"]` (app.py:899) | | 10 | **Every promotion records what decided it.** A promotion reordered by agency names the agency and the number it beat. | the `why` built in `check_waitlist` (app.py:1046-1056) | Invariant 1 and 2 are the ones worth a formal check. Both are held by the *same* lock and the *same* branch, so a model would need only three entities and a capacity of 1 to explore the interesting interleavings. ### Invariant 4 has a deliberate exception, and it is the most surprising thing here The rules are still evaluated against the profile **frozen at apply time** (invariant 4): nobody is refused because their evidence got worse while they queued. But **agency is read live at promotion time** — `check_waitlist` re-reads it in the same tick (app.py:1018) — because acting while you wait is exactly what should move you up. So one tick evaluates two things against two different vintages of evidence, on purpose: the rules -> the profile as it was when they applied (frozen) the order -> agency as it is right now (live) This is an asymmetry, not an oversight. If agency were frozen at apply time the queue could never move and the loop would stop, which is the whole feature. Anyone reading this file expecting a single consistent snapshot will be caught out by it. --- ## Gaps this reading found (honest, not fixed) 1. **A dropped entry is never told.** When a group is deleted, its waiting rows are removed and the applicant is not notified — the operator sees the names in the `dropped` list, the person learns nothing (app.py:929-931). 2. **No dedupe.** The same person (same contact) can apply twice and hold two waiting rows, or appear as two members. Nothing keys on identity, because there is no identity. 3. ~~**Refusals leave no record.**~~ **Closed.** A `not_a_fit` now records the refusal, the gaps that caused it, the moves that would close them and the profile it judged, so a group can answer "how many did we turn away, and on what rule" (`/api/considerations`) and the person can be re-judged later against the rules as they then are (`/api/improve`). What is still missing is delivery: the path exists and is returned with the refusal, but nothing sends it, for the same reason nothing is emailed at all — there is no mail channel. 4. **The tick holds the global lock across model calls.** `check_waitlist` evaluates every waiting entity inside `_LOCK`, and `evaluate_entry` can call a typed model once per `must_offer_any`/`must_need_any` term. A long waitlist on a semantic-ruled group therefore blocks every other write for the duration of those calls. It stays inside on purpose — evaluating outside would admit somebody against rules that changed while the tick was thinking, and invariant 1 is only safe because the seat check and the append share the lock — so this is a scaling limit, not an oversight. The **apply** path no no longer does any network work inside the lock (it measured 90s+ of blocking a second apply and a waitlist check behind one reach-gated application, since fixed), so the hot path is clear; the tick is not. ## Invariant 11 — a guideline orders who you are shown, and nothing else A member's own guidelines (`guidelines.md`) never admit, remove, reorder or waitlist anybody. No function in the joining path reads one: `evaluate_gate`, `evaluate_entry`, `apply_to_group`, `check_waitlist`, `leave_group` and `create_group` contain zero mentions of guidelines, and only `group_members` (reports them) and the MCP dispatch (routes them) touch the field at all. This is invariant 9's line held a second time, and it needs holding for a stronger reason. Agency is at least a measure of contributing to the group. A guideline is private and self-interested, so the moment it could affect the room, every member would be incentivised to write one that thins their own competition and the owner would lose control of who is in their group. The asymmetry is bounded instead: a guideline changes what **you** see. ## Invariant 12 — context is read only by the room it was given to Every observation carries a scope, and a group-facing read filters on it. A group id reads only itself; `self` is the person's private bucket and **no group-facing read may touch it**. The default when a scope is absent is `self`, because that is the safe direction — an unreadable scope hides the observation from every group rather than exposing it to all of them. Reading across every scope must be asked for (`all=true`) and is the person's own view of themselves. The gate's agency read and `intro_rules.min_agency` are both scoped to the group, so "has been showing up" always means *here*. The consequence is stated in `context.md` rather than discovered: **a newcomer to a room starts at zero in it**, because a score carried in from somewhere else is evidence nobody in that room can see. ## Invariant 13 — an introduction never changes anybody's standing `intro_rules` decides when two members may be introduced, and a blocked introduction adds and removes nothing: it does not admit, waitlist, reorder or remove. It is a to-do, not a verdict. This is the third time the same line is held — agency (9), guidelines (11), introductions (13) — and each one guards a different way of turning "you were not chosen" into "you are out". An introduction is the most tempting of the three to wire into standing, because it feels like the reward the whole room exists to produce. Wiring it in would make a slow introducer someone who gets *less* consideration over time, which is the opposite of what the room is for. ## Not covered - Anything about the model's *prose*: whether a label is any good is not a state machine property. - Cost limits for the paid routes beyond their counters. - Concurrency across processes: this is correct for one machine because it is one lock in one process. A second machine would need a real transaction, which is why the app is pinned to a single instance. --- ## M7 — ICP Onboarding, Micro/Huge Updates & Agent-Code Auth (the product loop) States per user/agent across all four ICP workflows (`Builder / Operator`, `Room Owner`, `Investor / Scout`, `AI Agency / Consultant`): `anonymous` -> `icp_selected` -> `interviewed` -> `bounced | waitlisted | admitted` -> `verified_self` -> `compounding` | From | Event | Guard | To | Code | |---|---|---|---|---| | `anonymous` | Picks ICP lane on `/` or `/join` | Copies tailored 1-line prompt pointing at `/llms.txt` | `icp_selected` | `landing.html`, `join.html` | | `icp_selected` | Agent calls `POST /api/profile` or `/api/questions` | `_dump_value_gate` (>=40 chars, >=6 distinct words, no boilerplate) | `interviewed` | `add_to_profile` | | `interviewed` | Agent calls `POST /api/groups/apply` | AI Bouncer (`evaluate_gate` + Treg measured reach + Jev typed read) | `admitted` / `waitlisted` / `bounced` (`not_a_fit`) | `apply_to_group` | | `admitted` / `waitlisted` | Agent logs **Micro Update** (`POST /api/signals`) | `_signal_value_gate` (>=12 chars, >=2 words, 24h dedupe, 0 LLM cost) | `compounding` (weekly streak + live agency order) | `add_signal` | | `admitted` / `waitlisted` | Agent logs **Huge Update** (`POST /api/profile` + `/api/waitlist/check`) | `_dump_value_gate` + full dossier re-read outside `_LOCK` | `compounding` / `admitted` (waitlist promotion) | `add_to_profile`, `check_waitlist` | | any handle | Human asks agent for `/you` code (`POST /api/auth/code`) | `bounce("access_code")` -> mints single-use 15-min `KLT-XXXX-XXXX` | `code_issued` | `issue_access_code` | | `code_issued` | Human pastes code into `/you` (`POST /api/auth/redeem`) | Code exists, unused, unexpired -> issues 7-day signed `member:` JWT | `verified_self` (unlocks `/you` + `members`-only room feeds) | `redeem_access_code` | | `verified_self` | Owner sets `activity_visibility: "members"` (`POST /api/groups/privacy`) | Caller handle matches `owner` | Room activity hidden from public; visible only to verified members | `set_group_privacy`, `public_group_activity_for_viewer` | **Invariant 11 (Private Self & Room Feeds):** `/api/me` never returns a person's dossier, observations, or agency breakdown without a signed `member:` JWT redeemed from a single-use agent code, and a room with `activity_visibility == "members"` never leaks its events or member micro-updates to unauthenticated viewers or `public_activity_all`. --- ## M8 — Growth & Scale State Machine (100 -> 1,000 -> 10,000+ users) | Stage | User band | Active storage & matching architecture | Hardening already wired | Quantitative trigger to transition | |---|---|---|---|---| | **Stage 1 (Current)** | 1 -> 100 users | Single Fly machine + atomic JSON files behind `_load`/`_save` | Slow LLM calls moved outside `_LOCK`; 5MB body cap; `_dump_value_gate` + `_signal_value_gate`; `signals.json` cap 25k; `KLT` agent-code auth | Any JSON file > 5 MB, `_LOCK` p99 > 50 ms, or `signals.json` approaching 25k rows | | **Stage 2 (Next)** | 100 -> 1,000 users | Single-machine SQLite WAL (`kilter.sqlite`) behind the same `_load`/`_save` seam + indexed `signals(scope, handle, t)` | Zero handlers bypass `_load`/`_save`; `check_waitlist` deterministic order | Need >1 Fly machine for multi-region HA or >50 members in a room | | **Stage 3 (Scale)** | 1,000 -> 10,000+ users | Managed Postgres + async waitlist/evaluation worker + vector embedding candidate shortlist | Rules + Jev typed judge stay as sole deciders (embeddings only shortlist top 20 pairs so every verdict stays arguable) | Sustained concurrent admissions > 10/sec or rooms > 200 members |