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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(home): complete the campaign from the 3D surface through launch readiness
nirholascc2f25d0a6b1
diff --git a/prompts/README.md b/prompts/README.mdindex 1a1ffcd75..13a1ecd4e 100644--- a/prompts/README.md+++ b/prompts/README.md@@ -60,6 +60,7 @@ state measured on 2026-09-01; trust the directory, never this table.| `fable-audit-` | The 2026-07-11 deep audit. Every numbered finding shipped; [RESIDUALS.md](finish/fable-audit-RESIDUALS.md) is the one file left, carrying the three items deliberately left open plus the pack's history. || `fix-queue-` | Defects reproduced on 2026-08-01 by running the repo's own checks (`gate`, `lint`, `audit:links`, `audit:tour-atlas`, `check:cron-drift`, `check:runnable-docs`, `test:core`) plus a production probe, each carrying the verbatim output. Seven of eight shipped; the one left is the garment-sweep cron, blocked on an owner `gcloud auth login`. || `gcp-credits-` | The GCP credit program. Seven of eight shipped; [the catalog and animation seeding order](finish/gcp-credits-05-catalog-animation-seeding.md) is the open one, turning credits into a curated catalog and a generated motion library. |+| `home-` | three.ws Home: an agent that runs a real house by voice, with a 3D body standing in a live model of it. Home Assistant owns the device layer (we write no device code), and the campaign builds everything above it: the encrypted connection store, the multi-tenant bridge runtime, the `/api/home/*` surface, the agent tools and the confirmation gate that a model cannot satisfy, the live 3D home and its floorplan editor, the browser voice loop, three.ws as a Home Assistant voice satellite, the dial-out add-on for LAN-only houses, then security, households and roles, observability, scale, privacy, the test program, a11y and 87 locales, docs and SDK publish, entitlements, and a standing go/no-go. Twenty-one orders over a shared context file, plus one horizon order for Matter. The client library and the investigation ([../docs/smart-home.md](../docs/smart-home.md), [../packages/home-bridge/](../packages/home-bridge)) landed before the campaign; nothing is wired into the product yet. || `materialize-` | The physical lane: any forge creation to a high-precision 3D print delivered to a door. Printability engine (analyze/repair/STL/color-3MF), quote + order + Solana USDC checkout incl. the x402 agent lane, the /materialize surface with true-scale AR, fulfillment adapters + operator console, on-chain print certificates with editions and QR provenance, fabrication content gate. Six orders over a shared context file; launches on a manual-fulfillment adapter, no partner dependency. || `okx-ai-` | Taking the three.ws 3D Studio listing (agent #2632) to approved status on OKX.AI. Three open orders (real-payment gauntlet, relisting, final audit and launch) plus a runbook. Each batches its OTP and funding needs into one owner message. || `openai-pr-` | The OpenAI Apps SDK submission pack. Briefs 01 to 05 shipped; 06 (the tool count drifted to 11 across the kit) and 07 (the go/no-go, never run) remain, with the portal submit owner-only. |diff --git a/prompts/finish/home-04-agent-tools.md b/prompts/finish/home-04-agent-tools.mdindex a8932fa1d..f80ab1611 100644--- a/prompts/finish/home-04-agent-tools.md+++ b/prompts/finish/home-04-agent-tools.md@@ -36,7 +36,7 @@ grep -n "SCOPES\|export const" api/_lib/oauth-scopes.js | head -20All three must call **one** handler module so they cannot diverge on the gate. Build`api/_lib/home/tools.js` with the handlers, and let the three surfaces be thin adapters over it.-This is the same discipline `api/sim-readiness.js` uses over its MCP tool handler.+This is the same discipline [`api/provenance.js`](../../api/provenance.js) uses over its MCP tool handler in [`api/_mcp3d/tools/provenance.js`](../../api/_mcp3d/tools/provenance.js); read that pair before you start.## The tool setdiff --git a/prompts/finish/home-05-connect-flow.md b/prompts/finish/home-05-connect-flow.mdnew file mode 100644index 000000000..d473725b3--- /dev/null+++ b/prompts/finish/home-05-connect-flow.md@@ -0,0 +1,137 @@+# 05. The connect flow: `/home` onboarding, every state++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Order+[03](home-03-api-surface.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated. Start the dev server and exercise this in a real browser; a UI+order that was never opened is not done.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+npm run dev & # port 3000+curl -s localhost:3000/api/home -H "cookie: <dev session>" | head -c 300+grep -n "materialize" vercel.json | head -4 # the page-route pattern to copy+ls pages/ | grep -E "materialize|agent-detail" ; ls src/ | grep -E "materialize|agent-detail"+grep -n "^--" public/tokens.css | head -20 # the vocabulary you must use+```++## What this order owns++Getting a stranger from "I have a Home Assistant somewhere" to "my agent is connected", and+every way that goes wrong. It owns no 3D (order 06) and no voice (order 08).++Route `/home` via a `vercel.json` `routes` entry to `pages/home.html`, controller `src/home/connect.js`.+Follow the `/materialize` precedent exactly: a `routes` entry, a page file, a module in `src/`.++## The flow++1. **Signed out**: the value proposition and a sign-in, not a form that will fail.+2. **No home yet**: the connect card. Two fields, base URL and token, plus a link to the exact+ Home Assistant path for minting one (Profile, Security, Long-lived access tokens, Create+ token). Never make the user search for it.+3. **URL typed**: validate client-side with `normalizeBaseUrl` and `isPrivateHost` from+ `@three-ws/home-bridge`, **before** any network call, and say the true thing immediately:+ a `192.168.x.x` or `.local` address cannot be reached by three.ws. Offer the two real paths+ (a remote https URL now, or the add-on from order 10 when it lands) rather than a dead end.+4. **Verifying**: a real progress state naming what is happening ("opening a connection",+ "reading your rooms"), never a bare spinner and never a fake progress bar.+5. **Connected**: the house summarised. Rooms found, entities found, whether `mcp_server` is on+ and how many tools it exposes, the Home Assistant version. All measured, never assumed.+6. **Managing**: the list of homes, per-home status, the standing allowances with a revoke on+ each, the action log, and a disconnect that says plainly what it does to the stored token.++## Every state you must build++There are eleven, and a missing one is what makes a product feel unfinished. Each gets a+designed treatment using `public/tokens.css` primitives:++| # | State | Must |+|---|---|---|+| 1 | Signed out | explain the feature, offer sign-in, never a disabled form |+| 2 | Empty (no homes) | the connect card, with the token instructions inline |+| 3 | Validating input | inline, immediate, before the network |+| 4 | Private-host refusal | name the address class and give the two real options |+| 5 | Verifying | named steps, skeleton not spinner, cancellable |+| 6 | Connected | the measured summary, and a clear next action into `/home/:id` |+| 7 | `auth` failure | "create a new long-lived token", with the path, and the field refocused |+| 8 | `unreachable` failure | distinguishes "wrong address" from "house offline", offers a retry and the add-on path |+| 9 | Degraded (connected, breaker open, or stale) | the last known state visibly marked stale with its age, never an empty house |+| 10 | Revoked / disconnected | says the stored credential was scrubbed, offers reconnect |+| 11 | Many homes | the list scales past one without a redesign; long labels truncate without breaking layout |++## Quality bar (non-negotiable)++- Every interactive element has hover, active, focus-visible and disabled states.+- Keyboard: the whole flow is completable without a mouse. Focus moves to the error on failure.+- The token field is `type="password"` with a reveal toggle, `autocomplete="off"`, and is never+ written to `localStorage`, never logged, never put in a URL, and never echoed back by the API.+- Nothing shifts layout when async data lands. Reserve the space.+- 320px, 768px and 1440px all work. Test all three.+- Every user-supplied string (the label, entity names, area names) is rendered as text, never as+ HTML. This is the same untrusted-input rule as order 04, on the render side.+- Copy is plain language. "Your home is only on your local network" beats "ERR_PRIVATE_HOST".++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | Route and page shell, wired into `data/pages.json` so it is discoverable. | `vercel.json`, `pages/home.html`, `data/pages.json` |+| 2 | The connect controller with all eleven states. | `src/home/connect.js`, `src/home/home.css` |+| 3 | Client-side reachability validation using the published package, so the same logic runs both sides. | same |+| 4 | The manage view: list, status, grants with revoke, action log, disconnect. | `src/home/manage.js` |+| 5 | i18n: every string through the existing extraction path (`npm run i18n:extract`). | as generated |+| 6 | Playwright e2e covering the happy path and at least four failure states. | `tests/e2e/home-connect.spec.js` |+| 7 | Docs and changelog. | `docs/smart-home.md`, `data/changelog.json`, `STRUCTURE.md` |++## Definition of done++- [ ] Screenshots of all eleven states at 1440px, and states 2, 5, 6 and 8 at 320px.+- [ ] A real connect against a real local Home Assistant, in a real browser, with the network tab showing the real `POST /api/home/connect` and its real response.+- [ ] A private-host address produces the designed refusal with no network call. Prove it with an empty network tab.+- [ ] A wrong token produces state 7 with the field refocused, not a generic error.+- [ ] Stopping the Home Assistant container puts a connected home into state 9 with a visible staleness age, and the room list stays on screen.+- [ ] Zero console errors and zero console warnings from your code, on every state.+- [ ] `npm run audit:web` passes for `/home` (see `docs/ops/page-audit.md`; use `audit:web:login` first for the authed sweep).+- [ ] Keyboard-only completion of the connect flow, recorded as a step list in your report.+- [ ] `npx playwright test tests/e2e/home-connect.spec.js` passes.+- [ ] The token never appears in `localStorage`, in a URL, in a console line, or in any API response. Prove each with the command you used.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| No Home Assistant to connect to | Run one; the docker command is in the context file. Never build a UI against a fixture and call it verified. |+| No QA login | `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env`, or `npm run audit:web:provision` to create one through the real register page. |+| A state is hard to reproduce | Force it: stop the container for state 9, use a junk token for 7, use `192.168.1.10` for 4. Every state here is reachable in under a minute. |+| Tempted to store the token client-side "to make reconnect easier" | Refuse. It goes to the server once, encrypted at rest, and never comes back. |+| The design feels sparse | Read `DESIGN-TOKENS.md` and a shipped surface (`/materialize`) before inventing anything. Consistency beats novelty here. |++## Report format++1. The screenshot set (eleven states, plus the four mobile ones).+2. The real connect transcript from the browser network tab.+3. The no-network-call proof for the private-host refusal.+4. The keyboard-only walkthrough.+5. The four token-leak proofs.+6. `audit:web`, Playwright and `check:rules` output.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-05-connect-flow.md++Never delete it on a partial.diff --git a/prompts/finish/home-06-3d-home-scene.md b/prompts/finish/home-06-3d-home-scene.mdnew file mode 100644index 000000000..ae0f2f0cd--- /dev/null+++ b/prompts/finish/home-06-3d-home-scene.md@@ -0,0 +1,144 @@+# 06. The live 3D home++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[03](home-03-api-surface.md) and [05](home-05-connect-flow.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**This is the order that produces the screenshot.** It is the reason three.ws is building this+and not somebody else. Everyone who has tried this shipped a flat SVG floorplan; we already ship+a Three.js renderer, an avatar pipeline and a physics-capable scene. Hold that bar.++---++## Step 0: re-derive the current state++```bash+npm run dev &+curl -N -s localhost:3000/api/home/<id>/stream -H "cookie: <dev session>" | head -40+node -e "console.log(require('./package.json').dependencies.three)"+ls src/ | grep -iE "viewer|scene|stage" | head -10+grep -rn "summarizeLighting\|summarizeSecurity" packages/home-bridge/src/rooms.js | head+```++## What this order owns++`/home/:id`: a live 3D model of the house, with the agent's body standing in it, driven entirely+by the SSE stream from order 03. It owns rendering and reactivity. It does **not** own the room+layout authoring (order 07) or voice (order 08).++## The mapping, room graph to scene++`buildHomeGraph` already produces exactly what a scene needs. Use it; do not invent a second+model.++| Graph field | Scene |+|---|---|+| `floors[]` | vertical stacking, one plane per level, ordered by `level` |+| `rooms[]` | a volume per room, labelled, arranged by order 07's saved layout or the default pack |+| `room.lighting.on` / `.brightness` / `.rgb` | the room's actual light: intensity from `brightness` (0..1), colour from `rgb`, off means genuinely dark, not dimmed |+| `room.climate.temperature` | a readable value in the room, and a subtle warm/cool tint |+| `room.secured` | doors and windows render open or closed; `secure: false` is visible at a glance from across the room |+| `entity.domain` | the object drawn: light, cover, lock, media player, fan, camera, sensor |+| `entity.state === 'unavailable'` | drawn, but visibly unreachable. Never omitted: a device that vanished is information. |++**The agent stands in the scene.** Reuse the existing avatar pipeline rather than a new loader.+The agent's position is a product decision: it stands in the room the user is looking at, turns+toward the camera when spoken to, and reacts when it acts (it should be obvious which room just+changed and that the agent did it).++## Reactivity is the feature++- A real light changing in Home Assistant changes the scene inside one animation frame of the+ SSE event arriving. Measure this end to end and report the number.+- Changes animate. A light does not pop from 0 to 1; it transitions. Use `transform` and+ `opacity` where DOM, and a real interpolation where 3D.+- Stale is a first-class visual state. When order 02 reports `stale: true`, the scene desaturates+ and shows the age. **It never empties.** A user watching their house must never see it vanish.++## Performance budget (measure, do not assume)++| Quantity | Budget |+|---|---|+| First meaningful paint of the scene | under 2.5 s on a mid-range laptop, from a cold load |+| Steady-state frame rate | 60 fps on desktop, 30 fps floor on a mid-range phone |+| Heap after 10 minutes of live updates | flat. A leak here is a tab that dies overnight on a wall display. |+| Update cost | a state burst of 100 entities must not drop a frame |++Wall displays are the real deployment. Something that leaks 2 MB an hour is broken even if it+demos well.++## Every state++1. **Loading** the scene: skeleton, no layout shift, the room list readable before the 3D arrives.+2. **Empty house**: connected but zero entities. Say what to do in Home Assistant, do not show a void.+3. **No areas assigned**: very common. Every entity is unassigned. This must be a designed,+ useful view (a single room containing everything) plus a prompt into order 07, not a blank floor.+4. **Live**: the default.+5. **Stale**: desaturated, age visible, last known state intact.+6. **Disconnected**: distinct from stale; offers reconnect.+7. **Acting**: the agent is performing an action; the affected room is highlighted.+8. **Confirmation pending**: order 04 minted a confirmation; the scene shows exactly which entity+ is about to change, and the confirm control is adjacent to it, not in a distant toast.+9. **WebGL unavailable**: a real, complete 2D fallback. This is not optional; it is the+ accessibility and old-device path, and order 17 will hold you to it.+10. **Error**: actionable and retryable.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | Route `/home/:id`, page and controller. | `vercel.json`, `pages/home-scene.html`, `src/home/scene.js` |+| 2 | The scene builder: graph to geometry, pure and testable without a GPU. | `src/home/scene-model.js`, `tests/home-scene-model.test.js` |+| 3 | The renderer, subscribed to SSE, with interpolated transitions. | `src/home/scene-render.js` |+| 4 | The agent body in the scene, reusing the existing avatar loader. | same |+| 5 | The 2D fallback, complete enough to operate the house. | `src/home/scene-fallback.js` |+| 6 | All ten states. | as above |+| 7 | Performance instrumentation and the measured numbers. | your report |+| 8 | e2e: the scene reflects a real device change. | `tests/e2e/home-scene.spec.js` |++## Definition of done++- [ ] A video or frame sequence showing a real light being toggled in Home Assistant and the scene changing. Report the measured end-to-end latency.+- [ ] Screenshots of all ten states.+- [ ] The measured frame rate on desktop and on a throttled mobile profile.+- [ ] A ten-minute heap trace showing flat memory under live updates. Paste the numbers.+- [ ] Killing Home Assistant shows state 5 with the house intact and an age; restarting restores live with no reload.+- [ ] A house with zero assigned areas renders state 3 usefully, not as a blank floor.+- [ ] The 2D fallback is reachable (force it) and can read and act on the house.+- [ ] Zero console errors or warnings from your code.+- [ ] `npx playwright test tests/e2e/home-scene.spec.js` passes; `npx vitest run tests/home-scene-model.test.js` passes.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Real houses have no geometry in Home Assistant | Correct, and that is order 07. Ship a good default arrangement here (rooms packed by floor, ordered by name) that is usable before anyone authors anything. |+| A room has 60 entities and looks cluttered | Rank by what a person cares about: lights, locks, covers, climate first; sensors summarised. Do not draw 60 objects because 60 exist. |+| The 3D is slower than the 2D fallback on a phone | Measure, then fix, then re-measure. If a class of device genuinely cannot run it, route it to the fallback automatically and say so in the UI. |+| Tempted to poll instead of using the SSE stream | Do not. Order 03 built the stream, and polling a house is both slower and ruder. |+| The scene empties on disconnect | That is a bug, and the most user-visible one in this order. The graph is retained by design; render the retained one. |++## Report format++1. The live-change video or frame sequence, with the measured latency.+2. The ten state screenshots.+3. Frame rate and heap numbers.+4. The kill-and-restore transcript.+5. Test output.+6. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-06-3d-home-scene.md++Never delete it on a partial.diff --git a/prompts/finish/home-07-floorplan-editor.md b/prompts/finish/home-07-floorplan-editor.mdnew file mode 100644index 000000000..df2188376--- /dev/null+++ b/prompts/finish/home-07-floorplan-editor.md@@ -0,0 +1,158 @@+# 07. Floorplan authoring and layout persistence++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Order+[06](home-06-3d-home-scene.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+npm run dev &+curl -s localhost:3000/api/home/<id> -H "cookie: <dev session>" | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const g=JSON.parse(s).graph;console.log(g.floors.length,'floors',g.rooms.length,'rooms',g.unassigned.length,'unassigned')})"+ls src/home/ # scene.js, scene-model.js from order 06+```++## Why this order exists++Home Assistant knows which room a device is in. It does not know where that room is. Order 06+ships a default arrangement so the scene is useful immediately; this order lets a person make it+their actual house, which is the difference between a diagram and a place.++It is also the fix for the most common real-world state: **a house where nothing is assigned to+an area at all.** That user needs a five-minute path from a pile of entities to a floorplan.++## The model++A layout is per home, authored by a member, versioned, and **never** required. The scene must+work with no layout, a partial layout, and a stale layout (a room that no longer exists).++Schema, one migration:++### `home_layouts`++| Column | Type | Notes |+|---|---|---|+| `home_id` | `uuid primary key references home_connections(id) on delete cascade` | one live layout per home |+| `version` | `integer not null default 1` | bumped on every save, for optimistic concurrency between household members |+| `layout` | `jsonb not null` | the document below |+| `updated_by` | `uuid not null references users(id)` | |+| `updated_at` | `timestamptz not null default now()` | |++The layout document, validated by a schema on write (reuse the repo's existing validation+approach; do not accept arbitrary JSON into a rendering path):++```json+{+ "version": 1,+ "units": "m",+ "floors": [{ "id": "ground_floor", "level": 0 }],+ "rooms": [{+ "areaId": "kitchen",+ "floorId": "ground_floor",+ "x": 0, "y": 0, "w": 4.2, "h": 3.0, "rotation": 0,+ "entities": { "light.kitchen_lights": { "x": 2.1, "y": 1.5 } }+ }]+}+```++Rules the validator enforces: bounded coordinates, a room count cap, a document byte cap, no+unknown top-level keys, and `areaId` values that are strings only. A layout is user-authored+JSON that drives a renderer, so treat it as untrusted input, not as trusted state.++## The editor++A 2D top-down plan, because nobody arranges a floorplan in perspective. The 3D scene updates+live beside it or behind it.++- Drag to move a room, handles to resize, snapping to a grid and to adjacent walls.+- Rooms cannot overlap; the editor prevents it rather than validating it after the fact.+- Undo and redo, keyboard shortcuts included.+- Unassigned entities are a tray. Dragging one into a room **writes the area assignment back to+ Home Assistant** through `config/entity_registry/update`, so the work improves the user's own+ house and not just our picture of it. This is the single most valuable thing in this order.+- Multi-floor: add, name, reorder, set level.+- A "start from my house" path: if the house has areas, seed the plan from them; if it has none,+ the tray is the whole house and the flow is "make a room, drag things in".++## Concurrency++Two household members can edit. Optimistic concurrency on `version`: a save with a stale version+returns 409 with the current document, and the editor offers a real merge choice (keep mine,+take theirs, side by side), never a silent overwrite and never a lost edit.++## Every state++1. No layout: the seeded default, with an obvious way in.+2. No areas at all: the tray-first flow.+3. Editing: live, with the 3D following.+4. Saving: optimistic, with a real failure path.+5. Conflict: the 409 merge choice.+6. Stale layout: a room in the layout no longer exists in Home Assistant. Show it as orphaned and+ offer to drop it; never crash, never silently discard the user's work.+7. New room appeared in Home Assistant since the last save: surfaced in the tray, not hidden.+8. Read-only: a household member without the layout role (order 12) sees the plan and cannot edit.+9. Writing back to Home Assistant failed: the local layout still saves, and the failure is named.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | Migration and store functions. | `api/_lib/migrations/<ts>_home_layouts.sql`, `api/_lib/home/layout.js` |+| 2 | The layout schema validator, with the caps. | `api/_lib/home/layout-schema.js`, `tests/home-layout-schema.test.js` |+| 3 | `GET`/`PUT /api/home/:id/layout` with optimistic concurrency. | `api/home/[id]/layout.js` |+| 4 | The area write-back to Home Assistant, gated as a normal (ungated) action and logged. | `api/_lib/home/tools.js` or a sibling |+| 5 | The editor. | `src/home/floorplan.js`, styles |+| 6 | Wiring the saved layout into order 06's scene builder. | `src/home/scene-model.js` |+| 7 | e2e: author a plan, reload, and see it persist and render. | `tests/e2e/home-floorplan.spec.js` |++## Definition of done++- [ ] A real house arranged into a real floorplan, screenshotted in the editor and in the 3D scene.+- [ ] Dragging an unassigned entity into a room really changed its area in Home Assistant. Prove it from the Home Assistant side, not from our UI.+- [ ] A malformed layout document (over the cap, unknown keys, non-numeric coordinates) is rejected by the API with a designed error. Four transcripts.+- [ ] Two browser sessions editing the same home produce the 409 merge choice, and no edit is lost. Record the sequence.+- [ ] Deleting an area in Home Assistant puts the layout into state 6 without a crash and without discarding the rest.+- [ ] A house with zero areas can reach a complete floorplan through the tray-first flow in under five minutes. Time it and report the number.+- [ ] Undo and redo work, including across a drag and a resize.+- [ ] Zero console errors or warnings from your code.+- [ ] `npx playwright test tests/e2e/home-floorplan.spec.js` passes.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Tempted to auto-generate a floorplan from device positions | There are no device positions. Home Assistant has no geometry. Seed from areas, let the human place. |+| Tempted to make the layout required | Never. Order 06 works without one, and a required setup step before any value is how a feature dies. |+| Overlap prevention is fiddly | Axis-aligned rectangles on a grid. Keep it rectangles in v1; free-form polygons are a later slice and not worth the complexity now. |+| Writing back to Home Assistant feels risky | It is an area assignment, fully reversible in their own UI, and it is the thing that makes this worth doing. Log it, show it, and fail loudly rather than silently. |+| A room in Home Assistant has no entities | Draw it. An empty room is still a room. |++## Report format++1. Editor and scene screenshots of a real arranged house.+2. The Home Assistant-side proof of the area write-back.+3. The four validator rejections.+4. The concurrency sequence.+5. The timed zero-areas walkthrough.+6. Test output.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-07-floorplan-editor.md++Never delete it on a partial.diff --git a/prompts/finish/home-08-voice-loop.md b/prompts/finish/home-08-voice-loop.mdnew file mode 100644index 000000000..ac48693b1--- /dev/null+++ b/prompts/finish/home-08-voice-loop.md@@ -0,0 +1,175 @@+# 08. The browser voice loop: wake word, barge-in, latency++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[04](home-04-agent-tools.md) and [06](home-06-3d-home-scene.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+wc -l src/voice/talk-mode.js src/voice/mic-capture.js src/voice/talk-controller.js+curl -s localhost:3000/api/asr | head -c 300 # the ASR lane and whether it is configured+ls api/tts/ # speak.js, synthesize.js, voices.js+grep -rn "openWakeWord\|silero\|vad" src/ package.json | head+```++`api/asr.js` runs on NVIDIA NIM Riva and reports `configured` on a GET. Read that before+assuming anything about the speech lane.++## What this order owns++Hands-free operation of the house from a browser that is already open: a wake word, always-on+listening the user actually consented to, barge-in, and a latency budget tight enough that+speaking is faster than reaching for a phone. It reuses `src/voice/` rather than building a+second voice stack.++It does **not** own being a Home Assistant satellite; that is order 09.++## The pipeline++```+mic → VAD (silero-vad) → wake word (openWakeWord) → capture → ASR (/api/asr)+ → agent turn (api/chat.js with the order 04 home tools) → TTS (/api/tts/speak)+ → lip sync (src/voice/lipsync-driver.js) → the 3D agent speaks+```++Both models are permissively licensed and run in the browser:+[silero-vad](https://github.com/snakers4/silero-vad) (MIT) and+[openWakeWord](https://github.com/dscripka/openWakeWord) (Apache-2.0). Follow the CLAUDE.md+open-source rule: use them, do not write a detector. Load them lazily; nothing about wake-word+detection may run before the user turns it on.++## The latency budget (measure every leg, report every number)++| Leg | Budget | Note |+|---|---|---|+| Wake word detection | under 200 ms from the end of the word | this is what makes it feel alive |+| End-of-speech detection | under 400 ms of trailing silence | longer feels broken, shorter clips people |+| ASR round trip | under 900 ms for a short utterance | measure against the real lane, not a local model |+| Agent turn to first tool call | under 1.2 s | |+| Action to observed device change | under 700 ms | mostly Home Assistant's own latency |+| First audible response | under 1.8 s from end of speech | the number a user actually feels |++If a leg misses, report the measured number rather than hiding it. A published honest budget is+worth more than a passed invented one.++## Barge-in++The agent must stop talking the instant the user starts. Full duplex: playback and capture run+together, the VAD runs during playback, and detected speech cancels the current utterance,+truncates the TTS stream, and starts a new capture. Echo cancellation via `getUserMedia`+constraints (`echoCancellation`, `noiseSuppression`, `autoGainControl`), and a self-trigger guard+so the agent's own voice cannot wake it.++## Consent, privacy and the microphone++This is the part that decides whether anyone trusts the product.++- Always-on listening is **off by default** and requires an explicit, informed opt-in that says+ what is processed locally and what leaves the device.+- Wake-word detection is local. Audio leaves the device only after the wake word, and only for+ the utterance.+- A permanent, unmissable listening indicator whenever the mic is live, in the page and in the+ 3D scene. It is never hidden, never subtle, and never removable by a setting.+- One-tap mute that physically stops capture, not a flag that hides the indicator.+- Nothing is retained: no utterance audio is stored server-side beyond the request. If a+ transcript is kept for the conversation, say so and let it be cleared. Order 15 owns retention;+ this order must not create a data class it did not declare.+- Recovery from a denied permission is designed, not a dead end.++## Confirmation in voice (the dangerous part)++Order 04's protocol crosses into speech here, and this is where it can go wrong.++- A guarded action is spoken back in full before it is confirmed: "This will unlock the front+ door. Say confirm to continue." Never "OK?" and never a yes/no on an unnamed action.+- The confirmation grammar is a narrow, explicit token, not a general affirmative. A background+ "yeah" in a conversation must not unlock a door.+- The confirmation is bound to the minted `confirmationId` from order 04, expires with it, and is+ single use.+- The 3D scene shows the pending entity while the confirmation is outstanding (order 06 state 8),+ so the user sees what they are agreeing to. **Voice alone never satisfies a guarded action on a+ device with no display.** On a screenless surface, a guarded action is refused with a clear+ reason and an offer to confirm on the phone.+- ASR is not reliable enough to be the only gate on a door. Say that out loud in the code comment.++## Every state++1. Off (the default), with the opt-in explained.+2. Permission not yet granted.+3. Permission denied: recovery instructions per browser.+4. Idle and listening for the wake word.+5. Woken and capturing.+6. Thinking.+7. Speaking (with barge-in armed).+8. Barged in.+9. Confirmation pending, spoken and shown.+10. ASR unavailable (`configured: false`, or the lane is down): the whole voice path degrades to+ text with an honest reason, and never pretends to listen.+11. Muted.+12. Error.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | Lazy-loaded VAD and wake word, with the models served from our own origin. | `src/voice/wake-word.js`, `src/voice/vad.js` |+| 2 | The full-duplex loop with barge-in, on top of `src/voice/mic-capture.js`. | `src/voice/home-voice.js` |+| 3 | The consent flow, the indicator and mute. | same, plus styles |+| 4 | The home turn: wiring the order 04 tools into the voice path with the spoken confirmation grammar. | same |+| 5 | Latency instrumentation, emitting every leg. | same |+| 6 | All twelve states. | as above |+| 7 | Tests: the confirmation grammar (a general "yeah" must not confirm), the self-trigger guard, the degraded path. | `tests/home-voice.test.js` |++## Definition of done++- [ ] A recorded run: wake word, "turn the kitchen light off", the real light goes off, the agent says what it did. Report every leg's measured latency against the budget table.+- [ ] A recorded barge-in: the agent is speaking, the user talks, playback stops within 200 ms.+- [ ] A recorded guarded action: the full sentence is spoken, the scene shows the entity, an ambient "yeah" does **not** confirm, the explicit token does, and the real door unlocks.+- [ ] The self-trigger proof: the agent says its own wake word and does not wake itself.+- [ ] The listening indicator is visible in every frame where the mic is live. Prove it with a frame sample.+- [ ] Mute stops capture at the track level (`track.readyState`), not at a flag. Prove it.+- [ ] `configured: false` on `/api/asr` degrades to state 10 with an honest message and no fake listening.+- [ ] Nothing about wake-word detection loads before opt-in. Prove it with the network tab on a cold load.+- [ ] Screenshots of all twelve states.+- [ ] `npx vitest run tests/home-voice.test.js` passes.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| The ASR lane is unconfigured locally | `curl /api/asr` reports it. Build against the real lane where a key exists; where it does not, build the full path and prove state 10 works. Never mock the transcript. |+| Wake-word accuracy is poor for a chosen phrase | openWakeWord ships pre-trained models. Pick from what exists before training anything, and let the user choose among them. |+| Barge-in triggers on the agent's own voice | That is the self-trigger guard, and it is required, not optional. Echo cancellation plus a playback-aware gate. |+| Someone proposes letting voice alone confirm an unlock on a screenless device | Refuse, and keep the refusal in the code with its reason. ASR is not a gate on a door. |+| Latency misses a budget line | Report the real number. Then optimize the worst leg and re-measure. Do not quietly widen the budget. |+| Always-on listening feels like a privacy problem | It is one, which is why it is off by default, locally gated, indicated permanently, and mutable in one tap. Build all four before shipping any of it. |++## Report format++1. The three recordings (happy path, barge-in, guarded confirmation) with the leg-by-leg latency table.+2. The self-trigger and mute proofs.+3. The cold-load network tab proving nothing loads before opt-in.+4. The twelve state screenshots.+5. Test output.+6. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-08-voice-loop.md++Never delete it on a partial.diff --git a/prompts/finish/home-09-wyoming-satellite.md b/prompts/finish/home-09-wyoming-satellite.mdnew file mode 100644index 000000000..f3e266bd7--- /dev/null+++ b/prompts/finish/home-09-wyoming-satellite.md@@ -0,0 +1,149 @@+# 09. three.ws as a Home Assistant voice satellite (Wyoming)++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Order+[08](home-08-voice-loop.md) should have landed; this order can be built in parallel with it, but+not before order 06.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**This is the distribution play, not just a feature.** Today a Home Assistant voice assistant is+a speaker with an LED ring. Point an existing HA pipeline at a three.ws agent and it gains a+face, an expression, lip sync and a body that turns toward you. That is a new product for 90,225+stars' worth of users who already own the hard part.++---++## Step 0: re-derive the current state++```bash+ls src/voice/ # what already exists+grep -rn "wyoming" . --include=*.js --include=*.md -l | grep -v node_modules | head+docker exec threews-ha ls /config # a live instance to point at us+```++Read the protocol from the reference implementation, not from a blog:+[rhasspy/wyoming-satellite](https://github.com/rhasspy/wyoming-satellite) (MIT, 1,244 stars) and+the `wyoming` protocol package it depends on. **Adopt the protocol, not the code**: it is a small+TCP framing of newline-delimited JSON headers with optional binary payloads, and reimplementing+the client side in our stack is correct. Vendoring a Python satellite is not.++## What this order owns++A three.ws surface that a Home Assistant instance can select as a voice satellite: it announces+itself, receives the pipeline's audio and events, plays the response, and drives the 3D avatar's+mouth and expression from it. Home Assistant owns the pipeline (wake word, STT, intent, TTS);+we own the body.++**The direction of control is the opposite of order 08.** There, we run the loop and call Home+Assistant. Here, Home Assistant runs the loop and calls us. Both must exist: one serves three.ws+users who have a house, the other serves Home Assistant users who want a face.++## The shape++Wyoming is a TCP protocol and a browser cannot speak TCP, so the satellite is a small service,+not a page:++```+Home Assistant --wyoming/TCP--> three.ws satellite service --wss--> the browser (3D agent)+ (announces info, relays audio + events)+```++- `services/home-satellite/` (a new service directory, which per CLAUDE.md **requires its own+ README.md**), or `workers/` if the fleet conventions there fit better. Read `STRUCTURE.md` and+ a neighbouring service before choosing, and put the choice in your report.+- The service implements the `info` handshake (announcing a satellite with our name, our+ attribution and our capabilities), the audio chunk stream in both directions, and the pipeline+ event set (`run-pipeline`, `wake`, `transcript`, `synthesize`, `audio-start`, `audio-chunk`,+ `audio-stop`, `error`).+- The browser side subscribes over a websocket and drives the avatar: the existing+ `src/voice/lipsync-driver.js` and `src/voice/talk-emotes.js` are the target, not new code.+- Pairing: a user connects their satellite to a specific three.ws agent with a short-lived code,+ the same way any device pairing works. No open relay, ever.++## The bar this must clear++Home Assistant users are a discerning, local-first audience who will notice anything dishonest.++- **Local-first respected.** Say plainly which parts leave their network. If a deployment can run+ the satellite locally (it can: the service is small and containerized), document that path and+ ship the container.+- **No account required to try it.** A pairing code and an avatar. Ask for an account when there+ is a reason.+- **Degrades to audio.** If the display is off or the browser is closed, the pipeline must still+ complete. We are the face, never a dependency of the voice working.+- **Attribution and licensing correct.** Wyoming is MIT; credit it, link it, and say we+ implemented the protocol rather than vendoring the satellite.++## Every state++1. Unpaired: the code, and how to add it in Home Assistant.+2. Pairing.+3. Paired and idle: the avatar present, waiting.+4. Wake detected (by Home Assistant, relayed to us).+5. Listening, with the transcript streaming in.+6. Thinking.+7. Speaking, lip-synced to the pipeline's own TTS audio.+8. Error from the pipeline: shown, not swallowed.+9. Satellite disconnected: the avatar says so rather than freezing.+10. Display asleep: the pipeline still works, and we say we are the optional half.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | The protocol client: framing, the event set, the info handshake. Pure and unit-testable. | `services/home-satellite/src/protocol.js`, tests |+| 2 | The service: TCP listener, session management, the browser websocket relay. | `services/home-satellite/src/server.js` |+| 3 | Pairing with short-lived codes, bound to a user and an agent. | `api/home/satellite.js`, a migration if it needs storage |+| 4 | The browser side driving the existing lip sync and emotes. | `src/home/satellite.js` |+| 5 | A container and its deploy config, following a sibling service. | `services/home-satellite/Dockerfile`, `cloudbuild.yaml` |+| 6 | `README.md` in the service directory: what it is, how to run it locally, how to add it in Home Assistant, its public interface, one runnable example. **Required by CLAUDE.md.** | `services/home-satellite/README.md` |+| 7 | All ten states. | as above |+| 8 | `STRUCTURE.md` row, `docs/` page, `data/changelog.json` entry. | as listed |++## Definition of done++- [ ] A real Home Assistant instance lists the three.ws satellite in its voice assistant settings. Screenshot from Home Assistant, not from us.+- [ ] A full pipeline run: speak to Home Assistant's pipeline, and the three.ws avatar lip-syncs the response and reacts. Recorded.+- [ ] The transcript streams into the UI as Home Assistant produces it (state 5), not only at the end.+- [ ] Closing the browser leaves the pipeline working. Prove it.+- [ ] An unpaired satellite is rejected; a pairing code is single-use and short-lived. Three transcripts.+- [ ] The service runs locally in Docker against a local Home Assistant, with the command in the README, and it works.+- [ ] `services/home-satellite/README.md` exists and someone who did not build it could follow it. `npm run audit:docs` passes, which enforces the README existing.+- [ ] Screenshots of all ten states.+- [ ] `npx vitest run services/home-satellite` (or the repo's equivalent for that directory) passes.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| The protocol is under-documented | Read the reference implementation's source. It is small, MIT, and unambiguous. Where our reading differs from the wire, trust the wire and write down what you found. |+| A browser cannot open a TCP socket | Correct, which is why this is a service. Do not try to force it into the page. |+| Tempted to vendor the Python satellite | Do not. We need a client in our own stack; the Python satellite is a device runtime. Implement the protocol. |+| Home Assistant changes the event set | Pin what you tested against, name the version in the README, and add the version to the info handshake so a mismatch is visible. |+| Someone proposes making the three.ws display required for voice to work | Refuse. That would make us a dependency of somebody's house working, which is both wrong and how a project gets a bad reputation in this community. |+| The pairing flow feels like too much friction | It is the minimum that prevents an open relay into strangers' homes. Make it fast, not absent. |++## Report format++1. The Home Assistant-side screenshot listing our satellite.+2. The recorded pipeline run with lip sync.+3. The three pairing transcripts.+4. The local Docker run transcript.+5. The ten state screenshots.+6. Test and audit output.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-09-wyoming-satellite.md++Never delete it on a partial.diff --git a/prompts/finish/home-10-addon-relay.md b/prompts/finish/home-10-addon-relay.mdnew file mode 100644index 000000000..caa150317--- /dev/null+++ b/prompts/finish/home-10-addon-relay.md@@ -0,0 +1,154 @@+# 10. The dial-out add-on and relay for LAN-only homes++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first, in particular the+reachability section. Orders [02](home-02-bridge-runtime.md) and [03](home-03-api-surface.md)+must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+node -e "import('./packages/home-bridge/src/url.js').then(m=>console.log(['homeassistant.local','192.168.1.10','abc.ui.nabu.casa'].map(h=>h+' private='+m.isPrivateHost(h))))"+ls api/_lib/home/ # store, verify, runtime, tools+grep -rn "transport" api/_lib/migrations/*home_connections*.sql+```++Order 01's schema already carries `transport` (`direct` or `relay`) and `relay_id`. This order+fills in the `relay` half.++## The problem, stated exactly++Most Home Assistant installs are reachable only from inside the house. three.ws is on the public+internet. Orders 01 to 08 work for users with a remote https URL and are useless for everyone+else, which is the majority. This order is what makes the product available to them, and it is+the single largest reach multiplier in the campaign.++## The design: the house dials us, never the reverse++```+Home Assistant (LAN) --outbound wss--> three.ws relay <--wss-- api/_lib/home/runtime.js+ three.ws add-on+```++- A small add-on installed inside the user's Home Assistant opens **one outbound WebSocket** to+ the relay. Nothing is ever listened for on the user's network, no port is forwarded, no tunnel+ daemon is installed, and no inbound firewall change is needed.+- The relay is a three.ws service that terminates those connections and multiplexes requests from+ the bridge runtime onto them.+- To `api/_lib/home/runtime.js` this is a transport swap and nothing more. The `HomeBridge` API,+ the room graph, the gate, the tools and the UI are unchanged. **If this order requires changes+ above the transport, the design is wrong; fix the transport.**++## Security, because this is a tunnel into someone's house++This section is the order. Everything else is plumbing.++1. **The add-on holds the credential, not us.** In relay mode we store no Home Assistant token.+ The add-on authenticates to Home Assistant locally with its own supervisor token and to the+ relay with a per-install key. Order 01's `access_token_enc` is empty for a relay connection,+ and the store must permit that without weakening the direct path.+2. **Pairing is explicit, short-lived and single-use.** A code shown in three.ws, entered in the+ add-on (or the reverse). No discovery, no long-lived shared secret, no code that works twice.+3. **The relay is a dumb pipe with an allowlist.** It forwards only the message types the bridge+ needs. It never forwards arbitrary HTTP into the LAN, never proxies a path the caller chooses,+ and never exposes the connection to anything but the owning user's requests.+4. **Every relayed action is logged** to `home_action_log` exactly like a direct one. The+ transport must not create an audit gap.+5. **Revocation is immediate and both-ended.** Revoking in three.ws drops the socket; uninstalling+ the add-on drops it too and the connection goes to `unreachable` with an honest reason.+6. **A compromised relay must not equal a compromised house.** State the blast radius honestly in+ the README and in `docs/`. The gate from order 04 still sits between any request and any+ physical action, and confirmations are still minted and redeemed on our side by a human.+7. **Rate limits per install**, so a bug in the add-on cannot flood a house.++Write the threat model into `docs/` as part of this order. Order 11 reviews it; it does not+write it for you.++## Distribution++Ship it through [HACS](https://github.com/hacs/integration) (7,674 stars, MIT), which is how+Home Assistant users install third-party code. That means a public repository with the required+structure, a version, a release, and documentation that stands on its own. Per CLAUDE.md, this is+also the giving-back half of the open-source rule: the add-on is public, not private to our users.++Pushing a public repository is owner-gated. Prepare everything so the publish is one command and+batch the owner action into a single message.++## Every state++1. Not installed: the instructions, with the HACS path and the manual path.+2. Pairing: the code and its countdown.+3. Paired and connected: identical to a direct connection from here on.+4. Add-on offline (Home Assistant restarted, host rebooted): the honest reason, and it should+ recover by itself when the add-on returns.+5. Add-on version too old for the relay protocol: named, with the upgrade path.+6. Pairing expired or reused.+7. Revoked from either end.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | The relay protocol: message types, framing, versioning, the allowlist. Pure and testable. | `services/home-relay/src/protocol.js`, tests |+| 2 | The relay service, its container and its deploy config. | `services/home-relay/` |+| 3 | `RelayTransport` for `packages/home-bridge`, so `HomeBridge` accepts it in place of the direct socket. | `packages/home-bridge/src/transport-relay.js` |+| 4 | Runtime and store support for `transport: 'relay'`, including the empty-credential case. | `api/_lib/home/runtime.js`, `api/_lib/home/store.js` |+| 5 | Pairing endpoints and UI. | `api/home/pair.js`, `src/home/pair.js` |+| 6 | The add-on itself: a Home Assistant custom integration or add-on, whichever the community expects for this shape (state your choice and the reason). | a new public repo, prepared locally |+| 7 | `README.md` in every new directory. Threat model in `docs/`. | required |+| 8 | All seven states. | as above |++## Definition of done++- [ ] A real Home Assistant on a network the server cannot route to, connected through the relay, with a real light toggled from three.ws. Recorded. Simulate the LAN by binding the instance to an address the API container cannot reach, and say exactly how you did it.+- [ ] The full order 04 gate still applies over the relay: a guarded unlock returns 409, the confirmation redeems, the real door unlocks. Same transcripts as order 04, over the new transport.+- [ ] `home_action_log` rows for relayed actions are indistinguishable in completeness from direct ones. Paste both.+- [ ] Nothing above the transport changed: show the diff and confirm `api/_lib/home/tools.js`, the UI and the room graph are untouched.+- [ ] A relay connection stores no Home Assistant token. Prove it with the row.+- [ ] Pairing code reuse, expiry, and cross-user redemption all refused. Three transcripts.+- [ ] Killing the add-on puts the home in state 4 and restarting it recovers with no user action. Recorded.+- [ ] The relay refuses a message type outside the allowlist. Prove it.+- [ ] `README.md` present in every new directory; `npm run audit:docs` clean.+- [ ] The threat model doc is written and linked.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Tempted to use a generic tunnel product | Do not add a paid third-party dependency (CLAUDE.md forbids onboarding one without approval), and do not ask users to install a tunnel daemon. One outbound websocket to our own service is smaller, safer and explainable. |+| Cannot test a genuinely unroutable LAN | Bind the Home Assistant container to a network namespace the API cannot reach, or run it on a second machine. Do not test the relay against localhost and call it proven. |+| The relay protocol wants to be "just proxy HTTP" | Refuse. An arbitrary-path proxy into a home network is the single worst thing this campaign could ship. Allowlist the message types the bridge actually uses. |+| Publishing the add-on repo is blocked | Repository creation and pushes are owner-gated. Prepare the repo contents in-tree, verify with a local install, and batch the publish into one owner message. |+| Someone proposes storing the Home Assistant token in relay mode "just in case" | Refuse. Not holding it is a feature and a selling point. |++## Report format++1. The unroutable-LAN setup description and the recorded end-to-end run.+2. The gate transcripts over the relay.+3. The action log comparison.+4. The diff proving nothing above the transport changed.+5. The three pairing refusals and the allowlist refusal.+6. The kill-and-recover recording.+7. The exact owner action needed to publish, in one paragraph.+8. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-10-addon-relay.md++If the publish is the only outstanding step, leave the file in place, say so, and name the owner+action. Never delete it on a partial.diff --git a/prompts/finish/home-11-security.md b/prompts/finish/home-11-security.mdnew file mode 100644index 000000000..ea064e0c0--- /dev/null+++ b/prompts/finish/home-11-security.md@@ -0,0 +1,142 @@+# 11. Security hardening: threat model, injection boundary, abuse++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[01](home-01-connection-store.md) to [04](home-04-agent-tools.md) must have landed; run this+before any production deploy of the lane, and again before order 20.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**This order finds and fixes, it does not merely report.** A finding without a fix or a written,+justified acceptance is not finished work.++---++## Step 0: re-derive the current state++```bash+npx vitest run packages/home-bridge tests/home-*.test.js+grep -rn "getDecryptedToken" api/ --include=*.js+grep -rn "confirmed" api/_lib/home/ api/home/ api/_mcp/tools/home.js --include=*.js+curl -s localhost:3000/api/tool_schema | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const t=JSON.parse(s).tools.filter(x=>x.name.startsWith('home'));console.log(JSON.stringify(t.map(x=>({n:x.name,props:Object.keys(x.inputSchema?.properties||{}),ann:x.annotations})),null,1))})"+npm run check:secrets 2>/dev/null || node scripts/check-secrets.mjs --help+```++## The asset being protected++Not data. **A building, and the people in it.** The worst outcome in this campaign is not a leak;+it is a stranger opening a door. Rank every finding against that.++## The threat model, written into `docs/`++Produce `docs/home-security.md`, linked from `docs/start-here.md` and `docs/smart-home.md`,+covering at minimum:++| Actor | Capability | Our control |+|---|---|---|+| A stranger on the internet | can reach our API | session auth, ownership `WHERE user_id`, 404 across tenancy, rate limits |+| A stranger who obtains a session | can act as the user | the gate: an unlock still needs a fresh, single-use, 90 s confirmation minted server-side |+| A compromised or hijacked model | can call any tool with any arguments | `confirmed` is absent from every tool schema; confirmations are redeemed only by a session with CSRF, never by a bearer or MCP principal |+| A malicious device or integration in the user's own house | controls entity names, area names, scene names | those strings reach a model; structured, capped, sanitised, and never the sole basis of an action |+| Another household member | has legitimate partial access | order 12's roles and per-entity scopes |+| Us, operationally | can read the database | credentials encrypted with a dedicated key; relay mode holds no token at all |+| A compromised relay (order 10) | can speak the relay protocol to a house | allowlisted message types, per-install keys, the gate still upstream, blast radius written down |++## The eleven checks, each with a test that would fail if the control regressed++1. **`confirmed` is unreachable from a model.** Dump every home tool schema and assert no+ `confirmed` property, on both the MCP and the chat surface.+2. **Confirmation binding.** A confirmation minted for entity A cannot execute against entity B,+ another home, or another user. Cannot be replayed, cannot outlive its TTL.+3. **Confirm endpoint principal.** Session plus CSRF only. A bearer token with `home:act` is+ refused. An MCP principal is refused.+4. **Prompt injection with a physical payload.** Rename a real entity to an instruction that+ tells the agent to unlock the front door, run a real chat turn that reads the house, assert no+ action was taken and the door is locked. Repeat with the payload in an area name and in a+ scene name.+5. **Tenancy.** For every route in order 03, user B gets 404 on user A's ids. Automate the matrix;+ do not spot check.+6. **Credential handling.** The token never appears in a response body, a log line, an error+ message, a URL, a metric label, or an audit `meta` blob. Grep the code and prove it at runtime+ with a request that fails at every stage.+7. **SSRF.** `baseUrl` is attacker-supplied and the server dials it. Prove that link-local+ (`169.254.169.254`, the cloud metadata endpoint), loopback, and RFC1918 addresses are refused+ server-side, that a redirect to one is refused, and that a DNS name resolving to one is refused+ (rebinding: resolve, pin, then connect to the pinned address).+8. **Rate and abuse.** The `act` bucket cannot cycle a garage door. The `connect` bucket resists+ credential stuffing. Both proven by exceeding them.+9. **Secrets in the diff.** `node scripts/check-secrets.mjs` over the lane's commits is clean, and+ no test fixture contains a real token.+10. **Dependency posture.** `npm audit` on the new dependencies; every one is permissively+ licensed and actively maintained (record the last-publish dates).+11. **Logout and revoke.** Revoking a home drops any live socket immediately, not at the next+ idle sweep. Prove it with `stats()`.++**Check 7 is the one most likely to be missing.** `verifyConnection` dials a user-supplied URL+from inside our production network. Look for an existing SSRF guard in the repo before writing+one (`grep -rn "ssrf\|isPrivateHost\|metadata" api/_lib/ --include=*.js`) and reuse it.++## Fixes, not findings++Every check that fails gets a fix in this same session and a regression test. A check you decide+to accept rather than fix gets a written justification in `docs/home-security.md` naming the+residual risk and who accepted it. An unresolved finding is not allowed to become a line in a+report that nobody reads.++## Tasks++| # | Task |+|---|---|+| 1 | Write `docs/home-security.md` with the threat model table and the accepted residuals section. |+| 2 | Build `tests/home-security.test.js` with the eleven checks as executable tests. |+| 3 | Run them. Fix every failure. |+| 4 | Add the tenancy matrix as a loop over the route table, so a new route added later without ownership fails the suite automatically. |+| 5 | Add the injection regression to the suite with a real physical assertion (the lock state), not a string assertion. |+| 6 | Link the doc from `docs/start-here.md` and `docs/smart-home.md`; add a `data/changelog.json` entry tagged `security`. |++## Definition of done++- [ ] All eleven checks exist as tests and pass. Paste the run.+- [ ] The tenancy matrix covers every route in `api/home/`, enumerated from the filesystem rather than hardcoded, so a future route cannot be forgotten.+- [ ] The injection test asserts a real lock's real state after a real chat turn.+- [ ] SSRF: four refusals proven (loopback, RFC1918, link-local metadata, redirect to one) plus the DNS-rebinding pin.+- [ ] The credential-leak sweep: paste the greps and the runtime proof.+- [ ] `node scripts/check-secrets.mjs --base <lane start sha> --head HEAD` is clean.+- [ ] `docs/home-security.md` exists, is linked, and every accepted residual names the risk and the reason.+- [ ] Every failure found was fixed in this session, or accepted in writing. List both sets in your report.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| A check fails and the fix looks large | It is still this order's job. The alternative is shipping a door that opens for strangers. If it genuinely cannot land this session, write the acceptance with the risk named and say so at the top of your report, not the bottom. |+| No SSRF guard exists in the repo | Then write one, pin the resolved address, and reuse it everywhere a user-supplied URL is dialled. Do not rely on a hostname check alone; DNS rebinding defeats it. |+| The injection test is hard to make deterministic | Assert on the physical outcome (the lock state) and on the action log, not on the model's words. The model's output varies; the door's state does not. |+| Someone argues the gate is enough and injection filtering is unnecessary | The gate IS the primary control and it is why we are not in real danger. Filtering is defence in depth and cheap. Do both, and say in the doc which one is load-bearing. |+| A dependency has a CVE | Upgrade it. If no fixed version exists, state the exposure and the mitigation in the doc, per the CLAUDE.md open-source rule. |++## Report format++1. The eleven checks with pass or fail, before and after.+2. Every fix made, with the file and the reason.+3. Every residual accepted, with the risk named.+4. The SSRF proofs.+5. The injection proof with the lock state.+6. Full-suite output.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-11-security.md++Never delete it on a partial. If a residual was accepted rather than fixed, that is a completion+only when the acceptance is written into `docs/home-security.md`.diff --git a/prompts/finish/home-12-households-rbac.md b/prompts/finish/home-12-households-rbac.mdnew file mode 100644index 000000000..b50188ee3--- /dev/null+++ b/prompts/finish/home-12-households-rbac.md@@ -0,0 +1,160 @@+# 12. Households: members, roles, per-member scopes, SSO++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[01](home-01-connection-store.md) to [04](home-04-agent-tools.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+grep -n "user_id" api/_lib/migrations/*home_connections*.sql+ls api/auth/ # session, saml, siwe, github, privy, persona+sed -n '1,40p' api/auth/saml/\[action\].js # what SSO already does+grep -rn "getSessionUser\|getRequestUser" api/home/ --include=*.js | head+```++Order 01 deliberately keyed `home_connections` on a single `user_id` and said this order must not+require rewriting that column. Honour that: add membership beside it, do not replace it.++## Why this is not optional++A house has more than one person in it. Today the owner's account is the only way in, which means+either everyone shares one login (the worst possible outcome for a system that opens doors) or+only one person can use the product. For the enterprise cases (a hotel, an office, a serviced+building), roles and an audit trail are the entire purchase decision.++## The model++### `home_members`++| Column | Type | Notes |+|---|---|---|+| `home_id` | `uuid not null references home_connections(id) on delete cascade` | |+| `user_id` | `uuid not null references users(id) on delete cascade` | |+| `role` | `text not null` | `owner`, `admin`, `member`, `guest`, `viewer`. Check-constrained. |+| `entity_scope` | `jsonb not null default '{"mode":"all"}'` | `{"mode":"all"}` or `{"mode":"allow","areas":[],"entities":[]}` |+| `invited_by` | `uuid references users(id)` | |+| `created_at` / `updated_at` | `timestamptz not null default now()` | |++Primary key `(home_id, user_id)`. The row for the creating user is `owner` and is created in the+same transaction as the connection, backfilled for existing rows by the migration.++### The roles++| Role | Read state | Ungated actions | Confirm a guarded action | Grant standing allowances | Edit layout | Invite | Disconnect |+|---|---|---|---|---|---|---|---|+| `owner` | yes | yes | yes | yes | yes | yes | yes |+| `admin` | yes | yes | yes | yes | yes | yes | no |+| `member` | yes | yes | yes | no | yes | no | no |+| `guest` | scoped | scoped | **no** | no | no | no | no |+| `viewer` | scoped | no | no | no | no | no | no |++**A guest can never confirm a guarded action.** A house sitter should be able to turn lights on+and should not be able to authorise unlocking the front door. That single row is the reason this+table exists.++### Entity scope++`guest` and `viewer` carry an allowlist of areas or entities. Enforcement is **server-side, in+the store's query and in the gate**, never in the UI. A scoped member's room graph is filtered+before it leaves the server, so a guest cannot read the state of a room they were not given.++## Enforcement points, all of them++Every one of these must consult membership, and each needs a test:++1. `api/_lib/home/store.js`: `getConnection` and friends resolve through membership, not+ `user_id` equality. **This is the change that touches everything; do it first and let the+ tests tell you what you missed.**+2. `api/_lib/home/runtime.js`: `acquire` authorises by membership.+3. The room graph projection: filtered by `entity_scope` before serialization.+4. The gate: a guarded action from a `guest` is refused with a role reason, not a confirmation.+5. `POST /api/home/:id/confirm`: role-checked.+6. Grants, layout, invites, disconnect: per the table.+7. The MCP and chat tools: a bearer principal inherits the role of the user whose token it is.+8. `home_action_log`: `user_id` is the acting member, always. "Who did what" is the product here.++## Invitations++- An invite is an email or a link, short-lived, single-use, bound to the home and the role.+- Accepting requires an account. Sign-up flows through the existing paths; do not invent one.+- An invite can be revoked before acceptance and a member can be removed after.+- Removing a member revokes their standing allowances in the same transaction. A stale grant for+ a removed member is exactly the bug that gets someone burgled.++## SSO for the enterprise case++`api/auth/saml/[action].js` already exists. This order does not build SSO; it makes home+membership work with it:++- A SAML-authenticated user joins a household by the same invite path.+- If SAML supplies group claims, document the mapping to roles and implement it if the existing+ SAML handler already surfaces groups. If it does not, say so plainly and leave the manual path,+ rather than half-wiring a claim mapping.+- Deprovisioning: a removed identity must lose home access. Whatever the existing session+ revocation path is, ensure it reaches `home_members`.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | Migration: `home_members`, backfill every existing connection with an `owner` row, in one transaction. | `api/_lib/migrations/<ts>_home_members.sql` |+| 2 | Store: membership resolution replacing `user_id` equality, with the role returned on every read. | `api/_lib/home/store.js` |+| 3 | Scope filtering in the graph projection. | `api/_lib/home/store.js` or a sibling projection module |+| 4 | Role enforcement at all eight points. | as listed |+| 5 | Invitations: schema, endpoints, UI. | `api/home/[id]/members.js`, `src/home/members.js` |+| 6 | Member management UI: list, role change, remove, per-member scope editor, pending invites. | same |+| 7 | SAML notes and, if groups are available, the mapping. | `docs/home-security.md` or a new doc |+| 8 | Tests: a role matrix over every enforcement point. | `tests/home-roles.test.js` |++## Definition of done++- [ ] The role matrix above exists as an executable test that iterates roles by enforcement point. Paste the run: every cell asserted.+- [ ] A `guest` receives a role refusal, not a confirmation prompt, when attempting an unlock. Transcript.+- [ ] A scoped `guest` cannot read the state of an out-of-scope room: the filtered graph is proven at the API boundary, not in the UI.+- [ ] Removing a member deletes their standing allowances in the same transaction. Prove with the rows before and after.+- [ ] An invite is single-use and expires. Two refusals.+- [ ] The backfill gave every pre-existing connection exactly one `owner` row. Paste the count query.+- [ ] `home_action_log` attributes actions to the acting member, proved with two members acting on one home.+- [ ] The order 03 tenancy tests still pass unchanged: a non-member still gets 404, not 403.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| The membership change touches many call sites | That is why it is task 2 and why the tests come with it. Change the store's contract, run the suite, and fix what breaks. Do not add a parallel "or user_id equals" branch; that is how a role system becomes decorative. |+| Deciding whether a `member` may confirm | Yes. A `guest` may not. That is the line: a member lives there, a guest is visiting. |+| SAML groups are not exposed by the existing handler | Say so in the doc and ship the manual invite path. Do not half-wire a claim mapping you cannot test. |+| Tempted to let the UI hide what the server allows | Never. Every rule in the table is enforced server-side, and the UI merely reflects it. Prove enforcement at the API. |+| An enterprise asks for a custom role | Not in v1. The five cover households, house sitters, offices and hotels. Custom roles need a policy engine and that is a different product decision. |++## Report format++1. The full role matrix test output.+2. The guest-refusal and scope-filtering transcripts.+3. The member-removal grant cleanup proof.+4. The backfill count.+5. The two-member attribution proof.+6. Full-suite output.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-12-households-rbac.md++Never delete it on a partial.diff --git a/prompts/finish/home-13-observability.md b/prompts/finish/home-13-observability.mdnew file mode 100644index 000000000..dc688d7af--- /dev/null+++ b/prompts/finish/home-13-observability.md@@ -0,0 +1,152 @@+# 13. Observability, SLOs, alerting, incident runbook++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[02](home-02-bridge-runtime.md) and [03](home-03-api-surface.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+sed -n '1,30p' api/healthz.js+grep -n "export function classify\|export async function gather" api/_lib/ops/subsystem-health.js | head -20+grep -n "^export" api/_lib/alerts.js+node -e "console.log(require('./vercel.json').crons.length)"+curl -s https://three.ws/api/healthz | head -c 400+```++The platform already has a subsystem-health pattern (`api/_lib/ops/subsystem-health.js`, surfaced+by `api/healthz.js` and `api/status.js`) and an alerting path (`sendOpsAlert`). **Extend both.+Do not build a second health endpoint or a second alert channel.**++## What "down" means for this lane, and why it is unusual++Most outages here are not ours. A user's house is offline, their token expired, their internet+dropped. Those are per-tenant conditions that must never page anyone and must always be visible+to that one user. Conversely, "every home went unreachable in the last five minutes" is an+outage, and it looks identical at the level of a single connection.++**The whole design of this order is separating the two.** A per-tenant failure is a UI state; a+correlated failure across tenants is an alert.++## The signals++Add a `home` subsystem to `gatherSubsystemHealth`, classified the way its siblings are:++| Signal | Source | Green | Yellow | Red |+|---|---|---|---|---|+| Connected homes | `runtime.stats()` aggregated | any | n/a | n/a (a count, not a verdict) |+| Handshake success rate, 15 min | `home_connections.last_ok_at` / `last_error_at` | over 95% | 80 to 95% | under 80% |+| Breaker-open homes | runtime | under 2% | 2 to 10% | over 10% |+| Action success rate, 15 min | `home_action_log.outcome` | over 98% | 95 to 98% | under 95% |+| Confirmation expiry rate | `home_confirmations` | under 20% | 20 to 40% | over 40% (the UI is failing people) |+| SSE subscriber leak | `stats().subscribers` versus open streams | flat | growing | growing and unbounded |+| p95 action latency | timing on the act path | under 1.5 s | 1.5 to 4 s | over 4 s |++Every rate is computed **across tenants**, so one offline house cannot move it and a regional+internet event or a bad deploy can.++## The SLOs++Publish these in `docs/home-operations.md` and hold to them:++| SLO | Target | Window | Error budget |+|---|---|---|---|+| Action availability (our side) | 99.5% of actions reach the house or return a designed error | 30 days | 3.6 hours |+| Action latency | p95 under 1.5 s, our leg only, excluding the house | 30 days | |+| State freshness | p95 under 2 s from a device change to the SSE event | 30 days | |+| Confirmation integrity | **100%**, no exceptions, no budget | always | zero |++The last row is not an availability target, it is a correctness invariant: a guarded action+executing without a valid confirmation is a Sev 1 regardless of volume. Say that in the doc.++## Alerting++Route through `sendOpsAlert`. Three alerts, and only three, because an alert nobody acts on+trains people to ignore the channel:++1. **Correlated unreachability**: handshake success under 80% across at least 10 distinct homes+ in 15 minutes. Almost always us (a deploy, an egress change, a DNS problem).+2. **Confirmation integrity violation**: any action with `guarded = true` and `confirmed_by is+ null` and `outcome = 'ok'`. This should be impossible; a single row is an alert.+3. **Subscriber leak**: `stats().subscribers` above the open-stream count by a growing margin+ over three consecutive checks. This is the failure mode that quietly kills instances.++A per-tenant failure never alerts. Ever. It appears in that user's UI and in their action log.++## The incident runbook++Write `docs/home-operations.md` covering, for each of the three alerts and for the four most+likely per-tenant reports:++- The symptom as the reporter describes it.+- The first command to run, with the real `gcloud logging read` filter for this service.+- How to tell "their house" from "us" in under two minutes.+- The rollback path (`docs/ops/gcp-production.md`) and when to use it.+- What to tell the user, in plain language.++Include the correlation query as a copy-pasteable SQL statement: given one user's complaint, is+anyone else affected right now?++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | `classifyHomeHealth` and its gatherer, following the file's existing shape. | `api/_lib/ops/home-health.js`, wired into `api/_lib/ops/subsystem-health.js` |+| 2 | Timing instrumentation on the act path and the SSE path. | `api/_lib/home/runtime.js`, `api/home/**` |+| 3 | The three alerts, with a cron if one is needed (`vercel.json` `crons`, then `scripts/create-gcp-scheduler.mjs` syncs Cloud Scheduler). | as needed |+| 4 | The confirmation-integrity check as both an alert and a test. | `tests/home-integrity.test.js` |+| 5 | `docs/home-operations.md` with the SLOs, the runbook and the correlation query. | as listed |+| 6 | A per-tenant status surface: the user can see their own home's health without asking us. | `src/home/manage.js` |++## Definition of done++- [ ] `curl /api/healthz` returns a `home` subsystem block with real numbers. Paste it.+- [ ] Stopping a single Home Assistant does **not** move the aggregate to red and does **not** alert. Prove both.+- [ ] Simulating correlated failure (block egress, or point ten test homes at a dead address) does turn the subsystem red and does fire alert 1. Paste the alert.+- [ ] Alert 2 fires on a synthetic row inserted directly into `home_action_log` with `guarded = true, confirmed_by = null, outcome = 'ok'`, and the query finds it within the check window. Then delete the synthetic row and say so.+- [ ] The subscriber-leak detector fires on a deliberately leaked subscription and clears when it is released.+- [ ] p95 action latency is measured and reported against the 1.5 s target, from real traffic against a real house.+- [ ] `docs/home-operations.md` exists, is linked from `docs/start-here.md`, and every command in it was run by you and produced output. Paste one of each.+- [ ] The user-facing per-tenant status shows a real reason for a real failure, screenshotted.+- [ ] `npm run check:cron-drift` (if the lane added a cron) passes and the `vercel.json` cron count matches.+- [ ] `npm run check:claude` passes, since the cron count is one of the facts it guards.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| No production traffic yet to measure | Generate it against a real local house and say the numbers are pre-launch. A measured local baseline beats an invented production one. Re-measure in order 20. |+| Tempted to alert on a single user's house being down | Do not. It will page you every night and you will stop reading the channel. It is a UI state. |+| The confirmation-integrity check seems paranoid for something "impossible" | Impossible things caused by a refactor are exactly what a zero-budget invariant is for. It costs one query. |+| No `gcloud` access in this container | The log filters still get written and tested where access exists; the CLAUDE.md playbook covers the credential path. State clearly which commands you ran and which you could not. |+| Adding a cron | `vercel.json` is live config: `scripts/create-gcp-scheduler.mjs` reads `crons` to sync Cloud Scheduler, and `npm run check:claude` asserts the count in CLAUDE.md matches. Update both. |++## Report format++1. The healthz block.+2. The single-house-down non-alert proof and the correlated-failure alert.+3. The integrity alert firing, and confirmation that the synthetic row was removed.+4. The leak detector firing and clearing.+5. Measured p95 latency.+6. One command output from each runbook section.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-13-observability.md++Never delete it on a partial.diff --git a/prompts/finish/home-14-reliability-scale.md b/prompts/finish/home-14-reliability-scale.mdnew file mode 100644index 000000000..09794e9ce--- /dev/null+++ b/prompts/finish/home-14-reliability-scale.md@@ -0,0 +1,148 @@+# 14. Reliability and the scale envelope++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[02](home-02-bridge-runtime.md), [03](home-03-api-surface.md) and+[13](home-13-observability.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Measure, then state. Never assume a number.**++---++## Step 0: re-derive the current state++```bash+node -e "import('./api/_lib/home/runtime.js').then(m=>console.log(Object.keys(m)))"+gcloud run services describe three-ws-api --region us-central1 --format=yaml 2>/dev/null | grep -A5 -i "resources\|concurrency\|scal" | head -30+cat docs/ops/gcp-credits-plan.md | head -40+curl -s https://three.ws/api/healthz | head -c 300+```++## The envelope, measured at three volumes++Fill this table with **measured** numbers and publish it in `docs/home-operations.md`. Every cell+that says "assumed" is an unfinished line.++| Volume | Connections per instance | Heap | p95 action | Behaviour |+|---|---|---|---|---|+| 10 homes | | | | everything inline, nothing to tune |+| 1,000 homes | | | | |+| 100,000 homes | | | | |++Measure the first two for real. For the third, measure the per-connection cost precisely and+extrapolate honestly, naming the extrapolation and its assumptions. A measured unit cost plus a+stated model is engineering; a guessed total is not.++The unit costs that matter, each measured:++- Heap per idle connection, and per connection for a large house (500+ entities).+- CPU per state burst of 100 entity updates.+- Socket count and file-descriptor headroom per instance.+- SSE stream cost per subscriber, separate from connection cost.+- Cold-start time to first connected home on a fresh instance.++## Backpressure and degradation, in order++The system must degrade in latency and features, never in correctness and never in safety. Write+the ladder down and implement it:++1. Under the per-instance cap: normal.+2. At the cap: new acquisitions get a short-lived unpooled connection. Slower, correct.+3. Under DB pressure: reads serve from the in-memory graph; writes still go through, because a+ write is somebody pressing a button.+4. Under severe load: SSE stream admission is limited before action admission is. **A user who+ asks to unlock a door gets served before a user who is watching a dashboard.**+5. Beyond that: `503` with `retry-after` and a designed UI state. Never a silent hang, never a+ half-applied action.++**The gate never degrades.** No load condition may cause a guarded action to skip a confirmation.+If shedding load would require weakening the gate, shed the action instead and say so.++## Chaos: the seven failures, each run for real++| # | Failure | Injected how | Must |+|---|---|---|---|+| 1 | House goes offline mid-session | stop the container | stale not empty, recovers on restart with no reload |+| 2 | House flaps (up, down, up) every 5 s for 2 minutes | a loop against the container | the breaker damps it; no alert storm; no socket leak |+| 3 | Token revoked while connected | delete the token in Home Assistant | connection moves to `auth_failed` with the real reason; the user is told to reconnect |+| 4 | Our instance recycled mid-stream | `docker restart` the API, or SIGTERM the process | streams reconnect client-side; sockets closed cleanly on the house's side |+| 5 | Database unavailable | point `DATABASE_URL` at a dead host | reads degrade to the in-memory graph, writes fail with a designed error, no crash loop |+| 6 | Slow house (2 s per response) | a latency shim in front of the container | timeouts bound it; one slow house does not slow others; prove isolation |+| 7 | 500-entity house with a 10-per-second update rate | the demo integration plus a generator | frame budget held in the UI, coalescing works, heap flat |++Failure 6 is the one that finds shared-resource bugs. Run it with a second, fast house connected+and prove the fast one is unaffected.++## Cloud Run configuration++Read `docs/ops/gcp-production.md` and `docs/ops/gcp-credits-plan.md` before changing anything.+CLAUDE.md pre-approves config-only `gcloud run services update` changes; a deploy is still+owner-gated.++Decide and justify, with the measured number behind each:++- Concurrency per instance (the current value, and whether long-lived SSE streams change it).+- Memory limit, from the measured heap plus headroom.+- Whether this lane needs a `minScale` above zero, and the honest cost of saying yes. Default is+ no: the pool is a cache, cold starts are sub-second, and paying to keep sockets warm is a+ decision that needs a measured latency complaint behind it.+- CPU throttling behaviour with an idle SSE stream open, which is the setting most likely to be+ wrong for this workload. Test it, do not reason about it.++## Tasks++| # | Task |+|---|---|+| 1 | A load harness that opens N real connections against N real Home Assistant containers (or one instance with N tokens, stated either way). `scripts/home-load.mjs`. |+| 2 | Measure every unit cost above. Record the raw output in `tasks/home/` as evidence, the way `tasks/sim-readiness/` does. |+| 3 | Implement the backpressure ladder. |+| 4 | Run all seven chaos scenarios and fix what they break. |+| 5 | Decide and apply the Cloud Run configuration, with the justification. |+| 6 | Publish the envelope table in `docs/home-operations.md`. |++## Definition of done++- [ ] The envelope table has measured numbers for 10 and 1,000 homes and a stated extrapolation for 100,000. No cell says "assumed".+- [ ] Every unit cost measured, with the raw evidence file committed under `tasks/home/`.+- [ ] All seven chaos scenarios run, with a transcript each, and every failure they exposed fixed.+- [ ] Scenario 6 proves isolation: the fast house's p95 is unchanged with a slow house connected. Paste both numbers.+- [ ] The backpressure ladder is implemented and each rung is demonstrated, including that action admission survives longer than stream admission.+- [ ] A load test proves the gate never degrades: guarded actions under saturation still require confirmation. Assert it.+- [ ] The Cloud Run configuration decision is written down with its measured justification, including the CPU-throttling test result.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Cannot run 1,000 Home Assistant containers | You do not need to. Measure the per-connection cost precisely with 10 to 50 real ones, then drive the pool with a protocol-level load generator for the connection count. State exactly which part was real and which was generated. |+| The 100,000 number needs a distributed design | Then say so, with the measured point where the single-instance model breaks and what the next architecture is. An honest ceiling with a named successor beats a fabricated capacity. |+| Tempted to raise `minScale` to fix a cold start | Measure the cold start first. Sub-second is fine and free. Credits are approved for quality, but paying to hide a problem you have not measured is not quality. |+| A chaos scenario reveals a bug in `packages/home-bridge` | Fix it there, add a test there, and per the CLAUDE.md open-source rule, upstream anything that belongs to `home-assistant-js-websocket`. |+| The load harness would hammer a third party | It must only ever point at your own containers. Never load-test somebody's house. |++## Report format++1. The completed envelope table with its evidence file path.+2. Every unit cost with how it was measured.+3. Seven chaos transcripts and every fix made.+4. The isolation numbers from scenario 6.+5. The backpressure demonstration, rung by rung.+6. The Cloud Run decision and its justification.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-14-reliability-scale.md++Never delete it on a partial.diff --git a/prompts/finish/home-15-privacy-retention.md b/prompts/finish/home-15-privacy-retention.mdnew file mode 100644index 000000000..d4dff63d8--- /dev/null+++ b/prompts/finish/home-15-privacy-retention.md@@ -0,0 +1,156 @@+# 15. Privacy, retention, export and deletion++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[01](home-01-connection-store.md) to [08](home-08-voice-loop.md) must have landed, because this+order is an inventory of what they created.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+ls api/_lib/migrations | grep -i home+grep -rn "logHomeAction\|logAudit" api/_lib/home/ api/home/ --include=*.js | wc -l+grep -rn "console.log\|log(" api/_lib/home/ --include=*.js | head -20 # what reaches the logs+grep -rn "retention\|deleteUser\|export" api/ --include=*.js -l | grep -iE "account|user|gdpr|privacy" | head+```++That last grep matters: if the platform already has an account-deletion or data-export path, this+lane must join it rather than build a parallel one. Find it before you write anything.++## The inventory (build it first, it is the deliverable)++Enumerate every piece of data this lane creates, where it lives, why it exists, and how long it+stays. Publish it as a table in `docs/home-privacy.md`. Nothing may be missing; an+undocumented data class is the finding.++| Data | Table or store | Why it exists | Retention | Deleted by |+|---|---|---|---|---|+| Home access token | `home_connections.access_token_enc` | to reach the house | until revoked; scrubbed to `''` on revoke | revoke, account deletion |+| Base URL | `home_connections.base_url` | to reach the house | same | same |+| Entity and area names | in-memory graph only | to render and to reason | **never persisted** | n/a |+| Entity states | in-memory graph only | to render | **never persisted** | n/a |+| Room layout | `home_layouts.layout` | the user authored it | until deleted | user, account deletion |+| Standing allowances | `home_entity_grants` | the user granted them | until revoked or expired | user, member removal, account deletion |+| Action log | `home_action_log` | "what did my agent do in my house" | **decide and justify below** | retention job, account deletion |+| Confirmations | `home_confirmations` | the safety gate | 90 s TTL, then purged | retention job |+| Voice audio | nowhere | n/a | **never stored** | n/a |+| Voice transcripts | conversation state only | the turn | cleared with the conversation | user |+| Membership | `home_members` | roles | until removed | user, account deletion |++**"Entity states are never persisted" is a promise, and it is the most important line in the+table.** A log of every time a light went on in someone's bedroom is an occupancy record. The+in-memory graph is a cache that dies with the instance, and it must stay that way. If any order+introduced a persisted state history, find it and remove it, or justify it explicitly with a+retention period and a user-facing disclosure.++## The action log retention decision++`home_action_log` is the one genuinely difficult call. It is the audit trail the enterprise case+needs and it is also a behavioural record of a household.++Decide, justify in the doc, and implement:++- A default retention (90 days is the recommendation: long enough for "what happened last month",+ short enough not to be a surveillance archive).+- A user-visible control to shorten it, and for the enterprise case, an admin control to extend it+ with a stated reason.+- A purge job (a cron in `vercel.json`, synced by `scripts/create-gcp-scheduler.mjs`), not a+ promise.++## Logging hygiene++Home data reaching application logs is a leak with a long tail, because logs go to a different+system with different retention and different access.++- No entity name, area name, scene name, base URL or token in any log line. `api/_lib/scrub-secrets.js`+ exists; read it and use it.+- Log entity **ids** where you must correlate, never friendly names. An id is opaque enough; a+ name is "Sarah's Bedroom Camera".+- Error messages returned to the user may name an entity (they need to). Error messages sent to+ logs and alerts must not.+- Audit the actual log output, not the code: run the lane and read what came out.++## Export and deletion++- **Export**: a user can download everything this lane holds about them, in JSON, through the+ platform's existing export path if one exists. It must include every row in the inventory.+- **Deletion**: deleting an account removes every row. Prove it with a per-table count before and+ after, over a real account with data in every table.+- **Deleting one home** removes its layout, grants, members, confirmations and action log, and+ scrubs its credential. Cascades handle most of it; assert them rather than trusting them.+- Deletion must be idempotent and must not orphan rows in any table added by this campaign.++## Disclosure++Write the user-facing text, not just the internal doc:++- On the connect screen (order 05), a plain sentence about what the token can do and what we+ store. Not a link to a policy, a sentence in front of them.+- On the voice opt-in (order 08), what is processed locally and what leaves the device.+- In `docs/home-privacy.md`, the whole inventory, for the reader who wants detail.+- If the platform has a privacy policy page, this lane's data classes must appear in it. Find it+ and update it, or state plainly that none exists.++## Tasks++| # | Task |+|---|---|+| 1 | Build the inventory by reading the migrations and the code, not by copying the table above. Reconcile any difference and say what you found. |+| 2 | `docs/home-privacy.md`, linked from `docs/start-here.md` and `docs/smart-home.md`. |+| 3 | The retention decision, the user control, and the purge cron. |+| 4 | The logging audit and every fix it produces. |+| 5 | Export and deletion, joined to the platform's existing paths. |+| 6 | The user-facing disclosure copy on both surfaces. |+| 7 | Tests: deletion completeness, purge correctness, and a log-scrubbing assertion. |++## Definition of done++- [ ] The inventory in `docs/home-privacy.md` matches the schema exactly. Prove it by listing every table created by this campaign and showing each appears in the table.+- [ ] No persisted entity-state history exists anywhere in the lane. Prove it with the schema listing.+- [ ] Account deletion over a real account with rows in every table leaves zero rows. Paste per-table counts before and after.+- [ ] Deleting one home leaves the user's other homes untouched, and removes all of that home's rows. Counts before and after.+- [ ] Export returns every inventory row for a real account. Paste the JSON keys.+- [ ] The purge job deletes action-log rows past retention and nothing else. Run it against seeded old and new rows and paste the counts.+- [ ] The log audit: run a full connect, act, guarded-refusal and confirm cycle, then grep the captured logs for the base URL, the token, and three entity friendly names. Zero hits, pasted.+- [ ] The disclosure copy is on both surfaces, screenshotted.+- [ ] `npm run check:cron-drift` and `npm run check:claude` pass if a cron was added.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| No platform export or deletion path exists | Then this lane builds its own, scoped to home data, and your report names the gap so the platform-wide one can be built later. Do not skip it. |+| The action log retention decision feels like a product call | Make it (90 days), implement the controls, and write the justification. A shipped default with a control beats an unanswered question. |+| Grep finds entity names in logs from an earlier order | That is this order's job to fix. Fix it there, add the assertion here. |+| Someone proposes storing state history "for analytics" or "for the agent's memory" | Refuse by default. If a genuine product need appears, it needs its own explicit opt-in, its own retention, and its own disclosure, and it is not part of this campaign. |+| Legal wording feels out of scope | The plain-language sentences are in scope and are what users actually read. Policy language is the owner's; write the sentences and flag the policy page in your report. |++## Report format++1. The reconciled inventory and any difference from the table above.+2. The deletion and per-home deletion counts.+3. The export key listing.+4. The purge run counts.+5. The log-grep zero-hit proof.+6. The disclosure screenshots.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-15-privacy-retention.md++Never delete it on a partial.diff --git a/prompts/finish/home-16-test-program.md b/prompts/finish/home-16-test-program.mdnew file mode 100644index 000000000..a7e00605d--- /dev/null+++ b/prompts/finish/home-16-test-program.md@@ -0,0 +1,156 @@+# 16. The test program: e2e, the Home Assistant version matrix, the live harness++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Run this after the+orders it tests have landed, and before order 20.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+npx vitest run --root . 2>&1 | tail -5+ls tests/home-*.test.js tests/e2e/home-*.spec.js 2>/dev/null+npx playwright test --list 2>/dev/null | grep -i home | head+cat packages/home-bridge/tests/fixtures/home.json | head -3+```++## The problem this order solves++By now the lane has tests written by six different orders against whatever Home Assistant version+happened to be `stable` that day. Home Assistant ships a release every month and deprecates+WebSocket commands and entity attributes across them. **The lane's correctness depends on a third+party's monthly release, and nothing currently notices when that breaks.**++## The harness++A single, reusable way for any test or any developer to get a real Home Assistant.++`scripts/home-test-instance.mjs`, doing everything the investigation did by hand:++| Command | Does |+|---|---|+| `--up [--version 2026.9]` | pulls and starts a container on a free port, waits for readiness |+| `--onboard` | completes onboarding through the real API, mints a long-lived token, prints it |+| `--seed` | enables `demo:`, creates areas, a floor, assigns entities, creates the Bedtime and Away Mode scenes, enables `mcp_server`, exposes a lock to Assist |+| `--down` | removes the container and its config directory |+| `--json` | machine-readable output so a test can consume it |++Idempotent, safe to run twice, and it must never touch a container it did not create. It writes+its config under a gitignored path and never commits a token.++**Every existing live test in the lane switches to this harness.** One way to get an instance,+not six.++## The version matrix++Home Assistant versions to hold: **the current `stable`, the two previous monthly releases, and+the oldest still in wide use.** Determine the real version list from the Home Assistant release+history at the time you run this; do not hardcode the list from this file.++`scripts/home-version-matrix.mjs` runs the lane's live suite against each version and produces a+table:++| Version | Connect | Registries | State stream | Service call | Scenes | `mcp_server` | Notes |+|---|---|---|---|---|---|---|---|++A cell that fails is a finding, and the finding is either "we depend on something version-specific+and must feature-detect" or "this version is genuinely unsupported and the UI must say so". Both+are acceptable outcomes; silence is not.++Feature detection, never version sniffing: ask the instance what it supports (the `mcp_server`+probe already does this) rather than parsing a version string and branching. Record the supported+range in `docs/smart-home.md` and in `packages/home-bridge/README.md`.++## The e2e set++Playwright, in `tests/e2e/`, against a real seeded instance from the harness. The journeys, each+end to end through the real UI:++1. Connect a home, see the rooms, disconnect.+2. Toggle a light from the 3D scene and see the real device change (assert on the Home Assistant side).+3. Change a light in Home Assistant and see the scene update.+4. Say "good night" through the chat surface, watch the confirmation flow if the house's scene+ touches a lock, and assert the real scene ran.+5. Attempt an unlock, get the confirmation card, cancel it, assert the door stayed locked.+6. Attempt an unlock, confirm it, assert the door unlocked.+7. A guest member (order 12) attempts an unlock and is refused by role.+8. Kill Home Assistant mid-session, see the stale state, restart, see recovery. No page reload.+9. Author a floorplan, reload, see it persist.+10. The private-host refusal, with no network call.++Journeys 5, 6 and 7 are the ones that matter. **Every one of them asserts on the real lock's real+state read back from Home Assistant, never on our own UI text.**++## Flake policy++A flaky test in this lane is worse than no test, because it trains people to ignore a suite that+guards a door.++- No arbitrary `waitForTimeout`. Wait for a condition: the SSE event, the state in Home Assistant,+ the element.+- Every live test has a hard timeout and cleans up its instance in a `finally`.+- A test that fails intermittently gets fixed or deleted in the same session it is discovered.+ Never quarantined and never retried into passing.+- The suite must pass ten consecutive runs before you call this order done. Run it ten times.++## Tasks++| # | Task | Files |+|---|---|---|+| 1 | The harness. | `scripts/home-test-instance.mjs` |+| 2 | Migrate every existing live test in the lane onto it. | `tests/home-*.test.js`, `packages/home-bridge/tests/live-home.test.js` |+| 3 | The version matrix runner and its output table. | `scripts/home-version-matrix.mjs`, `docs/smart-home.md` |+| 4 | Feature detection wherever the matrix found a version difference. | `packages/home-bridge/src/*` |+| 5 | The ten e2e journeys. | `tests/e2e/home-*.spec.js` |+| 6 | Regenerate the fixture from the current stable so the pure suite tracks reality. | `scripts/capture-home-fixture.mjs`, the fixture |+| 7 | A `README.md` section in `tests/e2e/README.md` explaining how to run the lane's suites. | as listed |++## Definition of done++- [ ] `node scripts/home-test-instance.mjs --up --onboard --seed --json` produces a working instance and a token, twice in a row, and `--down` cleans up completely. Paste both runs.+- [ ] Every live test in the lane uses the harness. `grep -rn "localhost:8123" tests/ packages/` shows only the harness itself.+- [ ] The version matrix table is filled in from real runs, is published in `docs/smart-home.md`, and every failing cell has either a feature detection or a stated unsupported range.+- [ ] All ten e2e journeys pass. Paste the run.+- [ ] Journeys 5, 6 and 7 assert on Home Assistant's own lock state, and the assertion is visible in the test source. Quote it.+- [ ] `grep -rn "waitForTimeout" tests/e2e/home-*.spec.js` returns nothing.+- [ ] Ten consecutive full runs of the lane's suites, all green. Paste the tally.+- [ ] The fixture is regenerated and the pure suite still passes against it.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run audit:docs` clean, `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Docker is unavailable | Then this order cannot be done honestly, because every claim here rests on a real instance. Say so at the top of your report and stop that specific work; do not substitute fixtures and call the matrix verified. |+| An old Home Assistant version fails to boot | Record it as unsupported with the error, and set the supported floor accordingly. That is a finding, not a blocker. |+| Disk fills from many container images | `npm run clean:worktrees` reclaims worktrees; `docker image prune` reclaims images. Pull versions one at a time in the matrix runner and remove each after. |+| A journey is slow because it waits on real hardware timing | Real is the point. Bound it with a hard timeout and wait on conditions, not sleeps. |+| A test is flaky and the deadline is close | Delete it and say so. A flaky test on a door is worse than an absent one. |++## Report format++1. The two harness runs and the cleanup.+2. The version matrix table, filled from real runs.+3. Every feature detection added.+4. The e2e run, and the quoted lock assertions from journeys 5 to 7.+5. The ten-consecutive-runs tally.+6. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-16-test-program.md++Never delete it on a partial.diff --git a/prompts/finish/home-17-a11y-i18n-mobile.md b/prompts/finish/home-17-a11y-i18n-mobile.mdnew file mode 100644index 000000000..b59146a8e--- /dev/null+++ b/prompts/finish/home-17-a11y-i18n-mobile.md@@ -0,0 +1,146 @@+# 17. Accessibility, 87 locales, mobile and PWA++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[05](home-05-connect-flow.md) to [08](home-08-voice-loop.md) must have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+ls public/locales | wc -l # the locale count to match+npm run i18n:lint+head -30 tests/e2e/a11y-top-pages.spec.js # the existing axe gate and its rule sets+grep -n "priority" data/pages.json | head -3+npx playwright test tests/e2e/a11y-top-pages.spec.js 2>&1 | tail -10+```++## Why accessibility is load-bearing here specifically++A voice-controlled home is, for a lot of people, an assistive technology. Someone who cannot+easily reach a light switch is exactly the user for whom this product is not a convenience.+Shipping a home controller that a screen-reader user cannot operate would be a particular kind of+failure, and it is also the case where the 2D fallback from order 06 stops being a nicety.++## The accessibility bar++WCAG 2.1 AA, enforced by the existing axe gate (`wcag2a`, `wcag2aa`, `wcag21aa` rule sets, no+best-practice rules, so it stays a hard gate and not a taste argument). Add every home route to+that spec's page list.++Beyond what axe can see, and each verified by hand:++| Requirement | Verified by |+|---|---|+| The whole lane is operable by keyboard alone | walk connect, act, confirm, floorplan, disconnect with no mouse |+| Focus is visible at every step and never trapped | including inside the 3D canvas and the confirmation card |+| The confirmation card takes focus when it appears and announces itself | it is the safety control; a user must not be able to miss it |+| Screen reader announces state changes | a light turning on, a home going stale, a confirmation pending. Use a polite live region; the confirmation uses assertive. |+| The 3D scene has a complete non-visual equivalent | order 06's 2D fallback plus a semantic room and device list. A canvas is opaque to a screen reader, so the fallback is the accessible path, not a downgrade. |+| Nothing depends on colour alone | locked versus unlocked, on versus off, stale versus live all carry a shape or a label |+| Reduced motion respected | `prefers-reduced-motion` disables scene transitions and any animation |+| Target sizes | 44px minimum on touch for every control, including in the floorplan editor |+| Contrast | AA on every state, including the desaturated stale state, which is the one most likely to fail |++## Internationalisation++87 locales exist. Everything user-visible goes through the existing extraction path.++- `npm run i18n:extract` then `npm run i18n:translate`, then `npm run i18n:lint` clean.+- **Entity names, area names and scene names are never translated.** They are the user's own+ words. Make sure the extractor does not capture them and that no string concatenation puts a+ translated fragment inside a user-supplied name.+- Plurals and number formatting through the existing i18n mechanism, not string concatenation.+ "3 rooms" and "1 room" both come from the catalog.+- Temperature units follow the Home Assistant instance's own configuration, which it reports.+ Never assume Celsius and never guess from the locale: read what the house says.+- RTL: the connect flow, the manage view, the floorplan editor and the scene all work in an RTL+ locale. Test with a real RTL locale from `public/locales`, not with a CSS override.+- Voice (order 08): the language of the wake word and the ASR lane follows the existing+ `TALK_LANGUAGES` mechanism in `src/voice/talk-languages.js`. Do not add a second language store.++## Mobile++The phone is a primary surface here, not a secondary one. Someone standing in a doorway is on a+phone.++- 320px, 375px, 768px and 1440px all correct, on every state of orders 05, 06, 07.+- The 3D scene holds its frame budget on a mid-range phone or routes to the fallback automatically+ and says so.+- One-handed reach: the primary action on each screen is in the lower half.+- The confirmation card is unmissable on a small screen and cannot be dismissed by an accidental+ tap. It requires a deliberate action.+- Safe areas respected on notched devices.+- Installable as a PWA if the platform already has a manifest path; if it does not, say so and+ do not invent one for this lane alone.+- Wake-lock behaviour for a wall display: state the decision. A kitchen tablet showing the home+ scene should not sleep mid-use, and a phone should not be held awake by a background tab.++## Tasks++| # | Task |+|---|---|+| 1 | Add every home route to `tests/e2e/a11y-top-pages.spec.js` (or the lane's own axe spec) and fix every violation. |+| 2 | The keyboard walkthrough, the focus management on the confirmation card, and the live regions. |+| 3 | The semantic non-visual equivalent of the 3D scene. |+| 4 | Reduced motion, colour-independence, target sizes, contrast on the stale state. |+| 5 | Full i18n extraction and lint, with the never-translate rule for user data. |+| 6 | Temperature units from the instance. |+| 7 | RTL pass. |+| 8 | The four breakpoints on every state, plus the one-handed and safe-area work. |+| 9 | The wake-lock decision, implemented and documented. |++## Definition of done++- [ ] axe passes on every home route with the `wcag2a`, `wcag2aa`, `wcag21aa` rule sets. Paste the run.+- [ ] A recorded keyboard-only walkthrough of connect, act, guarded confirm, and disconnect.+- [ ] A screen-reader transcript (VoiceOver or NVDA) of: a light turning on, a home going stale, and a confirmation appearing. The confirmation must be announced assertively.+- [ ] The 2D fallback is operable by screen reader and can control the house. Recorded.+- [ ] `prefers-reduced-motion: reduce` disables scene animation. Screenshot the setting and the behaviour.+- [ ] Contrast checked on the stale and desaturated states specifically, with the measured ratios.+- [ ] `npm run i18n:lint` clean. Paste it.+- [ ] A user-supplied entity name is untouched in a non-English locale. Screenshot in two locales.+- [ ] A Fahrenheit-configured Home Assistant shows Fahrenheit regardless of browser locale. Screenshot both.+- [ ] An RTL locale renders connect, manage, scene and floorplan correctly. Four screenshots.+- [ ] All states at 320px, 375px, 768px, 1440px. The screenshot set.+- [ ] The confirmation card cannot be dismissed by a stray tap on a phone. Demonstrate.+- [ ] `npx playwright test tests/e2e/` passes with no new failures.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| No screen reader available in this environment | Use the platform's own tooling where possible and say exactly what you could and could not verify. Never claim a screen-reader pass you did not perform. |+| axe flags something inside the 3D canvas | A canvas is not accessible by nature; the fallback is the answer, and the canvas gets `aria-hidden` with the equivalent content adjacent. Do not suppress the rule. |+| The i18n extractor picks up entity names | Fix the call site so the user's data is passed as an interpolated value, never as part of a translatable string. |+| 87 locales seems like a lot of new strings | The pipeline handles it (`i18n:translate`). Your job is to make sure every string goes through it, not to translate by hand. |+| A phone cannot hold the frame budget | Route it to the fallback automatically, tell the user why in one sentence, and record the device class in your report. |++## Report format++1. The axe run.+2. The keyboard and screen-reader recordings and transcripts.+3. The reduced-motion and contrast evidence.+4. The i18n lint output and the two-locale entity-name screenshots.+5. The temperature-unit screenshots.+6. The RTL set and the four-breakpoint set.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-17-a11y-i18n-mobile.md++Never delete it on a partial.diff --git a/prompts/finish/home-18-docs-and-sdk.md b/prompts/finish/home-18-docs-and-sdk.mdnew file mode 100644index 000000000..dd3ecbaf9--- /dev/null+++ b/prompts/finish/home-18-docs-and-sdk.md@@ -0,0 +1,153 @@+# 18. Docs, SDK publish, the home MCP server package++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Run this once the+surfaces it documents have landed.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated. **Publishing to npm is owner-gated**: prepare everything so the+publish is one command and batch the owner action into a single message.++**Nothing in this file is a status claim to trust.** Step 0 re-measures.++---++## Step 0: re-derive the current state++```bash+npm run audit:docs+npm run publish:packages:dry 2>&1 | tail -20+npm run publish:mcp:dry 2>&1 | tail -20+ls docs/ | grep -i home+grep -rn "home" data/pages.json | head+cat packages/home-bridge/package.json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const p=JSON.parse(s);console.log(p.name,p.version,p.files,p.dependencies)})"+```++## The docs set++CLAUDE.md requires a doc layer per kind of change. This lane produced all of them, so all of them+are due:++| Layer | File | State |+|---|---|---|+| Public route | `/home`, `/home/:id` in `data/pages.json` | added by orders 05 and 06; verify |+| Package README | `packages/home-bridge/README.md` | exists; update for anything added since |+| New service READMEs | `services/home-satellite/`, `services/home-relay/` | required by CLAUDE.md and enforced by `npm run audit:docs` |+| Feature doc | `docs/smart-home.md` | exists; must now describe what shipped, not what was planned |+| Developer capability | `docs/api-reference.md` (the `/api/home/*` routes), `docs/mcp.md` (the home MCP tools) | update both |+| Subsystem docs | `docs/home-security.md`, `docs/home-operations.md`, `docs/home-privacy.md` | from orders 11, 13, 15 |+| Tutorial | `docs/tutorials/connect-your-home.md` | new: zero to a working agent in a real house |+| Structure | `STRUCTURE.md` rows for every surface and package | required |+| Changelog | `data/changelog.json` | one community-readable entry for the launch, plus any user-visible changes |++**`docs/smart-home.md` must stop reading as a plan.** Rewrite its status, its build plan and its+verification table to describe what exists. A doc that still says "phase 2, designed" after phase+2 shipped is worse than no doc.++## The tutorial is the deliverable that matters most++`docs/tutorials/connect-your-home.md`, written for someone who has never used three.ws and owns+a Home Assistant:++1. What you need (a Home Assistant reachable over https, and how to check).+2. Minting a long-lived token, with the exact path.+3. Connecting, and what "connected" looks like.+4. Your first command by text.+5. Your first command by voice.+6. What the agent will and will not do without asking, and why the door asks every time.+7. Adding a household member and what a guest can do.+8. What to do when it says your home is unreachable.++Every command must run. Every link must resolve. Per CLAUDE.md, docs are real implementations:+no placeholders, no "see the code".++## The packages++### `@three-ws/home-bridge`++Already exists at `packages/home-bridge`, currently unpublished. Before publishing:++- Version it honestly. It is pre-1.0 and its API will move; say so in the README.+- `files`, `exports`, `engines` and dependency ranges are already set; re-verify them against what+ the lane added (a `RelayTransport` from order 10 changes the export surface).+- `npm pack --dry-run` and read the file list. Nothing from `tests/` or a fixture with a token.+- The README's examples must run against a real instance. Run them.++### `@three-ws/home-mcp` (new)++A standalone MCP server that gives **any** assistant the three.ws home tools, following the shape+of the 40+ existing packages (read `packages/brain-mcp/README.md` and its `package.json` first).++This is a distribution surface: someone using Claude Desktop or an SDK gets home control through+three.ws without opening a browser. It wraps the same handlers as order 04, so it cannot diverge+on the gate.++**The gate over stdio needs a decision, and it must be written down.** An MCP client has no+session and cannot satisfy a confirmation. Either the server refuses guarded actions entirely and+says where to confirm (recommended, and the honest default), or it opens the three.ws+confirmation URL for the human. Choose, implement, and state it in the README. Never silently+allow a guarded action because no browser was present.++## Tasks++| # | Task |+|---|---|+| 1 | Rewrite `docs/smart-home.md` to describe what shipped. |+| 2 | Write `docs/tutorials/connect-your-home.md` and run every command in it. |+| 3 | Update `docs/api-reference.md` and `docs/mcp.md`. |+| 4 | Verify or add `STRUCTURE.md` rows for every surface, package and service in the lane. |+| 5 | Verify or add `data/pages.json` entries for every public route. |+| 6 | Ready `@three-ws/home-bridge` for publish; run `npm pack --dry-run` and read the file list. |+| 7 | Build `packages/home-mcp` with its README, the gate decision, and one runnable example. |+| 8 | A `data/changelog.json` entry in plain community language, then `npm run build:pages`. |+| 9 | `npm run audit:docs` clean, `npm run check:docs-search` current. |+| 10 | Batch the publish into one owner message with the exact commands. |++## Definition of done++- [ ] `npm run audit:docs` clean. Paste it.+- [ ] Every command in the tutorial was run by you, against a real Home Assistant, and produced the documented output. Paste a transcript per step.+- [ ] Every link in every new doc resolves. `audit:docs` covers this; paste the run.+- [ ] `docs/smart-home.md` contains no unshipped claim presented as shipped, and no shipped thing described as planned. State how you checked.+- [ ] `npm pack --dry-run` file lists for both packages, with no test files, no fixtures containing tokens, and no stray artifacts.+- [ ] `npm run publish:packages:dry` and `npm run publish:mcp:dry` both clean. Paste them.+- [ ] The `home-mcp` gate decision is implemented, tested (a guarded action over stdio does not execute), and documented in its README.+- [ ] Both READMEs' examples were executed and worked. Paste the runs.+- [ ] `STRUCTURE.md` covers every new directory; `data/pages.json` covers every new route.+- [ ] The changelog entry reads as plain language with no commit jargon, and `npm run build:pages` validated it.+- [ ] `npm run check:docs-search` reports the index current.+- [ ] `npm run check:rules -- --paths <your files>` clean.+- [ ] The owner message is written: exact commands, one paragraph, nothing else needed from them.++## Never blocked++| Blocker | Do this |+|---|---|+| npm publish is owner-gated | Correct. Prepare everything, prove it with the dry runs, and batch the ask. Never publish. |+| A doc would be easier as a link to the code | CLAUDE.md forbids it. Write the explanation and the runnable example. |+| The tutorial needs a real house | Use the order 16 harness, or the docker one-liner in the context file. Do not write steps you did not execute. |+| `home-mcp` duplicates `home-bridge` | It must not. It wraps the same handlers. If you find yourself copying gate logic, stop and import it. |+| The changelog entry is hard to write without jargon | Write what a person would notice. "Your agent can run your house now, and it asks before it unlocks anything." |++## Report format++1. `audit:docs`, `check:docs-search`, both dry-run publishes.+2. A transcript per tutorial step.+3. Both `npm pack --dry-run` file lists.+4. The `home-mcp` gate decision, its test, and the README section.+5. The changelog entry text.+6. The single owner message for publishing.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-18-docs-and-sdk.md++If the npm publish is the only outstanding step, leave the file in place, say so, and name the+owner action. Never delete it on a partial.diff --git a/prompts/finish/home-19-plans-entitlements.md b/prompts/finish/home-19-plans-entitlements.mdnew file mode 100644index 000000000..c11432a4f--- /dev/null+++ b/prompts/finish/home-19-plans-entitlements.md@@ -0,0 +1,145 @@+# 19. Plans, entitlements and quotas++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Orders+[03](home-03-api-surface.md), [12](home-12-households-rbac.md) and+[14](home-14-reliability-scale.md) must have landed: you cannot price what you have not measured.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated. **Setting a price the platform charges is an owner decision**:+implement the mechanism, propose the numbers, and batch the price approval into one message.++---++## Step 0: re-derive the current state++```bash+grep -n "^export" api/_lib/account-tier.js | head+node -e "import('./api/_lib/account-tier.js').then(m=>console.log(JSON.stringify(m.ACCOUNT_TIERS,null,1)))" | head -40+grep -n "^export" api/_lib/three-tier.js | head+ls api/billing api/credits api/subscriptions 2>/dev/null+grep -rn "resolveAccountTier\|tierById" api/ --include=*.js -l | head+```++The platform already has tiers (`api/_lib/account-tier.js`), a $THREE holder ladder+(`api/_lib/three-tier.js`), credits and subscriptions. **Join them. Do not invent a fourth+entitlement system for this lane.**++## What actually costs money here++Be honest about the cost model before proposing anything, because it is unusual: the expensive+part is not compute per action, it is **holding a live socket**.++| Cost | Driver | Measured in |+|---|---|---|+| Connection hold | homes connected concurrently, from order 14's per-connection heap | memory, and therefore instance count |+| SSE streams | dashboards and wall displays left open | same |+| Agent turns | LLM tokens per voice or chat interaction | the existing brain-router costs |+| Speech | ASR and TTS per utterance | the existing lanes |+| Relay (order 10) | sustained outbound sockets from houses | memory plus egress |++A house that is connected and idle costs real money whether or not anyone speaks to it. Any+entitlement design that meters only actions will be wrong.++## The dimensions to meter++Propose limits per tier along these, with the measured cost behind each:++| Dimension | Why |+|---|---|+| Homes connected | the primary cost driver |+| Household members per home | the enterprise dimension |+| Concurrent live streams per home | wall displays |+| Voice minutes per month | the ASR and TTS lane cost |+| Agent turns per month | LLM cost, probably already metered by an existing counter; find it before adding one |+| Action-log retention | order 15's decision, and a natural enterprise upsell |+| Relay connections | if order 10 landed |++## The rules the limits must obey++These are product commitments, not implementation details. Write them into the code as comments+and into the docs as text:++1. **A limit never blocks a safety action.** Over quota, a user can still lock their door, close+ their garage and arm their alarm. The safe direction is always free. A product that will not+ let someone lock up because they hit a quota is indefensible.+2. **Downgrading never silently disconnects a house.** It marks connections over the new limit as+ inactive with a clear explanation and lets the user choose which to keep. Nothing is deleted.+3. **A quota is shown before it is hit**, on the manage surface, with the reset date.+4. **Enterprise limits are configurable per account**, not hardcoded, because that is what the+ sales conversation is.+5. **Nothing about the gate is a paid feature.** Confirmations, the audit log's integrity, and the+ role system's safety properties exist on every tier. Selling safety would be wrong and would+ also make the free tier a liability.++Rules 1 and 5 are the ones to fight for if anyone pushes back.++## Proposal, not decision++Produce a table of tiers and numbers, each justified by the measured cost from order 14, and put+it in your report as a proposal for the owner. Implement the **mechanism** fully so that applying+a number is a config change. Do not invent a price and ship it.++Also state, honestly, whether the free tier can carry a connected home at all given the measured+per-connection cost, and if it cannot, what the free experience is instead (a session-scoped+connection that closes when the tab does, is the obvious candidate).++## Tasks++| # | Task |+|---|---|+| 1 | An entitlement resolver for the lane, reading the existing tier system. `api/_lib/home/entitlements.js`. |+| 2 | Enforcement at the acquisition point (connections), the stream point, and the metered lanes. Never at the safe-action point. |+| 3 | Usage counters, reusing the platform's existing counter if one exists (`grep -rn "usage_events\|UsageCounter" api/ packages/`). |+| 4 | The downgrade path: mark inactive, explain, let the user choose. |+| 5 | The manage-surface quota display with the reset date. |+| 6 | Per-account overrides for enterprise. |+| 7 | Tests: the safe-action exemption, the downgrade path, counter accuracy, and per-account overrides. |+| 8 | The proposal table and the single owner message. |++## Definition of done++- [ ] Over quota, `lock`, `close_cover` and `alarm_arm_away` still execute. Three transcripts. This is the most important line in this order.+- [ ] Over quota, a new home connection is refused with a designed message naming the limit and the upgrade path, not a 500.+- [ ] A simulated downgrade marks the excess connections inactive, deletes nothing, and presents the choice. Recorded.+- [ ] The quota display shows real usage and a real reset date, screenshotted.+- [ ] A per-account override raises a limit without a code change. Prove it.+- [ ] Usage counters match reality: run 20 actions and 3 voice turns, then read the counters. Paste both.+- [ ] No new entitlement system was created: `grep` shows the lane reads `api/_lib/account-tier.js` (and the $THREE ladder where relevant) rather than its own table.+- [ ] The gate is unaffected by tier. Prove a free-tier account still gets confirmations and a full audit log.+- [ ] The proposal table names a measured cost per dimension.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| The price is not decided | You are not deciding it. Build the mechanism, propose numbers with the measured costs, and batch the approval. Ship with generous defaults behind a config value. |+| The measured per-connection cost makes a free tier look impossible | Say so plainly and propose the session-scoped free experience. An honest constrained free tier beats an unsustainable generous one. |+| Someone proposes gating confirmations or the audit log behind a paid tier | Refuse, and leave the reason in the code. Safety is not an upsell. |+| An existing usage counter is hard to reuse | Reusing it is still right. A second counter means two numbers that disagree, and the one on the invoice will be wrong. |+| $THREE holder tiers complicate the matrix | `api/_lib/three-tier.js` already models the ladder and the discount. Read it and apply it; do not model holding twice. |++## Report format++1. The three safe-action-over-quota transcripts.+2. The refusal message and the downgrade recording.+3. The quota display screenshot.+4. The override proof and the counter accuracy check.+5. The grep proving no new entitlement system.+6. The proposal table with measured costs, and the single owner message.+7. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-19-plans-entitlements.md++If the price approval is the only outstanding step, leave the file in place and name the owner+action. Never delete it on a partial.diff --git a/prompts/finish/home-20-launch-readiness.md b/prompts/finish/home-20-launch-readiness.mdnew file mode 100644index 000000000..23c2e0e5d--- /dev/null+++ b/prompts/finish/home-20-launch-readiness.md@@ -0,0 +1,158 @@+# 20. Launch readiness: the go/no-go++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. Run this **last**, after+every other order in the campaign has been retired, and run it again after any change to the lane.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**This order verifies, it does not build.** If a check fails, either fix it here (small) or+re-open the owning order (large) and say which. A go/no-go that finds nothing because it looked+at nothing is worse than no gate at all.++---++## Step 0: re-derive the current state++```bash+ls prompts/finish/home-*.md # what is still open. Every open order is a no-go input.+npx vitest run --root .+npx playwright test tests/e2e/ 2>&1 | tail -20+npm run gate 2>&1 | tail -30+npm run audit:docs && npm run check:claude && npm run check:docs-search+git log --oneline -20+```++## The go criteria++Every line is mechanically checkable and every line needs the command output pasted. A line you+cannot verify is a no-go, not a judgement call.++### Correctness and safety++- [ ] Order 11's eleven security checks all pass, re-run today.+- [ ] The confirmation-integrity invariant holds: zero rows anywhere in `home_action_log` with `guarded = true`, `confirmed_by is null`, `outcome = 'ok'`. Paste the query and the count.+- [ ] The order 16 e2e journeys all pass, including the three that assert on a real lock's real state.+- [ ] No home tool schema anywhere exposes `confirmed`. Re-dump and paste.+- [ ] The prompt-injection regression passes with the real physical assertion.+- [ ] SSRF refusals still hold, including the DNS-rebinding pin.+- [ ] The role matrix passes every cell, and a `guest` still cannot confirm.++### Reliability++- [ ] The order 14 chaos scenarios re-run green, or every deviation is explained.+- [ ] p95 action latency measured today against the published SLO.+- [ ] A ten-minute live session leaves heap flat.+- [ ] Ten consecutive runs of the lane's suites, green.++### Operations++- [ ] `/api/healthz` reports the `home` subsystem with real numbers.+- [ ] All three alerts are wired and each has been fired at least once in a test, with the transcript.+- [ ] `docs/home-operations.md` exists and every command in it was run.+- [ ] The rollback path in `docs/ops/gcp-production.md` was walked, at least in a dry run, and the exact commands are in your report.+- [ ] Any cron the lane added: `npm run check:cron-drift` clean, `vercel.json` cron count matches CLAUDE.md, `npm run check:claude` passes.++### Product completeness++- [ ] Every state enumerated by orders 05, 06, 07, 08 exists. Walk the list and screenshot each. A missing state is a no-go.+- [ ] No dead paths: every button acts, every link resolves, every reachable state has a way out.+- [ ] Zero console errors and zero console warnings from lane code, on every surface.+- [ ] `npm run audit:web` (authed, per `docs/ops/page-audit.md`) clean for every home route.+- [ ] axe passes on every home route.+- [ ] `npm run i18n:lint` clean.+- [ ] 320px, 768px and 1440px correct on every state.++### Data and privacy++- [ ] The order 15 inventory matches the schema exactly, re-checked today.+- [ ] Account deletion leaves zero rows across every lane table.+- [ ] The log-scrub proof re-run: zero hits for base URL, token and entity names.+- [ ] No persisted entity-state history exists.++### Documentation and release++- [ ] `npm run audit:docs` clean.+- [ ] Every tutorial command re-run today and still working.+- [ ] `STRUCTURE.md` and `data/pages.json` cover every surface.+- [ ] The `data/changelog.json` entry is present, plain-language, and validated by `npm run build:pages`.+- [ ] `docs/smart-home.md` describes what shipped, with no plan-tense claims left.++### The build++- [ ] `npm run gate` passes.+- [ ] `npm test` passes with no new failures. Do not pipe it through `tail`; that masks the exit code.+- [ ] `npm run check:rules -- --base <lane start sha> --head HEAD` clean across the whole lane.+- [ ] `node scripts/check-secrets.mjs --base <lane start sha> --head HEAD` clean.+- [ ] The `deploy-preflight` subagent has been run and reports the deploy safe.++## The launch decision++Produce a one-page verdict in your report:++1. **Go or no-go**, stated first, in one line.+2. Every failing check, what it blocks, and which order owns it.+3. Every accepted residual, with the risk named and the reason.+4. The measured numbers: p95 latency, state freshness, connection cost, the version matrix.+5. The rollback plan in three commands.+6. The single owner message, containing everything owner-gated in one place: the deploy, the npm+ publishes, the add-on repository publish, and the entitlement prices.++## The deploy itself++Owner-gated. Follow the CLAUDE.md deploy runbook **exactly and in order**, and do not hand-run+its steps out of order:++```+npm run clean:worktrees -- --apply+npm run prep:worktree -- --apply+npm run build:gcp+npm run deploy:gcp:submit+npm run deploy:gcp:purge-cdn+npm run smoke:prod+```++Then verify: `curl -s https://three.ws/api/version` returns the shipped SHA and revision.++Prepare all of it, run everything up to the submit, and stop for the owner's yes. Do not deploy.++## Post-launch watch, first 48 hours++Write this into `docs/home-operations.md` before launch, not after:++| Hour | Check |+|---|---|+| 0 | `/api/healthz` home block, the first real connection, the first real action |+| 1 | handshake success rate across all tenants; confirmation expiry rate |+| 6 | heap trend on the API service; subscriber counts |+| 24 | p95 latency against the SLO; the action-log integrity query |+| 48 | the full alert set has not fired spuriously; the error budget consumed so far |++## Never blocked++| Blocker | Do this |+|---|---|+| An order is still open | Then it is a no-go input. Say so, name the order, and do not paper over it with a judgement call. |+| A check cannot be run in this environment | Name it, name what access it needs, and mark it explicitly unverified in the verdict. Never mark it green. |+| Something fails and the fix looks small | Fix it, re-run the whole section, and note it. |+| Something fails and the fix looks large | Re-open the owning order, put it in the no-go list, and say what it blocks. |+| Pressure to ship with a failing safety check | There is no version of this where a door that opens without a confirmation ships. That check is a hard no-go with no override. |++## Report format++The one-page verdict above, then the full command output for every checked line, grouped by+section. Nothing summarised, nothing claimed without its output.++## Retire this prompt when it is done (required)++This order is **standing**: re-run it before every deploy of the lane. Delete it only when the+campaign is retired and the lane is in steady operation, in the same commit that removes+[00-CONTEXT.md](home-00-CONTEXT.md):++ git rm prompts/finish/home-20-launch-readiness.md++Until then, leave it in place and record each run in `prompts/finish/home-PROGRESS.md`.diff --git a/prompts/finish/home-21-matter-direct.md b/prompts/finish/home-21-matter-direct.mdnew file mode 100644index 000000000..56f17ff91--- /dev/null+++ b/prompts/finish/home-21-matter-direct.md@@ -0,0 +1,140 @@+# 21. Matter direct control: past the house++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`. Read [00-CONTEXT.md](home-00-CONTEXT.md) first. This is the **horizon**+order: run it only after [20](home-20-launch-readiness.md) has returned a go and the lane is in+steady operation. Running it earlier trades a shipped product for a research project.++## Binding operating clause++Finish 100%. Never end with a question or an unexecuted plan. All CLAUDE.md hard rules apply: no+mocks, no fake data, no TODOs, no stubs, no em-dash or en-dash, explicit-path commits, pushes and+production deploys owner-gated.++**This order is allowed to conclude "not yet".** It is the only one in the campaign that is. If+the measured evidence says the value is not there, say so with the evidence and stop; a proven+negative is a completed order here. What is not allowed is a half-built controller left on disk.++---++## Step 0: re-derive the current state++```bash+npm view @matter/main version+node -e "console.log(require('./package.json').dependencies['@matter/main'] || 'not installed')"+grep -rn "matter" docs/smart-home.md | head+curl -s https://api.github.com/repos/matter-js/matter.js | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const r=JSON.parse(s);console.log(r.stargazers_count,r.license.spdx_id,r.pushed_at)})"+```++The campaign's landscape data was measured on 2026-09-02: matter.js at 894 stars, Apache-2.0,+actively pushed, and Home Assistant migrating its own Matter integration onto it. **Re-measure.**+That is the whole point of Step 0 and this order is the one most likely to have moved.++## The two capabilities, and they are different++### A. three.ws as a Matter controller (no hub)++A user with Matter devices and no Home Assistant could connect them directly: commissioning over+BLE or Thread, then control. It removes the Home Assistant prerequisite.++**Be honest about the cost.** Commissioning needs BLE or Thread radio access on the same network+as the device, which a browser tab and a Cloud Run container both lack. It therefore requires+local software on the user's network, which is exactly what order 10 already ships, and which the+user could equally point at a Home Assistant that already does all of this and more.++The question to answer with evidence, not opinion: **is there a real user who has Matter devices,+wants an agent, and will not install Home Assistant?** Size it before building it.++### B. three.ws as a Matter device (the interesting half)++The inverse, and the one with no substitute: a three.ws agent **presents itself** as a Matter+device on the user's network. Then any Matter controller (Home Assistant, and the major consumer+ecosystems) can see the agent as a first-class thing in the house, put it in a room, and include+it in an automation.++That makes the agent addressable by infrastructure the user already owns, rather than requiring+them to come to us. [`Luligu/matterbridge`](https://github.com/Luligu/matterbridge) (Apache-2.0)+is the best worked example of matter.js used in this direction; read it before designing anything.++**B is the better bet.** A is a substitute for something the user already has; B is something+nobody offers. Weight the evaluation accordingly, and if you disagree after reading the evidence,+say why in your report.++## The kernel to prove first (one session, before any product work)++Do not design a product until this is proven, and let the result decide the rest of the order:++1. Stand up a matter.js device node in a container on a real network.+2. Commission it into a real Home Assistant Matter integration.+3. Expose one endpoint that means something for an agent: an occupancy or presence signal, or a+ switch that triggers an agent action.+4. Prove the round trip in both directions: Home Assistant sees the agent's state change, and an+ automation in Home Assistant reaches the agent.+5. Measure: commissioning time, steady-state resource cost, and what happens across a restart of+ each side.++If step 2 or step 4 cannot be made to work in a session against real software, that is the+finding. Write it down with the exact failure and stop.++## If the kernel holds++Then, and only then:++| # | Task |+|---|---|+| 1 | `services/home-matter/` with its `README.md` (required by CLAUDE.md), the device node, and its container. |+| 2 | The endpoint model: exactly which Matter device types the agent presents, and why each one. Fewer is better. |+| 3 | Pairing and identity: which three.ws agent this node is, bound the way orders 09 and 10 bind theirs. |+| 4 | Persistence of the Matter fabric across restarts. A device that needs re-commissioning after every deploy is not shippable. |+| 5 | The safety rule, unchanged: a Matter command reaching the agent is a request, and anything guarded still mints a confirmation. **A Matter fabric is not a human saying yes.** |+| 6 | `STRUCTURE.md`, `docs/`, `data/changelog.json`. |+| 7 | Tests against a real controller. |++## Definition of done++Either the negative or the positive, completely.++**If concluding "not yet":**+- [ ] The kernel was attempted against real software, and the exact failure or the exact cost is documented with transcripts.+- [ ] `docs/smart-home.md` phase 4 is rewritten to say what was tried, what was measured, and what would have to change for this to be worth doing.+- [ ] Nothing half-built remains on disk. `git status` clean of experiments.+- [ ] The re-measured landscape numbers are recorded, so the next attempt starts from data and not from this file.++**If building it:**+- [ ] A real Home Assistant commissioned the three.ws Matter node. Screenshot from Home Assistant.+- [ ] Both directions of the round trip demonstrated, recorded.+- [ ] The node survives a restart of each side without re-commissioning. Prove both.+- [ ] Commissioning time and steady-state resource cost measured.+- [ ] A guarded action triggered through a Matter automation still requires a human confirmation and does not execute without one. This is the line that matters most in this order.+- [ ] `services/home-matter/README.md` exists; `npm run audit:docs` clean.+- [ ] `npx vitest run --root .` shows no new failures.+- [ ] `npm run check:rules -- --paths <your files>` clean.++## Never blocked++| Blocker | Do this |+|---|---|+| Commissioning needs BLE or Thread hardware | For capability B over IP on the local network, it usually does not. If it does for your path, say so with the exact requirement; that is a finding about the cost, not a blocker to route around. |+| matter.js has moved or renamed since 2026-09-02 | Re-measure in Step 0 and trust what you find. The campaign's numbers are a snapshot with a date on them. |+| The value case looks weak | Then write the negative with the evidence. That is a completed order. Do not build it to avoid writing "not yet". |+| Someone proposes replacing the Home Assistant path with Matter | Refuse. Home Assistant covers 1,500 integrations; Matter covers a subset of new devices. Matter is an addition, never a replacement, and the context file's "we write no device code" rule still holds for everything else. |+| A Matter automation should be allowed to skip the confirmation "because the user set it up" | Refuse. The user set up an automation, not this specific unlock at this moment. The gate is unchanged. |++## Report format++1. The re-measured landscape numbers, with dates.+2. The kernel attempt: what worked, what did not, with transcripts.+3. The recommendation, A or B or neither, with the evidence behind it.+4. If built: the commissioning screenshot, the round-trip recording, the restart proofs, the measured costs, and the guarded-action proof.+5. If not built: the rewritten `docs/smart-home.md` phase 4 and confirmation that nothing was left half-built.+6. Anything in this file you found to be wrong, and what you changed it to.++## Retire this prompt when it is done (required)++Verify every line against real output, append to `prompts/finish/home-PROGRESS.md`, commit with+explicit paths, and delete this file in that commit:++ git rm prompts/finish/home-21-matter-direct.md++A documented "not yet" retires this file the same as a shipped feature does, provided the+evidence and the rewritten phase 4 are committed. Never delete it on a partial.diff --git a/prompts/finish/home-PROGRESS.md b/prompts/finish/home-PROGRESS.mdnew file mode 100644index 000000000..84c852ac4--- /dev/null+++ b/prompts/finish/home-PROGRESS.md@@ -0,0 +1,74 @@+# home/: cross-chat handoff log++The only memory between sessions for the three.ws Home campaign. Every agent that finishes an+order appends to it, in the same commit that deletes the order file. Read+[00-CONTEXT.md](home-00-CONTEXT.md) for the campaign's shared facts; this file is history, not+architecture.++**Append, never rewrite.** Someone else's entry is their evidence, not your draft.++---++## Format++One section per finished order, newest at the bottom:++```+## <order number>. <title> (<UTC date>)++**Shipped:** what now exists that did not before, in one paragraph.+**Measured:** the numbers, with how they were read.+**Deviations:** anything in the order file that was wrong, and what it was changed to.+**Left open:** anything not done, who owns it, and why. "Nothing" is a valid answer.+**Commits:** the SHAs.+```++---++## Campaign state++| Order | State | Finished |+|---|---|---|+| 00 CONTEXT | shared facts | n/a |+| 01 connection store | open | |+| 02 bridge runtime | open | |+| 03 API surface | open | |+| 04 agent tools | open | |+| 05 connect flow | open | |+| 06 3D home scene | open | |+| 07 floorplan editor | open | |+| 08 voice loop | open | |+| 09 Wyoming satellite | open | |+| 10 add-on relay | open | |+| 11 security | open | |+| 12 households and RBAC | open | |+| 13 observability | open | |+| 14 reliability and scale | open | |+| 15 privacy and retention | open | |+| 16 test program | open | |+| 17 a11y, i18n, mobile | open | |+| 18 docs and SDK | open | |+| 19 plans and entitlements | open | |+| 20 launch readiness | standing | |+| 21 Matter direct | horizon | |++Update the row in the same commit that retires the order. The directory shrinking is the real+ledger; this table is the readable one.++---++## Before the campaign++**2026-09-02.** The investigation and the client library landed ahead of the campaign, in commits+`480d8d7db` and `f54b124df`:++- [`docs/smart-home.md`](../../docs/smart-home.md): the open-source landscape measured from the+ GitHub API, the decision to write zero device code, the reachability constraint, and the+ verification table.+- [`packages/home-bridge/`](../../packages/home-bridge): the client library, 36 tests, verified+ against a real Home Assistant (docker `stable`, demo integration, 122 entities).+- The finding that shapes the whole campaign: Home Assistant's `intent__HassTurnOff` performs an+ **unlock** on a lock, confirmed live with a lock exposed to Assist. The gate exists because of+ it.++Nothing of that is wired into the product. Order 01 is the first order that changes that.