@emulates/aha 0.0.0-stage → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog — @emulates/aha
2
+
3
+ ## 2.3.1 (2026-10-06)
4
+
5
+ Initial release.
6
+
7
+ ### Dependencies
8
+
9
+ - `@emulates/sqlite`
package/DISCOVERY.md ADDED
@@ -0,0 +1,55 @@
1
+ # @emulates/aha discovery
2
+
3
+ This is the installed-package index for coding agents and tooling. All relative links resolve
4
+ inside `node_modules/@emulates/aha/`; no repository checkout is needed to discover the emulator's
5
+ supported surface or documented behavior.
6
+
7
+ ## Capability and behavior sources
8
+
9
+ | Question | Authoritative file | What it contains |
10
+ | --- | --- | --- |
11
+ | Behaviour and integration | [`README.md`](README.md) | Routes, state transitions, auth, webhooks, controls, presets and deliberate omissions. |
12
+ | Exact capabilities | [`SUPPORT.md`](SUPPORT.md) | Supported, unsupported and parity-covered operations or commands, including reasons for gaps. |
13
+ | Wire contract | [`openapi.yaml`](openapi.yaml) | Machine-readable paths, methods, schemas, responses and parity annotations. |
14
+ | Public API | [`dist/index.d.ts`](dist/index.d.ts) | The installed package's exact TypeScript exports and signatures. |
15
+ | Package metadata | [`package.json`](package.json) | Runtime/entry-point claims, vendor links, parity scope/tier and `emulates.discovery`. |
16
+
17
+ Read these together: the contract/capability matrix says *what* is available, while the README
18
+ defines stateful behavior, lifecycle rules, test controls, and intentional oracle differences.
19
+ If prose and an executable surface disagree, report a parity mismatch instead of adding a
20
+ consumer-side workaround.
21
+
22
+ ## Parity and oracle
23
+
24
+ - Declared parity surface: **Phlebotomy orders and result files**.
25
+ - Parity tier: **cold** (the repository controls when live checks run).
26
+ - Oracle: **Live vendor API or sandbox**.
27
+ - Repository command: `bun run parity:service -- aha`.
28
+ - Evidence model: Run from an Emulates checkout; credentials come only from .env.local or GitHub Actions secrets. Missing credentials exit 2.
29
+
30
+ The npm package contains evidence summaries and the exact contract, not credentials or the
31
+ repository-only parity harness. Self-parity/property and acceptance tests run in the Emulates
32
+ repository; live parity is an additional oracle check, not a substitute for the packaged matrix.
33
+
34
+ ## Runtime introspection
35
+
36
+ - `GET /__admin/health`
37
+ - `GET /__admin`
38
+ - `GET /__admin/state`
39
+ - `GET /__admin/requests`
40
+ - `GET /__admin/metrics`
41
+ - `GET /__admin/faults/presets`
42
+ - `GET /__admin/ui`
43
+
44
+ For HTTP services, use `x-emulates-namespace` (or the documented credential/path carrier) so
45
+ parallel tests do not share state. Admin state, journal, metrics and fault-preset endpoints are
46
+ designed for assertions and diagnosis by consuming test suites.
47
+
48
+ ## Report a mismatch or missing capability
49
+
50
+ Follow the [agent reporting contract](https://github.com/crvouga/emulators/blob/main/docs/REPORTING_ISSUES.md). Include package version,
51
+ operation/command, a minimal redacted request, actual emulator result, expected oracle result or vendor
52
+ documentation, and whether the mismatch appears in the matrix. Never include keys, tokens,
53
+ customer data, prompts, PHI, card data, or unredacted recordings.
54
+
55
+ Service key: `aha`.
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # @emulates/aha
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Part of [Emulates](https://github.com/crvouga/emulators): high-fidelity, in-process emulators for APIs and databases.
4
+
5
+ Stateful emulator of the **AHA (Advanced Health Academy) at-home phlebotomy** partner API for test
6
+ suites: HMAC-signed create-order and cancel, and — its main job — the order-status webhooks AHA
7
+ posts back. The vendor has no pull API, so every downstream effect (EMR appointment booking,
8
+ storefront status, "blood drawn") starts with a webhook; the emulator emits one on demand, with every
9
+ field our handler reads, so the ZIP-routed bloodwork path can finally be tested.
10
+
11
+ - Operation coverage: [SUPPORT.md](https://github.com/crvouga/emulators/blob/main/packages/service/aha/SUPPORT.md)
12
+ - The vendor publishes no spec: the contract (`openapi.yaml`) is hand-authored from our
13
+ consumers' zod schemas and wire shapes.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install -D @emulates/aha
19
+ ```
20
+
21
+ ESM only. Node >= 22 or Bun >= 1.2. No native dependencies. Serve it with
22
+ `npx emulates-aha serve`, `createServer` from `./server` (Node), or `createRuntime` with any
23
+ Fetch server.
24
+
25
+ ## Usage
26
+
27
+ Point the app at the emulator:
28
+
29
+ | Env | Value |
30
+ | --- | --- |
31
+ | `AHA_API_URL` | `http://127.0.0.1:8799` (the lab-provider path already allows loopback; `AhaService` needs an http exception, see G-A1 / S10.2) |
32
+ | `AHA_API_KEY` / `AHA_API_SECRET` | anything, or the pair passed as `--api-key` / `--api-secret` to verify signatures exactly |
33
+ | `AHA_USE_LEGACY_AUTH` | `true` switches to `X-<Partner>-Auth-Key` (e.g. `X-Acme-Auth-Key`); both modes are accepted |
34
+ | `AHA_WEBHOOK_SECRET` | the same value as `--webhook-secret` |
35
+
36
+ ```bash
37
+ npx emulates-aha serve --port 8799 \
38
+ --webhook-url http://127.0.0.1:3000/bloodwork/aha-webhook \
39
+ --webhook-secret "$AHA_WEBHOOK_SECRET" \
40
+ --api-key "$AHA_API_KEY" --api-secret "$AHA_API_SECRET" \
41
+ --envelope raw --auto-schedule 2000
42
+ ```
43
+
44
+ ```ts
45
+ import { createRuntime } from "@emulates/aha"
46
+
47
+ const aha = createRuntime({
48
+ webhooks: { url: "http://127.0.0.1:3000/bloodwork/aha-webhook", secret: "aha-webhook-secret" },
49
+ })
50
+ const admin = (path: string, body: unknown) =>
51
+ aha.fetch(
52
+ new Request(`http://aha.test/__admin${path}`, {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify(body),
56
+ }),
57
+ )
58
+
59
+ // …the app's checkout calls POST /v1/acme/create-order for AC-101…
60
+
61
+ // AHA books the draw: our handler books the EMR appointment for 10:30 Denver time.
62
+ await admin("/orders/AC-101/transition", {
63
+ status: "Scheduled",
64
+ scheduledAt: "2026-10-01T16:30:00Z",
65
+ timeZone: "America/Denver",
66
+ })
67
+ // The phlebotomist checks out with a sample: our handler sets vitalBloodDrawn.
68
+ await admin("/orders/AC-101/transition", { status: "Check Out", drawStatus: "Sample Collected" })
69
+ ```
70
+
71
+ ### Routes
72
+
73
+ The `{partner}` path segment is your account's slug (e.g. `acme`); the emulator accepts any.
74
+
75
+ | Route | Behaviour |
76
+ | --- | --- |
77
+ | `POST /v1/{partner}/create-order` | Validates the body (`partner_order_id`, patient fields, `biological_sex`, `service_type`, `npi`, `ordering_physician`, `test_codes`, optional `preferred_schedule_date/time`, `patient_timezone`). Create **or update**: a repeated `partner_order_id` keeps its `order_number`. Answers `{content: {partner_order_id, order_number}, message, status: "SUCCESS"}`. |
78
+ | `POST /v1/{partner}/cancel` | `{partner_order_id, notes: [{note_type: "CANCELLATION", notes}]}` → `{message, status}`. Emits a `Cancelled` webhook (turn off with `cancelWebhook: false`). Unknown id → 404; an order whose sample was collected → 200 with `status: "ERROR"`. The AHA `order_number` is accepted in `partner_order_id` too, because our lab-provider client sends it there (G-A1). |
79
+
80
+ **Auth.** HMAC mode: `X-API-KEY`, `X-TIMESTAMP` (epoch ms, within ±5 min of wall-clock time),
81
+ `X-SIGNATURE` = base64 HMAC-SHA256(secret, `"<apiKey>:<path>:<timestamp>"`), where `path` is the
82
+ request path without host, body or `/__admin/ns/<name>` prefix. With a known key + secret
83
+ (`--api-key/--api-secret` or `credentials` in settings) the signature is verified exactly;
84
+ with none configured any key is accepted and the signature is checked for shape only. Legacy
85
+ mode: `X-<Partner>-Auth-Key` (+ `X-API-Version: 1.0`), e.g. `X-Acme-Auth-Key`; any partner name is
86
+ accepted. Failures are 401 `{status: "ERROR", message}`.
87
+
88
+ **Envelope (G-A1).** `AhaService` expects the raw `{content, message, status}`;
89
+ `AhaLabProvider` expects `{success: true, data: {…}}`. Raw is the default; choose with
90
+ `--envelope raw|wrapped` or per namespace with `PUT /__admin/settings {"envelope": "wrapped"}`.
91
+
92
+ **Idempotency.** `X-Idempotency-Key` (the lab-provider path): the same key and body replays the
93
+ stored response (`idempotent-replayed: true`); the same key with a different body is 409.
94
+
95
+ ### Webhooks
96
+
97
+ `POST <webhook-url>` (our route: `POST /bloodwork/aha-webhook`) with
98
+ `Authorization: Token <AHA_WEBHOOK_SECRET>`. Every body has `status`, `partnerOrderId`, `ahaOrderId`,
99
+ plus, by status (all local times in the order's IANA zone):
100
+
101
+ | `status` | Extra fields |
102
+ | --- | --- |
103
+ | `Scheduled`, `Rescheduled` | **`scheduleServiceTime`** (`YYYY-MM-DDTHH:mm:ss`, moment-parsable) and **`scheduleServiceTimeZone`** (IANA) — required by our handler though absent from the DTO — plus `scheduledServiceDate/Time/TimeZone` and `scheduleConfirmationDate/Time/TimeZone` |
104
+ | `Check In` | `checkInDate`, `checkInTime`, `checkInTimeZone` |
105
+ | `Check Out` | `drawStatus` (default `Sample Collected`), `drawStatusDate/Time/TimeZone` |
106
+ | `Lab Testing In Progress` | `dropOffDate`, `dropOffTime`, `dropOffTimeZone` |
107
+ | `Cancelled`, `Non Scheduled Update` | — |
108
+
109
+ `drawStatus` values: `Sample Collected`, `Completed` (drawn), `Patient Refused`, `UTO`,
110
+ `Patient Not Home`, `Patient Rescheduled`, `Order Cancelled`, `Others`,
111
+ `Patient Asked to Reschedule` (draw failed). Non-2xx answers are retried (immediately, 5 s,
112
+ 5 min, 30 min, 2 h); `GET /__admin/webhooks`, `…/events`, `…/replay`, `…/flush` as usual.
113
+
114
+ ### Admin (beyond the standard contract)
115
+
116
+ | Route | Effect |
117
+ | --- | --- |
118
+ | `POST /__admin/orders/:partnerOrderId/transition` | `{status, drawStatus?, scheduledAt?, timeZone?}` emits the webhook. `status` is any value above (case and `_` forgiven; unknown values are sent verbatim). `scheduledAt` (ISO or epoch ms) defaults to the order's preferred slot, else the next hour 24 h out; `Rescheduled` defaults to one day later. `timeZone` defaults to the order's `patient_timezone`, else `America/New_York`. `:partnerOrderId` may also be the `order_number`. |
119
+ | `PUT /__admin/settings` | `{envelope?, credentials?: [{apiKey, apiSecret?}], allowLegacy?, timestampToleranceMs?, defaultTimeZone?, cancelWebhook?, autoSchedule?: {afterMs, leadMs?} \| ms \| null}` for the calling namespace. `GET` shows them with secrets masked. |
120
+ | `POST /__admin/tick` | Emit every `autoSchedule` webhook that is due on the emulator clock (the served emulator ticks every 100 ms). |
121
+ | `GET /__admin/orders` | The namespace's orders (ids, status, appointment, zone — no patient data). |
122
+
123
+ Fault presets (`POST /__admin/faults {"preset": "<name>", "count"?: n}`): `bad_signature` (401),
124
+ `rate_limited` (429 → `rate_limit`), `server_error` (500), `order_error` (200 with inner
125
+ `status: "ERROR"`), `invalid_response` (200 with a body neither zod schema accepts),
126
+ `webhook_duplicate`, `webhook_reorder`, `webhook_drop`.
127
+
128
+ ### Namespaces
129
+
130
+ `x-emulates-namespace`, a `/__admin/ns/<name>` prefix on `AHA_API_URL` (the signature still covers
131
+ only the path after it), or by API key:
132
+ `PUT /__admin/credentials {"credentials": {"<AHA_API_KEY>": "<namespace>"}}`.
133
+
134
+ ### SFTP result delivery
135
+
136
+ `createAhaSftpServer` from `./sftp` starts a real SSH/SFTP server on an ephemeral port and shares order state with `createRuntime`. It supports password or public-key authentication, host-key verification, `list`/`stat`, binary upload/download, atomic temp-file rename, delete, nested directories, stable POSIX permissions and emulator-clock timestamps. The deterministic Ed25519 host key is stable between runs.
137
+
138
+ ```ts
139
+ import { createRuntime } from "@emulates/aha"
140
+ import { createAhaSftpServer } from "@emulates/aha/sftp"
141
+
142
+ const runtime = createRuntime()
143
+ const sftp = await createAhaSftpServer({
144
+ runtime,
145
+ accounts: [{ username: "aha", password: "local-test-password" }],
146
+ })
147
+ console.log(sftp.host, sftp.port, sftp.hostPublicKey)
148
+ ```
149
+
150
+ Use `seed()` to install arbitrary binary fixtures or `publishResult(orderId, bytes)` to place a stable `AHA-…_result.pdf` in `/outbox`. The first complete download moves the linked HTTP order to `Lab Testing In Progress` and emits its webhook; repeat polling/download does not repeat that transition. `fault()` forces the next operation to disconnect, deny permission, report disk-full, or accept only part of a write. `journal()` exposes paths, operation names, byte counts, and outcomes—never credentials or file contents. `reset(namespace?)` clears deterministic filesystem state. Duplicate destination names fail, so `.tmp` → final rename is atomic.
151
+
152
+ ### Deliberately not modelled
153
+
154
+ - Downstream S3 ingestion and `aha_results_queue` processing after the SFTP handoff.
155
+ - Real scheduling: AHA contacts the patient; nothing moves unless a test transitions the order
156
+ or sets `autoSchedule`.
157
+ - The serviceable-ZIP list (our app's own fixture decides eligibility before calling AHA).
158
+ - Patient details are validated, never stored or echoed.
159
+ - Which envelope the real vendor uses (G-A1): both are served, one per namespace.
160
+
161
+ ## API
162
+
163
+ | Export | Kind | Description |
164
+ | --- | --- | --- |
165
+ | `AhaAPI` | class | The in-process emulator: `fetch(request)`, `reset()`, `transition(id, {status, drawStatus?, scheduledAt?, timeZone?})`, `tick()`, `orders()`. Options: `sqlite`, `now`, `namespace`, `settings`, `onWebhook`, `wallClock`. |
166
+ | `createRuntime` | function | The emulator with the full service contract. Options: `webhooks: {url, secret, retryDelaysMs?, fetch?}`, `settings`, `tickMs`, `wallClock`, `clock`, `seed`, `adminKey`, `onLog`. |
167
+ | `AHA_PRESETS` | object | Every named fault preset. |
168
+ | `AHA_NAMESPACE` | string | The service name, `"aha"`. |
169
+ | `WEBHOOK_PATH` | string | `"/bloodwork/aha-webhook"`, our receiver's route. |
170
+ | `ORDER_STATUSES`, `DRAW_STATUSES` | arrays | The vendor status spellings the webhooks use. |
171
+ | `verifyAuth` | function | The HMAC / legacy verification the emulator applies (an error message, or `undefined`). |
172
+ | `apiKeyCredential` | function | The API key a request carries (how credentials map to namespaces). |
173
+ | `isTimeZone`, `zonedParts`, `zonedToEpoch` | functions | IANA-zone helpers used to fill the local date/time fields. |
174
+ | `document`, `operationIds`, `supportedOperationIds` | values | The vendored OpenAPI contract and its operation ids. |
175
+ | `createServer`, `serveTarget`, `DEFAULT_PORT` (`./server`) | Node | Serve over `node:http` (autoSchedule ticks every 100 ms); the `serve` CLI target; port 8799. |
176
+ | `createAhaSftpServer` (`./sftp`) | Node | Real SSH/SFTP endpoint with deterministic host key/filesystem, shared order state, transfer controls, and an ephemeral port. |
177
+
178
+ Part of [emulators](https://github.com/crvouga/emulators).
package/SUPPORT.md ADDED
@@ -0,0 +1,12 @@
1
+ # AHA (Advanced Health Academy) partner API (Emulates subset) — operation support
2
+
3
+ Generated from `openapi.yaml`; do not edit by hand.
4
+
5
+ - operations in spec: **2**
6
+ - supported by the emulator: **2**
7
+ - parity enabled: **2**
8
+
9
+ | operationId | route | emulator | parity | notes |
10
+ | --- | --- | --- | --- | --- |
11
+ | `CreateOrder` | `POST /v1/{partner}/create-order` | ✅ supported | ⚠️ unsafe (opt-in) | |
12
+ | `CancelOrder` | `POST /v1/{partner}/cancel` | ✅ supported | ⚠️ unsafe (opt-in) | |