diff --git a/docs/agent-guide.md b/docs/agent-guide.md index fd76ad9..5632ada 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -1,748 +1,101 @@ # Building a Miakapp home -This guide is written for a coding agent — Claude Code, Codex, or any successor — -that has been handed someone's house and asked to make it work. You are expected -to read the existing installation, write a coordinator, write an interface, test -both, and publish. The owner is not a home-automation developer and should not -have to become one. - -Everything below is true of the code in this repository. Where a rule exists for -a reason that is not obvious, the reason is given, because a rule whose purpose -you cannot see is one you will optimize away. - -## 0. What "done" means - -The owner asked for a home they can use, not for a picture of one. You are done -when the household can open the published interface, read real values from it -and use every control the owner authorized — and you checked that yourself. -Concretely: - -- **Publish, then verify.** A build that only runs on your machine, a mockup, a - prototype kept offline or a screenshot is an intermediate result, never the - deliverable. Do not stop to show one and ask whether to continue: the owner - asked for the home, and publication is reversible in one command (§8). The - checkpoints below are not that: each one shows the real, published app. -- **Hand over a link that works.** Give the owner the `home_url` that - `miakapp publish` and `miakapp status` print — the Miakapp address where the - home opens for its members — and say what you verified there. The - `artifact_url` (JSON `url`) is the raw bundle, not an interface: never send it - as "the link". If the control plane advertises no `home_url`, say so instead of - inventing one, and say what `miakapp status` proved. -- **Ask once, at the start, and only for what you cannot find.** Access comes - from pairing (§9), the existing installation from inventory (§3), and the - right to wire physical controls from one question at the start of the - step-by-step journey (below). Repeated permission questions in the middle of - the work are a failure of the work. -- **Get it right the first time.** The owner should never have to ask you to - remove something you added or to fix how it looks or feels. Before you - publish, read `miakapp docs design` and follow it to the letter, check the - app for real (§5, "Check it for real"), and remove anything the guides - tell you not to add (a connection banner, your own bottom bar, a value - nobody asked for). -- **You need nothing from the platform's source.** This guide and the published - CLI — including the app starter `miakapp init --starter app` writes — are the - whole toolchain for the interface. Never edit or redeploy the Miakapp - platform to make one house work; if a capability is missing, report it to the - owner as missing instead of patching around it. - -### Build it with the owner, one visible step at a time - -The owner must never feel lost, and should feel they are building their home -with you. Work in short steps. Each step ends with something the owner can see -in the published app, a few plain sentences on what changed, and **one** clear -question that opens the next step. Then wait for the answer. - -A first session usually goes like this: - -1. Right after pairing, publish the empty app and send its `home_url`: - *"Here is your home's app. As you can see, it is empty for now. Do you - already have something precise in mind? Otherwise, tell me which connected - devices you have. Later we can also look at devices that are not connected - (gate, roller shutters, air conditioning, radiators…): I can very likely - find a way to control them from Miakapp."* -2. The owner lists devices ("I have Hue lamps…"). Ask only for what you need - to reach them: the credentials of the brand's account, or whether there is a - Raspberry Pi or a small PC that can run 24/7 in the house. In the same - message, ask **once** for the green light on physical controls: *"As we go, - I'll add the buttons that act on the house (lights, shutters, gate, - heating…), each one reserved to the people you choose. OK for you?"* That - answer covers every control of the journey: do not ask again device by - device. You still never trigger something that opens, unlocks or heats on - the real hardware yourself: when such a control is ready, tell the owner it +For a coding agent handed someone's house: read what is there, write a +coordinator and an app, check them on the real home, publish. The owner is not a +home-automation developer and should not have to become one. + +The how-to lives in short skills, one per job (listed at the end). This page is +what holds across all of them. + +## What "done" means + +The household can open the published app, read real values in it and use every +control the owner authorized — and you checked that yourself on the real home. + +- **Publish, then verify.** A mockup, a local build or a screenshot is never the + deliverable, and never something to stop and ask about: publication is + reversible in one command. +- **Hand over the `home_url`** that `miakapp publish` and `miakapp status` + print, and say what you verified there. Never the artifact URL. +- **Ask once, at the start, for what you cannot find.** Access comes from + pairing, the house from inventory, physical controls from one question. +- **Right the first time.** The owner should never have to ask you to remove + or restyle something you added. +- **Nothing from the platform's source.** The CLI, its starter and these skills + are the whole toolchain. If a capability is missing, tell the owner; never + patch or redeploy the platform for one house. + +## Build it with the owner, one visible step at a time + +Each step ends with something the owner sees in the published app, a few plain +sentences, and **one** question that opens the next step. A first session: + +1. Right after pairing, publish the empty app and send its `home_url`: "Here is + your home's app, empty for now. Do you have something precise in mind? + Otherwise, which connected devices do you have?" +2. Ask only what you need to reach the devices (account, a Pi or small PC that + runs 24/7), and **once** for the green light on physical controls, each + reserved to the people the owner chooses. That answer covers the journey; + still never trigger something that opens, unlocks or heats yourself — say it is ready to try. -3. Connect them, publish, check, then: *"I've just added your lamps! Do you want - me to group them by room? Otherwise we can start adding people to the home: - family members, guests or friends?"* -4. Carry on the same way: rooms, **people and their rights** (who may join, how - they are invited, what each role sees and does: build it the way - `miakapp docs members` explains, early, before the owner shares the home), - automations, then the devices that were not connected. - -Rules for every checkpoint: - -- what the owner looks at is the real published app, never a mockup; -- one question at a time, with the likely answer suggested; -- small steps, minutes rather than hours: add a few things, show them, move on; -- the owner's words, no technical detail unless they ask; -- if the owner says "carry on without me", chain the steps and report at the end. +3. Connect, publish, check, then propose the next step: rooms, **people and + their rights** (early, before the home is shared), automations, devices that + are not connected yet. -Two scopes must not be confused: +The owner's words, no technical detail unless asked. "Carry on without me" +means chain the steps and report at the end. | In scope by default | Needs the owner's explicit request | | --- | --- | -| reading the existing installation (§3) | changing flows, automations or devices that already run the house | -| giving the coordinator its own access to devices (its own broker user, token, GPIO) | removing or replacing the existing hub (the switch-over) | -| writing and testing a coordinator and an app | physical controls, until the owner answered the one question above | -| publishing, verifying and rolling back the V4 interface | anything on the owner's own machines beyond the coordinator you were asked to run | +| reading the existing installation | changing flows, automations or devices that already run the house | +| giving the coordinator its own access to devices | removing or replacing the existing hub | +| writing, testing, publishing and rolling back | physical controls, until the one question is answered | -Caution about the second column is not a reason to withhold the first. A new V4 -interface that only reads is still a useful, publishable V1; say plainly which -controls are not offered and why. +## What you are building -## 1. What you are building - -Three artifacts, and no more: - -| Artifact | Where it runs | What it owns | +| Artifact | Runs | Owns | | --- | --- | --- | -| Coordinator | the owner's machine, under Bun | state, events, functions, **authorization** | -| Interface | an isolated frame in the household's browser | what residents see and touch | -| `miakapp.yaml` | neither; it is the contract | what the interface may ask for | - -The interface is a **whole-house application** (`app:` in `miakapp.yaml`, ABI -`miakapp.app/1`): your own HTML, CSS, layout, navigation and libraries, bundled -into one file. Miakapp draws nothing for you, and no longer draws the old -semantic `component:` kind at all: a home published that way shows as having no -interface. §5 covers the app. - -The coordinator is trusted. The interface is not. The relay between them is -platform-untrusted but not blind: it terminates TLS, stores plaintext state and -enforces routing, so self-hosting it does not give end-to-end confidentiality. -Do not tell the owner otherwise. - -Start the interface with the starter the CLI ships, in an empty directory: - -```bash -miakapp init --starter app # home and issuer from the paired context -bun run build && bun run check # Bun >= 1.2.23 bundles; Node >= 22.9 runs the CLI -``` - -It writes `miakapp.yaml`, `app/main.ts` (the interface to edit), -`app/miakapp.ts` (the bridge to the home, copied from this CLI release), -`package.json`, `tsconfig.json` and `app/README.md`. It needs no source -repository and no unpublished package, and it refuses — writing nothing — if -any of those files already exists. As generated it shows only what the home -shares, with an honest empty state; it is where your work starts, never what -you publish. Without `--starter`, `init` writes `miakapp.yaml` alone. - -This guide covers the judgment no starter can. - -### Leave the repository readable by the next agent - -You are probably not the last agent to open this repository, and the next one -will not have this conversation. Run the pack once, in the repository root: - -```bash -miakapp agent-pack -``` - -It copies this guide to `.miakapp/agent-guide.md`, points `AGENTS.md` and -`CLAUDE.md` at it, and registers `miakapp mcp` in `.mcp.json` so the tools are -wired rather than described. It edits instead of replacing: prose outside the -`` markers is kept, other MCP servers are kept by name, -and running it twice changes nothing. - -If you are reading this file *as* `.miakapp/agent-guide.md`, someone already -ran it. Run it again after upgrading the CLI, and commit what changes — a guide -that contradicts the CLI installed beside it is worse than no guide. - -## 2. The division of responsibility - -**The coordinator authorizes everything.** The relay proves *who* is calling and -attaches non-spoofable caller metadata. Deciding whether that person *may* act is -the coordinator's job and nobody else's. In a well-built coordinator that decision is the -first line of the function body: - -```ts -if (call.source.kind !== 'user' || call.source.id !== options.ownerUserId) { - throw new ApplicationCallError(2003, 'Only the owner may drive the lights'); -} -``` - -Removing that check does not produce an error anywhere. It produces a home that -anyone enrolled can drive. There is no second layer that will catch it for you. - -**The app trusts nothing it was not given.** It has no network and no storage -shared with anyone. It cannot reach the lamp except through a call the -coordinator declared, and it cannot read a state path the coordinator did not -grant. This is why it is safe to let an app be rewritten often and reviewed -lightly, and why it is not safe to move a decision into it. - -**You own the UI; the coordinator owns the facts.** The coordinator exposes state -and actions. What the household actually sees — the layout, the wording, the -language, which controls are prominent — is yours to design (§5). Do not push -presentation choices into the coordinator, and do not push authorization into -the app. - -## 3. Before you write anything: characterize the house - -You are almost never starting from an empty building. Read what is already there -before you design anything: - -- existing hubs and brokers — Node-RED, MQTT, Zigbee/Z-Wave coordinators, an - HTTP-speaking hub; -- what each device actually reports, and how often; -- which values are *measurements* (temperature, power) and which are - *commanded* (a lamp, a valve) — they have different failure modes; -- which actions are physically consequential: anything that heats, locks, - unlocks, opens or closes. - -Write down what you found before you write the configuration. The state paths you -choose become a disclosure boundary and a public interface at the same time, and -renaming one after the household has used it is not free. - -### Talk to the devices, not to the old hub - -Read the existing hub to learn the house, never to depend on it. The -coordinator talks **directly** to the devices: MQTT and Zigbee2MQTT topics, the -Pi's GPIO for relays, the local HTTP or UDP API of a device, an RF or IR -transmitter. Owners move to Miakapp to get rid of the old stack (Node-RED, Home -Assistant, a vendor bridge), and a home that still needs it is not finished. - -- Give the coordinator its own access: its own MQTT user on the broker, its own - token. Do not reuse the hub's credentials, and do not call the hub's API - (Node-RED HTTP endpoints, its context files, a Home Assistant REST call) for - something the device itself can tell you or do. -- When a direct path is not ready yet, the hub may serve as a **temporary - bridge** for that one datum or action: mark it `bridge: ` in - `docs/inventory.md`, keep it behind one function you can swap, and tell the - owner what is left before the hub can be switched off. -- Two masters on the same relay or device disagree about its state. While the - old hub still drives something, keep your direct driver ready but off, and - switch over in one step with the owner. - -### The inventory comes before the design - -Commit the inventory as `docs/inventory.md` in the home repository, one line per -datum or action, before you design a single screen: - -| Field | Example | -| --- | --- | -| source | `zigbee2mqtt/salon_thermo` over the house broker | -| what it is | temperature, °C, one decimal | -| how fresh | reports every ~60 s; last seen 2 min ago | -| who may read it | every member / owner only | -| command | none — a measurement, not a control | -| path | direct (MQTT) / bridge: Node-RED until the switch-over | - -Then design **from** it: the V1 shows every datum the household would care -about and every action that is both technically possible and authorized, -grouped the way people live in the house — by room or by use, not by device -or protocol. Anything you leave out, leave out on purpose, and say why in the -inventory. A V1 that shows three values when the house reports twenty is not a -first version; it is an unfinished one. - -What the interface must never do: - -- **invent data.** A value with no source is shown as absent, never filled in - with a plausible number or a demo fixture; -- **blur freshness.** Distinguish *current*, *stale* (with its age) and - *unavailable* for every value, in words a resident understands; -- **spend space on plumbing.** No protocol or platform vocabulary - (`ACCEPTED`, "relay connected", ABI, schema names, IDs), no banner restating - that a view is read-only, no title repeating the home's name on every card. - Every line of text is either information or an action. - -### Reading a V3 house you inherited - -Most houses arriving at V4 already run Node-RED with the v3 MiakAPI nodes. Ask -the owner for the `flows.json` Node-RED writes, or for an *Export > All flows* -download, and read it before you read anything else: - -``` -miakapp discover --flows ~/node-red/flows.json -miakapp discover --flows ~/node-red/flows.json --json -``` - -The command is offline and read-only: it opens no socket, contacts no broker and -never writes back into the export. It reports the tabs, the MQTT brokers with the -topics their nodes actually reach, the `initMiakapi` home bindings, every -`commitVariables` path as a state candidate, every `onUserAction` id as a -function candidate with the groups allowed to invoke it, and every node type it -does not model — so you know what the inventory missed rather than assuming it -missed nothing. - -Four of its findings decide work you would otherwise discover late: - -- **`secret_in_export`.** The v3 `initMiakapi` node declares `coordSecret` in its - `defaults`, not in its `credentials`, so Node-RED stores that secret in - cleartext in `flows.json` rather than in the encrypted `flows_cred.json`. If - the export has one, treat it as leaked: rotate it, and keep the file out of - Git. §9 is the V4 rule that replaces it. -- **`unrestricted_action`.** The v3 handler allows an action outright when its - node lists no group, so an empty `allowedGroups` is a grant to every signed-in - user, not a deny. Each one needs a deliberate V4 rule before you port it. -- **`name_needs_rename`.** A v3 variable path or action id that is not a legal V4 - dotted name has to be renamed now, while nobody depends on it. -- **`wildcard_subscription`.** A topic holding `#` or `+` is a subscription - pattern, not one device. Enumerate what it actually matches. - -The command deliberately does not tell you which actions are physically -consequential. It lists every action it found; deciding which of them heats, -locks, unlocks, opens or closes is a judgement you make with the owner, and no -keyword list should make it for you. - -### When the owner needs a new device - -Recommend open protocols that work locally: **Zigbee** (through a Zigbee -coordinator and Zigbee2MQTT), **MQTT**, devices that run **Tasmota** or -ESPHome, and anything else that does not need the vendor's cloud. Avoid, when -there is a choice: - -- **Bluetooth**: its range is too short for a house; -- **Wi-Fi**: hard to extend, the router caps the number of devices, and - everything depends on the internet box. - -Say why in one sentence, name one or two concrete models and a price range. -For a device that cannot be connected at all (proprietary RF or IR remote, a -gate or shutter with only a wired switch), look for a bridge: an RF or IR -transmitter, or a Zigbee relay module wired to the existing switch. - -## 4. The coordinator - -Keep the coordinator in the same shape: the configuration is a -**pure function of its options**, so it can be tested without a relay, a control -plane or a network. `coordinator/main.ts` is the only file that touches the -outside world. Keep that split. It is what makes `test/home.test.ts` possible, -and the authorization rules are exactly the thing you want under test. - -Four declarations: - -```ts -{ - state: { 'zone.living_room.light.on': false }, // paths and initial values - stateAccess: [{ userId, patterns: ['zone.living_room.*'] }], - events: [{ topic, directions: EventDirection.publishToUsers }], - eventAccess: [{ userId, publish: [], subscribe: [topic] }], - functions: { async 'lighting.set'(call) { /* authorize, act, return */ } }, -} -``` - -`stateAccess[].patterns` is the disclosure boundary. A user sees exactly those -paths and nothing else. Widen it deliberately, one path at a time, and never with -a wildcard that happens to be convenient. - -Three ordering and failure rules that are easy to get wrong: - -**State first, event second.** Write the state, *then* publish the event: - -```ts -await coordinator.state.set([{ path: STATE.lightOn, value: on }]); -await coordinator.events.publish(EVENT_LIGHT_CHANGED, { on }); -``` - -A subscriber that reacts to the event and immediately reads the state must never -see the old value. The reverse order is a race that will reproduce once a month -and waste a day. - -**Reject bad arguments with a typed application error.** `ApplicationCallError` -carries a numeric code the app can branch on. Do not throw a bare `Error` -for a caller mistake; the distinction between "you asked wrongly" and "something -broke" is the one the interface needs most. - -**A home has several coordinators.** Names are namespace sharding by convention. -The relay keeps ownership tables for topics, state paths and functions, detects -collisions and rejects with `4409`. If you claim `lighting.set` for the whole -house, you have taken a name another integration may need; scope what you own. - -## 5. The interface - -### A whole-house application (default) - -`miakapp init --starter app` writes an `app:` section and a buildable app to -edit. You own the document: build any DOM, ship your own CSS, use React, -Svelte, Vue, charts or WebAssembly — anything a bundler can inline. Navigate -with the starter's `createNav()`, which gives every page a history entry and a -swipe back. The deliverable is **one classic-script IIFE** of at most 2 MiB, -with no `import()` and no source map; the starter's `bun run build` is: +| Coordinator | the owner's machine, under Bun (`miakapi`) | state, events, functions, **authorization** | +| App | an isolated frame in each resident's browser | what residents see and touch | +| `miakapp.yaml` | — the contract | what the app may ask for | -```bash -bun build app/main.ts --format=iife --minify --outfile dist/app.js -``` - -Miakapp runs it in an isolated, opaque-origin frame below a permanent Miakapp -bar, after the resident agreed to open the home. The frame has no network, no -cookies or storage, no popups and no fullscreen; assets go in the bundle as -`data:`/`blob:` URLs. Its only way to the home is `window.miakapp`, through the -bridge the starter writes as `app/miakapp.ts` — the source of the `@miakapp/app` -SDK, which is not on npm yet, so import the local file: - -```ts -import { callErrorCode, connect } from './miakapp.js'; - -const home = connect(); -home.subscribe((state) => render(state)); // also called once immediately -await home.call('lighting.set', { on: true }); // rejects with a closed code -``` - -Do not edit the bridge; a newer CLI's starter carries any change to it. - -**Make it beautiful from the first build.** Run `miakapp docs design` before you -draw anything, and follow its "Make it beautiful" recipe: Miakapp ships design -tokens, four themes (Minuit, Lumière, Miel, Craie), CSS recipes, line icons, an -embedded font and example screens. The starter's `app/theme.ts` already uses -them. They are a starting point you may change -entirely; the Miakapp bar at the bottom, outside your frame, is not yours to -redraw, but `home.bar.setButtons()` can add one or two of your own screens to it -(icons: grid, bolt, light, thermometer, camera, lock, list, chart, leaf, star, -people, bell), each with an optional `badge` count (e.g. join requests waiting; -0 shows none). Call it again whenever the count changes. - -Your frame cannot open the share sheet or write the clipboard. For a "Share" or -"Copy" button, call `home.share({ title, text, url })` or `home.copy(text)` -directly in the tap handler: Miakapp does it (share sheet, else copy), only on -that fresh tap, url https only. It resolves `'shared'`, `'copied'`, -`'cancelled'` or `'unavailable'`; tell the resident which, and on -`'unavailable'` show the text in a read-only field. - -Declare every state path (exact or `prefix.*`) under `app.requires.state_read` -and every function under `app.requires.call`. Events, media and `miakapp.*` -functions are refused by `miakapp check`. Show `state.stale`, disable controls -while it is true, and handle `outcome_unknown` exactly as below. +The coordinator is trusted, the app is not. The relay terminates TLS and stores +plaintext state: self-hosting it is not end-to-end encryption; never say so. -**The bundle is not private.** Any signed-in user who learns its digest can -fetch it. Put no household data in it — no names, rooms, devices or accounts — -and read everything from state, which the coordinator filters per resident. +## Access -### Two states the interface must never hide - -**Staleness.** `home.state.stale` means the snapshot may no longer reflect the -house. Show it. Per RFC 0002 §12.2 it is exposed, never hidden — a thermostat -reading that is silently forty minutes old is worse than one labelled uncertain. -Showing it is the Miakapp bar's job and yours together: the bar says -"Connecting…" or "Reconnecting…", and your app **dims** the values that may be -old (`.is-stale` on `.mk-app`) and disables the controls. Never add a banner, -toast or strip of your own for it ("The home is not answering"): it repeats the -bar, and every resident sees it each time the app opens. - -**Staging.** `home.staging` is true while a release is staged: rendering works, -calls and events do not. Disable the controls and say why. -An interface that looks live and silently does nothing is the worst outcome -available. - -### An unknown outcome is never retried - -This is the rule that will most tempt you to break it, so it is stated plainly: - -```ts -try { - await home.call('lighting.set', { on }, { deadlineMs: 10_000 }); -} catch (error) { - // Deliberately not retried. The call may already have reached the lamp, - // and the next state snapshot settles the question. - failure = error instanceof Error ? error.message : 'The command failed'; -} -``` - -A failed call is not a call that did not happen. `CallOutcomeUnknownError` exists -precisely to name the case where the effect is undetermined, and the physical -world does not have a rollback. Surface it, let the next state snapshot settle -it, and let the person decide. The same principle has a CLI counterpart: exit -code 7. - -### Check it for real - -Never check against a bridge you wrote yourself: it hides what breaks on a -phone (sandbox refusals, late answers, refused calls, rate limits). Run the app -against the real home: +Never ask for a password, a login or a key. The owner opens +https://miakapp.com/pair, picks the home, and sends you a one-time code +(10 minutes, once): ```bash -bun run build -miakapp preview --as member # your build, not activated: prints a link -miakapp taps --as member # taps every control there, reports what is wrong +printf '%s\n' "" | miakapp pair # --issuer if the page shows one +miakapp context list # homes this machine can publish to ``` -`preview` (your build) and `open` (the live release) print a link, valid up to -an hour, that opens the home at phone size (390 × 844) as the test member -`test:`, with no account: the real Miakapp bar, sandbox, relay and -coordinator. Your coordinator gives `test:` the rights of that role, like -any member (`miakapp docs members`); check once per role. Open the link in the -browser you drive (never install one) and look at every page, with touch. +The key lands in `~/.miakapp` (or `MIAKAPP_HOME_KEY` for CI), never in the +repository. The home's own coordinators may use the same key: give it to them +through their environment, never ask for a second pairing. Keys and wiring are +your business; tell the owner what works, not how. -`taps` reports every control with no call, no navigation and no visible change, -failed calls, start-up calls that failed or took over 1.5 s, errors the app -threw, and saves a screenshot of each page. A call a tap makes is held, never -sent, unless you name its function with `--send` (reads only, never something -that moves). Fix what it reports and run it again until it reports nothing. +## Keep this repository readable by the next agent -## 6. The intersection rule +`miakapp agent-pack` (once) installs this guide, the skills below, a pointer in +`AGENTS.md` and `CLAUDE.md`, and the `miakapp` MCP server pinned in `.mcp.json`. +It only rewrites what it generated. `miakapp update` moves the repository to a +newer CLI (see the `miakapp-update` skill). -Every name an app may touch appears in **two** places, and the effective -grant is the intersection: +## Skills -| `miakapp.yaml` → `requires` | `coordinator/home.ts` | +| Skill | Use it to | | --- | --- | -| `state_read` | `stateAccess[].patterns` | -| `event_subscribe` | `eventAccess[].subscribe` | -| `event_publish` | `eventAccess[].publish` | -| `call` | `functions` | - -Asking for more than the coordinator grants **does not fail loudly at -publication**. The app simply never receives that path, and the interface -renders a hole — an empty card, a control that does nothing, a temperature that -is permanently unavailable. This is the single most common way a Miakapp home -breaks, and it breaks quietly. - -So: assert the correspondence in a test, so a mismatch fails in CI rather than -in someone's living room. When you add a path, change four things in one commit — -the state declaration, the access pattern, the `requires` entry, and the test. - -## 7. The loop - -```bash -bun run check # typecheck → bundle → test → validate the artifact offline -``` - -Run it before every publication and in CI. It costs nothing and catches the -artifact rules the runtime would reject anyway. - -Do not treat a check that exists as a check that runs. On 2026-09-14 this -repository had two example packages that were both verified locally and built -by nobody, because the workflow called `bun run check` and not -`check:packages`; when CI finally exercised them they failed three times in a -row on defects that had been sitting there invisibly. If you add a package, add -it to the job that runs in CI, then watch one run go green before believing it. - -Reproduce CI with the toolchain version it pins, not the one you have. Bun 1.4 -self-references the root package and resolves `bunx` from `node_modules`; the -pinned 1.2.23 does neither, so a green local run proves nothing about the runner. -Install the pinned version alongside yours: - -```bash -BUN_INSTALL=/tmp/bun1223 curl -fsSL https://bun.sh/install | bash -s bun-v1.2.23 -``` - -Note also that `bun test foo/` is a **substring filter**, not a directory scope. - -## 8. Publishing - -The CLI builds, validates, publishes and rolls back. **It never owns Git.** It -writes no history, rewrites no source it did not generate, and invents no -control-plane endpoint. The repository is the owner's. - -```bash -miakapp docs start # this guide, from the installed CLI -miakapp pair # once per home and machine (§9) -miakapp agent-pack # once, per repository -miakapp init --starter app # manifest + buildable app; plain init writes the manifest only -miakapp check -miakapp status # what is live now: generation, release, digest -miakapp publish # upload, finalize, activate -miakapp status # verify the new digest is what is live -miakapp activate --sha256 # promote an already finalized digest -miakapp rollback --sha256 # alias of activate -miakapp release # read one finalized release -miakapp upload # reconcile a lost request -``` - -Activation is a compare-and-set on the home's component pointer. Without -`--expected-generation` the CLI reads the live generation first and activates -the next one; the read takes no lock, so another publication landing in between -still fails with `conflict` instead of being overwritten. Pass -`--expected-generation ` when you want to assert the state you reviewed. - -Rollback is `activate` pointed at a digest you already trust. Keep the digest of -every release you shipped; a rollback you can perform in one command is worth -more than an incident you can explain. - -`miakapp status` after `publish` is the minimum verification: the live `sha256` -must be the one you just built. It proves what the home runs, not that the -interface is right: `miakapp open` it and look before telling the owner it works. - -### Driving the CLI as a program - -Every failure maps to exactly one stable exit code and one stable -machine-readable kind. New kinds may be added; existing codes never change -meaning. Pass `--json` and you get exactly one closed object on stdout. - -| Code | Kind | Meaning | -| --- | --- | --- | -| 0 | `success` | | -| 1 | `usage` | the invocation was wrong | -| 2 | `project` | `miakapp.yaml` is missing or invalid | -| 3 | `artifact` | the built bytes violate an artifact rule | -| 4 | `authorization` | the Home Key is missing, wrong or unscoped | -| 5 | `contract` | the control plane rejected the request | -| 6 | `conflict` | `--expected-generation` did not match; re-read, do not retry | -| 7 | `unknown_outcome` | **effect undetermined — reconcile with a read** | - -Branch on the code, not on the prose. On 7, call `miakapp upload ` or -`miakapp release ` and reconcile before acting again. Never retry a 7 -with a fresh capability. - -### If you speak MCP instead of shell - -`miakapp mcp` serves the same commands as tools over JSON-RPC on stdio. It is the -same code: a tool call becomes the argv a person would have typed and runs the -same dispatch, so everything above still holds — the same defaults, the same -validation, the same `kind` on every failure. - -Three differences are worth knowing before you call anything: - -- `miakapp_publish`, `miakapp_activate` and `miakapp_rollback` refuse to run - without `confirm: true`. Set it when the owner asked for that publication, and - not to get past an error; -- a failure arrives as a tool result with `isError: true`, carrying the same - closed object, not as a JSON-RPC error. A JSON-RPC error means your call never - happened; `isError` means it ran and failed, and `kind` says what to do next; -- a tool argument is the option name with `_` instead of `-`. An argument the - tool does not declare is refused, never ignored. - -`packages/cli/README.md` lists the tools. The exit codes above are the -`exit_code` field in every result, so branch on the same table either way. - -### Notifying the people of the home - -```sh -miakapp notify --to [,…] --title "Front door" --body "Open for 10 minutes" -``` - -Reaches only the people you name, on the devices where they opened the home and -turned notifications on (Settings → Notifications). Anyone can turn -notifications on for any home, so the platform never notifies "the whole home": -**you decide who is told**, from the members your coordinator knows -(`miakapp docs members`). User IDs -are the `id` of the `user` principal your coordinator receives with every call -and event (`principal.kind === 'user'`). It needs -only the paired context, not a project file. `delivered: 0` is not an error: -the people named have not turned notifications on (on iPhone they first add -Miakapp to the Home Screen). - -### At home and without the internet: direct mode (on by default) - -A coordinator built on `miakapi` 4.1 or later also listens for residents on the -local network (UDP 4455, WebRTC). There is nothing to code: through the relay, -each resident's browser learns how to reach the coordinator, then opens the home -**directly** when it is on the same network (lower latency), and keeps working -when the internet is down (the Miakapp page and the app open from the phone's -cache). What is yours to get right: - -- **Network.** In Docker, run the coordinator with host networking - (`network_mode: host`). Otherwise publish `4455/udp` and pass - `direct: { hosts: [''] }` to `createCoordinator`. -- **A persistent identity.** The coordinator keeps its certificate, ICE - password and ticket key in `.miakapp/direct` (relative to its working - directory, or `direct.directory`). Keep it on a persistent volume: browsers - pin that certificate, and losing it means every phone must be online once more. -- **A fixed address.** Ask the owner to reserve the coordinator machine's - address in the router (DHCP reservation): an offline phone can only reach the - address it last saw. -- **Do not wait for the relay.** Without the internet, `coordinator.start()` - resolves only once the relay is back, while `state.set` and function calls - already work locally. Do not `await start()` before wiring the devices. -- Every coordinator of the home must run `miakapi` 4.1 or later and be - reachable on the LAN: the phone goes direct only when all of them answer - (without the internet, it opens with those that do). Events are not carried - on it. `direct: false` turns it off. - -## 9. Access: pairing and contexts - -You never sign in as the owner and never ask for a password, a Google login or -an existing key. The owner grants access to one home, in their own browser: - -1. Ask the owner to open **https://miakapp.com/pair**, sign in to their own - account, choose the home (or create it), confirm the access it grants, and - send you the one-time code it shows. A code works once, for ten minutes. -2. Redeem it. The code is read from stdin and never echoed: - - ```bash - printf '%s\n' "" | miakapp pair # add --issuer if the page shows one - ``` - - Over MCP, call `miakapp_pair` with `code`. Never repeat the code back in a - message, and never retry a refused code — ask for a new one. -3. `pair` stores a **new, separately revocable** Home Key for this machine as a - context in `~/.miakapp`, keeps every other context, makes the new one - current, and proves the key can publish. It prints the key ID and label, - never the key. - -```bash -miakapp context list # every home this machine can publish to -miakapp context show [name] # one context; the key is never printed -miakapp context use # make a context current -miakapp context remove # delete it locally (the owner revokes it server-side) -``` - -`~/.miakapp/config.json` holds names, homes, issuers and key IDs; -`credentials.json` holds the keys. Both are mode 0600 in a 0700 directory and -are replaced atomically; the CLI refuses a credentials file other accounts can -read. `MIAKAPP_CONFIG_DIR` relocates the directory. - -Which key a command uses, highest precedence first: - -1. `--context `, then `MIAKAPP_CONTEXT=`; -2. `MIAKAPP_HOME_KEY`, a raw key for CI and compatibility; -3. the stored context paired with the home and issuer in `miakapp.yaml` — the - current context breaks a tie between two keys for that same home. - -A context, or a known key, for a different home than `miakapp.yaml` names is -refused before any request: a key can never publish into the wrong house. - -One pairing is enough. The coordinators you run for this home (on a Raspberry -Pi, a small PC…) may use the same Home Key as you: hand it to them yourself, -through their environment, from `~/.miakapp/credentials.json`. Never ask the -owner for another pairing code just to give a machine its own key. - -Keys, tokens, contexts and pairing internals are your business, not the -owner's. Tell them what works ("the Pi is connected, your lamps answer"), -never how it is wired, unless they ask. - -If you are about to write a secret into `miakapp.yaml` or any file in the -repository so something works, stop: that is the failure this design exists to -prevent. - -## 10. Before you tell the owner you are done - -- [ ] `docs/inventory.md` lists every source, datum and action you found, and - the interface covers it or says why not. -- [ ] Every value shows whether it is current, stale or unavailable; nothing is - invented, and no technical vocabulary is on screen. -- [ ] The interface is published and `miakapp status` shows your digest live. -- [ ] `miakapp taps` reports nothing, for each role you built. -- [ ] The owner received a working link and the rollback digest, not a - screenshot or a mockup. -- [ ] Every physically consequential function authorizes its caller on its first - line, and a test proves an unauthorized caller is refused. -- [ ] Every name in `miakapp.yaml` is covered by the coordinator, and a test - asserts the correspondence. -- [ ] `home.state.stale` dims the values and disables the controls, with no - banner of your own; `home.staging` is visible. -- [ ] You looked at every page of `miakapp preview` (§5): pages slide, the - left-edge swipe goes back, held actions fire after 0.3 s. -- [ ] States use the four colours of `miakapp docs design` (green safe, - orange to look at, gold on, red alarm only), always with a word. -- [ ] The coordinator talks to the devices directly; any hub left is a - `bridge:` line in the inventory with what remains to switch it off. -- [ ] No call path retries an unknown outcome. -- [ ] State is written before its event is published. -- [ ] `bun run check` is green, and CI ran it — not just you. -- [ ] The Home Key exists only in `~/.miakapp` or the environment, never in the - repository. -- [ ] You recorded the digest of what you published, so rollback is one command. - -## Where to read further - -Everything a home needs is above and in the CLI with its starter. The RFCs and -platform paths below explain *why* the platform behaves as it does; you never -need them, or the platform repository, to build and publish a home. - -- `miakapp docs members` — members, join requests, invitations, roles and who - is notified: the coordinator decides, Miakapp only says who is calling. -- `packages/cli/README.md` — every command and every tool, including what the - pack writes and what it refuses to overwrite. -- `docs/rfcs/0001` (Miakapp/Miakapp) — wire protocol: ownership, collisions, `4409`. -- `docs/rfcs/0002` — release pointer, capabilities and the staleness rule; - `docs/specs/2026-10-03-house-app-abi.md` — the app frame and its bridge. -- `docs/rfcs/0003` — the coordinator SDK surface. -- `docs/rfcs/0004` — Home Key bootstrap, scopes, publication. -- `docs/rfcs/0005` — the trusted browser client. +| `miakapp-coordinator` | inventory the house, talk to devices, write and test the coordinator | +| `miakapp-interface` | build the app: starter, design, state, calls | +| `miakapp-test-real` | check the app on the real home with `open`, `preview`, `taps` | +| `miakapp-publish` | publish, verify, roll back; exit codes; MCP | +| `miakapp-members` | members, join requests, invitations, roles, notifications | +| `miakapp-update` | a newer Miakapp exists: tell the owner, update, migrate | + +They live in `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). +`miakapp docs start` prints this page and every skill; `miakapp docs design` +and `miakapp docs members` print the design and members guides. diff --git a/packages/cli/README.md b/packages/cli/README.md index 7738218..9e09521 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -112,7 +112,9 @@ duplicate keys — is rejected with the offending line rather than guessed at. | `pair` | Redeems a one-time pairing code into a new stored context. | | `context list\|show\|use\|remove` | Manages stored contexts. Never prints a key. | | `init` | Writes `miakapp.yaml`; with `--starter app`, also a buildable app. Never overwrites. | -| `agent-pack` | Offline. Installs the guide and the MCP wiring into a repository. | +| `agent-pack` | Offline. Installs the guide, the skills and the MCP wiring into a repository. | +| `changes` | What each release after the repository's pin brings the home, and what to migrate. | +| `update` | Moves a home repository to this CLI: pins, pack, generated bridge, check, migrations. | | `discover` | Offline. Inventories a Node-RED installation from its flows export. | | `check` | Offline. Parses the project, verifies the artifact, prints the digest. | | `status` | Reads the live generation, release and digest of the home. | @@ -140,7 +142,7 @@ flows, the MQTT brokers with the topics their nodes actually reach, the v3 MiakAPI surface as V4 state and function candidates, and every node type it does not model, so the reader knows what the inventory missed. It reports that a coordinator secret is present in the export; it never prints the secret itself. -`docs/agent-guide.md` §3 explains what to do with each finding. +The `miakapp-coordinator` skill explains what to do with each finding. ## The agent pack @@ -151,17 +153,19 @@ agent to open it arrives already knowing the rules: miakapp agent-pack # or --dir /path/to/the/repository ``` -It writes four files and reports what it did to each one: +It writes these files and reports what it did to each one: | File | Why | | --- | --- | -| `.miakapp/agent-guide.md` | The full guide, copied out of this package. No network, no stale bookmark. | +| `.miakapp/agent-guide.md` | The short guide, copied out of this package. No network, no stale bookmark. | +| `.claude/skills/miakapp-*/SKILL.md` | One skill per job, for Claude Code: coordinator, interface, test-real, publish, members, update. | +| `.agents/skills/miakapp-*/SKILL.md` | The same skills, where Codex discovers repository skills. | | `AGENTS.md` | The instruction file Codex reads. | | `CLAUDE.md` | The instruction file Claude Code reads. | | `.mcp.json` | Project-scope MCP configuration, registering `miakapp mcp`. | -The repository is yours, so the pack edits rather than replaces. The guide is a -file it owns outright. The instruction files are touched only between +The repository is yours, so the pack edits rather than replaces. The guide and +the `miakapp-*` skill folders are files it owns outright. The instruction files are touched only between `` and ``: prose above and below the markers is copied through byte for byte, and a second run rewrites the block in place instead of appending another copy. `.mcp.json` is merged as a structure — @@ -175,6 +179,27 @@ on a global binary or this machine's directory layout. Run it again whenever the CLI is upgraded: an unchanged file is reported `unchanged`, and a guide that moved on is reported `updated`. +## Updates + +Every command checks the npm registry for a newer release at most once a day +(cached in `~/.miakapp/update-check.json`, silent offline, off under `CI` or +with `MIAKAPP_UPDATE_CHECK=0`). A newer release is announced once a day on +stderr; with `--json`, and in every MCP tool result, it is an +`update_available` field instead. + +``` +npx -y @miakapp/cli@latest changes # since the pin in .mcp.json, or --since 4.7.1 +npx -y @miakapp/cli@latest update # then: bun install, bun run check, migrations +``` + +`changes` reads `assets/changelog.json` (each release: what it brings the home, +and the agent's migration steps), and the newer release's own changelog from +the CDN. `update` re-pins `.mcp.json` and the `@miakapp/cli` entry of +`package.json`, rewrites the pack, refreshes `app/miakapp.ts` when it is still +the generated bridge, runs `check`, and prints the migrations. It installs +nothing and runs no shell. The `miakapp-update` skill tells the agent to ask the +owner first. + ## MCP An agent that already runs a shell does not need this. An agent that speaks the @@ -206,6 +231,8 @@ tools over newline-delimited JSON-RPC on stdio. | `miakapp_upload` | `upload` | read-only | | `miakapp_init` | `init` | writes `miakapp.yaml` (and the app starter with `starter: "app"`), never overwrites | | `miakapp_agent_pack` | `agent-pack` | offline, writes the pack into a repository | +| `miakapp_changes` | `changes` | read-only; reads the npm registry | +| `miakapp_update` | `update` | rewrites the pack and pins to this server's release | | `miakapp_publish` | `publish` | **moves the pointer — needs `confirm: true`** | | `miakapp_activate` | `activate` | **moves the pointer — needs `confirm: true`** | | `miakapp_rollback` | `rollback` | **moves the pointer — needs `confirm: true`** | diff --git a/packages/cli/assets/agent-guide.md b/packages/cli/assets/agent-guide.md index fd76ad9..5632ada 100644 --- a/packages/cli/assets/agent-guide.md +++ b/packages/cli/assets/agent-guide.md @@ -1,748 +1,101 @@ # Building a Miakapp home -This guide is written for a coding agent — Claude Code, Codex, or any successor — -that has been handed someone's house and asked to make it work. You are expected -to read the existing installation, write a coordinator, write an interface, test -both, and publish. The owner is not a home-automation developer and should not -have to become one. - -Everything below is true of the code in this repository. Where a rule exists for -a reason that is not obvious, the reason is given, because a rule whose purpose -you cannot see is one you will optimize away. - -## 0. What "done" means - -The owner asked for a home they can use, not for a picture of one. You are done -when the household can open the published interface, read real values from it -and use every control the owner authorized — and you checked that yourself. -Concretely: - -- **Publish, then verify.** A build that only runs on your machine, a mockup, a - prototype kept offline or a screenshot is an intermediate result, never the - deliverable. Do not stop to show one and ask whether to continue: the owner - asked for the home, and publication is reversible in one command (§8). The - checkpoints below are not that: each one shows the real, published app. -- **Hand over a link that works.** Give the owner the `home_url` that - `miakapp publish` and `miakapp status` print — the Miakapp address where the - home opens for its members — and say what you verified there. The - `artifact_url` (JSON `url`) is the raw bundle, not an interface: never send it - as "the link". If the control plane advertises no `home_url`, say so instead of - inventing one, and say what `miakapp status` proved. -- **Ask once, at the start, and only for what you cannot find.** Access comes - from pairing (§9), the existing installation from inventory (§3), and the - right to wire physical controls from one question at the start of the - step-by-step journey (below). Repeated permission questions in the middle of - the work are a failure of the work. -- **Get it right the first time.** The owner should never have to ask you to - remove something you added or to fix how it looks or feels. Before you - publish, read `miakapp docs design` and follow it to the letter, check the - app for real (§5, "Check it for real"), and remove anything the guides - tell you not to add (a connection banner, your own bottom bar, a value - nobody asked for). -- **You need nothing from the platform's source.** This guide and the published - CLI — including the app starter `miakapp init --starter app` writes — are the - whole toolchain for the interface. Never edit or redeploy the Miakapp - platform to make one house work; if a capability is missing, report it to the - owner as missing instead of patching around it. - -### Build it with the owner, one visible step at a time - -The owner must never feel lost, and should feel they are building their home -with you. Work in short steps. Each step ends with something the owner can see -in the published app, a few plain sentences on what changed, and **one** clear -question that opens the next step. Then wait for the answer. - -A first session usually goes like this: - -1. Right after pairing, publish the empty app and send its `home_url`: - *"Here is your home's app. As you can see, it is empty for now. Do you - already have something precise in mind? Otherwise, tell me which connected - devices you have. Later we can also look at devices that are not connected - (gate, roller shutters, air conditioning, radiators…): I can very likely - find a way to control them from Miakapp."* -2. The owner lists devices ("I have Hue lamps…"). Ask only for what you need - to reach them: the credentials of the brand's account, or whether there is a - Raspberry Pi or a small PC that can run 24/7 in the house. In the same - message, ask **once** for the green light on physical controls: *"As we go, - I'll add the buttons that act on the house (lights, shutters, gate, - heating…), each one reserved to the people you choose. OK for you?"* That - answer covers every control of the journey: do not ask again device by - device. You still never trigger something that opens, unlocks or heats on - the real hardware yourself: when such a control is ready, tell the owner it +For a coding agent handed someone's house: read what is there, write a +coordinator and an app, check them on the real home, publish. The owner is not a +home-automation developer and should not have to become one. + +The how-to lives in short skills, one per job (listed at the end). This page is +what holds across all of them. + +## What "done" means + +The household can open the published app, read real values in it and use every +control the owner authorized — and you checked that yourself on the real home. + +- **Publish, then verify.** A mockup, a local build or a screenshot is never the + deliverable, and never something to stop and ask about: publication is + reversible in one command. +- **Hand over the `home_url`** that `miakapp publish` and `miakapp status` + print, and say what you verified there. Never the artifact URL. +- **Ask once, at the start, for what you cannot find.** Access comes from + pairing, the house from inventory, physical controls from one question. +- **Right the first time.** The owner should never have to ask you to remove + or restyle something you added. +- **Nothing from the platform's source.** The CLI, its starter and these skills + are the whole toolchain. If a capability is missing, tell the owner; never + patch or redeploy the platform for one house. + +## Build it with the owner, one visible step at a time + +Each step ends with something the owner sees in the published app, a few plain +sentences, and **one** question that opens the next step. A first session: + +1. Right after pairing, publish the empty app and send its `home_url`: "Here is + your home's app, empty for now. Do you have something precise in mind? + Otherwise, which connected devices do you have?" +2. Ask only what you need to reach the devices (account, a Pi or small PC that + runs 24/7), and **once** for the green light on physical controls, each + reserved to the people the owner chooses. That answer covers the journey; + still never trigger something that opens, unlocks or heats yourself — say it is ready to try. -3. Connect them, publish, check, then: *"I've just added your lamps! Do you want - me to group them by room? Otherwise we can start adding people to the home: - family members, guests or friends?"* -4. Carry on the same way: rooms, **people and their rights** (who may join, how - they are invited, what each role sees and does: build it the way - `miakapp docs members` explains, early, before the owner shares the home), - automations, then the devices that were not connected. - -Rules for every checkpoint: - -- what the owner looks at is the real published app, never a mockup; -- one question at a time, with the likely answer suggested; -- small steps, minutes rather than hours: add a few things, show them, move on; -- the owner's words, no technical detail unless they ask; -- if the owner says "carry on without me", chain the steps and report at the end. +3. Connect, publish, check, then propose the next step: rooms, **people and + their rights** (early, before the home is shared), automations, devices that + are not connected yet. -Two scopes must not be confused: +The owner's words, no technical detail unless asked. "Carry on without me" +means chain the steps and report at the end. | In scope by default | Needs the owner's explicit request | | --- | --- | -| reading the existing installation (§3) | changing flows, automations or devices that already run the house | -| giving the coordinator its own access to devices (its own broker user, token, GPIO) | removing or replacing the existing hub (the switch-over) | -| writing and testing a coordinator and an app | physical controls, until the owner answered the one question above | -| publishing, verifying and rolling back the V4 interface | anything on the owner's own machines beyond the coordinator you were asked to run | +| reading the existing installation | changing flows, automations or devices that already run the house | +| giving the coordinator its own access to devices | removing or replacing the existing hub | +| writing, testing, publishing and rolling back | physical controls, until the one question is answered | -Caution about the second column is not a reason to withhold the first. A new V4 -interface that only reads is still a useful, publishable V1; say plainly which -controls are not offered and why. +## What you are building -## 1. What you are building - -Three artifacts, and no more: - -| Artifact | Where it runs | What it owns | +| Artifact | Runs | Owns | | --- | --- | --- | -| Coordinator | the owner's machine, under Bun | state, events, functions, **authorization** | -| Interface | an isolated frame in the household's browser | what residents see and touch | -| `miakapp.yaml` | neither; it is the contract | what the interface may ask for | - -The interface is a **whole-house application** (`app:` in `miakapp.yaml`, ABI -`miakapp.app/1`): your own HTML, CSS, layout, navigation and libraries, bundled -into one file. Miakapp draws nothing for you, and no longer draws the old -semantic `component:` kind at all: a home published that way shows as having no -interface. §5 covers the app. - -The coordinator is trusted. The interface is not. The relay between them is -platform-untrusted but not blind: it terminates TLS, stores plaintext state and -enforces routing, so self-hosting it does not give end-to-end confidentiality. -Do not tell the owner otherwise. - -Start the interface with the starter the CLI ships, in an empty directory: - -```bash -miakapp init --starter app # home and issuer from the paired context -bun run build && bun run check # Bun >= 1.2.23 bundles; Node >= 22.9 runs the CLI -``` - -It writes `miakapp.yaml`, `app/main.ts` (the interface to edit), -`app/miakapp.ts` (the bridge to the home, copied from this CLI release), -`package.json`, `tsconfig.json` and `app/README.md`. It needs no source -repository and no unpublished package, and it refuses — writing nothing — if -any of those files already exists. As generated it shows only what the home -shares, with an honest empty state; it is where your work starts, never what -you publish. Without `--starter`, `init` writes `miakapp.yaml` alone. - -This guide covers the judgment no starter can. - -### Leave the repository readable by the next agent - -You are probably not the last agent to open this repository, and the next one -will not have this conversation. Run the pack once, in the repository root: - -```bash -miakapp agent-pack -``` - -It copies this guide to `.miakapp/agent-guide.md`, points `AGENTS.md` and -`CLAUDE.md` at it, and registers `miakapp mcp` in `.mcp.json` so the tools are -wired rather than described. It edits instead of replacing: prose outside the -`` markers is kept, other MCP servers are kept by name, -and running it twice changes nothing. - -If you are reading this file *as* `.miakapp/agent-guide.md`, someone already -ran it. Run it again after upgrading the CLI, and commit what changes — a guide -that contradicts the CLI installed beside it is worse than no guide. - -## 2. The division of responsibility - -**The coordinator authorizes everything.** The relay proves *who* is calling and -attaches non-spoofable caller metadata. Deciding whether that person *may* act is -the coordinator's job and nobody else's. In a well-built coordinator that decision is the -first line of the function body: - -```ts -if (call.source.kind !== 'user' || call.source.id !== options.ownerUserId) { - throw new ApplicationCallError(2003, 'Only the owner may drive the lights'); -} -``` - -Removing that check does not produce an error anywhere. It produces a home that -anyone enrolled can drive. There is no second layer that will catch it for you. - -**The app trusts nothing it was not given.** It has no network and no storage -shared with anyone. It cannot reach the lamp except through a call the -coordinator declared, and it cannot read a state path the coordinator did not -grant. This is why it is safe to let an app be rewritten often and reviewed -lightly, and why it is not safe to move a decision into it. - -**You own the UI; the coordinator owns the facts.** The coordinator exposes state -and actions. What the household actually sees — the layout, the wording, the -language, which controls are prominent — is yours to design (§5). Do not push -presentation choices into the coordinator, and do not push authorization into -the app. - -## 3. Before you write anything: characterize the house - -You are almost never starting from an empty building. Read what is already there -before you design anything: - -- existing hubs and brokers — Node-RED, MQTT, Zigbee/Z-Wave coordinators, an - HTTP-speaking hub; -- what each device actually reports, and how often; -- which values are *measurements* (temperature, power) and which are - *commanded* (a lamp, a valve) — they have different failure modes; -- which actions are physically consequential: anything that heats, locks, - unlocks, opens or closes. - -Write down what you found before you write the configuration. The state paths you -choose become a disclosure boundary and a public interface at the same time, and -renaming one after the household has used it is not free. - -### Talk to the devices, not to the old hub - -Read the existing hub to learn the house, never to depend on it. The -coordinator talks **directly** to the devices: MQTT and Zigbee2MQTT topics, the -Pi's GPIO for relays, the local HTTP or UDP API of a device, an RF or IR -transmitter. Owners move to Miakapp to get rid of the old stack (Node-RED, Home -Assistant, a vendor bridge), and a home that still needs it is not finished. - -- Give the coordinator its own access: its own MQTT user on the broker, its own - token. Do not reuse the hub's credentials, and do not call the hub's API - (Node-RED HTTP endpoints, its context files, a Home Assistant REST call) for - something the device itself can tell you or do. -- When a direct path is not ready yet, the hub may serve as a **temporary - bridge** for that one datum or action: mark it `bridge: ` in - `docs/inventory.md`, keep it behind one function you can swap, and tell the - owner what is left before the hub can be switched off. -- Two masters on the same relay or device disagree about its state. While the - old hub still drives something, keep your direct driver ready but off, and - switch over in one step with the owner. - -### The inventory comes before the design - -Commit the inventory as `docs/inventory.md` in the home repository, one line per -datum or action, before you design a single screen: - -| Field | Example | -| --- | --- | -| source | `zigbee2mqtt/salon_thermo` over the house broker | -| what it is | temperature, °C, one decimal | -| how fresh | reports every ~60 s; last seen 2 min ago | -| who may read it | every member / owner only | -| command | none — a measurement, not a control | -| path | direct (MQTT) / bridge: Node-RED until the switch-over | - -Then design **from** it: the V1 shows every datum the household would care -about and every action that is both technically possible and authorized, -grouped the way people live in the house — by room or by use, not by device -or protocol. Anything you leave out, leave out on purpose, and say why in the -inventory. A V1 that shows three values when the house reports twenty is not a -first version; it is an unfinished one. - -What the interface must never do: - -- **invent data.** A value with no source is shown as absent, never filled in - with a plausible number or a demo fixture; -- **blur freshness.** Distinguish *current*, *stale* (with its age) and - *unavailable* for every value, in words a resident understands; -- **spend space on plumbing.** No protocol or platform vocabulary - (`ACCEPTED`, "relay connected", ABI, schema names, IDs), no banner restating - that a view is read-only, no title repeating the home's name on every card. - Every line of text is either information or an action. - -### Reading a V3 house you inherited - -Most houses arriving at V4 already run Node-RED with the v3 MiakAPI nodes. Ask -the owner for the `flows.json` Node-RED writes, or for an *Export > All flows* -download, and read it before you read anything else: - -``` -miakapp discover --flows ~/node-red/flows.json -miakapp discover --flows ~/node-red/flows.json --json -``` - -The command is offline and read-only: it opens no socket, contacts no broker and -never writes back into the export. It reports the tabs, the MQTT brokers with the -topics their nodes actually reach, the `initMiakapi` home bindings, every -`commitVariables` path as a state candidate, every `onUserAction` id as a -function candidate with the groups allowed to invoke it, and every node type it -does not model — so you know what the inventory missed rather than assuming it -missed nothing. - -Four of its findings decide work you would otherwise discover late: - -- **`secret_in_export`.** The v3 `initMiakapi` node declares `coordSecret` in its - `defaults`, not in its `credentials`, so Node-RED stores that secret in - cleartext in `flows.json` rather than in the encrypted `flows_cred.json`. If - the export has one, treat it as leaked: rotate it, and keep the file out of - Git. §9 is the V4 rule that replaces it. -- **`unrestricted_action`.** The v3 handler allows an action outright when its - node lists no group, so an empty `allowedGroups` is a grant to every signed-in - user, not a deny. Each one needs a deliberate V4 rule before you port it. -- **`name_needs_rename`.** A v3 variable path or action id that is not a legal V4 - dotted name has to be renamed now, while nobody depends on it. -- **`wildcard_subscription`.** A topic holding `#` or `+` is a subscription - pattern, not one device. Enumerate what it actually matches. - -The command deliberately does not tell you which actions are physically -consequential. It lists every action it found; deciding which of them heats, -locks, unlocks, opens or closes is a judgement you make with the owner, and no -keyword list should make it for you. - -### When the owner needs a new device - -Recommend open protocols that work locally: **Zigbee** (through a Zigbee -coordinator and Zigbee2MQTT), **MQTT**, devices that run **Tasmota** or -ESPHome, and anything else that does not need the vendor's cloud. Avoid, when -there is a choice: - -- **Bluetooth**: its range is too short for a house; -- **Wi-Fi**: hard to extend, the router caps the number of devices, and - everything depends on the internet box. - -Say why in one sentence, name one or two concrete models and a price range. -For a device that cannot be connected at all (proprietary RF or IR remote, a -gate or shutter with only a wired switch), look for a bridge: an RF or IR -transmitter, or a Zigbee relay module wired to the existing switch. - -## 4. The coordinator - -Keep the coordinator in the same shape: the configuration is a -**pure function of its options**, so it can be tested without a relay, a control -plane or a network. `coordinator/main.ts` is the only file that touches the -outside world. Keep that split. It is what makes `test/home.test.ts` possible, -and the authorization rules are exactly the thing you want under test. - -Four declarations: - -```ts -{ - state: { 'zone.living_room.light.on': false }, // paths and initial values - stateAccess: [{ userId, patterns: ['zone.living_room.*'] }], - events: [{ topic, directions: EventDirection.publishToUsers }], - eventAccess: [{ userId, publish: [], subscribe: [topic] }], - functions: { async 'lighting.set'(call) { /* authorize, act, return */ } }, -} -``` - -`stateAccess[].patterns` is the disclosure boundary. A user sees exactly those -paths and nothing else. Widen it deliberately, one path at a time, and never with -a wildcard that happens to be convenient. - -Three ordering and failure rules that are easy to get wrong: - -**State first, event second.** Write the state, *then* publish the event: - -```ts -await coordinator.state.set([{ path: STATE.lightOn, value: on }]); -await coordinator.events.publish(EVENT_LIGHT_CHANGED, { on }); -``` - -A subscriber that reacts to the event and immediately reads the state must never -see the old value. The reverse order is a race that will reproduce once a month -and waste a day. - -**Reject bad arguments with a typed application error.** `ApplicationCallError` -carries a numeric code the app can branch on. Do not throw a bare `Error` -for a caller mistake; the distinction between "you asked wrongly" and "something -broke" is the one the interface needs most. - -**A home has several coordinators.** Names are namespace sharding by convention. -The relay keeps ownership tables for topics, state paths and functions, detects -collisions and rejects with `4409`. If you claim `lighting.set` for the whole -house, you have taken a name another integration may need; scope what you own. - -## 5. The interface - -### A whole-house application (default) - -`miakapp init --starter app` writes an `app:` section and a buildable app to -edit. You own the document: build any DOM, ship your own CSS, use React, -Svelte, Vue, charts or WebAssembly — anything a bundler can inline. Navigate -with the starter's `createNav()`, which gives every page a history entry and a -swipe back. The deliverable is **one classic-script IIFE** of at most 2 MiB, -with no `import()` and no source map; the starter's `bun run build` is: +| Coordinator | the owner's machine, under Bun (`miakapi`) | state, events, functions, **authorization** | +| App | an isolated frame in each resident's browser | what residents see and touch | +| `miakapp.yaml` | — the contract | what the app may ask for | -```bash -bun build app/main.ts --format=iife --minify --outfile dist/app.js -``` - -Miakapp runs it in an isolated, opaque-origin frame below a permanent Miakapp -bar, after the resident agreed to open the home. The frame has no network, no -cookies or storage, no popups and no fullscreen; assets go in the bundle as -`data:`/`blob:` URLs. Its only way to the home is `window.miakapp`, through the -bridge the starter writes as `app/miakapp.ts` — the source of the `@miakapp/app` -SDK, which is not on npm yet, so import the local file: - -```ts -import { callErrorCode, connect } from './miakapp.js'; - -const home = connect(); -home.subscribe((state) => render(state)); // also called once immediately -await home.call('lighting.set', { on: true }); // rejects with a closed code -``` - -Do not edit the bridge; a newer CLI's starter carries any change to it. - -**Make it beautiful from the first build.** Run `miakapp docs design` before you -draw anything, and follow its "Make it beautiful" recipe: Miakapp ships design -tokens, four themes (Minuit, Lumière, Miel, Craie), CSS recipes, line icons, an -embedded font and example screens. The starter's `app/theme.ts` already uses -them. They are a starting point you may change -entirely; the Miakapp bar at the bottom, outside your frame, is not yours to -redraw, but `home.bar.setButtons()` can add one or two of your own screens to it -(icons: grid, bolt, light, thermometer, camera, lock, list, chart, leaf, star, -people, bell), each with an optional `badge` count (e.g. join requests waiting; -0 shows none). Call it again whenever the count changes. - -Your frame cannot open the share sheet or write the clipboard. For a "Share" or -"Copy" button, call `home.share({ title, text, url })` or `home.copy(text)` -directly in the tap handler: Miakapp does it (share sheet, else copy), only on -that fresh tap, url https only. It resolves `'shared'`, `'copied'`, -`'cancelled'` or `'unavailable'`; tell the resident which, and on -`'unavailable'` show the text in a read-only field. - -Declare every state path (exact or `prefix.*`) under `app.requires.state_read` -and every function under `app.requires.call`. Events, media and `miakapp.*` -functions are refused by `miakapp check`. Show `state.stale`, disable controls -while it is true, and handle `outcome_unknown` exactly as below. +The coordinator is trusted, the app is not. The relay terminates TLS and stores +plaintext state: self-hosting it is not end-to-end encryption; never say so. -**The bundle is not private.** Any signed-in user who learns its digest can -fetch it. Put no household data in it — no names, rooms, devices or accounts — -and read everything from state, which the coordinator filters per resident. +## Access -### Two states the interface must never hide - -**Staleness.** `home.state.stale` means the snapshot may no longer reflect the -house. Show it. Per RFC 0002 §12.2 it is exposed, never hidden — a thermostat -reading that is silently forty minutes old is worse than one labelled uncertain. -Showing it is the Miakapp bar's job and yours together: the bar says -"Connecting…" or "Reconnecting…", and your app **dims** the values that may be -old (`.is-stale` on `.mk-app`) and disables the controls. Never add a banner, -toast or strip of your own for it ("The home is not answering"): it repeats the -bar, and every resident sees it each time the app opens. - -**Staging.** `home.staging` is true while a release is staged: rendering works, -calls and events do not. Disable the controls and say why. -An interface that looks live and silently does nothing is the worst outcome -available. - -### An unknown outcome is never retried - -This is the rule that will most tempt you to break it, so it is stated plainly: - -```ts -try { - await home.call('lighting.set', { on }, { deadlineMs: 10_000 }); -} catch (error) { - // Deliberately not retried. The call may already have reached the lamp, - // and the next state snapshot settles the question. - failure = error instanceof Error ? error.message : 'The command failed'; -} -``` - -A failed call is not a call that did not happen. `CallOutcomeUnknownError` exists -precisely to name the case where the effect is undetermined, and the physical -world does not have a rollback. Surface it, let the next state snapshot settle -it, and let the person decide. The same principle has a CLI counterpart: exit -code 7. - -### Check it for real - -Never check against a bridge you wrote yourself: it hides what breaks on a -phone (sandbox refusals, late answers, refused calls, rate limits). Run the app -against the real home: +Never ask for a password, a login or a key. The owner opens +https://miakapp.com/pair, picks the home, and sends you a one-time code +(10 minutes, once): ```bash -bun run build -miakapp preview --as member # your build, not activated: prints a link -miakapp taps --as member # taps every control there, reports what is wrong +printf '%s\n' "" | miakapp pair # --issuer if the page shows one +miakapp context list # homes this machine can publish to ``` -`preview` (your build) and `open` (the live release) print a link, valid up to -an hour, that opens the home at phone size (390 × 844) as the test member -`test:`, with no account: the real Miakapp bar, sandbox, relay and -coordinator. Your coordinator gives `test:` the rights of that role, like -any member (`miakapp docs members`); check once per role. Open the link in the -browser you drive (never install one) and look at every page, with touch. +The key lands in `~/.miakapp` (or `MIAKAPP_HOME_KEY` for CI), never in the +repository. The home's own coordinators may use the same key: give it to them +through their environment, never ask for a second pairing. Keys and wiring are +your business; tell the owner what works, not how. -`taps` reports every control with no call, no navigation and no visible change, -failed calls, start-up calls that failed or took over 1.5 s, errors the app -threw, and saves a screenshot of each page. A call a tap makes is held, never -sent, unless you name its function with `--send` (reads only, never something -that moves). Fix what it reports and run it again until it reports nothing. +## Keep this repository readable by the next agent -## 6. The intersection rule +`miakapp agent-pack` (once) installs this guide, the skills below, a pointer in +`AGENTS.md` and `CLAUDE.md`, and the `miakapp` MCP server pinned in `.mcp.json`. +It only rewrites what it generated. `miakapp update` moves the repository to a +newer CLI (see the `miakapp-update` skill). -Every name an app may touch appears in **two** places, and the effective -grant is the intersection: +## Skills -| `miakapp.yaml` → `requires` | `coordinator/home.ts` | +| Skill | Use it to | | --- | --- | -| `state_read` | `stateAccess[].patterns` | -| `event_subscribe` | `eventAccess[].subscribe` | -| `event_publish` | `eventAccess[].publish` | -| `call` | `functions` | - -Asking for more than the coordinator grants **does not fail loudly at -publication**. The app simply never receives that path, and the interface -renders a hole — an empty card, a control that does nothing, a temperature that -is permanently unavailable. This is the single most common way a Miakapp home -breaks, and it breaks quietly. - -So: assert the correspondence in a test, so a mismatch fails in CI rather than -in someone's living room. When you add a path, change four things in one commit — -the state declaration, the access pattern, the `requires` entry, and the test. - -## 7. The loop - -```bash -bun run check # typecheck → bundle → test → validate the artifact offline -``` - -Run it before every publication and in CI. It costs nothing and catches the -artifact rules the runtime would reject anyway. - -Do not treat a check that exists as a check that runs. On 2026-09-14 this -repository had two example packages that were both verified locally and built -by nobody, because the workflow called `bun run check` and not -`check:packages`; when CI finally exercised them they failed three times in a -row on defects that had been sitting there invisibly. If you add a package, add -it to the job that runs in CI, then watch one run go green before believing it. - -Reproduce CI with the toolchain version it pins, not the one you have. Bun 1.4 -self-references the root package and resolves `bunx` from `node_modules`; the -pinned 1.2.23 does neither, so a green local run proves nothing about the runner. -Install the pinned version alongside yours: - -```bash -BUN_INSTALL=/tmp/bun1223 curl -fsSL https://bun.sh/install | bash -s bun-v1.2.23 -``` - -Note also that `bun test foo/` is a **substring filter**, not a directory scope. - -## 8. Publishing - -The CLI builds, validates, publishes and rolls back. **It never owns Git.** It -writes no history, rewrites no source it did not generate, and invents no -control-plane endpoint. The repository is the owner's. - -```bash -miakapp docs start # this guide, from the installed CLI -miakapp pair # once per home and machine (§9) -miakapp agent-pack # once, per repository -miakapp init --starter app # manifest + buildable app; plain init writes the manifest only -miakapp check -miakapp status # what is live now: generation, release, digest -miakapp publish # upload, finalize, activate -miakapp status # verify the new digest is what is live -miakapp activate --sha256 # promote an already finalized digest -miakapp rollback --sha256 # alias of activate -miakapp release # read one finalized release -miakapp upload # reconcile a lost request -``` - -Activation is a compare-and-set on the home's component pointer. Without -`--expected-generation` the CLI reads the live generation first and activates -the next one; the read takes no lock, so another publication landing in between -still fails with `conflict` instead of being overwritten. Pass -`--expected-generation ` when you want to assert the state you reviewed. - -Rollback is `activate` pointed at a digest you already trust. Keep the digest of -every release you shipped; a rollback you can perform in one command is worth -more than an incident you can explain. - -`miakapp status` after `publish` is the minimum verification: the live `sha256` -must be the one you just built. It proves what the home runs, not that the -interface is right: `miakapp open` it and look before telling the owner it works. - -### Driving the CLI as a program - -Every failure maps to exactly one stable exit code and one stable -machine-readable kind. New kinds may be added; existing codes never change -meaning. Pass `--json` and you get exactly one closed object on stdout. - -| Code | Kind | Meaning | -| --- | --- | --- | -| 0 | `success` | | -| 1 | `usage` | the invocation was wrong | -| 2 | `project` | `miakapp.yaml` is missing or invalid | -| 3 | `artifact` | the built bytes violate an artifact rule | -| 4 | `authorization` | the Home Key is missing, wrong or unscoped | -| 5 | `contract` | the control plane rejected the request | -| 6 | `conflict` | `--expected-generation` did not match; re-read, do not retry | -| 7 | `unknown_outcome` | **effect undetermined — reconcile with a read** | - -Branch on the code, not on the prose. On 7, call `miakapp upload ` or -`miakapp release ` and reconcile before acting again. Never retry a 7 -with a fresh capability. - -### If you speak MCP instead of shell - -`miakapp mcp` serves the same commands as tools over JSON-RPC on stdio. It is the -same code: a tool call becomes the argv a person would have typed and runs the -same dispatch, so everything above still holds — the same defaults, the same -validation, the same `kind` on every failure. - -Three differences are worth knowing before you call anything: - -- `miakapp_publish`, `miakapp_activate` and `miakapp_rollback` refuse to run - without `confirm: true`. Set it when the owner asked for that publication, and - not to get past an error; -- a failure arrives as a tool result with `isError: true`, carrying the same - closed object, not as a JSON-RPC error. A JSON-RPC error means your call never - happened; `isError` means it ran and failed, and `kind` says what to do next; -- a tool argument is the option name with `_` instead of `-`. An argument the - tool does not declare is refused, never ignored. - -`packages/cli/README.md` lists the tools. The exit codes above are the -`exit_code` field in every result, so branch on the same table either way. - -### Notifying the people of the home - -```sh -miakapp notify --to [,…] --title "Front door" --body "Open for 10 minutes" -``` - -Reaches only the people you name, on the devices where they opened the home and -turned notifications on (Settings → Notifications). Anyone can turn -notifications on for any home, so the platform never notifies "the whole home": -**you decide who is told**, from the members your coordinator knows -(`miakapp docs members`). User IDs -are the `id` of the `user` principal your coordinator receives with every call -and event (`principal.kind === 'user'`). It needs -only the paired context, not a project file. `delivered: 0` is not an error: -the people named have not turned notifications on (on iPhone they first add -Miakapp to the Home Screen). - -### At home and without the internet: direct mode (on by default) - -A coordinator built on `miakapi` 4.1 or later also listens for residents on the -local network (UDP 4455, WebRTC). There is nothing to code: through the relay, -each resident's browser learns how to reach the coordinator, then opens the home -**directly** when it is on the same network (lower latency), and keeps working -when the internet is down (the Miakapp page and the app open from the phone's -cache). What is yours to get right: - -- **Network.** In Docker, run the coordinator with host networking - (`network_mode: host`). Otherwise publish `4455/udp` and pass - `direct: { hosts: [''] }` to `createCoordinator`. -- **A persistent identity.** The coordinator keeps its certificate, ICE - password and ticket key in `.miakapp/direct` (relative to its working - directory, or `direct.directory`). Keep it on a persistent volume: browsers - pin that certificate, and losing it means every phone must be online once more. -- **A fixed address.** Ask the owner to reserve the coordinator machine's - address in the router (DHCP reservation): an offline phone can only reach the - address it last saw. -- **Do not wait for the relay.** Without the internet, `coordinator.start()` - resolves only once the relay is back, while `state.set` and function calls - already work locally. Do not `await start()` before wiring the devices. -- Every coordinator of the home must run `miakapi` 4.1 or later and be - reachable on the LAN: the phone goes direct only when all of them answer - (without the internet, it opens with those that do). Events are not carried - on it. `direct: false` turns it off. - -## 9. Access: pairing and contexts - -You never sign in as the owner and never ask for a password, a Google login or -an existing key. The owner grants access to one home, in their own browser: - -1. Ask the owner to open **https://miakapp.com/pair**, sign in to their own - account, choose the home (or create it), confirm the access it grants, and - send you the one-time code it shows. A code works once, for ten minutes. -2. Redeem it. The code is read from stdin and never echoed: - - ```bash - printf '%s\n' "" | miakapp pair # add --issuer if the page shows one - ``` - - Over MCP, call `miakapp_pair` with `code`. Never repeat the code back in a - message, and never retry a refused code — ask for a new one. -3. `pair` stores a **new, separately revocable** Home Key for this machine as a - context in `~/.miakapp`, keeps every other context, makes the new one - current, and proves the key can publish. It prints the key ID and label, - never the key. - -```bash -miakapp context list # every home this machine can publish to -miakapp context show [name] # one context; the key is never printed -miakapp context use # make a context current -miakapp context remove # delete it locally (the owner revokes it server-side) -``` - -`~/.miakapp/config.json` holds names, homes, issuers and key IDs; -`credentials.json` holds the keys. Both are mode 0600 in a 0700 directory and -are replaced atomically; the CLI refuses a credentials file other accounts can -read. `MIAKAPP_CONFIG_DIR` relocates the directory. - -Which key a command uses, highest precedence first: - -1. `--context `, then `MIAKAPP_CONTEXT=`; -2. `MIAKAPP_HOME_KEY`, a raw key for CI and compatibility; -3. the stored context paired with the home and issuer in `miakapp.yaml` — the - current context breaks a tie between two keys for that same home. - -A context, or a known key, for a different home than `miakapp.yaml` names is -refused before any request: a key can never publish into the wrong house. - -One pairing is enough. The coordinators you run for this home (on a Raspberry -Pi, a small PC…) may use the same Home Key as you: hand it to them yourself, -through their environment, from `~/.miakapp/credentials.json`. Never ask the -owner for another pairing code just to give a machine its own key. - -Keys, tokens, contexts and pairing internals are your business, not the -owner's. Tell them what works ("the Pi is connected, your lamps answer"), -never how it is wired, unless they ask. - -If you are about to write a secret into `miakapp.yaml` or any file in the -repository so something works, stop: that is the failure this design exists to -prevent. - -## 10. Before you tell the owner you are done - -- [ ] `docs/inventory.md` lists every source, datum and action you found, and - the interface covers it or says why not. -- [ ] Every value shows whether it is current, stale or unavailable; nothing is - invented, and no technical vocabulary is on screen. -- [ ] The interface is published and `miakapp status` shows your digest live. -- [ ] `miakapp taps` reports nothing, for each role you built. -- [ ] The owner received a working link and the rollback digest, not a - screenshot or a mockup. -- [ ] Every physically consequential function authorizes its caller on its first - line, and a test proves an unauthorized caller is refused. -- [ ] Every name in `miakapp.yaml` is covered by the coordinator, and a test - asserts the correspondence. -- [ ] `home.state.stale` dims the values and disables the controls, with no - banner of your own; `home.staging` is visible. -- [ ] You looked at every page of `miakapp preview` (§5): pages slide, the - left-edge swipe goes back, held actions fire after 0.3 s. -- [ ] States use the four colours of `miakapp docs design` (green safe, - orange to look at, gold on, red alarm only), always with a word. -- [ ] The coordinator talks to the devices directly; any hub left is a - `bridge:` line in the inventory with what remains to switch it off. -- [ ] No call path retries an unknown outcome. -- [ ] State is written before its event is published. -- [ ] `bun run check` is green, and CI ran it — not just you. -- [ ] The Home Key exists only in `~/.miakapp` or the environment, never in the - repository. -- [ ] You recorded the digest of what you published, so rollback is one command. - -## Where to read further - -Everything a home needs is above and in the CLI with its starter. The RFCs and -platform paths below explain *why* the platform behaves as it does; you never -need them, or the platform repository, to build and publish a home. - -- `miakapp docs members` — members, join requests, invitations, roles and who - is notified: the coordinator decides, Miakapp only says who is calling. -- `packages/cli/README.md` — every command and every tool, including what the - pack writes and what it refuses to overwrite. -- `docs/rfcs/0001` (Miakapp/Miakapp) — wire protocol: ownership, collisions, `4409`. -- `docs/rfcs/0002` — release pointer, capabilities and the staleness rule; - `docs/specs/2026-10-03-house-app-abi.md` — the app frame and its bridge. -- `docs/rfcs/0003` — the coordinator SDK surface. -- `docs/rfcs/0004` — Home Key bootstrap, scopes, publication. -- `docs/rfcs/0005` — the trusted browser client. +| `miakapp-coordinator` | inventory the house, talk to devices, write and test the coordinator | +| `miakapp-interface` | build the app: starter, design, state, calls | +| `miakapp-test-real` | check the app on the real home with `open`, `preview`, `taps` | +| `miakapp-publish` | publish, verify, roll back; exit codes; MCP | +| `miakapp-members` | members, join requests, invitations, roles, notifications | +| `miakapp-update` | a newer Miakapp exists: tell the owner, update, migrate | + +They live in `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). +`miakapp docs start` prints this page and every skill; `miakapp docs design` +and `miakapp docs members` print the design and members guides. diff --git a/packages/cli/assets/changelog.json b/packages/cli/assets/changelog.json new file mode 100644 index 0000000..99b6cad --- /dev/null +++ b/packages/cli/assets/changelog.json @@ -0,0 +1,100 @@ +{ + "schema": "miakapp.changelog/1", + "package": "@miakapp/cli", + "releases": [ + { + "version": "4.8.0", + "date": "2026-11-19", + "home": "The agent looking after the home now has short skills for each job and hears about Miakapp updates, so it can tell you what a new version brings before applying it.", + "steps": [ + "Commit the skills `miakapp update` wrote in .claude/skills/ and .agents/skills/ with the shorter guide and instruction blocks.", + "From now on, when a command reports a newer Miakapp, follow the `miakapp-update` skill: tell the owner what it brings and ask before updating." + ] + }, + { + "version": "4.7.2", + "date": "2026-11-19", + "home": "Publishing right after a preview works the first time.", + "steps": [ + "Nothing to change. `miakapp publish` activates a build that `preview` or `taps` already registered instead of failing." + ] + }, + { + "version": "4.7.1", + "date": "2026-11-18", + "home": "Checking the app before publishing is faster and more reliable.", + "steps": [ + "Nothing to change. `miakapp preview` reuses an already finalized build; `miakapp taps` waits for start-up answers before tapping." + ] + }, + { + "version": "4.7.0", + "date": "2026-11-18", + "home": "Every button is now tested on the real home, at phone size, before you see it: fewer buttons that do nothing.", + "steps": [ + "Stop testing against a hand-written fake bridge: delete any phone.html / frame.html test harness.", + "Check the app with `miakapp preview --as ` then `miakapp taps --as ` for each role, and fix what taps reports.", + "Give `test:` that role's rights in the coordinator's member list (never owner), so test links see what that role sees." + ] + }, + { + "version": "4.6.1", + "date": "2026-11-17", + "home": "Visitors can ask to join the home or use an invitation from its page.", + "steps": [ + "An app may now call `miakapp.join`: declare it under `app.requires.call` if the app offers 'ask to join' or 'redeem an invitation'.", + "Read `miakapp docs members` again for the join flow." + ] + }, + { + "version": "4.6.0", + "date": "2026-11-17", + "home": "Invitation links can be shared straight from the app (share sheet or copy).", + "steps": [ + "Refresh the bridge app/miakapp.ts (`miakapp update` does it) to get `home.share()` and `home.copy()`.", + "Coordinator: bump `miakapi` to 4.6.0 or later to declare `miakapp.join`, the visitors' door, and restart it." + ] + }, + { + "version": "4.5.1", + "date": "2026-11-17", + "home": "Guests can be given access to the rest of the house only while they are on its Wi-Fi.", + "steps": [ + "Coordinator: `miakapi` 4.4.0+ adds `call.source.transport` (direct or relay) and `stateAccess[].directPatterns`; 4.5.0+ adds `address`, the phone's home-network address on direct calls; 4.5.1+ passes the coordinator's error sentence to the app. Bump and restart if the home uses them." + ] + }, + { + "version": "4.5.0", + "date": "2026-11-17", + "home": "The home can have members with roles, join requests and invitations, decided by the home itself.", + "steps": [ + "Read `miakapp docs members` and build the member list in the coordinator before the home is shared.", + "Refresh the bridge app/miakapp.ts to get `home.link` (an invitation code carried by the home's link)." + ] + }, + { + "version": "4.4.1", + "date": "2026-11-17", + "home": "Bar buttons can show a count, for example join requests waiting.", + "steps": [ + "Refresh the bridge app/miakapp.ts to pass `badge` in `home.bar.setButtons()` and use the `people` and `bell` icons." + ] + }, + { + "version": "4.4.0", + "date": "2026-11-17", + "home": "Notifications reach only the people the home chooses, never everyone who opened it.", + "steps": [ + "`miakapp notify` now requires `--to [,…]`: update every script or coordinator that calls it without recipients." + ] + }, + { + "version": "4.3.1", + "date": "2026-11-14", + "home": "The home's link has its new address.", + "steps": [ + "Older CLIs refuse to publish: pin 4.3.1 or later." + ] + } + ] +} diff --git a/packages/cli/assets/members.md b/packages/cli/assets/members.md index 7ec0ad1..0376d58 100644 --- a/packages/cli/assets/members.md +++ b/packages/cli/assets/members.md @@ -24,7 +24,7 @@ What Miakapp gives you: | Testing as each role | `miakapp open --as ` (also `preview`, `taps`) opens the home as `test:`, with no e-mail: give that id the role's rights in your member list (never owner), and nothing else. | Anyone signed in can open any home's address and load its app (the bundle holds -no household data: §5 of `docs start`). A person you have not admitted must get +no household data: see the `miakapp-interface` skill). A person you have not admitted must get **nothing** from the coordinator: no state path, no event, no function. **A visitor can call one function only: `miakapp.join`.** The relay refuses diff --git a/packages/cli/assets/skills/miakapp-coordinator/SKILL.md b/packages/cli/assets/skills/miakapp-coordinator/SKILL.md new file mode 100644 index 0000000..fef619f --- /dev/null +++ b/packages/cli/assets/skills/miakapp-coordinator/SKILL.md @@ -0,0 +1,72 @@ +--- +name: miakapp-coordinator +description: Inventory a Miakapp house and write its coordinator (miakapi, Bun) — reading an existing Node-RED/MQTT/Zigbee install, talking to devices directly, state, events, functions, authorization, direct mode on the home network, tests. Use when adding a device, a datum or an action, or touching coordinator/. +--- + +# The coordinator + +The coordinator runs on the owner's machine and **authorizes everything**. The +relay says who is calling; deciding whether they may act is the first line of +every function, and nothing else will catch a missing check: + +```ts +if (call.source.kind !== 'user' || !canDriveLights(call.source.id)) { + throw new ApplicationCallError(2003, 'Only the household may drive the lights'); +} +``` + +## Inventory first + +Before designing anything, write `docs/inventory.md`: one line per datum or +action — source, what it is (unit), how fresh, who may read it, command or +measurement, path (`direct` or `bridge: `). On an inherited V3 house, read +the Node-RED export offline first: + +```bash +miakapp discover --flows ~/node-red/flows.json +``` + +Act on its findings: `secret_in_export` (rotate it, keep the file out of Git), +`unrestricted_action` (an empty group list granted everyone), `name_needs_rename`, +`wildcard_subscription`. Which actions heat, lock, open or close is your +judgement with the owner, never a keyword list. + +## Talk to the devices, not the old hub + +MQTT/Zigbee2MQTT topics, GPIO, the device's local API, an RF/IR bridge — with +the coordinator's own broker user or token. A hub may serve as a temporary +`bridge:` for one datum, behind one function you can swap; never two masters +on one device. For new hardware recommend local open protocols (Zigbee, +MQTT, Tasmota/ESPHome), not Bluetooth or Wi-Fi. + +## Shape + +Keep the configuration a pure function of its options (`coordinator/home.ts`), +with `coordinator/main.ts` the only file touching the outside world, so +authorization is under test. + +- `stateAccess[].patterns` is the disclosure boundary: widen it one path at a + time. `directPatterns` (miakapi ≥ 4.4) are seen only on the home network. +- **State first, event second**, or a subscriber reads the old value. +- Caller mistakes throw `ApplicationCallError` (2000–2999); the app gets its + sentence (≥ 4.5.1). +- Several coordinators share a home: scope your names, or the relay rejects + with `4409`. +- `call.source.transport` is `direct` or `relay` (≥ 4.4); `address` is the + phone's LAN address on direct calls (≥ 4.5). + +**Intersection rule.** Every name the app uses is in `miakapp.yaml` +`requires` *and* granted here (`state_read` ↔ `stateAccess`, `call` ↔ +`functions`, events likewise). A mismatch fails silently as a hole in the UI: +assert the correspondence in a test, and change state, access, `requires` and +test in one commit. + +## Direct mode (on by default, miakapi ≥ 4.1) + +Phones on the home network talk to the coordinator directly (UDP 4455, +WebRTC) and keep working without internet. Run it with host networking (or +publish 4455/udp and pass `direct: { hosts: [...] }`), keep `.miakapp/direct` +on a persistent volume, ask the owner for a DHCP reservation, and don't +`await start()` before wiring devices: it resolves only once the relay answers. + +`bun run check` before every publication, and in CI with the pinned Bun. diff --git a/packages/cli/assets/skills/miakapp-interface/SKILL.md b/packages/cli/assets/skills/miakapp-interface/SKILL.md new file mode 100644 index 0000000..b978ebd --- /dev/null +++ b/packages/cli/assets/skills/miakapp-interface/SKILL.md @@ -0,0 +1,59 @@ +--- +name: miakapp-interface +description: Build or change a Miakapp home app (the whole-house interface in app/) — starter, design system and themes, navigation, the window.miakapp bridge, state, calls, stale and staging states, bar buttons, share/copy. Use for any screen, layout, style or control change. +--- + +# The app + +One classic-script IIFE (≤ 2 MiB, no `import()`, no source map) that owns its +whole document, in an isolated frame with no network, storage or popups, +below the Miakapp bar. Start from the starter, in the home repository: + +```bash +miakapp init --starter app # miakapp.yaml, app/main.ts, app/miakapp.ts, app/theme.ts… +bun run build && bun run check +``` + +`app/miakapp.ts` is the bridge, copied from the CLI: never edit it +(`miakapp update` refreshes it). + +```ts +import { connect } from './miakapp.js'; +const home = connect(); +home.subscribe((state) => render(state)); +await home.call('lighting.set', { on: true }); +``` + +## Make it beautiful the first time + +Read `miakapp docs design` before drawing anything and follow it: tokens, four +themes, recipes, line icons, example screens. Group by room or use, never by +device. States use its four colours, always with a word. Navigate with the +starter's `createNav()` (history + swipe back). + +## Rules that bite + +- **Never invent data.** No source → shown as absent. Every value is current, + stale (with its age) or unavailable, in residents' words. +- **No plumbing on screen**: no protocol words, IDs, "connected" banners, no + read-only banner, no home name on every card. +- **`home.state.stale`**: dim values (`.is-stale` on `.mk-app`) and disable + controls. No banner of your own: the Miakapp bar already says it. +- **`home.staging`**: disable controls and say why. +- **An unknown outcome is never retried**: show it, let the next snapshot + settle it. +- **The bundle is public** to any signed-in user: no names, rooms or accounts + in it; everything comes from state. +- Declare every path and function in `app.requires`; events and media are + refused. + +## Platform helpers + +- `home.bar.setButtons([{ id, label, icon, badge? }])` + `onSelect`: up to two + of your screens in the Miakapp bar. Never draw your own bottom bar. +- `home.share({ title, text, url })` / `home.copy(text)` from the tap handler; + handle `'shared' | 'copied' | 'cancelled' | 'unavailable'`. +- `home.link.params` / `home.link.hash`: what the home's link carried + (e.g. `?invite=`). + +Then check it on the real home: skill `miakapp-test-real`. diff --git a/packages/cli/assets/skills/miakapp-members/SKILL.md b/packages/cli/assets/skills/miakapp-members/SKILL.md new file mode 100644 index 0000000..9b13a50 --- /dev/null +++ b/packages/cli/assets/skills/miakapp-members/SKILL.md @@ -0,0 +1,34 @@ +--- +name: miakapp-members +description: Members of a Miakapp home — who is in, roles and rights, join requests, invitations (e-mail, links), the miakapp.join visitors' door, guests on the home Wi-Fi, who gets notified. Use before the home is shared with anyone, or when adding people, roles or invitations. +--- + +# Members + +Miakapp only says **who is calling** (account id, verified e-mail; on direct +calls, transport and LAN address). It keeps no member list and grants nothing: +**your coordinator decides who is a member, what each role sees and does, and +who is told.** Read the full guide before building it: + +```bash +miakapp docs members +``` + +The shape it describes: + +- A member list in the coordinator's own storage (never the repository): + id, e-mail, name, role. Roles designed once with the owner ("parents: + everything; kids: lights and shutters; guests: lights"). +- Rights applied the moment the list changes: recompute `stateAccess` / + `eventAccess` and `declareState(...)` again; every function checks the role + on its first line. +- A visitor can call one function only: **`miakapp.join`** (miakapi ≥ 4.6), + with `action: 'me' | 'request' | 'redeem'` — who am I, ask to join, redeem an + invite. Anyone not admitted gets nothing else. +- Invitation links `…/h/?invite=`, read in the app from + `home.link.params.invite`; share them with `home.share()`. +- Join requests notify the owner and admins with `miakapp notify --to`, and a + badge on a bar button (`home.bar.setButtons([{ …, icon: 'people', badge }])`). +- Guests on the home Wi-Fi only: `directPatterns` and `call.source.transport`. +- Test each role with `miakapp taps --as `: map `test:` to that + role in your list. diff --git a/packages/cli/assets/skills/miakapp-publish/SKILL.md b/packages/cli/assets/skills/miakapp-publish/SKILL.md new file mode 100644 index 0000000..eeef4dc --- /dev/null +++ b/packages/cli/assets/skills/miakapp-publish/SKILL.md @@ -0,0 +1,56 @@ +--- +name: miakapp-publish +description: Publish a Miakapp home app, verify what is live, roll back, reconcile a lost request — miakapp check/status/publish/activate/rollback/release/upload, exit codes, the MCP tools and their confirm guard, notify. Use whenever shipping, verifying or undoing a release. +--- + +# Publish, verify, roll back + +```bash +bun run check # typecheck, bundle, test, validate offline +miakapp status # what is live: generation, release, digest +miakapp publish # upload, finalize, activate +miakapp status # the live sha256 must be the one you built +miakapp rollback --sha256 # back to a digest you trust +miakapp activate --sha256 # same: promote any finalized digest +``` + +Then `miakapp open` it (skill `miakapp-test-real`) and hand the owner the +`home_url`, what you verified, and the previous digest. Keep every digest you +shipped: rollback is one command. + +Activation is a compare-and-set on the home's generation; pass +`--expected-generation ` to assert the state you reviewed. + +## Failures: branch on the kind + +| Exit | Kind | Do | +| --- | --- | --- | +| 1 | `usage` | fix the invocation | +| 2 | `project` | fix `miakapp.yaml` | +| 3 | `artifact` | fix the bundle | +| 4 | `authorization` | pair again (ask the owner for a code) | +| 5 | `contract` | read the message; the control plane refused | +| 6 | `conflict` | the pointer moved: re-read with `status`, don't retry | +| 7 | `unknown_outcome` | **never retry**: reconcile with `miakapp release ` or `miakapp upload ` | + +`--json` prints one closed object. Over MCP (`miakapp mcp`, wired in +`.mcp.json`), each command is a `miakapp_*` tool; `publish`, `activate` and `rollback` need `confirm: true` — +set it because the owner asked for that publication, never to get past an +error. A failure is a result with `isError: true` carrying the same `kind`. + +## Notify + +```bash +miakapp notify --to [,…] --title "Front door" --body "Open for 10 minutes" +``` + +Only the people you name, on devices where they turned notifications on; +`delivered: 0` is not an error. You decide who is told (skill `miakapp-members`). + +## Before saying it is done + +Inventory covered or explained · nothing invented, no technical words on +screen · `status` shows your digest · `taps` clean per role · physical +functions authorize on their first line, with a test · `requires` ↔ coordinator +asserted by a test · no unknown outcome retried · `bun run check` green in CI · +no key in the repository · owner has the link and the rollback digest. diff --git a/packages/cli/assets/skills/miakapp-test-real/SKILL.md b/packages/cli/assets/skills/miakapp-test-real/SKILL.md new file mode 100644 index 0000000..35cca23 --- /dev/null +++ b/packages/cli/assets/skills/miakapp-test-real/SKILL.md @@ -0,0 +1,33 @@ +--- +name: miakapp-test-real +description: Check a Miakapp app on the real home before and after publishing — miakapp open, preview and taps at phone size as a test member, per role. Use before telling the owner something works, after any app change, or when a button seems dead. +--- + +# Check it on the real home + +Never test against a bridge you wrote yourself: it hides what breaks on a phone +(sandbox refusals, late answers, refused calls). Use the real home: + +```bash +bun run build +miakapp preview --as member # your build, not activated: prints a link (≤ 1 h) +miakapp taps --as member # taps every control, reports what is wrong +miakapp open --as member # the live release, same kind of link +``` + +The links open the home at phone size (390 × 844) as `test:`, with no +account, through the real bar, relay and coordinator. Your coordinator gives +`test:` that role's rights (never owner). Check once per role you built. + +Open the link in the browser you already drive — never install one — and look +at every page with touch: pages slide, the left-edge swipe goes back, held +actions fire after 0.3 s. + +`taps` reports controls with no call, no navigation and no visible change, +failed calls, start-up calls that failed or took over 1.5 s, app errors, and +saves a screenshot per page. Calls a tap makes are **held, never sent**, unless +you name the function with `--send` — reads only, never something that moves. +It drives a browser over CDP (`--cdp`, default `$MIAKAPP_CDP` or +`$AGENT_BROWSER_BASIC_CDP`). + +Done when `taps` reports nothing for each role and you looked at every page. diff --git a/packages/cli/assets/skills/miakapp-update/SKILL.md b/packages/cli/assets/skills/miakapp-update/SKILL.md new file mode 100644 index 0000000..6801e98 --- /dev/null +++ b/packages/cli/assets/skills/miakapp-update/SKILL.md @@ -0,0 +1,46 @@ +--- +name: miakapp-update +description: A newer Miakapp CLI is available ("Miakapp X is available", an update_available field, or the owner asks) — tell the owner what it improves for their home and what you will change, ask, then update the repository, apply the migrations and verify on the real home. Also use to check whether this home is up to date. +--- + +# Update Miakapp + +Run `miakapp changes` and `miakapp update` through the newest CLI, never the +pinned one — an old release cannot describe or install what came after it. + +1. **See what changed** since the version this repository pins: + + ```bash + npx -y @miakapp/cli@latest changes + ``` + + Each version says what it brings the home (plain words) and what you must + change (migration steps). + +2. **Ask the owner, briefly**, in their words: what it improves for them, what + you will change (e.g. "I'll update the app's toolkit and check every + button again; nothing changes in how you use it"), and whether to do it + now. Suggest "yes". Don't update without that answer, unless the owner + already said to keep Miakapp up to date. + +3. **Update the repository** with the new CLI: + + ```bash + npx -y @miakapp/cli@latest update + bun install + ``` + + It pins the new version in `.mcp.json` and `package.json`, rewrites the + pack (guide, skills, instruction block), refreshes the generated bridge + `app/miakapp.ts`, checks the project, and prints the migrations to apply. + It never touches anything else. + +4. **Apply each migration**, then `bun run check`. If a step concerns the + coordinator (a `miakapi` bump), restart it the way this home runs it. + +5. **Verify on the real home** (skill `miakapp-test-real`), publish if the app + changed (skill `miakapp-publish`), commit, and tell the owner what is new + in one or two sentences. + +Restart the session or reload MCP servers afterwards: the `miakapp` server +runs the version pinned in `.mcp.json`. diff --git a/packages/cli/assets/starter/app/app/README.md b/packages/cli/assets/starter/app/app/README.md index 01dee6e..0aa5f90 100644 --- a/packages/cli/assets/starter/app/app/README.md +++ b/packages/cli/assets/starter/app/app/README.md @@ -51,7 +51,7 @@ shared. `app.requires` in `miakapp.yaml` starts empty, so the first build shows only that empty state. It invents no value and offers no control. That is a starting point, not a deliverable: -1. **Inventory the house first** (`miakapp docs start`, §3): every source, what +1. **Inventory the house first** (skill `miakapp-coordinator`, or `miakapp docs start`): every source, what each value means, how fresh it is, who may see it, which actions exist. 2. **Declare what the app needs** under `app.requires.state_read` (exact paths or `prefix.*`) and `app.requires.call`. The coordinator still decides per diff --git a/packages/cli/package.json b/packages/cli/package.json index 488ac4e..80a9ace 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@miakapp/cli", - "version": "4.7.2", + "version": "4.8.0", "description": "Agent-first Miakapp command line: check, build, publish, activate and roll back home interfaces", "type": "module", "engines": { diff --git a/packages/cli/src/agent-pack.ts b/packages/cli/src/agent-pack.ts index 1258e64..021516e 100644 --- a/packages/cli/src/agent-pack.ts +++ b/packages/cli/src/agent-pack.ts @@ -5,14 +5,15 @@ * home is built. It arrives in the owner's repository, with whatever files are * already there. This command puts three things in that repository: * - * - the guide, as a file, so the knowledge survives without a network; + * - the guide and the skills (one per job, for Claude Code and Codex), as + * files, so the knowledge survives without a network; * - a pointer to it in the instruction file each client actually reads — * `AGENTS.md` for Codex, `CLAUDE.md` for Claude Code; * - the MCP server entry, so the tools are wired rather than described. * * The repository belongs to the owner, and the CLI's rule that it never * rewrites what it did not generate holds here too. That rule is what shapes - * every merge below: the guide is a file this command owns outright, the + * every merge below: the guide and the skills are files this command owns outright, the * instruction files are edited only between markers this command wrote, and * `.mcp.json` is edited as a structure — one key, by name — never as text. * Bytes outside those regions are copied through untouched. @@ -42,6 +43,21 @@ export const INSTRUCTION_FILES: readonly { readonly path: string; readonly clien { path: 'CLAUDE.md', client: 'Claude Code' }, ]; +/** + * Where each client discovers repository skills. Both are written, like the + * instruction files: the owner may hand the repository to either agent. + */ +export const SKILL_ROOTS: readonly { readonly directory: string; readonly client: string }[] = [ + { directory: '.claude/skills', client: 'Claude Code' }, + { directory: '.agents/skills', client: 'Codex' }, +]; + +/** One skill the pack owns: `//SKILL.md`, rewritten on every run. */ +export interface PackSkill { + readonly name: string; + readonly content: string; +} + export const BEGIN_MARKER = ''; export const END_MARKER = ''; @@ -80,7 +96,7 @@ function decode(bytes: Uint8Array, path: string): string { * Returns `unchanged` when the bytes already on disk are identical, so a second * run of the pack reports honestly instead of claiming work it did not do. */ -async function put( +export async function put( files: FileStore, path: string, content: string, @@ -98,46 +114,32 @@ async function put( /** * The block written into each instruction file. * - * It is short on purpose. Everything an agent needs to know is in the guide, - * and a summary that drifts from the guide is worse than no summary: the agent - * would believe the stale copy it read first. + * Short on purpose: the guide and the skills carry the knowledge, and a summary + * that drifts from them is worse than none. The skills are listed here because + * a client that does not discover repository skills still reads this file. */ -export function instructionBlock(client: string): string { +export function instructionBlock(client: string, skills: readonly string[] = []): string { + const skillLines = skills.length === 0 + ? '' + : `\nSkills, one per job — read the one that matches the task: +${skills.map((name) => `\`${name}\``).join(', ')}. +They are in \`${SKILL_ROOTS.map((entry) => entry.directory).join('/` and `')}/\`.\n`; return `${BEGIN_MARKER} ## Miakapp -This repository is a Miakapp home: a coordinator that runs on the owner's -machine and owns state, events and authorization, and an interface — by default -a whole-house application bundled as one IIFE — that runs isolated in the -household's browser and owns nothing but what residents see. - -**Read \`${GUIDE_FILE}\` before writing or publishing anything here.** It is the -full guide, copied into this repository so it is readable offline, and it is the -source of truth for the rules below. - -The \`${SERVER_NAME}\` MCP server in \`${MCP_FILE}\` exposes the toolchain to ${client}: -inventory an existing installation, validate the project, publish, and roll back. -The same commands exist as \`${SERVER_NAME}\` on the command line; they are one -implementation, so neither surface can drift from the other. - -Four rules the guide explains and this file repeats because getting them wrong -is expensive: - -- Done means published and verified: inventory the house first, publish a V1 - that covers the real data, check \`${SERVER_NAME} status\`, open it as a member - would, and hand the owner the printed \`home_url\` — never the artifact URL, a - screenshot or a mockup. -- \`publish\`, \`activate\` and \`rollback\` change what every device in the home - runs. Over MCP they refuse to act without \`confirm: true\`. Set it when the - owner asked for that publication, never to get past an error. -- Every failure carries a stable \`kind\`. Branch on it, not on the message. - \`conflict\` means re-read the pointer; \`unknown_outcome\` means the effect is - undetermined — reconcile with \`${SERVER_NAME} release\` or \`${SERVER_NAME} upload\` - before acting again, and never retry it. -- Access comes from \`${SERVER_NAME} pair\`: the owner confirms the home at - https://miakapp.com/pair and sends a one-time code; never ask for a login or - a key. Keys live in \`~/.miakapp\` (or \`MIAKAPP_HOME_KEY\` for CI), never in - this repository and never in a command argument. +This repository is a Miakapp home: a coordinator on the owner's machine owns +state, events and authorization; an app, published as one bundle, owns only +what residents see. + +**Read \`${GUIDE_FILE}\` before changing or publishing anything here.** +${skillLines} +The \`${SERVER_NAME}\` MCP server in \`${MCP_FILE}\` gives ${client} the same commands as the +\`${SERVER_NAME}\` CLI. Done means published and checked on the real home +(\`${SERVER_NAME} taps\`), with the owner holding the \`home_url\`. Never retry an +\`unknown_outcome\`; never put a key in this repository. When a command says a +newer Miakapp is available, follow the \`miakapp-update\` skill. + +Generated by \`${SERVER_NAME} agent-pack\` / \`${SERVER_NAME} update\`: edit outside the markers. ${END_MARKER}`; } @@ -251,16 +253,28 @@ export async function installPack( files: FileStore, root: string, guide: string, + skills: readonly PackSkill[] = [], ): Promise { const written: PackedFile[] = []; await files.makeDirectory(`${root}/${PACK_DIRECTORY}`); written.push(await put(files, `${root}/${GUIDE_FILE}`, guide)); + // Skills are owned outright, like the guide: the directory names carry the + // `miakapp-` prefix so they never collide with the owner's own skills. + for (const { directory } of SKILL_ROOTS) { + for (const skill of skills) { + const folder = `${root}/${directory}/${skill.name}`; + await files.makeDirectory(folder); + written.push(await put(files, `${folder}/SKILL.md`, skill.content)); + } + } + + const names = skills.map((skill) => skill.name); for (const { path, client } of INSTRUCTION_FILES) { const full = `${root}/${path}`; const existing = await files.exists(full) ? decode(await files.read(full), full) : undefined; - written.push(await put(files, full, mergeInstructions(existing, instructionBlock(client)))); + written.push(await put(files, full, mergeInstructions(existing, instructionBlock(client, names)))); } const mcpPath = `${root}/${MCP_FILE}`; @@ -269,3 +283,57 @@ export async function installPack( return { root, files: written }; } + +/** + * The CLI version a repository's `.mcp.json` pins, if the pack wrote one. + * Read, never trusted for anything but choosing where a changelog starts. + */ +export function pinnedVersion(mcpConfig: string | undefined): string | undefined { + if (mcpConfig === undefined) return undefined; + try { + const entry = (JSON.parse(mcpConfig) as { mcpServers?: Record }) + .mcpServers?.[SERVER_NAME]; + const args = Array.isArray(entry?.args) ? entry.args : []; + for (const argument of args) { + if (typeof argument === 'string' && argument.startsWith(`${PACKAGE_NAME}@`)) { + const version = argument.slice(PACKAGE_NAME.length + 1); + return /^\d+\.\d+\.\d+/.test(version) ? version : undefined; + } + } + } catch { + // A broken file pins nothing; installPack reports it properly. + } + return undefined; +} + +/** + * Re-pins this package in a `package.json` that already depends on it. + * + * Returns `undefined` when there is nothing to do — no dependency on the CLI — + * because adding one is the owner's decision, not the update's. Only that one + * key changes; every other key keeps its order and value. + */ +export function mergePackageJson(existing: string, path = 'package.json'): string | undefined { + let document: unknown; + try { + document = JSON.parse(existing); + } catch (error) { + throw projectError( + `${path} is not valid JSON: ${error instanceof Error ? error.message : 'parse failed'}`, + 'Fix the JSON, then run the update again.', + ); + } + if (!isPlainObject(document)) return undefined; + let touched = false; + const updated: Record = { ...document }; + for (const key of ['dependencies', 'devDependencies']) { + const section = document[key]; + if (isPlainObject(section) && typeof section[PACKAGE_NAME] === 'string') { + updated[key] = { ...section, [PACKAGE_NAME]: CLI_VERSION }; + touched = true; + } + } + if (!touched) return undefined; + const indent = /^\{\s*\n(\s+)"/.exec(existing)?.[1] ?? ' '; + return `${JSON.stringify(updated, null, indent)}\n`; +} diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index fe0b406..88935b9 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -15,8 +15,32 @@ * - `--json`, which prints exactly one closed object on stdout. */ import { homedir, hostname } from 'node:os'; -import { installPack } from './agent-pack.js'; +import { + GUIDE_FILE, + MCP_FILE, + installPack, + mergePackageJson, + pinnedVersion, + put, + type PackSkill, + type PackedFile, +} from './agent-pack.js'; import { CLI_VERSION } from './version.js'; +import { + UPDATE_CHECK_VARIABLE, + changesBetween, + checkForUpdate, + compareVersions, + fetchChangelog, + fetchLatestVersion, + isVersion, + mergeChangelogs, + parseChangelog, + updateJson, + updateNotice, + type ChangelogEntry, + type UpdateInfo, +} from './updates.js'; import { prepareArtifact, type Artifact } from './artifact.js'; import { exchangePublisherToken, @@ -127,6 +151,8 @@ export interface CliHost { * protocol stream. */ readSecret?(prompt: string): Promise; + /** Milliseconds since the epoch. Injected by tests; defaults to `Date.now()`. */ + now?(): number; } type Field = readonly [key: string, value: string | number | readonly string[]]; @@ -152,7 +178,7 @@ Usage miakapp [options] Commands - docs start Print the complete agent guide bundled with this CLI + docs start Print the agent guide and every skill bundled with this CLI docs design Print the design guide: tokens, themes, recipes, examples docs members Print the members guide: requests, invitations, roles, who is notified pair Redeem a one-time pairing code into a stored context @@ -161,7 +187,9 @@ Commands context use Make a context current context remove Delete a context and its stored key init Write ${PROJECT_FILE} (add --starter app for a buildable app) - agent-pack Install the guide and the MCP wiring into a repository + agent-pack Install the guide, the skills and the MCP wiring into a repository + changes What each newer release brings the home, and what to migrate + update Move a home repository to this CLI: pins, pack, bridge, checks discover Inventory an existing Node-RED installation offline check Validate the project and the artifact offline status Read the live generation and release of the home @@ -228,6 +256,15 @@ mcp options agent-pack options --dir Repository to install into (default: cwd) +changes options + --since Start after this version (default: the version + .mcp.json pins, else this CLI's) + --dir Repository whose pin to read (default: cwd) + +update options + --dir Repository to update (default: cwd). Run it with + the release you want: npx -y @miakapp/cli@latest update + init options --home Home ID (default: from the selected context) --control-plane Control-plane issuer (default: from the context) @@ -251,6 +288,7 @@ Credentials, highest precedence first Environment MIAKAPP_CONFIG_DIR Absolute directory replacing ~/.miakapp + ${UPDATE_CHECK_VARIABLE}=0 No daily check for a newer release (also off when CI is set) Exit codes 0 success 1 usage 2 project 3 artifact @@ -267,6 +305,8 @@ export const COMMAND_OPTIONS: Record = { context: [], init: ['home', 'control-plane', 'artifact', 'release', 'context', 'starter'], 'agent-pack': ['dir'], + changes: ['since', 'dir'], + update: ['dir'], discover: ['flows'], check: [], status: ['context'], @@ -823,6 +863,57 @@ export async function guideAssetPath(): Promise { return fileURLToPath(new URL('../assets/agent-guide.md', import.meta.url)); } +/** The skills the pack installs, in the order the guide lists them. */ +export const SKILL_NAMES = [ + 'miakapp-coordinator', + 'miakapp-interface', + 'miakapp-test-real', + 'miakapp-publish', + 'miakapp-members', + 'miakapp-update', +] as const; + +export async function skillAssetPath(name: string): Promise { + const { fileURLToPath } = await import('node:url'); + return fileURLToPath(new URL(`../assets/skills/${name}/SKILL.md`, import.meta.url)); +} + +export async function changelogAssetPath(): Promise { + const { fileURLToPath } = await import('node:url'); + return fileURLToPath(new URL('../assets/changelog.json', import.meta.url)); +} + +export async function bridgeAssetPath(): Promise { + const { fileURLToPath } = await import('node:url'); + return fileURLToPath(new URL('../assets/starter/app/app/miakapp.ts', import.meta.url)); +} + +/** Reads one packaged text asset; a missing one means a broken install. */ +async function packagedText(host: CliHost, path: string): Promise { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(await (await files(host)).read(path)); + } catch { + throw projectError( + `A packaged file is missing or unreadable at ${path}`, + 'Reinstall @miakapp/cli: its guides ship in the package and open no network connection.', + ); + } +} + +async function packagedSkills(host: CliHost): Promise { + const skills: PackSkill[] = []; + for (const name of SKILL_NAMES) { + skills.push({ name, content: await packagedText(host, await skillAssetPath(name)) }); + } + return skills; +} + +/** Strips the YAML front matter a skill carries for its client. */ +function skillBody(content: string): string { + const match = /^---\n[\s\S]*?\n---\n+/.exec(content); + return match === null ? content : content.slice(match[0].length); +} + /** Directory of the design files (`tokens.css`, `gallery.html`…), resolved like the guide. */ export async function designAssetDirectory(): Promise { const { fileURLToPath } = await import('node:url'); @@ -873,6 +964,12 @@ async function runDocs(host: CliHost, invocation: Invocation): Promise\n${skillBody(skill.content)}`; + if (!guide.endsWith('\n')) guide += '\n'; + } return { summary: 'Miakapp agent guide', fields: [], json: { topic, guide }, text: guide }; } return { @@ -897,18 +994,8 @@ async function runAgentPack(host: CliHost, invocation: Invocation): Promise entry.action !== 'unchanged').length; return { summary: changed === 0 @@ -923,6 +1010,224 @@ async function runAgentPack(host: CliHost, invocation: Invocation): Promise { + const filesystem = await files(host); + if (!await filesystem.exists(path)) return undefined; + try { + return new TextDecoder('utf-8', { fatal: true }).decode(await filesystem.read(path)); + } catch { + throw projectError(`${path} is not readable as UTF-8 text`); + } +} + +async function packagedChangelog(host: CliHost): Promise { + return parseChangelog(await packagedText(host, await changelogAssetPath()), 'the packaged changelog'); +} + +function fetcherOf(host: CliHost): FetchLike { + return host.fetch ?? ((input, init) => globalThis.fetch(input, init)); +} + +function releaseJson(entry: ChangelogEntry): Record { + return { version: entry.version, date: entry.date, home: entry.home, steps: entry.steps }; +} + +function releaseText(entry: ChangelogEntry): string { + const steps = entry.steps.map((step) => ` - ${step}`).join('\n'); + return `${entry.version} (${entry.date})\n For the home: ${entry.home}\n To do:\n${steps}\n`; +} + +/** + * Lists what each release after the repository's pin brings, newest first. + * + * The packaged changelog answers offline; when the registry knows a newer + * release, that release's own changelog is read from the CDN, because an old + * CLI cannot describe what was written after it shipped. + */ +async function runChanges(host: CliHost, invocation: Invocation): Promise { + const root = invocation.options.get('dir') ?? host.cwd(); + const sinceOption = invocation.options.get('since'); + if (sinceOption !== undefined && !isVersion(sinceOption)) { + throw usageError(`--since must be a version such as 4.7.1, received ${sinceOption}`); + } + const pinned = pinnedVersion(await readTextIfPresent(host, `${root}/${MCP_FILE}`)); + const since = sinceOption ?? pinned ?? CLI_VERSION; + + const fetcher = fetcherOf(host); + let entries = await packagedChangelog(host); + let latest: string | undefined; + try { + latest = await fetchLatestVersion(fetcher); + } catch { + latest = undefined; + } + let undescribed: string | undefined; + if (latest !== undefined && compareVersions(latest, CLI_VERSION) > 0) { + const remote = await fetchChangelog(fetcher, latest); + if (remote === undefined) undescribed = latest; + else entries = mergeChangelogs(remote, entries); + } + const until = latest !== undefined && compareVersions(latest, CLI_VERSION) > 0 ? latest : CLI_VERSION; + const releases = changesBetween(entries, since, until); + const upToDate = compareVersions(since, until) >= 0; + + const header = upToDate + ? `Up to date: ${since} is the newest release${latest === undefined ? ' this CLI knows (registry unreachable)' : ''}` + : `${releases.length} release${releases.length === 1 ? '' : 's'} after ${since}, up to ${until}`; + const lines = [header, '']; + for (const entry of releases) lines.push(releaseText(entry)); + if (undescribed !== undefined) { + lines.push(`${undescribed} exists, but its notes could not be fetched: run npx -y @miakapp/cli@${undescribed} changes.`, ''); + } + if (!upToDate) { + lines.push('Next: tell the owner what it brings, ask, then run npx -y @miakapp/cli@latest update.'); + } + return { + summary: header, + fields: [], + json: { + since, + pinned: pinned ?? null, + cli_version: CLI_VERSION, + latest: latest ?? null, + up_to_date: upToDate, + releases: releases.map(releaseJson), + ...(undescribed === undefined ? {} : { undescribed }), + }, + text: `${lines.join('\n').trimEnd()}\n`, + }; +} + +/** + * The bridge `init --starter app` copies is generated: the guide forbids + * editing it, and a newer CLI is how it changes. It is refreshed only when it + * still opens with the canonical header, so a file someone rewrote is left alone. + */ +function isGeneratedBridge(existing: string, canonical: string): boolean { + const header = canonical.split('\n').slice(0, 3).join('\n'); + return header.length > 0 && existing.startsWith(header); +} + +/** + * Moves a home repository to the running CLI release. + * + * Every write is one this CLI owns: the pack (guide, skills, marked blocks, + * the `.mcp.json` entry), the CLI's own entry in `package.json`, and the + * generated bridge. It installs no dependency and runs no shell: `bun install` + * and the migrations are the agent's, printed at the end. + */ +async function runUpdate(host: CliHost, invocation: Invocation): Promise { + const filesystem = await files(host); + const root = invocation.options.get('dir') ?? host.cwd(); + if (!await filesystem.exists(root)) { + throw projectError(`No directory at ${root}`, 'Point --dir at the home repository.'); + } + const previous = pinnedVersion(await readTextIfPresent(host, `${root}/${MCP_FILE}`)); + if (previous !== undefined && compareVersions(previous, CLI_VERSION) > 0) { + throw usageError( + `This repository pins ${previous}, newer than this CLI (${CLI_VERSION})`, + `Run npx -y @miakapp/cli@${previous} update, or @latest. Nothing was written.`, + ); + } + + const guide = await packagedText(host, await guideAssetPath()); + const pack = await installPack(filesystem, root, guide, await packagedSkills(host)); + const written: PackedFile[] = [...pack.files]; + + const manifestPath = `${root}/package.json`; + const manifest = await readTextIfPresent(host, manifestPath); + const merged = manifest === undefined ? undefined : mergePackageJson(manifest, manifestPath); + if (merged !== undefined) written.push(await put(filesystem, manifestPath, merged)); + + const bridgePath = `${root}/app/miakapp.ts`; + const bridge = await readTextIfPresent(host, bridgePath); + let bridgeKept = false; + if (bridge !== undefined) { + const canonical = await packagedText(host, await bridgeAssetPath()); + if (isGeneratedBridge(bridge, canonical)) written.push(await put(filesystem, bridgePath, canonical)); + else bridgeKept = true; + } + + let check: Record = { ran: false }; + if (await filesystem.exists(`${root}/${PROJECT_FILE}`)) { + try { + const options = new Map(invocation.options); + options.set('project', root); + const result = await runCheck(host, { ...invocation, command: 'check', options }); + check = { ran: true, ok: true, summary: result.summary }; + } catch (error) { + if (!(error instanceof CliError)) throw error; + check = { ran: true, ok: false, kind: error.kind, message: error.message }; + } + } + + const migrations = previous === undefined + ? [] + : changesBetween(await packagedChangelog(host), previous, CLI_VERSION).reverse(); + const changed = written.filter((entry) => entry.action !== 'unchanged'); + + const lines = [ + previous === undefined || previous === CLI_VERSION + ? `Pack at ${CLI_VERSION} in ${root}` + : `Updated ${root} from ${previous} to ${CLI_VERSION}`, + ]; + for (const entry of changed) lines.push(` ${entry.action}: ${entry.path}`); + if (bridgeKept) lines.push(` kept: ${bridgePath} (not the generated bridge; compare it with miakapp init --starter app in a scratch directory)`); + lines.push(check['ran'] === true + ? ` check: ${check['ok'] === true ? 'ok' : `${String(check['kind'])}: ${String(check['message'])}`}` + : ` check: no ${PROJECT_FILE} here, skipped`); + if (migrations.length > 0) { + lines.push('', 'Apply, oldest first:'); + for (const entry of migrations) { + for (const step of entry.steps) lines.push(` [${entry.version}] ${step}`); + } + } + lines.push('', 'Then: bun install, bun run check, check on the real home (miakapp taps), commit,' + + ' and restart the session so the miakapp MCP server runs the new pin.'); + + return { + summary: lines[0] as string, + fields: [], + json: { + root, + previous: previous ?? null, + version: CLI_VERSION, + changed: changed.length, + files: written.map((entry) => ({ path: entry.path, action: entry.action })), + ...(bridgeKept ? { bridge_kept: bridgePath } : {}), + check, + migrations: migrations.map(releaseJson), + guide: GUIDE_FILE, + }, + text: `${lines.join('\n')}\n`, + }; +} + +/** + * The daily "newer release" check every command runs after succeeding. + * Off under CI and with MIAKAPP_UPDATE_CHECK=0; never fails a command. + */ +export async function automaticUpdateCheck( + host: CliHost, + command: string, +): Promise { + if (command === 'changes' || command === 'update') return undefined; + if (host.env(UPDATE_CHECK_VARIABLE) === '0' || nonEmpty(host.env('CI')) !== undefined) return undefined; + let directory: string; + try { + directory = storeDirectory(host); + } catch { + return undefined; + } + return await checkForUpdate({ + directory, + files: await files(host), + fetch: fetcherOf(host), + now: host.now?.() ?? Date.now(), + current: CLI_VERSION, + }); +} + /** * Reads an existing installation. `discover` never loads the project file: an * agent runs it on a house that has no V4 project yet, which is the whole point @@ -1658,6 +1963,10 @@ export async function dispatch(host: CliHost, invocation: Invocation): Promise { + const entry = raw as Record; + const { version, date, home, steps } = entry; + if (typeof version !== 'string' || !isVersion(version) + || typeof date !== 'string' || typeof home !== 'string' + || !Array.isArray(steps) || !steps.every((step) => typeof step === 'string')) { + throw projectError(`${origin}: release #${index + 1} is malformed`); + } + return { version, date, home, steps: steps as string[] }; + }); +} + +/** Merges two changelogs by version; `preferred` wins a duplicate. Newest first. */ +export function mergeChangelogs( + preferred: readonly ChangelogEntry[], + other: readonly ChangelogEntry[], +): ChangelogEntry[] { + const byVersion = new Map(); + for (const entry of other) byVersion.set(entry.version, entry); + for (const entry of preferred) byVersion.set(entry.version, entry); + return [...byVersion.values()].sort((a, b) => compareVersions(b.version, a.version)); +} + +/** Entries strictly after `since`, up to and including `until`. Newest first. */ +export function changesBetween( + entries: readonly ChangelogEntry[], + since: string, + until: string, +): ChangelogEntry[] { + return entries + .filter((entry) => compareVersions(entry.version, since) > 0 + && compareVersions(entry.version, until) <= 0) + .sort((a, b) => compareVersions(b.version, a.version)); +} + +// --------------------------------------------------------------------------- +// Network + +async function getJson(fetcher: FetchLike, url: string): Promise { + const response = await fetcher(url, { + method: 'GET', + headers: { accept: 'application/json' }, + redirect: 'follow', + signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS), + }); + if (!response.ok) throw contractError(`${url} answered ${response.status}`); + const text = await response.text(); + if (text.length > 1_048_576) throw contractError(`${url} answered more than 1 MiB`); + return JSON.parse(text) as unknown; +} + +/** The registry's `latest` dist-tag. Throws on any failure; callers decide. */ +export async function fetchLatestVersion(fetcher: FetchLike): Promise { + const body = await getJson(fetcher, REGISTRY_LATEST_URL); + const version = (body as { version?: unknown } | null)?.version; + if (typeof version !== 'string' || !isVersion(version)) { + throw contractError('The npm registry answered without a version'); + } + return version; +} + +/** The changelog of a published release, or `undefined` when unreachable. */ +export async function fetchChangelog( + fetcher: FetchLike, + version: string, +): Promise { + try { + const body = await getJson(fetcher, changelogUrl(version)); + return parseChangelog(JSON.stringify(body), changelogUrl(version)); + } catch { + return undefined; + } +} + +// --------------------------------------------------------------------------- +// Daily check + +export interface UpdateCache { + readonly checkedAt: number; + readonly latest: string | undefined; + readonly notifiedAt: number | undefined; +} + +export interface CacheStore { + read(path: string): Promise; + replace(path: string, bytes: Uint8Array): Promise; + exists(path: string): Promise; +} + +export function decodeCache(bytes: Uint8Array): UpdateCache | undefined { + try { + const raw = JSON.parse(new TextDecoder().decode(bytes)) as Record; + const checkedAt = Date.parse(String(raw['checked_at'])); + if (Number.isNaN(checkedAt)) return undefined; + const latest = typeof raw['latest'] === 'string' && isVersion(raw['latest']) ? raw['latest'] : undefined; + const notified = typeof raw['notified_at'] === 'string' ? Date.parse(raw['notified_at']) : Number.NaN; + return { checkedAt, latest, notifiedAt: Number.isNaN(notified) ? undefined : notified }; + } catch { + return undefined; + } +} + +function encodeCache(cache: UpdateCache): Uint8Array { + return new TextEncoder().encode(`${JSON.stringify({ + checked_at: new Date(cache.checkedAt).toISOString(), + latest: cache.latest ?? null, + notified_at: cache.notifiedAt === undefined ? null : new Date(cache.notifiedAt).toISOString(), + }, null, 2)}\n`); +} + +export interface UpdateCheckOptions { + readonly directory: string; + readonly files: CacheStore; + readonly fetch: FetchLike; + readonly now: number; + readonly current: string; +} + +export interface UpdateInfo { + readonly current: string; + readonly latest: string; + /** True when this run is the first to report it in a day. */ + readonly fresh: boolean; +} + +/** + * Returns the newer version when one is known, refreshing the cache at most + * once a day. Never throws: an update notice is never worth a failed command. + * + * Runs only when the CLI's directory already exists (the machine was paired): + * the check creates nothing, so a test or a fresh CI runner stays untouched. + */ +export async function checkForUpdate(options: UpdateCheckOptions): Promise { + try { + if (!await options.files.exists(options.directory)) return undefined; + const path = `${options.directory}/${UPDATE_CACHE_FILE}`; + let cache = await options.files.exists(path) + ? decodeCache(await options.files.read(path)) + : undefined; + + if (cache === undefined || options.now - cache.checkedAt >= CHECK_INTERVAL_MS + || options.now < cache.checkedAt) { + let latest = cache?.latest; + try { + latest = await fetchLatestVersion(options.fetch); + } catch { + // Offline or the registry is down: keep what we knew, ask again tomorrow. + } + cache = { checkedAt: options.now, latest, notifiedAt: cache?.notifiedAt }; + await options.files.replace(path, encodeCache(cache)); + } + + const latest = cache.latest; + if (latest === undefined || compareVersions(latest, options.current) <= 0) return undefined; + const fresh = cache.notifiedAt === undefined || options.now - cache.notifiedAt >= CHECK_INTERVAL_MS; + if (fresh) await options.files.replace(path, encodeCache({ ...cache, notifiedAt: options.now })); + return { current: options.current, latest, fresh }; + } catch { + return undefined; + } +} + +export function updateNotice(info: { current: string; latest: string }): string { + return `Miakapp ${info.latest} is available (you have ${info.current}). ` + + 'Run `npx -y @miakapp/cli@latest changes` to see what it brings, ' + + 'then ask the owner before `npx -y @miakapp/cli@latest update`.'; +} + +export function updateJson(info: { current: string; latest: string }): Record { + return { + current: info.current, + latest: info.latest, + next_step: 'npx -y @miakapp/cli@latest changes', + }; +} diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts index 4c19d9d..726b54d 100644 --- a/packages/cli/src/version.ts +++ b/packages/cli/src/version.ts @@ -12,4 +12,4 @@ */ export const PACKAGE_NAME = '@miakapp/cli'; -export const CLI_VERSION = '4.7.2'; +export const CLI_VERSION = '4.8.0'; diff --git a/packages/cli/test/agent-pack.test.ts b/packages/cli/test/agent-pack.test.ts index dbd9b3a..1404ed9 100644 --- a/packages/cli/test/agent-pack.test.ts +++ b/packages/cli/test/agent-pack.test.ts @@ -7,6 +7,7 @@ import { GUIDE_FILE, INSTRUCTION_FILES, MCP_FILE, + SKILL_ROOTS, SERVER_NAME, instructionBlock, mergeInstructions, @@ -14,7 +15,7 @@ import { serverEntry, } from '../src/agent-pack.js'; import { EXIT_CODE } from '../src/errors.js'; -import { COMMAND_OPTIONS, guideAssetPath, run } from '../src/main.js'; +import { COMMAND_OPTIONS, SKILL_NAMES, guideAssetPath, run, skillAssetPath } from '../src/main.js'; import { TOOLS, buildArgv } from '../src/mcp.js'; import { CLI_VERSION, PACKAGE_NAME } from '../src/version.js'; import { MemoryFiles, PROJECT_ROOT, testHost } from './support/host.js'; @@ -26,9 +27,15 @@ async function repository(entries: Record = {}): Promise { return JSON.parse(files.text(`${PROJECT_ROOT}/${MCP_FILE}`)); } @@ -38,6 +45,13 @@ function failure(host: { stderr(): string }): Record { return JSON.parse(host.stderr()) as Record; } +/** The guide plus every skill, as `docs start` serves them. */ +async function packText(): Promise { + let text = await readFile(await guideAssetPath(), 'utf8'); + for (const name of SKILL_NAMES) text += await readFile(await skillAssetPath(name), 'utf8'); + return text; +} + describe('the pack installs into an empty repository', () => { test('it writes the guide, both instruction files and the server entry', async () => { const files = await repository(); @@ -47,9 +61,15 @@ describe('the pack installs into an empty repository', () => { const result = host.json(); expect(result['root']).toBe(PROJECT_ROOT); - expect(result['changed']).toBe(4); - expect((result['files'] as { path: string; action: string }[]).map((entry) => entry.action)) - .toEqual(['created', 'created', 'created', 'created']); + expect(result['changed']).toBe(PACK_FILES); + expect((result['files'] as { path: string; action: string }[]).every((entry) => entry.action === 'created')) + .toBe(true); + for (const { directory } of SKILL_ROOTS) { + for (const name of SKILL_NAMES) { + const skill = files.text(`${PROJECT_ROOT}/${directory}/${name}/SKILL.md`); + expect(skill).toBe(await readFile(await skillAssetPath(name), 'utf8')); + } + } expect(files.text(`${PROJECT_ROOT}/${GUIDE_FILE}`)).toBe(GUIDE_TEXT); for (const { path } of INSTRUCTION_FILES) { @@ -221,23 +241,20 @@ describe('running the pack twice is safe', () => { }); describe('the block tells an agent what it must not get wrong', () => { - test('it names the guide, the server and the confirmation rule', () => { - const block = instructionBlock('Codex'); + test('it names the guide, the skills, the server and the rules that cost most', () => { + const block = instructionBlock('Codex', [...SKILL_NAMES]); expect(block).toContain(GUIDE_FILE); expect(block).toContain(MCP_FILE); - expect(block).toContain('confirm: true'); - expect(block).toContain('MIAKAPP_HOME_KEY'); + for (const name of SKILL_NAMES) expect(block).toContain(`\`${name}\``); + for (const { directory } of SKILL_ROOTS) expect(block).toContain(directory); expect(block).toContain('unknown_outcome'); + expect(block).toContain('home_url'); + expect(block).toContain('miakapp taps'); + expect(block).toContain('miakapp-update'); }); - test('it sends the agent through pairing and to a verified publication', () => { - const block = instructionBlock('Codex'); - expect(block).toContain('miakapp pair'); - expect(block).toContain('https://miakapp.com/pair'); - expect(block).toContain('miakapp status'); - expect(block).toContain('home_url'); - expect(block).toContain('never the artifact URL'); - expect(block).toContain('screenshot'); + test('it stays short: the guide and the skills carry the rest', () => { + expect(instructionBlock('Codex', [...SKILL_NAMES]).split('\n').length).toBeLessThanOrEqual(25); }); test('each instruction file names the client that reads it', () => { @@ -259,23 +276,39 @@ describe('the packaged guide is the repository guide', () => { expect(shipped.equals(source)).toBe(true); }); - test('the guide teaches every command an agent can run', async () => { - const guide = (await readFile(await guideAssetPath())).toString('utf8'); + test('the guide and its skills teach every command an agent can run', async () => { + const guide = await packText(); const commands = Object.keys(COMMAND_OPTIONS).filter((name) => !['help', 'version'].includes(name)); for (const command of commands) { expect([command, guide.includes(`miakapp ${command}`)]).toEqual([command, true]); } - for (const action of ['list', 'show', 'use', 'remove']) { + for (const action of ['list']) { expect([action, guide.includes(`miakapp context ${action}`)]).toEqual([action, true]); } }); test('the guide makes a verified publication the deliverable', async () => { - const guide = (await readFile(await guideAssetPath())).toString('utf8'); + const guide = await packText(); expect(guide).toContain('docs/inventory.md'); expect(guide).toContain('https://miakapp.com/pair'); expect(guide).toMatch(/screenshot/); - expect(guide).toContain('You need nothing from the platform'); + expect(guide).toContain('Nothing from the platform'); + }); + + test('every skill has a name matching its folder and a description that says when to use it', async () => { + for (const name of SKILL_NAMES) { + const text = await readFile(await skillAssetPath(name), 'utf8'); + const front = /^---\nname: (.+)\ndescription: (.+)\n---\n/.exec(text); + expect([name, front?.[1]]).toEqual([name, name]); + expect([name, (front?.[2] ?? '').length > 80 && /\buse\b/i.test(front?.[2] ?? '')]).toEqual([name, true]); + expect([name, text.split('\n').length <= 80]).toEqual([name, true]); + } + }); + + test('every packaged skill folder is installed, and none is forgotten', async () => { + const { readdir } = await import('node:fs/promises'); + const folders = await readdir(fileURLToPath(new URL('../assets/skills/', import.meta.url))); + expect(folders.sort()).toEqual([...SKILL_NAMES].sort()); }); test('the guide is served as a tool and reaches the command as plain argv', () => { diff --git a/packages/cli/test/main.test.ts b/packages/cli/test/main.test.ts index d45672d..5a0cb40 100644 --- a/packages/cli/test/main.test.ts +++ b/packages/cli/test/main.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { readFile, stat } from 'node:fs/promises'; import { join } from 'node:path'; import { EXIT_CODE } from '../src/errors.js'; -import { COMMAND_OPTIONS, HOME_KEY_VARIABLE, designAssetDirectory, guideAssetPath, parseArguments, run } from '../src/main.js'; +import { COMMAND_OPTIONS, HOME_KEY_VARIABLE, SKILL_NAMES, designAssetDirectory, guideAssetPath, parseArguments, run, skillAssetPath } from '../src/main.js'; import { CLI_VERSION } from '../src/version.js'; import { digestOf, fakeControlPlane, homeKey } from './support/control-plane.js'; import { @@ -81,14 +81,25 @@ describe('offline commands', () => { expect(host.stdout().trim()).toBe(CLI_VERSION); }); - test('docs start prints the complete bundled guide without a project or network', async () => { + test('docs start prints the bundled guide and every skill without a project or network', async () => { const files = new MemoryFiles({ [await guideAssetPath()]: '# Miakapp agent guide\n\nStart here.\n', }); + for (const name of SKILL_NAMES) { + await files.write( + await skillAssetPath(name), + new TextEncoder().encode(`---\nname: ${name}\ndescription: d\n---\n\n# ${name}\n`), + ); + } const host = testHost({ files, fetch: async () => { throw new Error('network used'); } }); expect(await run(['docs', 'start'], host)).toBe(EXIT_CODE.success); - expect(host.stdout()).toBe('# Miakapp agent guide\n\nStart here.\n'); + const text = host.stdout(); + expect(text.startsWith('# Miakapp agent guide\n\nStart here.\n')).toBe(true); + for (const name of SKILL_NAMES) { + expect(text).toContain(`\n# ${name}\n`); + expect(text).not.toContain(`name: ${name}`); + } expect(host.stderr()).toBe(''); }); diff --git a/packages/cli/test/package.test.ts b/packages/cli/test/package.test.ts index c2fbe9f..1e0b547 100644 --- a/packages/cli/test/package.test.ts +++ b/packages/cli/test/package.test.ts @@ -34,6 +34,10 @@ describe('the published package', () => { const results = JSON.parse(packed.stdout.toString()) as PackResult[]; const files = results[0]?.files.map(({ path }) => path).sort() ?? []; expect(files).toContain('assets/agent-guide.md'); + expect(files).toContain('assets/changelog.json'); + for (const skill of ['coordinator', 'interface', 'test-real', 'publish', 'members', 'update']) { + expect(files).toContain(`assets/skills/miakapp-${skill}/SKILL.md`); + } for (const asset of ['guide.md', 'tokens.css', 'components.css', 'fonts.css', 'gallery.html', 'OFL-Manrope.txt']) { expect(files).toContain(`assets/design/${asset}`); } diff --git a/packages/cli/test/starter.test.ts b/packages/cli/test/starter.test.ts index 0098cc3..4424526 100644 --- a/packages/cli/test/starter.test.ts +++ b/packages/cli/test/starter.test.ts @@ -430,7 +430,8 @@ describe('the generated starter builds, typechecks, checks and runs', () => { describe('the docs send a new agent through the starter', () => { test('the bundled guide and the CLI README name the starter and never an unpublished import', async () => { - const guide = await readFile(join(import.meta.dir, '../assets/agent-guide.md'), 'utf8'); + const guide = await readFile(join(import.meta.dir, '../assets/agent-guide.md'), 'utf8') + + await readFile(join(import.meta.dir, '../assets/skills/miakapp-interface/SKILL.md'), 'utf8'); const readme = await readFile(join(import.meta.dir, '../README.md'), 'utf8'); for (const [name, text] of [['guide', guide], ['README', readme]] as const) { expect([name, text.includes('init --starter app')]).toEqual([name, true]); diff --git a/packages/cli/test/support/host.ts b/packages/cli/test/support/host.ts index 7e97a3c..94dc41c 100644 --- a/packages/cli/test/support/host.ts +++ b/packages/cli/test/support/host.ts @@ -86,7 +86,9 @@ export function testHost(options: { } = {}): TestHost { const out: string[] = []; const err: string[] = []; - const environment = options.env ?? {}; + // The daily update check is tested on its own; elsewhere it would add a + // registry request and a cache file to every test that uses a real store. + const environment: Record = { MIAKAPP_UPDATE_CHECK: '0', ...options.env }; return { out, err, diff --git a/packages/cli/test/updates.test.ts b/packages/cli/test/updates.test.ts new file mode 100644 index 0000000..f47efab --- /dev/null +++ b/packages/cli/test/updates.test.ts @@ -0,0 +1,341 @@ +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { MCP_FILE, SKILL_ROOTS, mergePackageJson, pinnedVersion } from '../src/agent-pack.js'; +import { EXIT_CODE } from '../src/errors.js'; +import { + SKILL_NAMES, + bridgeAssetPath, + changelogAssetPath, + guideAssetPath, + run, + skillAssetPath, +} from '../src/main.js'; +import { TOOLS, callTool } from '../src/mcp.js'; +import { + CHECK_INTERVAL_MS, + REGISTRY_LATEST_URL, + UPDATE_CACHE_FILE, + changelogUrl, + changesBetween, + checkForUpdate, + compareVersions, + parseChangelog, +} from '../src/updates.js'; +import { CLI_VERSION, PACKAGE_NAME } from '../src/version.js'; +import { MemoryFiles, PROJECT_ROOT, testHost } from './support/host.js'; + +const STORE = '/home/tester/.miakapp'; + +/** A repository that pins `pinned`, with the packaged assets in place. */ +async function repository(entries: Record = {}): Promise { + const files = new MemoryFiles(entries); + await files.makeDirectory(PROJECT_ROOT); + const assets = [ + await guideAssetPath(), + await changelogAssetPath(), + await bridgeAssetPath(), + fileURLToPath(new URL('../assets/members.md', import.meta.url)), + ...await Promise.all(SKILL_NAMES.map((name) => skillAssetPath(name))), + ]; + for (const path of assets) await files.write(path, await readFile(path)); + return files; +} + +function mcpPinning(version: string): string { + return `${JSON.stringify({ + mcpServers: { + other: { command: 'x' }, + miakapp: { type: 'stdio', command: 'npx', args: ['-y', `${PACKAGE_NAME}@${version}`, 'mcp'] }, + }, + }, null, 2)}\n`; +} + +/** A registry and CDN double: answers `latest`, and a changelog per version. */ +function network(latest: string | undefined, changelogs: Record = {}) { + const requests: string[] = []; + const fetch = async (url: string): Promise => { + requests.push(url); + if (url === REGISTRY_LATEST_URL) { + if (latest === undefined) throw new Error('offline'); + return Response.json({ name: PACKAGE_NAME, version: latest }); + } + for (const [version, body] of Object.entries(changelogs)) { + if (url === changelogUrl(version)) return Response.json(body); + } + return new Response('not found', { status: 404 }); + }; + return { fetch, requests }; +} + +function bump(version: string): string { + const [major, minor] = version.split('.').map(Number); + return `${major}.${(minor ?? 0) + 1}.0`; +} + +describe('versions', () => { + test('compare by semver precedence, prereleases first', () => { + expect(compareVersions('4.7.1', '4.8.0')).toBeLessThan(0); + expect(compareVersions('4.10.0', '4.9.9')).toBeGreaterThan(0); + expect(compareVersions('4.0.0-alpha.9', '4.0.0-alpha.10')).toBeLessThan(0); + expect(compareVersions('4.0.0-alpha.15', '4.0.0')).toBeLessThan(0); + expect(compareVersions('4.7.1', '4.7.1')).toBe(0); + }); + + test('the pin is read from .mcp.json, and only from the miakapp entry', () => { + expect(pinnedVersion(mcpPinning('4.7.1'))).toBe('4.7.1'); + expect(pinnedVersion('{"mcpServers":{"miakapp":{"args":["-y","@miakapp/cli@latest"]}}}')).toBeUndefined(); + expect(pinnedVersion('not json')).toBeUndefined(); + expect(pinnedVersion(undefined)).toBeUndefined(); + }); +}); + +describe('the packaged changelog', () => { + test('parses, is newest first, and describes this very release', async () => { + const entries = parseChangelog(await readFile(await changelogAssetPath(), 'utf8'), 'changelog'); + expect(entries[0]?.version).toBe(CLI_VERSION); + const versions = entries.map((entry) => entry.version); + expect([...versions].sort((a, b) => compareVersions(b, a))).toEqual(versions); + for (const entry of entries) { + expect([entry.version, entry.home.length > 0 && entry.steps.length > 0]).toEqual([entry.version, true]); + } + for (const version of ['4.4.0', '4.5.0', '4.6.0', '4.7.0']) { + expect(versions).toContain(version); + } + }); + + test('a malformed entry is refused rather than skipped', () => { + expect(() => parseChangelog('{"releases":[{"version":"4.8"}]}', 'x')).toThrow(/malformed/); + }); + + test('changesBetween excludes the start and includes the end', async () => { + const entries = parseChangelog(await readFile(await changelogAssetPath(), 'utf8'), 'changelog'); + expect(changesBetween(entries, '4.6.1', '4.7.1').map((entry) => entry.version)).toEqual(['4.7.1', '4.7.0']); + }); +}); + +describe('miakapp changes', () => { + test('lists what came after the pinned version, with steps for the agent', async () => { + const files = await repository({ [`${PROJECT_ROOT}/${MCP_FILE}`]: mcpPinning('4.6.1') }); + const host = testHost({ files, fetch: network(CLI_VERSION).fetch }); + + expect(await run(['changes', '--json'], host)).toBe(EXIT_CODE.success); + const result = host.json(); + expect(result['since']).toBe('4.6.1'); + expect(result['up_to_date']).toBe(false); + const versions = (result['releases'] as { version: string }[]).map((entry) => entry.version); + expect(versions[0]).toBe(CLI_VERSION); + expect(versions).toContain('4.7.0'); + expect(versions).not.toContain('4.6.1'); + }); + + test('reads the newer release\'s own changelog when the registry has one', async () => { + const newer = bump(CLI_VERSION); + const files = await repository({ [`${PROJECT_ROOT}/${MCP_FILE}`]: mcpPinning(CLI_VERSION) }); + const remote = { + releases: [{ version: newer, date: '2027-01-01', home: 'Something new for the home.', steps: ['Do the new thing.'] }], + }; + const host = testHost({ files, fetch: network(newer, { [newer]: remote }).fetch }); + + expect(await run(['changes'], host)).toBe(EXIT_CODE.success); + expect(host.stdout()).toContain(`${newer} (2027-01-01)`); + expect(host.stdout()).toContain('For the home: Something new for the home.'); + expect(host.stdout()).toContain('- Do the new thing.'); + expect(host.stdout()).toContain('npx -y @miakapp/cli@latest update'); + }); + + test('offline, it answers from the packaged changelog', async () => { + const files = await repository(); + const host = testHost({ files, fetch: network(undefined).fetch }); + expect(await run(['changes', '--since', '4.7.0', '--json'], host)).toBe(EXIT_CODE.success); + const result = host.json(); + expect(result['latest']).toBeNull(); + expect((result['releases'] as { version: string }[]).map((entry) => entry.version)).toContain('4.7.1'); + }); + + test('a newer release whose notes cannot be fetched is named, never invented', async () => { + const newer = bump(CLI_VERSION); + const files = await repository(); + const host = testHost({ files, fetch: network(newer).fetch }); + expect(await run(['changes', '--json'], host)).toBe(EXIT_CODE.success); + expect(host.json()['undescribed']).toBe(newer); + }); + + test('a --since that is not a version is a usage error', async () => { + const host = testHost({ files: await repository(), fetch: network(undefined).fetch }); + expect(await run(['changes', '--since', 'yesterday'], host)).toBe(EXIT_CODE.usage); + }); +}); + +describe('miakapp update', () => { + const OLD_BRIDGE_TAIL = '\n// an older bridge body\n'; + + async function oldRepository(extra: Record = {}): Promise { + const canonical = await readFile(await bridgeAssetPath(), 'utf8'); + const header = canonical.split('\n').slice(0, 3).join('\n'); + return await repository({ + [`${PROJECT_ROOT}/${MCP_FILE}`]: mcpPinning('4.6.1'), + [`${PROJECT_ROOT}/package.json`]: `${JSON.stringify({ + name: 'miakapp-home-test', + scripts: { check: 'x' }, + devDependencies: { [PACKAGE_NAME]: '4.6.1', typescript: '7.0.2' }, + dependencies: { miakapi: '4.6.0' }, + }, null, 2)}\n`, + [`${PROJECT_ROOT}/app/miakapp.ts`]: `${header}${OLD_BRIDGE_TAIL}`, + [`${PROJECT_ROOT}/AGENTS.md`]: '# Our house\n\nKeep the heating off in summer.\n', + ...extra, + }); + } + + test('pins, rewrites the pack, refreshes the bridge and prints the migrations', async () => { + const files = await oldRepository(); + const host = testHost({ files }); + + expect(await run(['update', '--json'], host)).toBe(EXIT_CODE.success); + const result = host.json(); + expect(result['previous']).toBe('4.6.1'); + expect(result['version']).toBe(CLI_VERSION); + + expect(pinnedVersion(files.text(`${PROJECT_ROOT}/${MCP_FILE}`))).toBe(CLI_VERSION); + expect(JSON.parse(files.text(`${PROJECT_ROOT}/${MCP_FILE}`))['mcpServers']['other']).toEqual({ command: 'x' }); + + const manifest = JSON.parse(files.text(`${PROJECT_ROOT}/package.json`)); + expect(manifest['devDependencies'][PACKAGE_NAME]).toBe(CLI_VERSION); + expect(manifest['dependencies']['miakapi']).toBe('4.6.0'); + expect(Object.keys(manifest)).toEqual(['name', 'scripts', 'devDependencies', 'dependencies']); + + expect(files.text(`${PROJECT_ROOT}/app/miakapp.ts`)).toBe(await readFile(await bridgeAssetPath(), 'utf8')); + expect(files.text(`${PROJECT_ROOT}/AGENTS.md`).startsWith('# Our house\n\nKeep the heating off in summer.\n')).toBe(true); + for (const { directory } of SKILL_ROOTS) { + expect(await files.exists(`${PROJECT_ROOT}/${directory}/miakapp-update/SKILL.md`)).toBe(true); + } + + const migrations = (result['migrations'] as { version: string }[]).map((entry) => entry.version); + expect(migrations[0]).toBe('4.7.0'); + expect(migrations.at(-1)).toBe(CLI_VERSION); + expect(result['check']).toEqual({ ran: false }); + }); + + test('a bridge someone rewrote is kept and reported', async () => { + const files = await oldRepository({ [`${PROJECT_ROOT}/app/miakapp.ts`]: '// my own bridge\n' }); + const host = testHost({ files }); + expect(await run(['update'], host)).toBe(EXIT_CODE.success); + expect(files.text(`${PROJECT_ROOT}/app/miakapp.ts`)).toBe('// my own bridge\n'); + expect(host.stdout()).toContain('kept:'); + }); + + test('a repository pinned to a newer release is refused, writing nothing', async () => { + const newer = bump(CLI_VERSION); + const files = await repository({ [`${PROJECT_ROOT}/${MCP_FILE}`]: mcpPinning(newer) }); + const host = testHost({ files }); + expect(await run(['update'], host)).toBe(EXIT_CODE.usage); + expect(pinnedVersion(files.text(`${PROJECT_ROOT}/${MCP_FILE}`))).toBe(newer); + expect(await files.exists(`${PROJECT_ROOT}/.claude/skills`)).toBe(false); + }); + + test('a project that no longer checks is reported, not fatal', async () => { + const files = await oldRepository({ [`${PROJECT_ROOT}/miakapp.yaml`]: 'schema: nope\n' }); + const host = testHost({ files }); + expect(await run(['update', '--json'], host)).toBe(EXIT_CODE.success); + const check = host.json()['check'] as Record; + expect(check['ran']).toBe(true); + expect(check['ok']).toBe(false); + }); + + test('running it twice changes nothing the second time', async () => { + const files = await oldRepository(); + expect(await run(['update'], testHost({ files }))).toBe(EXIT_CODE.success); + const second = testHost({ files }); + expect(await run(['update', '--json'], second)).toBe(EXIT_CODE.success); + expect(second.json()['changed']).toBe(0); + expect(second.json()['migrations']).toEqual([]); + }); + + test('package.json without the CLI is left alone', () => { + expect(mergePackageJson('{"dependencies":{"mqtt":"5"}}')).toBeUndefined(); + }); +}); + +describe('the daily update notice', () => { + const newer = bump(CLI_VERSION); + + async function store(): Promise { + const files = await repository(); + await files.makeDirectory(STORE); + return files; + } + + async function runAt(files: MemoryFiles, fetch: (url: string) => Promise, now: number, argv: string[]) { + const h = { ...testHost({ files, fetch, home: '/home/tester', env: { MIAKAPP_UPDATE_CHECK: '1' } }), now: () => now }; + const code = await run(argv, h); + return { code, h }; + } + + test('a command tells the agent once a day, on stderr, and asks the registry once a day', async () => { + const files = await store(); + const net = network(newer); + const start = Date.parse('2026-11-19T08:00:00Z'); + + const first = await runAt(files, net.fetch, start, ['version']); + expect(first.code).toBe(EXIT_CODE.success); + + const one = await runAt(files, net.fetch, start, ['docs', 'members']); + expect(one.h.stderr()).toContain(`Miakapp ${newer} is available (you have ${CLI_VERSION})`); + expect(one.h.stdout()).not.toContain('is available'); + + const two = await runAt(files, net.fetch, start + 60_000, ['docs', 'members']); + expect(two.h.stderr()).toBe(''); + expect(net.requests.filter((url) => url === REGISTRY_LATEST_URL).length).toBe(1); + + const tomorrow = await runAt(files, net.fetch, start + CHECK_INTERVAL_MS + 1, ['docs', 'members']); + expect(tomorrow.h.stderr()).toContain('is available'); + expect(net.requests.filter((url) => url === REGISTRY_LATEST_URL).length).toBe(2); + }); + + test('--json carries a field instead of a sentence', async () => { + const files = await store(); + const { code, h } = await runAt(files, network(newer).fetch, Date.now(), ['docs', 'members', '--json']); + expect(code).toBe(EXIT_CODE.success); + expect(h.stderr()).toBe(''); + expect(h.json()['update_available']).toEqual({ + current: CLI_VERSION, + latest: newer, + next_step: 'npx -y @miakapp/cli@latest changes', + }); + }); + + test('offline, nothing is printed and the command succeeds', async () => { + const files = await store(); + const { code, h } = await runAt(files, network(undefined).fetch, Date.now(), ['docs', 'members']); + expect(code).toBe(EXIT_CODE.success); + expect(h.stderr()).toBe(''); + expect(await files.exists(`${STORE}/${UPDATE_CACHE_FILE}`)).toBe(true); + }); + + test('no store directory, no check: nothing is created', async () => { + const files = await repository(); + const net = network(newer); + const result = await checkForUpdate({ directory: STORE, files, fetch: net.fetch, now: Date.now(), current: CLI_VERSION }); + expect(result).toBeUndefined(); + expect(net.requests).toEqual([]); + }); + + test('CI and MIAKAPP_UPDATE_CHECK=0 turn it off', async () => { + for (const env of [{ CI: 'true', MIAKAPP_UPDATE_CHECK: '1' }, { MIAKAPP_UPDATE_CHECK: '0' }]) { + const files = await store(); + const net = network(newer); + const h = testHost({ files, fetch: net.fetch, home: '/home/tester', env }); + expect(await run(['docs', 'members', '--json'], h)).toBe(EXIT_CODE.success); + expect(h.json()['update_available']).toBeUndefined(); + expect(net.requests).toEqual([]); + } + }); + + test('over MCP, a tool result carries update_available and changes/update are tools', async () => { + const files = await store(); + const h = testHost({ files, fetch: network(newer).fetch, home: '/home/tester', env: { MIAKAPP_UPDATE_CHECK: '1' } }); + const result = await callTool(h, 'miakapp_docs', { topic: 'members' }) as { structuredContent: Record }; + expect((result.structuredContent['update_available'] as Record)['latest']).toBe(newer); + expect(TOOLS.map((tool) => tool.name)).toEqual(expect.arrayContaining(['miakapp_changes', 'miakapp_update'])); + }); +});