Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
# `@suaveplan/api-router-hono` — Hono-backed Router adapter
**Package**: `@suaveplan/api-router-hono`
**Status**: PROPOSED
**Type**: new-package
**Stage**: 4 (Base adapters) — see umbrella `openspec/changes/api-plugin-foundation/`
## Why
The plugin host needs a production-grade HTTP router. Hono is fast, Bun-native, has a mature middleware ecosystem, and supports streaming. This package implements the abstract `Router` contract from `@suaveplan/api-router` against Hono, including blue-green slot management so a plugin's route table can be swapped atomically during hot reload (design doc §8.1).
Per design doc §15 Stage 4: every adapter ships both a direct callable surface and a `MessagePort`-marshalled worker-proxy surface so it can serve `trusted`-tier and `isolated`/`sandboxed`-tier plugins from one codebase (§5.2a). The same conformance suite (`runRouterConformance` from §13.4) MUST pass against both surfaces — anything less is not shippable.
## What changes
Net-new package depending on `@suaveplan/api-router` (contract), `@suaveplan/api-types`, `@suaveplan/api-worker-rpc`, `@suaveplan/error`, `@suaveplan/logger`, and `hono` as a peer dependency.
- ADDED: `createHonoRouter(opts)` — factory returning the direct in-process `Router` implementation backed by a Hono instance per blue-green slot.
- ADDED: `createHonoRouterWorkerProxy(port, opts)` — factory returning the proxy surface; calls marshall over a `MessagePort` to a host-side Hono instance via `api-worker-rpc`.
- ADDED: `HonoRouterOptions` — Zod-validated config (basePath, trustProxy, maxBodyBytes, streamingTimeoutMs, blue-green strategy: `"swap-on-health" | "swap-immediately"`).
- ADDED: `HonoBlueGreenSlot` — internal `BlueGreenSlot` impl managing two Hono instances (blue + green) and an atomic pointer. In-flight requests complete on the old slot; new requests route to the new slot once health passes.
- ADDED: `ROUTER_HONO_*` error codes (e.g. `ROUTER_HONO_BLUE_GREEN_SWAP_FAILED`, `ROUTER_HONO_SLOT_NOT_READY`, `ROUTER_HONO_DUPLICATE_ROUTE`, `ROUTER_HONO_INVALID_PATTERN`).
- ADDED: `./testing` subpath — re-exports `runRouterConformance` from `@suaveplan/api-router/testing` already bound to `createHonoRouter`; convenience for downstream tests.
## Out of scope
- The abstract `Router` interface, conformance suite, and `BlueGreenSlot` contract — those live in `api-router` (Stage 1).
- HTTP server lifecycle (Bun.serve, address binding) — `api-router-hono` is a router only; `api-host` owns the listening socket.
- WebSocket upgrade — `api-ws-bun` Stage 7.
- OpenAPI integration — `api-openapi` Stage 8 consumes route metadata from this adapter via the `Router` contract.
## Source mapping
Genesis-original. Source of design intent: `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md`.
| Requirement | Design doc section |
|---|---|
| `Router` contract implementation | §2.1, §6 (steps 1-2, 10) |
| Blue-green slot management | §8.1 |
| Worker-proxy variant required | §5.2a |
| Streaming bypasses buffering | §6 (streaming bullet) |
| Conformance suite passes both surfaces | §5.2a, §13.4 |
## Verification approach
- `src/factory/create-hono-router.test.ts` — direct-surface unit tests: route registration, dispatch, middleware ordering, streaming response.
- `src/factory/create-hono-router.spec-conformance.test.ts` — runs `runRouterConformance("hono-direct", createHonoRouter)` and asserts the full ~30 invariants pass.
- `src/proxy/create-hono-router-worker-proxy.test.ts` — proxy-surface unit tests over an in-process `MessageChannel`.
- `src/proxy/create-hono-router-worker-proxy.spec-conformance.test.ts` — runs `runRouterConformance("hono-worker-proxy", makeProxyFactory)` over a real `Worker` (or `MessageChannel` simulation) and asserts every invariant passes.
- `src/blue-green/hono-blue-green-slot.test.ts` — atomic swap, in-flight completion on old slot, health-gated cutover, swap rollback on health failure.
- `tests/integration/integration.test.ts` — booting `createHonoRouter` against a real `Bun.serve` listener and exercising the full request pipeline end-to-end.
## Migration impact
None — additive only. No package consumes `@suaveplan/api-router-hono` yet.

View File

@@ -0,0 +1,116 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: api-router-hono (api-router-hono)
**Package**: `@suaveplan/api-router-hono`
**Status**: PROPOSED
> Every requirement carries a `**Verified by:**` line at authoring time. (See `openspec/AGENTS.md` Section 13.)
## ADDED Requirements
### Requirement: Direct surface implements the Router contract
The package SHALL export `createHonoRouter(opts)` returning a `Router` (from `@suaveplan/api-router`) backed by a Hono instance. The returned router MUST pass `runRouterConformance` from `@suaveplan/api-router/testing`.
#### Scenario: factory returns a conformant Router
- **WHEN** `createHonoRouter({ basePath: "/" })` is called
- **THEN** the result satisfies the `Router` type AND `runRouterConformance("hono-direct", () => createHonoRouter(...))` reports zero failures
#### Scenario: route registration is order-independent for static paths
- **WHEN** `/a/b` is registered after `/a/:p`
- **THEN** a request to `/a/b` matches the static route AND a request to `/a/c` matches the param route
**Verified by:** `src/factory/create-hono-router.spec-conformance.test.ts::"hono-direct conforms to Router contract"` AND `src/factory/create-hono-router.test.ts::"static routes win over param routes when registered in either order"`
---
### Requirement: Worker-proxy surface implements the Router contract
The package SHALL export `createHonoRouterWorkerProxy(port, opts)` returning a `Router` whose calls are marshalled over a `MessagePort` via `@suaveplan/api-worker-rpc`. The proxy MUST pass the same `runRouterConformance` suite as the direct surface — no invariant may regress under marshalling.
#### Scenario: proxy passes every conformance invariant
- **WHEN** `runRouterConformance("hono-worker-proxy", () => createHonoRouterWorkerProxy(channel.port2, ...))` runs against a real `MessageChannel` bridged to a direct router on `channel.port1`
- **THEN** every invariant passes AND no invariant is skipped
#### Scenario: AbortSignal propagates across the proxy
- **WHEN** a route handler is invoked through the proxy AND the caller aborts via `AbortSignal`
- **THEN** the in-flight handler on the host side observes `signal.aborted === true` within one event-loop tick
**Verified by:** `src/proxy/create-hono-router-worker-proxy.spec-conformance.test.ts::"hono-worker-proxy conforms to Router contract"` AND `src/proxy/create-hono-router-worker-proxy.test.ts::"AbortSignal aborts the host-side handler"`
---
### Requirement: Dual-surface conformance gate
The adapter SHALL pass its capability's conformance suite under BOTH the direct surface AND the worker-proxy surface in the same test run. Failing either surface MUST fail the package's pre-publish gate.
#### Scenario: both surfaces run side by side
- **WHEN** the conformance suite executes
- **THEN** two `describe` blocks emit results — one labelled `hono-direct`, one labelled `hono-worker-proxy` — AND both report zero failures
**Verified by:** `src/factory/create-hono-router.spec-conformance.test.ts::"hono-direct conforms to Router contract"` AND `src/proxy/create-hono-router-worker-proxy.spec-conformance.test.ts::"hono-worker-proxy conforms to Router contract"`
---
### Requirement: Blue-green slot management
The package SHALL expose `HonoBlueGreenSlot` implementing the `BlueGreenSlot` contract from `api-router`. It maintains two Hono instances and an atomic active-slot pointer. New requests route to the active slot; in-flight requests on the inactive slot complete normally. A `swap()` call MUST be gated on a health-probe result when `strategy === "swap-on-health"`.
#### Scenario: in-flight requests complete on the old slot
- **WHEN** a request is in-flight on the blue slot AND `swap()` cuts over to green
- **THEN** the in-flight blue request completes its response AND any new request after `swap()` lands on green
#### Scenario: health-gated swap rolls back on failure
- **WHEN** the new slot's health probe throws OR returns false
- **THEN** the pointer remains on the old slot AND `ROUTER_HONO_BLUE_GREEN_SWAP_FAILED` is thrown to the caller
**Verified by:** `src/blue-green/hono-blue-green-slot.test.ts::"in-flight requests complete on the old slot after swap"` AND `src/blue-green/hono-blue-green-slot.test.ts::"swap rolls back when health probe fails"`
---
### Requirement: Streaming routes bypass buffering
Routes registered with `streaming: true` SHALL receive the raw `ReadableStream` body and SHALL write responses via a streaming bridge that emits chunks to the underlying socket without intermediate buffering.
#### Scenario: streaming handler writes chunks incrementally
- **WHEN** a streaming handler emits 3 chunks separated by event-loop ticks
- **THEN** the client observes 3 distinct read events AND no buffering across the whole response
**Verified by:** `src/streaming/streaming-bridge.test.ts::"streaming handler emits chunks incrementally without buffering"`
---
### Requirement: Options are Zod-validated
`HonoRouterOptions` SHALL be parsed through a Zod schema. Invalid options (negative `maxBodyBytes`, non-positive `streamingTimeoutMs`, unknown `strategy`) MUST throw at factory construction.
#### Scenario: invalid options throw at construction
- **WHEN** `createHonoRouter({ maxBodyBytes: -1 } as never)` is called
- **THEN** a `ZodError`-wrapped `SuaveplanError` with code `ROUTER_HONO_INVALID_OPTIONS` is thrown synchronously
**Verified by:** `src/options/hono-router-options.test.ts::"invalid options throw at factory construction"`
---
### Requirement: Telemetry instruments emitted
The adapter SHALL emit `api.router.match_duration_ms` (histogram, tagged with `route`, `method`, `outcome`) and `api.router.blue_green_swaps_total` (counter) on every match and every successful swap respectively.
#### Scenario: histogram records on every route match
- **WHEN** 5 requests are dispatched through `createHonoRouter`
- **THEN** the in-memory `MeterProvider` records exactly 5 observations on `api.router.match_duration_ms`
**Verified by:** `src/factory/create-hono-router.spec-conformance.test.ts::"emits api.router.match_duration_ms on every match"`
<!-- markdownlint-enable MD024 -->

View File

@@ -0,0 +1,72 @@
# Tasks — `@suaveplan/api-router-hono`
> Every checkbox MUST reflect work actually done in this change.
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Spec authoring
- [x] 1.1 Read design doc `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md` (§2.1, §5.2a, §6, §8.1, §13.4, §15 Stage 4)
- [x] 1.2 Read `openspec/changes/api-router/` and `openspec/changes/api-worker-rpc/` for upstream contracts
- [x] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
- [x] 1.4 Draft `proposal.md` from `openspec/templates/proposal.md`
- [x] 1.5 Draft `specs/api-router-hono/spec.md` from `openspec/templates/spec-delta.md`
- [x] 1.6 Every requirement carries a `**Verified by:**` line naming concrete `it(...)` titles
## 2. Implementation
- [ ] 2.1 Scaffold `packages/api/api-router-hono/` with `package.json` (`"version": "0.1.0"`, `"sideEffects": false`, hono as `peerDependencies`)
- [ ] 2.2 `src/options/hono-router-options.ts` — Zod schema for `HonoRouterOptions`
- [ ] 2.3 `src/factory/create-hono-router.ts` — direct-surface `Router` factory backed by Hono
- [ ] 2.4 `src/blue-green/hono-blue-green-slot.ts` — atomic two-instance pointer with health-gated swap
- [ ] 2.5 `src/proxy/create-hono-router-worker-proxy.ts` — `MessagePort`-marshalled proxy via `api-worker-rpc`
- [ ] 2.6 `src/streaming/streaming-bridge.ts` — Hono `ReadableStream` adapter for `streaming: true` routes
- [ ] 2.7 `src/error-codes.ts` — `ROUTER_HONO_*` codes via `defineCodes`
- [ ] 2.8 `src/testing/index.ts` — re-export `runRouterConformance` pre-bound to `createHonoRouter`
- [ ] 2.9 `src/index.ts` — explicit named re-exports (no `export *`)
## 3. Tests
- [ ] 3.1 `src/factory/create-hono-router.test.ts` — direct-surface unit tests
- [ ] 3.2 `src/factory/create-hono-router.spec-conformance.test.ts` — invokes `runRouterConformance` against the direct factory
- [ ] 3.3 `src/proxy/create-hono-router-worker-proxy.test.ts` — proxy-surface unit tests over `MessageChannel`
- [ ] 3.4 `src/proxy/create-hono-router-worker-proxy.spec-conformance.test.ts` — invokes `runRouterConformance` against the proxy factory
- [ ] 3.5 `src/blue-green/hono-blue-green-slot.test.ts` — swap semantics, in-flight completion, rollback on health failure
- [ ] 3.6 `src/streaming/streaming-bridge.test.ts` — stream chunk preservation, abort propagation
- [ ] 3.7 `tests/integration/integration.test.ts` — boot against real `Bun.serve`
- [ ] 3.8 Every `it(...)` carries `{ timeout: 5000 }` (30000 for genuinely async)
## 4. Documentation
- [ ] 4.1 Sibling `.md` for every implementation `.ts` (≥200 words, basic + advanced examples, full API reference)
- [ ] 4.2 README links every co-located `.md` under `## Modules`
- [ ] 4.3 Register `@suaveplan/api-router-hono` as the production router adapter in `@suaveplan/api-host`'s adapter table documentation
## 5. Pre-archive verification (the 5-gate triple)
- [ ] 5.1 `bun run check` — Biome 0 errors / 0 warnings / 0 info
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/api-router-hono` — green
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-router-hono` — 100/100/100/100
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/api-router-hono` — exit 0
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/api-router-hono` — green
## 6. Pre-archive 7-row checklist (AGENTS.md Section 13)
- [ ] 6.1 Generics threaded through every `Router` method signature; `expectTypeOf` assertions on route-handler typing
- [ ] 6.2 Zod schemas wired at the `HonoRouterOptions` boundary
- [ ] 6.3 Every `ROUTER_HONO_*` error code thrown by at least one production path
- [ ] 6.4 Strict-mode behaviors (trustProxy on/off, maxBodyBytes enforcement) tested both on and off
- [ ] 6.5 OTel instruments emitted from production paths (route-match histogram, swap counter) asserted with in-memory `MeterProvider`
- [ ] 6.6 Blue-green swap dedup tested (concurrent `swap()` calls collapse to one)
- [ ] 6.7 No retroactive tick — every box above reflects work done in this change
## 7. Archive
- [ ] 7.1 Fold spec delta into `openspec/specs/api-router-hono/spec.md`
- [ ] 7.2 Move `openspec/changes/api-router-hono/` → `openspec/archive/<yyyy-mm-dd>-api-router-hono/`
- [ ] 7.3 Tick the corresponding Stage 4 box in umbrella `openspec/changes/api-plugin-foundation/tasks.md`
- [ ] 7.4 Refresh `MANIFEST.md`