Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(home): enforce the monthly agent-turn quota, and never let it refuse a lock

nirholas1e4e20dbc19e
diff --git a/STRUCTURE.md b/STRUCTURE.md
index aef18a259..9ca593fbe 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -166,7 +166,7 @@ bottom.
| Sign Mirror (camera-graded handshape practice) | [pages/sign-mirror.html](pages/sign-mirror.html) `→ /sign-mirror` + [src/sign-mirror-page.js](src/sign-mirror-page.js), grader [src/sign-grader.js](src/sign-grader.js), reference hand [src/sign-hand-model.js](src/sign-hand-model.js) | Live | The practice half of the signing loop: the avatar forms the target letter, MediaPipe's hand landmarker watches the learner's hand in-tab, and the grader scores the handshape live, finger by finger, naming the finger that is off. Avatar pose, target diagram, and grading all read the same handshape spec ([src/sign-handshapes.js](src/sign-handshapes.js)) so taught and graded can never drift. The whole practice loop is on-device: no frame, landmark, or score is ever uploaded. Course rail orders the alphabet easiest-first with localStorage progress; shared sign prefs (hand, avatar) carry over from `/sign-language` and `/asl-alphabet`. Tests: [tests/sign-grader.test.js](tests/sign-grader.test.js) |
| ASL recognition (webcam signing → text) | worker [workers/model-asl-recognition/](workers/model-asl-recognition), API [api/asl-recognition.js](api/asl-recognition.js) (`GCP_ASL_RECOGNITION_URL`) | Live | The reverse direction of [sign speech](docs/sign-language.md): the browser extracts MediaPipe landmarks from the webcam (video never leaves the device) and the worker transcribes continuous ASL fingerspelling to text on CPU via LiteRT, with a decode-confidence score and an LLM cleanup pass on the API. Model: Kaggle 2023 ASLFR 1st-place (Apache-2.0 code + weights, FSboard CC BY 4.0 corpus, the license-clean chain most ASL models lack). Cloud Run gen2 + `patchelf --clear-execstack` on the LiteRT .so. Next: word-level signs (PopSign retrain). Tests: [test_decode.py](workers/model-asl-recognition/test_decode.py) (schema + decode, no weights) and [test_model_smoke.py](workers/model-asl-recognition/test_model_smoke.py) (real weights end to end, run inside the built image). |
| Smart home: the connect flow and household management | Page [pages/smart-home.html](pages/smart-home.html) `-> /smart-home` + controller [src/home/connect.js](src/home/connect.js), manage view [src/home/manage.js](src/home/manage.js), styles [src/home/home.css](src/home/home.css). Consumes [api/home/index.js](api/home/index.js) (`GET`/`POST /api/home`), [api/home/[id].js](api/home/[id].js), `/api/home/:id/grants` and `/api/home/:id/log`. Reachability rules shared with the server through the [@three-ws/home-bridge](packages/home-bridge) `./url` subpath export | Live | The front door of the Home lane: how a stranger gets from "I have a Home Assistant somewhere" to "my agent is connected", and every way that goes wrong. Twelve designed states rather than a happy path plus an error toast: signed out, empty, inline validation, the private-host refusal, verifying, connected, a rejected token, unreachable, degraded, disconnected, many homes, and the plan ceiling. Two rules hold the surface together. **The token goes to the server once and never comes back**: the field is `type=password` with a reveal toggle, it is never written to storage, never put in a URL, never logged and never echoed by the API, and it is gone from the DOM the moment a connect succeeds. **Reachability is decided in the browser, before the network**: a `192.168.x.x` or `.local` address is refused with zero network calls using the same `normalizeBaseUrl`/`isPrivateHost` the server validates with, so the two can never disagree and nobody waits out a timeout to be told something we knew at the first keystroke. Every string that came from a house (a label, an entity id, an area name) is rendered as `textContent`, because those are attacker-influenceable and there is a physical actuator on the other end. Docs: [docs/smart-home.md](docs/smart-home.md). Tests: [tests/e2e/home-connect.spec.js](tests/e2e/home-connect.spec.js) |
-| Smart home: plans, entitlements and quotas (`/smart-home/plan`) | Page [pages/smart-home-plan.html](pages/smart-home-plan.html) `-> /smart-home/plan` + controller [src/home/plan.js](src/home/plan.js), styles [src/home/plan.css](src/home/plan.css). Resolver [api/_lib/home/entitlements.js](api/_lib/home/entitlements.js), counters [api/_lib/home/usage.js](api/_lib/home/usage.js), endpoint [api/home/plan.js](api/home/plan.js). Enforced at [api/home/index.js](api/home/index.js) (acquisition), [api/home/[id]/stream.js](api/home/[id]/stream.js) (streams), [api/home/[id]/members.js](api/home/[id]/members.js) (seats), [api/home/[id]/call.js](api/home/[id]/call.js) (paused homes), [api/_lib/home/privacy.js](api/_lib/home/privacy.js) (retention ceiling). Cost measurement [scripts/measure-home-entitlement-cost.mjs](scripts/measure-home-entitlement-cost.mjs). Migration `api/_lib/migrations/20260903160000_home_plan_overrides.sql` | Live | What a plan covers for connected houses, and the two things no plan may ever refuse. **A limit never blocks a safety action:** over quota, downgraded or paused, locking a door, closing a garage or valve and arming an alarm always execute, checked before any counter is read and classified from the domain and service alone so the exemption never depends on a healthy socket. **Nothing about the gate is sold:** confirmations, the action log's integrity and every role safety property are on every tier and there is deliberately no dimension for any of them. Seven metered dimensions (homes, seats, streams, voice minutes, agent turns, log retention, relay connections), each carrying the measured cost that justifies it. **No fourth entitlement system:** limits resolve from `account-tier.js` badges merged by MAX (so holding $THREE never costs a Pro their Pro limits) and are scaled by the `three-tier.js` holder multiplier, never by thresholds of our own. **One counter:** an agent turn is the same priced `usage_events` chat row an invoice reads, tagged with `home_id`, not a second tally that could disagree. **A downgrade pauses, it never disconnects:** excess homes get `deactivated_at` with a written reason, the credential and the action log survive, `revoked_at` stays null, and the user swaps which houses are live. Enterprise limits are a `home_plan_overrides` row with the reason on it, not a tier. Every number is env-overridable (`HOME_LIMIT_<TIER>_<DIMENSION>`), so applying an owner-approved price is a config change. Docs: [docs/home-plans.md](docs/home-plans.md). Tests: [tests/home-entitlements.test.js](tests/home-entitlements.test.js) |
+| Smart home: plans, entitlements and quotas (`/smart-home/plan`) | Page [pages/smart-home-plan.html](pages/smart-home-plan.html) `-> /smart-home/plan` + controller [src/home/plan.js](src/home/plan.js), styles [src/home/plan.css](src/home/plan.css). Resolver [api/_lib/home/entitlements.js](api/_lib/home/entitlements.js), counters [api/_lib/home/usage.js](api/_lib/home/usage.js), endpoint [api/home/plan.js](api/home/plan.js). Enforced at [api/home/index.js](api/home/index.js) (acquisition), [api/home/[id]/stream.js](api/home/[id]/stream.js) (streams), [api/home/[id]/members.js](api/home/[id]/members.js) (seats), [api/home/[id]/call.js](api/home/[id]/call.js) (paused homes), [api/_lib/home/privacy.js](api/_lib/home/privacy.js) (retention ceiling), [api/_lib/home/turn-gate.js](api/_lib/home/turn-gate.js) called from [api/chat.js](api/chat.js) (agent turns). Cost measurement [scripts/measure-home-entitlement-cost.mjs](scripts/measure-home-entitlement-cost.mjs). Migration `api/_lib/migrations/20260903160000_home_plan_overrides.sql` | Live | What a plan covers for connected houses, and the two things no plan may ever refuse. **A limit never blocks a safety action:** over quota, downgraded or paused, locking a door, closing a garage or valve and arming an alarm always execute, checked before any counter is read and classified from the domain and service alone so the exemption never depends on a healthy socket. **Nothing about the gate is sold:** confirmations, the action log's integrity and every role safety property are on every tier and there is deliberately no dimension for any of them. Seven metered dimensions (homes, seats, streams, voice minutes, agent turns, log retention, relay connections), each carrying the measured cost that justifies it. **No fourth entitlement system:** limits resolve from `account-tier.js` badges merged by MAX (so holding $THREE never costs a Pro their Pro limits) and are scaled by the `three-tier.js` holder multiplier, never by thresholds of our own. **One counter:** an agent turn is the same priced `usage_events` chat row an invoice reads, tagged with `home_id`, not a second tally that could disagree. That row is also what the turn gate reads: over quota the agent refuses a home action, but read-only tools stay open (the model has to see which door is open before it can lock it) and safety actions are never reached by the gate at all. The gate **fails open**, so a billing read that hiccups serves the user rather than locking them out of their own house. **A downgrade pauses, it never disconnects:** excess homes get `deactivated_at` with a written reason, the credential and the action log survive, `revoked_at` stays null, and the user swaps which houses are live. Enterprise limits are a `home_plan_overrides` row with the reason on it, not a tier. Every number is env-overridable (`HOME_LIMIT_<TIER>_<DIMENSION>`), so applying an owner-approved price is a config change. Docs: [docs/home-plans.md](docs/home-plans.md). Tests: [tests/home-entitlements.test.js](tests/home-entitlements.test.js), [tests/home-turn-gate.test.js](tests/home-turn-gate.test.js), [tests/e2e/home-plan.spec.js](tests/e2e/home-plan.spec.js) |
| Smart home: the live 3D home (`/smart-home/:id`) | Page [pages/home-scene.html](pages/home-scene.html) `-> /smart-home/:id` and `-> /home/:id`, styles [public/home-scene.css](public/home-scene.css). Pure layout [src/home/scene-model.js](src/home/scene-model.js), WebGL renderer [src/home/scene-render.js](src/home/scene-render.js), the 2D house [src/home/scene-fallback.js](src/home/scene-fallback.js), page controller [src/home/scene.js](src/home/scene.js), the top-down floorplan editor the scene follows [src/home/floorplan.js](src/home/floorplan.js) with its validation and storage [api/_lib/home/layout.js](api/_lib/home/layout.js) behind `GET`/`PUT`/`DELETE /api/home/:id/layout` [api/home/[id]/layout.js](api/home/%5Bid%5D/layout.js), browser half of the API contract [src/home/api.js](src/home/api.js). Consumes `GET /api/home/:id`, the SSE stream [api/home/[id]/stream.js](api/home/%5Bid%5D/stream.js), [api/home/[id]/call.js](api/home/%5Bid%5D/call.js) and `/api/home/:id/grants` | Live | A live 3D model of the user's house, driven entirely by their own Home Assistant, with the agent's body standing in it. **Home Assistant stores no geometry**, so everything spatial is derived from its four flat registries by a PURE module with no Three.js in it: floors stack by level, rooms pack per floor in name order, and a saved floorplan overrides the packing through one `layout` option. That split is why the layout of a real recorded house is asserted in a unit test without a GPU. **A room is lit the way the room is lit**: colour and intensity from the lights that are actually on, genuinely dark when they are all off, and the outline around its footprint goes amber the moment anything in it is unlocked or open. **A room with sixty entities is not sixty objects**: objects are ranked (lights, locks, covers, climate, alarms, media, fans, cameras, the rest), capped per surface, and the remainder summarized; numeric sensors become readouts, never objects. A device Home Assistant cannot reach is drawn as a ghost with a marker, never omitted. **The house never empties**: a dropped connection greys the scene, keeps every room, and says how old it is. Stale (the platform is retrying) and disconnected (nobody is) are different pills, and only the second offers a button. **The 2D view is not a consolation prize**: same model, real rows and real buttons, reads and operates the whole house, and it is where a browser with no WebGL or a device measured below 18 fps is routed automatically, with the page saying so. A guarded action answers 409 and the question is rendered on the object it would move, with an optional standing allowance for that one entity. Measured: 86 ms median from a real Home Assistant service call to the SSE frame, 10 to 23 ms from that frame to the painted one, 0.1 to 0.3 ms of per-frame work, 108 draw calls, and a flat heap across ten minutes of live updates. Docs: [docs/home-scene.md](docs/home-scene.md). Tests: [tests/home-scene-model.test.js](tests/home-scene-model.test.js), [tests/e2e/home-scene.spec.js](tests/e2e/home-scene.spec.js) |
| three.ws Home privacy, retention, export and deletion | Inventory + purge + export + deletion [api/_lib/home/privacy.js](api/_lib/home/privacy.js), disclosure copy [api/_lib/home/disclosure.js](api/_lib/home/disclosure.js), endpoint [api/home/privacy.js](api/home/privacy.js) `-> /api/home/privacy`, schema [api/_lib/migrations/20260903180000_home_privacy_retention.sql](api/_lib/migrations/20260903180000_home_privacy_retention.sql), purge section E of [api/cron/db-retention.js](api/cron/db-retention.js) | Live | The single place that knows everything the Home lane stores. `INVENTORY` is not documentation of the code, it IS the code: the endpoint renders it, the export walks it, and [tests/home-privacy.test.js](tests/home-privacy.test.js) re-derives the set of `home_*` tables from the migration files and fails the build if one of them has no row, which is what stops an undocumented data class from ever landing. The load-bearing promise is that entity names and states are never persisted (the room graph lives in the bridge runtime's memory and dies with the instance); a second test fails any migration that creates a table shaped like a state history. The action log's window is per home and the owner's, 90 days by default, adjustable down to a day and up to ten years with a written reason the schema also enforces, applied immediately on change and swept by the platform's existing retention cron rather than a cron of its own. Deletion goes further than the cascades: memberships and grants on other people's homes, the departed user's id inside another household's action log, invitations addressed to their email, and the lane's rows in the 365-day `audit_log`. Docs: [docs/home-privacy.md](docs/home-privacy.md). Tests: [tests/home-privacy.test.js](tests/home-privacy.test.js) |
| Avatar thumbnail coverage | [api/_lib/avatar-thumbs.js](api/_lib/avatar-thumbs.js) + crons [api/cron/avatar-thumbnail-backfill.js](api/cron/avatar-thumbnail-backfill.js) (absent thumbnails, `*/5`) and [api/cron/avatar-thumbnail-render.js](api/cron/avatar-thumbnail-render.js) (stale marketplace thumbnails, `*/10`) | Live | The single owner of `avatars.thumbnail_key`. Enforces the invariant that a thumbnail key is persisted **only after** its R2 object is confirmed to exist — a key pointing at a missing object makes R2 return 404 `text/plain`, which Chrome blocks as `ERR_BLOCKED_BY_ORB` inside an `<img>`. Fills coverage cheapest-first: zero-copy adoption of `forge_creations.preview_key`, then a headless-chromium GLB→PNG render to `thumb/<avatarId>.png` ([api/_lib/render-glb.js](api/_lib/render-glb.js)). Bounded retries via the `avatar_thumbnail_backfill` claim ledger ([migration](api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql)), with `isBrowserInfrastructureError()` separating an OOM-killed browser from a genuinely broken model so a crash never retires healthy avatars. Bulk runner: [scripts/backfill-avatar-thumbnails.mjs](scripts/backfill-avatar-thumbnails.mjs) (`--status`, `--adopt-only`, `--loop`, `--reset-infra`). Docs: [docs/avatar-thumbnails.md](docs/avatar-thumbnails.md). Tests: [tests/avatar-thumbs.test.js](tests/avatar-thumbs.test.js), [tests/home-thumbnail-orb.test.js](tests/home-thumbnail-orb.test.js) |
diff --git a/api/_lib/home/entitlements.js b/api/_lib/home/entitlements.js
index eb44f9246..68e36c112 100644
--- a/api/_lib/home/entitlements.js
+++ b/api/_lib/home/entitlements.js
@@ -20,7 +20,12 @@
* the same turn on Claude Sonnet 5 → $0.0228
*
* The finding that number produces is worth stating plainly: **one agent turn on
- * a paid model costs more than a year of holding that house's socket.** The free
+ * a paid model costs weeks of holding that house's socket** ($0.0228 against
+ * $0.0155 a month, so about six weeks for one sentence). A re-measurement on
+ * 2026-09-09 reproduced the heap and stream figures and put resident memory
+ * higher, at $0.0738 per home per month; even there a Sonnet turn is nine days
+ * of socket, so the shape below holds across the range. See
+ * docs/home-plans.md. The free
* tier can therefore carry a genuinely connected home, and the limits below are
* generous on connections and careful on paid-model turns, which is the opposite
* of what the cost model looked like before it was measured.
@@ -151,7 +156,7 @@ export const HOME_DIMENSIONS = Object.freeze({
scalesWithHolding: true,
costPerUnitUsd: 0,
costBasis: 'the default provider chain leads with platform-held free lanes (isFreeLane in api/_lib/llm-pricing.js); the same 6,359-token home prompt costs $0.0025 on Vertex Gemini 2.5 Flash and $0.0228 on Claude Sonnet 5 when a paid model is chosen',
- why: 'The room graph makes a home prompt large. On a paid model one turn costs more than a year of holding that house’s socket, so the turn is the dimension that actually needs a ceiling.',
+ why: 'The room graph makes a home prompt large. On a paid model one turn costs weeks of holding that house’s socket, so the turn is the dimension that actually needs a ceiling.',
}),
logRetentionDays: Object.freeze({
id: 'logRetentionDays',
@@ -428,6 +433,42 @@ export async function resolveHomeEntitlementsForUser(userId) {
return resolveHomeEntitlements(user, { walletAddresses: wallets });
}
+/**
+ * The account's limits WITHOUT reading the chain: the floor below which no
+ * holder standing can matter.
+ *
+ * `detectHolder` is an on-chain balance read. It is 60-second cached and it is
+ * fine on a page load, but the agent-turn gate runs inside a chat turn, and
+ * putting a Solana RPC on that path to answer a question that is almost always
+ * "yes, obviously" would be a real latency regression for every user who talks
+ * to their house.
+ *
+ * It is skippable because of an ordering property in `computeEntitlements`: the
+ * holder multiplier is `Math.max(1, ...)`, so it only ever RAISES a limit, and a
+ * per-account override is applied AFTER it and therefore lands identically in
+ * both paths. So this floor is always less than or equal to the real limit, and
+ * a caller that is inside the floor is inside the real limit too. A caller that
+ * is NOT inside the floor has to do the full read, because that is exactly the
+ * account whose holding might be the thing that saves them.
+ *
+ * @param {string} userId
+ * @returns {Promise<object>} the same shape as resolveHomeEntitlements, holder-free
+ */
+export async function resolveHomeEntitlementsFloor(userId) {
+ const rows = await withDbRetry(() => sql`
+ select id, plan, account_tier, wallet_address
+ from users
+ where id = ${userId} and deleted_at is null
+ limit 1
+ `);
+ const user = rows[0];
+ if (!user) throw new Error('resolveHomeEntitlementsFloor: no such account');
+
+ const override = await getAccountOverride(userId).catch(() => null);
+ const resolved = computeEntitlements(user, { override: override?.limits || null });
+ return { ...resolved, override };
+}
+
// ── Per-account overrides ────────────────────────────────────────────────────
/**
diff --git a/api/_lib/home/turn-gate.js b/api/_lib/home/turn-gate.js
index cac416254..cbb61eef1 100644
--- a/api/_lib/home/turn-gate.js
+++ b/api/_lib/home/turn-gate.js
@@ -22,6 +22,7 @@ import {
HomeQuotaError,
isQuotaExempt,
quotaPeriod,
+ resolveHomeEntitlementsFloor,
resolveHomeEntitlementsForUser,
} from './entitlements.js';
import { readUsage } from './usage.js';
@@ -78,16 +79,26 @@ export function homeCallShape(call) {
* @returns {Promise<{ allowed: boolean, error: HomeQuotaError|null }>}
*/
export async function homeTurnGate(userId, deps = {}) {
- const resolve = deps.resolveHomeEntitlementsForUser || resolveHomeEntitlementsForUser;
+ const resolveFull = deps.resolveHomeEntitlementsForUser || resolveHomeEntitlementsForUser;
+ const resolveFloor = deps.resolveHomeEntitlementsFloor || resolveHomeEntitlementsFloor;
const read = deps.readUsage || readUsage;
+ const resetAt = quotaPeriod().endIso;
try {
- const [entitlements, used] = await Promise.all([resolve(userId), read(userId, 'agentTurns')]);
- assertWithinLimit({
- entitlements,
- dimension: 'agentTurns',
- used,
- resetAt: quotaPeriod().endIso,
- });
+ // The cheap pass first: no chain read, and it settles almost every turn.
+ // The floor can only be lower than the real limit, so an account inside it
+ // is inside the real one and nothing further needs to be known.
+ const [floor, used] = await Promise.all([resolveFloor(userId), read(userId, 'agentTurns')]);
+ try {
+ assertWithinLimit({ entitlements: floor, dimension: 'agentTurns', used, resetAt });
+ return { allowed: true, error: null };
+ } catch (err) {
+ if (!(err instanceof HomeQuotaError)) throw err;
+ }
+
+ // Past the floor. THIS is the account whose $THREE standing might be the
+ // thing that raises the ceiling, so now the chain read is worth paying for.
+ const entitlements = await resolveFull(userId);
+ assertWithinLimit({ entitlements, dimension: 'agentTurns', used, resetAt });
return { allowed: true, error: null };
} catch (err) {
if (err instanceof HomeQuotaError) return { allowed: false, error: err };
diff --git a/data/changelog.json b/data/changelog.json
index d2495d56a..7ff5822b4 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -21,7 +21,7 @@
{
"date": "2026-09-09",
"title": "Your monthly agent turns now count, and locking up never does",
- "summary": "Talking to the agent about your house is the one part of the smart-home lane that can really cost money: the room graph makes a home prompt large, and on a paid model a single turn costs more than a year of holding that house’s connection open. Those turns were being counted but never actually limited. They are now, against the monthly allowance shown on your plan page, and if you run out the agent says so in a sentence that names the limit, the date it resets and where to raise it, instead of failing at you. Two things are deliberately left outside that limit. Asking the agent what the house is doing still works, because you have to be able to see which door is open. And telling it to lock a door, close a garage or a valve, or arm the alarm still runs, over quota, on a paused home, in every state we can put an account in: the safe direction is free, always, on every plan. If our own billing lookup fails, the turn is allowed through rather than refused.",
+ "summary": "Talking to the agent about your house is the one part of the smart-home lane that can really cost money: the room graph makes a home prompt large, and on a paid model a single turn costs several weeks of holding that house’s connection open. Those turns were being counted but never actually limited. They are now, against the monthly allowance shown on your plan page, and if you run out the agent says so in a sentence that names the limit, the date it resets and where to raise it, instead of failing at you. Two things are deliberately left outside that limit. Asking the agent what the house is doing still works, because you have to be able to see which door is open. And telling it to lock a door, close a garage or a valve, or arm the alarm still runs, over quota, on a paused home, in every state we can put an account in: the safe direction is free, always, on every plan. If our own billing lookup fails, the turn is allowed through rather than refused.",
"tags": [
"feature",
"improvement"
diff --git a/docs/home-plans.md b/docs/home-plans.md
index fc25177aa..ea846b71f 100644
--- a/docs/home-plans.md
+++ b/docs/home-plans.md
@@ -69,9 +69,21 @@ from a remembered figure. The production service shape comes from
Two findings inverted the assumptions this work started from, and both are worth stating plainly
because they point the pricing in the opposite direction:
-**One agent turn on a paid model costs more than a year of holding that house's socket.**
-$0.0228 against $0.0155 per month. The connection is not the expensive part after all; the prompt
-is, because the room graph makes a home prompt large.
+**One agent turn on a paid model costs weeks of holding that house's socket.** $0.0228 for a
+single Claude Sonnet 5 turn, against $0.0155 per home per month: about six weeks of connection for
+one sentence. The connection is not the expensive part after all; the prompt is, because the room
+graph makes a home prompt large.
+
+That ratio was re-measured on 2026-09-09 against a second real Home Assistant and it does not come
+back identical, so the honest version is a range rather than a point. The heap figure reproduces
+almost exactly (309 KB marginal per connection against the original 302 KB) and the stream figure
+reproduces to the cent, but resident memory does not: 1.25 MB marginal per connection against the
+original 262 KB, which prices a home at **$0.0738/month** instead of $0.0155. The re-measurement ran
+on a machine at load 83 with several other agents building, and RSS under memory pressure includes
+a great deal that is not attributable to the connection, so $0.0155 remains the figure to price from
+and $0.0738 is a defensible upper bound. Priced at the upper bound a Sonnet turn still costs
+**nine days** of holding the socket, so the conclusion below is unchanged at either end of the
+range, which is the only reason this is a footnote and not a re-plan.
**Voice is not a cost driver at all.** The default speech lanes are keyless and cost the platform
nothing per utterance. Voice minutes are metered because an unbounded always-listening satellite is
@@ -81,7 +93,9 @@ money.
### Can the free tier carry a connected home?
**Yes, comfortably.** At 1.6 cents per home per month, ten thousand free connected homes cost
-about $155 a month, which is roughly one warm Cloud Run instance. The honest constrained free tier
+about $155 a month, which is roughly one warm Cloud Run instance. At the loaded-machine upper bound
+above the same ten thousand homes cost about $740 a month, which is still a rounding error against
+the credit grant and still does not change the answer. The honest constrained free tier
some cost models would have forced (a session-scoped connection that closes when the tab does) is
not necessary and would make the free tier worse for no saving worth having. The free tier gets a
real, persistent, always-connected home.
@@ -248,9 +262,37 @@ user can predict, and it is shown on the plan page with that date.
| Seats | [`api/home/[id]/members.js`](../api/home/%5Bid%5D/members.js) | an invitation past `members`, counting outstanding invites as well as members, billed to the home's **owner** |
| Retention | [`api/_lib/home/privacy.js`](../api/_lib/home/privacy.js) | raising retention past the plan's ceiling. Never applied retroactively |
| Actions | [`api/home/[id]/call.js`](../api/home/%5Bid%5D/call.js) | an ordinary action on a paused home. **The safety exemption is checked first**, so a safety action is never reached by this code |
+| Agent turns | [`api/_lib/home/turn-gate.js`](../api/_lib/home/turn-gate.js), called from [`api/chat.js`](../api/chat.js) | a home tool the agent tried to run past `agentTurns`. Read-only tools are never gated and safety actions are never gated, so over quota the agent can still be asked what the house is doing and told to lock up |
Ordinary service calls are **not** metered at all. Actions are cheap; the socket is the cost. A
-user can run twenty lights all evening without touching a quota.
+user can run twenty lights all evening without touching a quota. What is metered is the *agent
+turn* that drives them, because on a paid model one turn costs weeks of holding that house's
+socket.
+
+Two deliberate holes in the agent-turn gate, both of which exist so commitment 1 survives contact
+with a real conversation rather than only with a unit test:
+
+* **Read-only home tools are never gated.** The agent finds the door by reading the house
+ (`home_status`) and only then targets the lock. Gate the read and the safety exemption ends one
+ step before it was needed. A read also spends nothing the turn had not already spent by the time
+ the model emitted the call.
+* **A safety action inside a gated tool is never refused.** `home_call` carries its domain and
+ service on the input, which is exactly what the safety classifier reads, so a lock, a close or an
+ arm is recognised with no live entity list and therefore in precisely the degraded states where
+ somebody most needs to lock up.
+
+The gate also **fails open**. An unreadable entitlement row or an unreachable usage counter
+resolves to "allowed", never to "refused": a quota that errs must err toward serving the user, and
+refusing a person access to their own house over a billing hiccup is the failure this lane is least
+willing to ship.
+
+And it resolves in **two passes**, so it does not put a Solana RPC on the chat critical path.
+`resolveHomeEntitlementsFloor` answers without reading the chain; because the $THREE multiplier is
+`Math.max(1, ...)` it can only ever raise a limit, so an account inside the floor is inside its real
+limit and nothing further needs to be known. Only an account that is PAST the floor pays for the
+full read, which is exactly the account whose holding might be the thing that raises its ceiling.
+A per-account override is applied after the multiplier in both passes, so it lands identically in
+each and the floor is never wrong about an enterprise row.
There is also a separate, unrelated ceiling: the per-instance backpressure ladder in
[`api/_lib/home/admission.js`](../api/_lib/home/admission.js). That answers "is this instance
diff --git a/prompts/finish/_context/home-PROGRESS.md b/prompts/finish/_context/home-PROGRESS.md
index 70bf3b33f..f2df6862a 100644
--- a/prompts/finish/_context/home-PROGRESS.md
+++ b/prompts/finish/_context/home-PROGRESS.md
@@ -48,7 +48,7 @@ One section per finished order, newest at the bottom:
| 16 test program | open | |
| 17 a11y, i18n, mobile | open | |
| 18 docs and SDK | docs done, npm publish owner-gated | 2026-09-03 |
-| 19 plans and entitlements | open | |
+| 19 plans and entitlements | built and verified, browser journeys queued, price owner-gated | 2026-09-09 |
| 20 launch readiness | standing | |
| 21 Matter direct | done, documented negative | 2026-09-03 |
@@ -1110,3 +1110,113 @@ standalone at HEAD. Left to their authors, who are mid-lane, rather than edited
**Commits:** `ac390203d` carries `tests/home-confirm-endpoint.test.js`; it was swept into a
peer's `git add -A` before this session could stage it, under an accurate message. This entry
is its own commit.
+
+---
+
+## 19. Plans, entitlements and quotas (2026-09-09)
+
+**Shipped:** most of this order was already in the tree, written on 2026-09-03 and swept into a
+peer's `git add -A` under an unrelated message (`2849cafb6`, "chore(scripts): add the EPA
+fuel-economy probe"), which is why nothing recorded it and the order file was never retired.
+`api/_lib/home/entitlements.js` (the resolver, the safety exemption, the downgrade path, the
+override row, `describeEntitlements`), `api/_lib/home/usage.js` (counters over the existing
+`usage_events`), `api/home/plan.js`, `src/home/plan.js`, the `home_plan_overrides` migration and
+`docs/home-plans.md` were all there and all correct. This session verified every line of the
+order's Definition of Done against real infrastructure rather than assuming, and closed the two
+gaps that verification found.
+
+**Gap 1, closed: the metered lanes were metered but not enforced.** `agentTurns` was counted
+(api/chat.js stamps `home_id` into the priced `usage_events` chat row it already writes) and
+never gated: nothing in the tree called a quota check before running a home tool. New
+`api/_lib/home/turn-gate.js` holds that gate and `api/chat.js` calls it from `runHomeRound`. Two
+holes in it are deliberate and both exist so commitment 1 survives a real conversation rather than
+only a unit test: read-only home tools are never gated (the model reads the house to find the
+door, then targets the lock; gate the read and the safety exemption ends one step before it was
+needed), and a safety action inside a gated tool is never refused (`home_call` carries its domain
+and service on the input, which is what the classifier reads, so a lock is recognised with no live
+entity list). The gate fails open on any read failure and resolves in two passes so it does not put
+a Solana RPC on the chat critical path: `resolveHomeEntitlementsFloor` answers without reading the
+chain, and because the $THREE multiplier is `Math.max(1, ...)` it can only raise a limit, so an
+account inside the floor is inside its real limit. Only an account past the floor pays for the full
+read, which is exactly the account whose holding might save it.
+
+**Gap 2, closed: a false number was load-bearing.** The header of `entitlements.js` and
+`docs/home-plans.md` both stated that "one agent turn on a paid model costs more than a year of
+holding that house's socket", citing "$0.0228 against $0.0155 per month". That is 1.5 months, not
+a year: the comparison had lost a factor of twelve, and it was the stated justification for the
+whole shape of the tier table. Corrected to "weeks" in both files, in the `agentTurns` dimension's
+`why` string, and in the changelog entry written for this order. The qualitative conclusion the
+number was used to support (turns are the dimension worth capping, connections are cheap enough to
+give the free tier a real one) survives the correction and survives the re-measurement below, which
+is the only reason this was a correction and not a re-plan.
+
+**`voiceMinutes` is recorded but has no caller yet, on purpose.** `recordHomeUsage` is built,
+tested and proven against the live database, but order 08 (voice loop) is still open, so there is
+no voice lane to call it from. The dimension is wired end to end and the call site lands with 08.
+
+**Measured** (real Neon, a real Home Assistant 2026.9.0 on the `plan19` container, 125 entities):
+
+- `npx vitest run tests/home-entitlements.test.js`: **55 passed, 0 skipped** with `DATABASE_URL`
+ set (50 passed / 5 skipped without it: the 5 live blocks refuse to run against a mock).
+- `tests/home-turn-gate.test.js`, new: **18 passed**, covering the four safety domains, the unsafe
+ direction of each, the read-only exemption, both fail-open paths and the two-pass fall-through.
+- `tests/api-home-contract.test.js`: **44 passed**, up from 42 passed / 2 failed. Both failures
+ were pre-existing and are fixed at root cause, not masked: the file's `vi.mock` of
+ `api/_lib/auth.js` listed its exports by hand, so the day `api/_lib/home/access.js` started
+ calling `hasScope` two tests failed with "No hasScope export is defined on the mock", which reads
+ as a handler bug. The mock now spreads `importOriginal()`. That exposed a second staleness: a
+ fixture granting a bare `home` scope where acting requires `home:act`, so the real `hasScope`
+ correctly refused it. Fixture corrected.
+- **The three safe actions, over quota AND on a paused home**, driven through `runHomeTool` against
+ the real house with every dimension overridden to 0: `lock.lock` unlocked -> locked,
+ `cover.close_cover` opening -> closing, `alarm_control_panel.alarm_arm_away` disarmed -> arming.
+ All three `ok=true`, all three verified by reading the state back out of Home Assistant. In the
+ same moment on the same account, `lock.unlock` returned a pending confirmation rather than
+ running, and the door stayed locked.
+- **The acquisition refusal, end to end over HTTP** against a real server on :8163 with a real
+ logged-in session: the first home connects `HTTP 201`, the second returns **`HTTP 402`** with
+ `quota_exceeded`, the limit, the usage, the tier and `upgrade: /pricing`. Not a 500.
+- **The override, on the same running server with no restart and no code change:** writing
+ `{ homes: 25 }` to `home_plan_overrides` turned that same 402 into a 502 `unreachable`, which is
+ the request getting past the quota gate and failing on the deliberately fake hostname behind it.
+- **The downgrade:** 4 connected homes, limit 1. Three paused, `revoked_at` null on all four,
+ `access_token_enc` intact on all four, **row count 4 before and 4 after, zero deleted**. Resuming
+ the fourth was refused while no slot was free, and succeeded after the user paused a different
+ house. The explanation string is rendered in full in the session transcript.
+- **Counter accuracy:** 20 real service calls and 3 voice turns produced 20 `home_action_log` rows,
+ 20 `usage_events` chat rows carrying `home_id`, and 3 `home.voice` rows; `readHomeUsage` reported
+ `agentTurns: 20, voiceMinutes: 3`. Both exact.
+- **The gate is unaffected by tier:** a free-tier account (`user`, badges `user`) got the same
+ pending confirmation on an unlock and a full-fidelity action log.
+- **Cost re-measured** with `scripts/measure-home-entitlement-cost.mjs` against a second real
+ instance: marginal heap per connection **309 KB** (original: 302 KB) and the stream figure
+ **$0.0066/month** reproduce; resident memory does not, at **1.25 MB** marginal against the
+ original 262 KB, pricing a home at **$0.0738/month** instead of $0.0155. The re-measurement ran at
+ load 83 with several agents building concurrently and RSS under memory pressure includes much that
+ is not the connection, so $0.0155 stays the figure to price from and $0.0738 is a defensible upper
+ bound. At either end a Sonnet turn costs between nine days and six weeks of socket, so the free
+ tier still comfortably carries a real connected home. Both figures and the caveat are now in
+ `docs/home-plans.md`.
+- `npm run check:rules -- --paths <the 9 files touched>`: clean. `npm run audit:docs`: clean
+ (1586 files). `npm run db:status`: nothing pending.
+- Full `npx vitest run --root .`, sharded into quarters: **41 failures across 4 shards, none in
+ this lane and none mine.** Verified by checking out HEAD into a throwaway worktree and running a
+ representative sample there: the same files fail identically without any of this session's
+ changes. They are peers' in-flight work (for example a committed `check:windows-widget` gate step
+ that `data/guards.json` does not register) plus env-dependent suites. Left alone rather than
+ fixed: none of them block this lane and editing a peer's live work would collide.
+
+**Deviations:** the order asked for a proposal table and got one that already existed and is good;
+it was corrected rather than rewritten. The order also implies `voiceMinutes` enforcement, which
+cannot exist before order 08 ships the lane that spends them.
+
+**Left open:** the two browser journeys in `tests/e2e/home-plan.spec.js` are written and queued but
+have not executed: the machine has sat at load 50-85 all session with three concurrent agents
+running Playwright and Cloud builds, and order 07 already lost its browser verification to exactly
+this. Until they run, the screenshot line of this order's Definition of Done is unmet. Re-run with
+`HOME_E2E_API_PORT=<free> HOME_E2E_WEB_PORT=<free> HOME_LIVE=1 HOME_LIVE_NAME=plan19 npx playwright
+test --config playwright.home.config.js tests/e2e/home-plan.spec.js` when the box is quiet.
+Everything below the browser is verified against real infrastructure. **The price itself is the
+owner's, and is the one thing this order was never allowed to decide:** the mechanism is complete
+and every number is a config value (`HOME_LIMIT_<TIER>_<DIMENSION>` on the running service), so
+applying an approved price is an env change, not a deploy.
diff --git a/tests/api-home-contract.test.js b/tests/api-home-contract.test.js
index 889083aa2..82ce84c16 100644
--- a/tests/api-home-contract.test.js
+++ b/tests/api-home-contract.test.js
@@ -67,7 +67,14 @@ vi.mock('../api/_lib/home/runtime.js', () => runtime);
const sessionUser = vi.fn();
const bearerUser = vi.fn();
-vi.mock('../api/_lib/auth.js', () => ({
+// Spread the real module rather than listing its exports. This mock only needs
+// to control who the caller is; everything else auth.js exports is pure logic
+// the handlers under test should run for real. Listing exports by hand meant
+// that the day api/_lib/home/access.js started calling `hasScope`, two contract
+// tests failed with "No hasScope export is defined on the mock", which reads as
+// a handler bug and is a stale mock.
+vi.mock('../api/_lib/auth.js', async (importOriginal) => ({
+ ...(await importOriginal()),
getSessionUser: (...a) => sessionUser(...a),
authenticateBearer: (...a) => bearerUser(...a),
extractBearer: (req) => {
@@ -387,7 +394,10 @@ describe('POST /api/home/:id/call, the gate', () => {
it('meters an agent principal separately in the log', async () => {
sessionUser.mockResolvedValue(null);
- bearerUser.mockResolvedValue({ userId: USER_A, scope: 'home' });
+ // `home:act`, not a bare `home`: acting is its own scope, and this fixture
+ // is about how an agent principal is METERED, not about whether an
+ // under-scoped token may act. That refusal has its own test.
+ bearerUser.mockResolvedValue({ userId: USER_A, scope: 'home:act' });
checkout(mkBridge());
await homeCall(mkReq({
method: 'POST', query: { id: HOME_ID }, headers: { authorization: 'Bearer tok' },
diff --git a/tests/home-turn-gate.test.js b/tests/home-turn-gate.test.js
index 3d3451317..5b086ad02 100644
--- a/tests/home-turn-gate.test.js
+++ b/tests/home-turn-gate.test.js
@@ -87,14 +87,43 @@ describe('the gate resolves a verdict', () => {
it('allows an account inside its limit', async () => {
const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(1000),
resolveHomeEntitlementsForUser: async () => entitlements(1000),
readUsage: async () => 999,
});
expect(gate).toEqual({ allowed: true, error: null });
});
+ it('never reads the chain for a turn the floor already allows', async () => {
+ // The floor pass is holder-free. Putting a Solana balance read on the chat
+ // critical path for a turn that is obviously inside the limit would be a
+ // latency regression for every user who talks to their house.
+ const full = vi.fn(async () => entitlements(1000));
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(1000),
+ resolveHomeEntitlementsForUser: full,
+ readUsage: async () => 10,
+ });
+ expect(gate.allowed).toBe(true);
+ expect(full).not.toHaveBeenCalled();
+ });
+
+ it('falls through to the full read when the floor is not enough, and a holder is saved by it', async () => {
+ // Past the free floor, but this account holds $THREE and the ladder's
+ // multiplier raises the ceiling. The floor pass must not refuse them.
+ const full = vi.fn(async () => entitlements(4000));
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(1000),
+ resolveHomeEntitlementsForUser: full,
+ readUsage: async () => 1500,
+ });
+ expect(gate.allowed).toBe(true);
+ expect(full).toHaveBeenCalledOnce();
+ });
+
it('refuses the turn that would cross the limit, and says how to fix it', async () => {
const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(1000),
resolveHomeEntitlementsForUser: async () => entitlements(1000),
readUsage: async () => 1000,
});
@@ -108,6 +137,7 @@ describe('the gate resolves a verdict', () => {
it('never refuses an unlimited plan', async () => {
const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(UNLIMITED),
resolveHomeEntitlementsForUser: async () => entitlements(UNLIMITED),
readUsage: async () => 10_000_000,
});
@@ -117,6 +147,7 @@ describe('the gate resolves a verdict', () => {
it('FAILS OPEN when the entitlement read throws', async () => {
const onError = vi.fn();
const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => { throw new Error('neon is down'); },
resolveHomeEntitlementsForUser: async () => { throw new Error('neon is down'); },
readUsage: async () => 0,
onError,
@@ -127,6 +158,7 @@ describe('the gate resolves a verdict', () => {
it('FAILS OPEN when the usage counter is unreachable', async () => {
const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsFloor: async () => entitlements(10),
resolveHomeEntitlementsForUser: async () => entitlements(10),
readUsage: async () => { throw new Error('redis and postgres both refused'); },
onError: () => {},