# airing

**One button, many agents.** A press grammar, an intent router and a confirmation gate for single-input wearables — a ring, a pendant, a clip — plus the wellness maths such a device needs and a battery-budget model.

A ring has one input. You press it; agents do the work. Between those two things sit four decisions that are easy to get wrong:

1. **Which gesture was that?** Raw press edges become `tap`, `double`, `triple`, `long`, `hold` or `tap-hold`.
2. **What does it mean?** A binding table maps gestures to tasks; `hold` lets the wearer speak.
3. **Who should do it?** A few words are classified into an intent and routed to the agent with the best skill and trust.
4. **Should it happen now?** Anything that spends, sends, unlocks or cannot be undone waits for a deliberate confirmation. A ring gets pressed by accident — in a pocket, on a railing, in a handshake.

`airing` does all four, in one file, with no dependencies. It runs in Node 18+ and in the browser (`window.airing`).

> airing decides and records. It does not talk to hardware or to any agent service: you feed it edges and text, it hands you the task, the agent and the decision. It is not a medical device; the wellness functions compute standard measures from data you give them.

## Install

```
npm install ./airing        # or copy src/airing.js into your project
```

```js
const airing = require("airing");          // browser: <script src="airing.js"></script> -> window.airing
```

## Quick start

```js
const ring = airing.createRing();                           // default bindings, nine demo agents, default gate

ring.feed("0d 110u");  ring.tick(1000);                     // tap  -> "capture a note" -> Scribe, dispatched
ring.say("reorder my shampoo under $20");                   // what the wearer says while holding
ring.feed("5000d 6700u");                                   // hold -> Errand, awaiting: "confirm with a hold"
ring.feed("8000d 9600u");                                   // a deliberate second hold -> dispatched
ring.log();                                                 // every step, with the reason
```

`examples/press-to-agent.js` prints:

```
   430 ms  tap      dispatched "capture a note" -> Scribe  (reversible)
  2650 ms  double   dispatched "what's next on my calendar" -> Almanac  (read-only)
  6400 ms  hold     awaiting   "reorder my shampoo under $20" -> Errand  (spends up to $20 — confirm with a hold)
  9400 ms  hold     dispatched "reorder my shampoo under $20" -> Errand  (confirmed with a hold)
```

## 1. The press grammar

Edges are written `<ms>d` and `<ms>u` (or `<ms>:down`, or `[down, up]` pairs).

| Gesture | What the wearer does | Default threshold |
|---|---|---|
| tap | one short press | shorter than `longMin` 600 ms |
| double / triple | two / three short presses, each release followed by the next press within `gap` | `gap` 320 ms |
| long | one press held past `longMin`, released before `holdMin` | 600–1400 ms |
| hold | a press held past `holdMin` — fires while still held, so it can open the microphone | `holdMin` 1400 ms |
| tap-hold | a tap, then a press held past `holdMin` | — |

Presses shorter than `debounce` (25 ms) are contact noise; a release and re-press within `debounce` is chatter and counts as one press. Nothing is longer than a triple: a fourth quick press starts a new burst.

**Binding a longer gesture slows the shorter one.** If `double` is bound, a tap cannot fire on release — the decoder must wait `gap` ms to see whether a second press follows. If nothing longer is bound, a tap fires after the debounce. `latency(bound)` reports it:

```js
airing.latency(["tap", "hold"]).tap.waitMs            // 25
airing.latency(["tap", "double", "hold"]).tap.waitMs  // 320
```

`decode(edges, opts)` decodes a recording; `createDecoder(opts)` is the streaming form (`down(t)`, `up(t)`, `tick(t)`).

## 2. Bindings and the grammar check

```js
airing.DEFAULT_BINDINGS
// { tap: "capture a note", double: "what's next on my calendar", triple: "turn off the lights",
//   long: "@repeat", hold: "@voice", "tap-hold": "@cancel" }
```

A binding is either a task in plain words (it is classified and routed like speech) or a command: `@voice` (send what was said while held), `@repeat` (the last dispatched task, gated again), `@cancel` (drop the task waiting for confirmation).

`grammar(bindings)` returns `{ok, errors, warnings, latency, bound}`. Errors: an unknown gesture, an unknown command, `@voice` on a gesture that is not held. Warnings: a consequential task on `tap` or `double` (easy to trigger by accident), a tap made slow by a longer bound gesture, no `@cancel`, no `@voice`.

## 3. Intents and the router

`classify(text)` scores eleven intents by weighted words and phrases and returns `{intent, kind, confidence, scores, slots}`.

| Intent | Kind | Example |
|---|---|---|
| schedule | read | what's next on my calendar |
| reminder | reversible | remind me to stretch in 20 minutes |
| note | reversible | capture a note |
| device | reversible | turn off the lights |
| security | security | unlock the front door |
| purchase | spend | reorder my shampoo under $20 |
| booking | spend | book a table for two tomorrow at 7pm |
| message | send | send the notes to Sam |
| code | reversible | fix the failing test |
| workout | reversible | start tracking my run |
| question | read | tell me the weather? |

Risky words raise the kind: *delete, erase, deploy, merge, release* → irreversible; *pay, transfer, tip* → spend; *unlock, disarm* → security. Slots: `amount` or `limit` ("under $20" is a limit), `when`, `to`, `device`, `item`.

`createRouter(agents, {pins})` routes to the agent with the best `skill × (0.6 + 0.4 × trust)`; a pin (`{purchase: "concierge"}`) always wins. The nine demo agents — Scribe, Almanac, Hearth, Errand, Concierge, Courier, Forge, Stride, Sage — are placeholders for whatever agents you run.

```
$ node bin/airing.js route "reorder my shampoo under \$20"
intent   purchase (100%), kind spend
slots    {"limit":20,"item":"shampoo"}
agent    Errand   Errand has the best skill × trust for purchase
gate     confirm (hold)   spends up to $20 — confirm with a hold
```

## 4. The confirmation gate

| Kind | Decision | How to confirm |
|---|---|---|
| read, reversible | run | — |
| send | confirm | a double tap, after the draft is read back |
| spend | confirm | a hold; over `spendCap` ($150) it is refused |
| security, irreversible | confirm | a hold |

While a task waits, the confirming gesture means *confirm*; any other gesture cancels it (and `@cancel` only cancels). After `confirmWindow` (8 s) it expires.

## 5. Wellness

`hrv(rr)` cleans beat-to-beat intervals (drops beats outside 300–2000 ms and ectopic jumps over 20%) and returns mean RR and HR, **RMSSD**, **SDNN**, **pNN50**, and the Poincaré **SD1 / SD2**. `restingHR(series, {window})` is the lowest rolling mean of a per-minute heart rate. `synthRR` and `synthNight` make synthetic series for demos and tests — they are not measurements.

```
$ node bin/airing.js hrv --demo
beats 300, kept 297 (3 removed)
mean RR 970.8 ms, mean HR 61.8 bpm
RMSSD 40.3 ms, SDNN 45.8 ms, pNN50 25.3%, SD1 28.5 ms, SD2 58.2 ms
```

## 6. The battery budget

`battery(profile, spec)` adds up a day's charge per part. The default spec is **illustrative**, not any product's datasheet — replace it with your hardware's figures.

| Part | mAh / day (typical profile) |
|---|---|
| idle | 0.768 |
| heart sensor | 1.392 |
| skin temperature | 0.072 |
| motion | 0.216 |
| sync | 0.192 |
| presses | 0.060 |
| voice | 0.227 |
| haptics | 0.027 |
| **total** | **2.954 → about 7.4 days on 22 mAh** |

## 7. Simulations

`simulate()` has simulated wearers (each with their own tempo, some contact chatter) perform every gesture and counts what the decoder reads. At the default 320 ms gap, 4,320 trials:

| meant \ read | tap | double | triple | long | hold | tap-hold | other |
|---|---|---|---|---|---|---|---|
| tap | 717 | 0 | 0 | 1 | 0 | 0 | 2 |
| double | 0 | 670 | 0 | 0 | 0 | 0 | 50 |
| triple | 0 | 0 | 627 | 0 | 0 | 0 | 93 |
| long | 13 | 0 | 0 | 690 | 17 | 0 | 0 |
| hold | 0 | 0 | 0 | 37 | 673 | 0 | 10 |
| tap-hold | 0 | 0 | 0 | 0 | 1 | 623 | 96 |

Overall accuracy **92.6%**. `sweepGap()` shows the trade-off: a shorter gap answers a tap sooner but splits slow doubles into two taps.

| gap | accuracy | double | triple | a tap waits |
|---|---|---|---|---|
| 160 ms | 71.4% | 53.8% | 34.9% | 160 ms |
| 240 ms | 86.0% | 82.2% | 69.6% | 240 ms |
| 320 ms | 92.6% | 93.1% | 87.1% | 320 ms |
| 450 ms | 95.8% | 98.2% | 95.6% | 450 ms |
| 550 ms | 96.7% | 99.6% | 98.2% | 550 ms |

`accidental({hours, bindings, policy})` scatters random contact over a worn ring. With a hasty table (`tap` sends a location, `double` reorders), 2,000 hours give 1,653 contacts: **1,445 consequential tasks go out without the gate, none with it** (`examples/design-a-grammar.js`).

## Command line

```
node bin/airing.js decode "0d 110u 250d 360u"
node bin/airing.js route "book a table for two tomorrow at 7pm"
node bin/airing.js grammar bindings.json
node bin/airing.js ring "0d 1600u" --say "unlock the front door"
node bin/airing.js hrv rr.txt          (or --demo)
node bin/airing.js battery --voice 900
node bin/airing.js sim --gap 280
node bin/airing.js sweep
node bin/airing.js accidental --risky
```

## API

| Call | Returns |
|---|---|
| `decode(edges, opts)` | gestures `{gesture, presses, start, end, at, latency, durations}` |
| `createDecoder(opts)` | `{down(t), up(t), tick(t), flush()}` — each returns the gestures that became final |
| `latency(bound, opts)` | per gesture `{pressMs, waitMs}` |
| `grammar(bindings)` | `{ok, errors, warnings, latency, bound}` |
| `classify(text)` / `slots(text)` | intent, kind, confidence, scores, slots |
| `createRouter(agents, {pins})` | `{route(text), agents()}` |
| `gate(task, policy)` | `{decision: run / confirm / block, how, reason}` |
| `createRing({bindings, agents, pins, policy, thresholds})` | `{feed(edges), tick(t), say(text), pending(), log()}` |
| `hrv(rr)`, `cleanRR`, `rmssd`, `sdnn`, `pnn50`, `poincare`, `restingHR` | wellness measures |
| `battery(profile, spec)` | `{parts, perDay, days, capacity}` |
| `simulate(opts)`, `sweepGap(gaps)`, `accidental(opts)` | the experiments above |

## Tests

```
npm test        # 22 tests, about two seconds
```

## Licence

MIT. See `LICENSE`.
