Merge pull request 'docs: bring the contributor docs and examples in line with the repository' (#177) from docs/repo-docs-refresh into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 21s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 23s
CI / runtimes (deno) (push) Successful in 34s
Promote → GitHub / push-github (push) Successful in 7s

This commit was merged in pull request #177.
This commit is contained in:
chrnx committed 2026-10-28 19:37:16 +00:00
commit 068614ef11
18 files changed
+49 -2812

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
## Environment
- green-tea version:
- Runtime and version: <!-- Node 22.12 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- Runtime and version: <!-- e.g. Node 22.20 / Deno 2.5 / Bun 1.3 / Cloudflare Workers -->
- OS:
<!--
+1
View File
@@ -11,6 +11,7 @@ Closes #
- [ ] The base branch above is `contrib`
- [ ] Commits are signed off (`git commit -s`)
- [ ] `npm run lint`, `npm run format:check`, `npm run typecheck`, `npm test`, `npm run complexity:check` and `npm run build` pass locally
- [ ] The runtime suites this change touches pass locally (`npm run test:deno`, `test:bun`, `test:edge`, or `test:all`), and they are named here
- [ ] New behavior has a test
- [ ] A new public option or method is also declared in `src/app/types.ts`, and noted in `README.md`
- [ ] Behavior is the same on Node, Deno and Bun — or the difference is deliberate, and said out loud here
+2 -2
View File
@@ -646,8 +646,8 @@ npm treats versions as semver and semver forbids leading zeros.
So the change is for the teacup that does *not* depend on that teapot: it starts, rather than
refusing over a dependency it never had. It is not graceful degradation of the dependency, and
cannot be — answering `503` for an absent teapot's tokens means knowing what it *would* have
exported, and only a declaration can say. That declaration is the `expects` list in
`docs/plans/2026-08-18-mesh-degrade-plan.md`, which is planned and not built. Two things are
exported, and only a declaration can say. That declaration is a per-teapot `expects` list,
which is planned and not built. Two things are
unchanged: a **permanent refusal** — a wrong secret, a protocol mismatch — still fails the boot
without spending the grace, because it is the teapot's decision rather than the network's and will
be the same decision in thirty seconds; and the missing-token error, which now says "local or
+11 -4
View File
@@ -74,7 +74,7 @@ So go through the diff the way you would go through a stranger's, because that i
**What assistants tend to get wrong here in particular** — worth checking before you push:
- They add dependencies. Core has one runtime dependency, and that is a design constraint rather than an oversight.
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` does not cover them.
- They write for Node and assume the rest follows. It doesn't — green-tea also runs on Deno, Bun and the edge, and `npm test` is the Node suite only. CI runs the other three, and `npm run test:all` runs them locally.
- They delete comments they read as redundant. In this codebase a comment usually carries reasoning the code can't show on its own.
- They skip the test.
@@ -120,16 +120,19 @@ If it prints nothing, run `git config core.hooksPath .githooks` yourself. If you
something other than npm, check this before your first commit rather than after.
`npm test` runs the Node suite under Vitest. The other three runtimes have their own commands
and their own toolchains, and none of them run in CI:
and their own toolchains:
```bash
npm run test:deno # needs deno
npm run test:bun # needs bun
npm run test:edge # Miniflare
npm run test:all # all four, plus the JSR gate (deno publish --dry-run)
```
You are not expected to install all three to fix a typo. You are expected to run the one your
change touches, and to say in the pull request which ones you ran.
CI runs all three on every push and pull request, in the `runtimes` job, and each one gates a
merge just as the Node suite does. You are not expected to install all three to fix a typo. You
are expected to run the one your change touches, and to say in the pull request which ones you ran,
so a red Bun job is not the first time anyone hears about it.
## Before you open a pull request
@@ -142,8 +145,12 @@ npm run typecheck # must be clean — this includes the compile-time-guarantee t
npm test # all tests must pass
npm run complexity:check
npm run build
npm audit --omit=dev # only what ships blocks; CI reports the rest
```
plus the runtime suite for whatever your change touches (see *Local setup* above). CI runs Deno,
Bun and the edge in its `runtimes` job.
- Write tests for new behavior (TDD welcome). We use Vitest.
- `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it.
- Keep runtime dependencies at zero beyond `reflect-metadata`.
+18 -7
View File
@@ -43,6 +43,8 @@ Less to hold in your head. That's the tea.
npm install @green-tea/core@beta reflect-metadata
```
Requires Node 22 or newer. Node 18 and 20 are end-of-life and are not supported. Deno, Bun and Cloudflare Workers run the same code.
`@green-tea/core` — **beta**, RC-track. One runtime dependency: `reflect-metadata`. Two optional peers you install only if you use them:
```bash
@@ -152,13 +154,22 @@ without growing the runtime dependency tree past `reflect-metadata`:
## Benchmarks
We built a reproducible [autocannon harness](./BENCHMARKS.md) comparing green-tea to Express 5, Fastify 5, NestJS (on both Express and Fastify), and raw Node `http` — and we wrote it to be **hard on ourselves**, not flattering.
green-tea keeps a reproducible [autocannon](https://github.com/mcollina/autocannon) harness in
`bench/`, and it is written to be hard on green-tea rather than flattering. It answers two
different questions, and they need different setups:
On that harness green-tea is in the same class as Fastify and NestJS-on-Fastify, roughly 2.8× ahead of Express, and behind raw `http` with no framework at all. Within that class the shape reproduces on two very different machines: green-tea is **behind** Fastify on the JSON, routing and pipeline scenarios, and **ahead** of it on POST-plus-validation. How far behind is a property of the box rather than a constant — 2-8% on a laptop M4 Max, 7-15% on an idle desktop Ryzen — which is why the table carries its hardware and its date, and why a percentage quoted without them says little. Read [BENCHMARKS.md](./BENCHMARKS.md) rather than a sentence here: a ranking written into prose once is a claim nobody re-measures.
- **How does green-tea compare to other frameworks?** `npm run bench` runs green-tea, Express 5,
Fastify 5, NestJS on Express and on Fastify, and raw Node `http` through the same scenarios on
one box, then writes [BENCHMARKS.md](./BENCHMARKS.md).
- **Did the last N commits cost anything?** `npm run bench:compare` runs two versions of green-tea
on one box in one sitting, alternating sides, so the difference is the code rather than the
machine's mood that day.
The question a release actually has to pass is the other one — *did the last N commits cost anything* — and comparing today's numbers against a table generated weeks ago answers it with two machines in a mood rather than two versions. `npm run bench:compare` runs both trees on one box in one sitting, alternating sides; `26.9.0-beta.1 → 26.9.0-beta.2` came out flat on every case.
Read the honest caveats in [BENCHMARKS.md](./BENCHMARKS.md): the numbers are single-box + loopback (absolute throughput is overstated and differences compressed — trust the *ratios*), the cross-framework table runs green-tea with `security:false` for header parity, and the real cost of secure-by-default is measured separately. Regenerate any time with `npm run bench`.
This section carries no numbers on purpose. A ranking written into prose is a claim nobody
re-measures, and it goes stale with the next release. The figures, the hardware and date they
were taken on, and the caveats live in [BENCHMARKS.md](./BENCHMARKS.md). The caveats include
single-box loopback, trusting the ratios over the absolute numbers, and green-tea running with
`security: false` for header parity, with the cost of secure-by-default measured separately.
## How it compares
@@ -300,7 +311,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is the `expects` list in [the mesh degrade plan](./docs/plans/2026-08-18-mesh-degrade-plan.md), which is planned and not built.
**What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built.
**What is settled, and what is still moving.** Present state, not a roadmap and not the API freeze — this is spare-time work by one person, and a schedule it cannot keep would cost more than it earns. The **graph is the settled part**: `needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key have not changed since the beta hardening on 7 July, and `@Provider`, `@Step`, `@Route` and handler shapes still mean what they meant then — the decorator *set* has grown (`@Head`, `@Options`, `@Html`), which only ever adds. **Still moving:** the plugin API, which became `{ name, mount }` and gained `onShutdown`; the runtime entry points, where `serveDeno()` and `serveBun()` became async so they boot before they bind; `createApp`'s options, which gain fields most months; and the pipeline context, which in July became one object mutated in place rather than copied per step — so a step that captured it now sees later steps' writes. **Alpha:** mesh, above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it.
@@ -345,7 +356,7 @@ consumer would have received.
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
- ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
- **next** — API freeze + first stable release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
## Versioning
@@ -1,170 +0,0 @@
# Router correctness and security beta design
**Date:** 2026-08-02
**Target:** `26.8.0-beta.0`
**Status:** Approved
## Goal
Prepare the August beta by completing the router's missing HTTP behavior, adding safe segment constraints, aligning the public documentation with the code, and removing known dependency vulnerabilities from the core repository and documentation site.
The release keeps the current linear matcher. A radix tree remains a separate performance project that must earn its complexity through benchmarks.
## Scope
This change includes:
- first-class `HEAD` and `OPTIONS` routes;
- automatic `HEAD` fallback to `GET`;
- automatic bare `OPTIONS` responses;
- correct and deterministic `Allow` headers;
- a tolerant trailing-slash policy with rejection of repeated internal slashes;
- route-pattern validation at boot;
- safe parameter constraints such as `:id(\d+)`;
- malformed URI handling as a client error;
- duplicate and ambiguous route detection;
- OpenAPI projection of constrained parameters;
- dependency remediation for the root package and `website/`;
- public documentation and changelog updates;
- the `26.8.0-beta.0` package-version bump.
This change excludes:
- a radix-tree matcher;
- arbitrary, unrestricted regular expressions;
- manual publication, npm tags, or registry mutations;
- mesh discovery, load balancing, and failover.
## Route semantics
### Path normalization
`/users` and `/users/` identify the same route. The matcher removes one trailing slash except for `/`.
The ingress rejects repeated slashes, including `/users//42`, with `400 Bad Request`. It applies this rule before declared-route matching and static-file fallback, so Node and Fetch adapters behave alike.
Malformed percent encoding also returns `400 Bad Request`. A malformed path never escapes the matcher as `URIError` and never becomes `500`.
### Methods
The public `HttpMethod` type and decorator surface gain `HEAD` and `OPTIONS`. `@Head` and `@Options` accept the same route options as the existing buffered method decorators.
For `HEAD`, an explicit `HEAD` route wins. Without one, the router matches the corresponding `GET` route and executes its pipeline, but every adapter suppresses the response body. The response retains the status and headers that `GET` would produce. Streaming routes do not serve as implicit `HEAD` handlers.
For a bare `OPTIONS` request, an explicit `OPTIONS` route wins. Without one, any matching path receives `204 No Content` and an `Allow` header. CORS preflight remains the earlier specialized branch and keeps its configured CORS response.
`Allow` uses a stable method order. It adds `HEAD` when a buffered `GET` route exists and adds `OPTIONS` whenever the path exists. A request with another unsupported method receives `405` plus the same value.
### Pattern validation
The application compiles and validates route patterns during graph construction. Invalid declarations fail before the app serves traffic. Validation rejects:
- a catch-all outside the final segment;
- empty parameter or catch-all names;
- repeated parameter names in one pattern;
- repeated internal slashes in declarations;
- malformed constraints;
- duplicate routes with the same method and effective pattern;
- patterns that differ only by parameter names and therefore match the same requests with equal precedence.
Errors name the method, pattern, controller origin, and conflict when applicable.
### Segment constraints
The matcher accepts a constrained parameter such as `:id(\d+)`. A constraint matches the whole decoded segment. `/users/12` matches `:id(\d+)`; `/users/12x` does not. A failed constraint remains a normal non-match, so another route may win before the router returns `404`.
The implementation compiles constraints once and caches the compiled pattern. It accepts a deliberately small regular-expression subset for common numeric, UUID, slug, and enumerated segments. It rejects lookarounds, backreferences, nested groups, nested quantifiers, and other constructs that create a practical ReDoS risk. This keeps the advertised syntax without executing unrestricted attacker-facing regular expressions.
Specificity remains deterministic:
1. static segment;
2. constrained parameter;
3. unconstrained parameter;
4. catch-all.
Registration order resolves only genuine, non-ambiguous ties that survive boot validation.
## Architecture
`src/http/router.ts` owns pattern parsing, validation, compilation, matching, method fallback, and `Allow` calculation. A compiled representation records normalized segments, parameter names, optional constraints, catch-all state, and specificity.
`src/metadata.ts` exposes the new method type and decorators. Application graph construction compiles route definitions and reports declaration errors with controller context. The runtime-neutral HTTP core decides `HEAD`, `OPTIONS`, `400`, `404`, and `405`; Node and Fetch adapters only serialize its outcome.
`src/openapi.ts` converts constrained paths to OpenAPI templates and places the accepted expression in the path parameter's `schema.pattern`. It lists explicit `HEAD` and `OPTIONS` operations but does not invent operations for automatic fallbacks.
Mesh route manifests carry the expanded method union. Existing wire behavior stays compatible because method values are strings and the change adds values without changing the envelope shape.
## Error behavior
Declaration errors fail at boot. Request syntax errors return the standard error envelope with status `400` and pass through the configured `onError` renderer. Pattern non-matches return `404`; method mismatches return `405`; automatic `OPTIONS` returns `204`.
Error responses keep the existing security and CORS header injection. They do not include decoded attacker input, stack traces, or internal regular-expression details.
## Dependency remediation
The published runtime dependency set is already clean: `npm audit --omit=dev` reports zero vulnerabilities. The full development tree and documentation site require remediation.
The root update will prefer the smallest supported versions that close each advisory:
- Vitest moves to `3.2.6`, which fixes the critical advisory while preserving Node 18 support;
- the Nest benchmark packages move to `11.1.28`, including Multer `2.2.0`;
- Miniflare moves to its current compatible patch with fixed Sharp;
- Fastify and compatible toolchain packages receive current patch/minor updates;
- `find-my-way` receives a narrow `9.7.0` override while Nest pins the vulnerable `9.6.0`, with Nest/Fastify benchmarks as a compatibility gate;
- Autocannon's `hyperid`/`uuid` chain receives an isolated remediation only if the benchmark suite proves it compatible; otherwise the benchmark dependency will be replaced or isolated rather than suppressing the advisory.
The documentation site moves Astro to `7.1.6`, Starlight to `0.41.6`, and resolves the patched PostCSS and SVGO versions. Both lockfiles will be regenerated from their manifests.
The work will not use `npm audit fix --force`, security-audit suppression, or an incompatible downgrade merely to produce a green report.
## Documentation
The change updates:
- the README routing section and roadmap;
- the Routing guide;
- the Decorators reference;
- the OpenAPI guide where constrained parameters affect output;
- the CHANGELOG and package version;
- the Starlight 404 configuration that currently emits a build warning.
Examples will state the trailing-slash policy, double-slash rejection, automatic method behavior, constraint limits, and the deferred radix-tree work.
## Verification
The implementation adds unit and integration coverage for:
- explicit and implicit `HEAD`;
- body suppression and header preservation;
- explicit and automatic `OPTIONS`;
- CORS-preflight precedence;
- deterministic `Allow` values;
- trailing slash equivalence and double-slash rejection;
- invalid percent encoding;
- route-declaration failures;
- constrained matches, non-matches, precedence, and unsafe-expression rejection;
- OpenAPI path and `schema.pattern` output;
- Node and Fetch parity;
- mesh method serialization where relevant.
The release gate runs:
- root and website audits with zero known vulnerabilities;
- the runtime-only root audit separately;
- Node tests, typecheck, lint, format, complexity, and build;
- Deno, Bun, and Edge suites when their runtimes are available;
- documentation build without the current 404 warning;
- framework benchmarks, including the Nest/Fastify paths affected by overrides;
- `npm pack --dry-run` to inspect the published artifact.
## CI and publication flow
Gitea remains the source of the release flow:
1. CI runs on `develop` and `main`.
2. A merge to Gitea `main` publishes the package to internal Verdaccio under `stg`.
3. Gitea's promotion workflow pushes only `main` and version tags to GitHub.
4. A promoted `v*` tag triggers GitHub's `release.yml`.
5. GitHub publishes to npm through Trusted Publishing/OIDC and derives `beta` from `26.8.0-beta.0`.
This implementation prepares the version and validates the workflows. It does not merge to `main`, create a release tag, publish to Verdaccio, or invoke `npm publish` locally.
@@ -1,679 +0,0 @@
# Router Security Beta Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Ship `26.8.0-beta.0` with complete HEAD/OPTIONS behavior, safe constrained route parameters, strict path handling, accurate documentation, and clean dependency audits.
**Architecture:** Keep the linear route table, but compile and validate each pattern once. Centralize path syntax, matching, method fallback, and `Allow` calculation in the runtime-neutral HTTP layer so Node and Fetch adapters stay behaviorally identical. Remediate tooling dependencies without changing the package's Node 18 runtime contract or its one required runtime dependency.
**Tech Stack:** TypeScript, legacy decorators, Node HTTP, Fetch API, Vitest, OpenAPI 3.1, Astro/Starlight, npm lockfiles, GitHub/Gitea Actions.
---
### Task 1: Compile and validate route patterns
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/types.ts`
- Test: `test/router.test.ts`
**Step 1: Write failing compiler tests**
Add tests that establish the supported grammar and precedence:
```typescript
describe('compilePattern', () => {
it('compiles constrained params and gives them precedence over plain params', () => {
const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')];
expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)');
expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value');
});
it.each([
'/files/:rest*/tail',
'/users/:',
'/users/:id/:id',
'/users//:id',
'/users/:id((a+)+)',
'/users/:id((?=a)a)',
'/users/:id(\\1)',
])('rejects invalid or unsafe pattern %s', (pattern) => {
expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/);
});
});
```
Also cover numeric, UUID-like, slug, and bounded-quantifier examples; a constraint must match the complete decoded segment.
**Step 2: Run the focused test and confirm RED**
Run:
```bash
npx vitest run test/router.test.ts
```
Expected: FAIL because `compilePattern` and constrained matching do not exist.
**Step 3: Implement the compiled representation**
In `src/http/router.ts`, add:
```typescript
type CompiledSegment =
| { kind: 'static'; value: string }
| { kind: 'param'; name: string; constraint?: RegExp }
| { kind: 'catchAll'; name: string };
export interface CompiledPattern {
source: string;
normalized: string;
shape: string;
segments: CompiledSegment[];
kinds: number[]; // static=3, constrained=2, param=1; catch-all stored separately
catchAll: boolean;
}
```
Implement `compilePattern(pattern)`, `matchCompiled(compiled, pathSegments)`, and a string-keyed cache used by `matchPattern`. Parse `:name(expr)` only when the closing `)` ends the segment. Anchor accepted constraints as `^(?:${expr})$`.
Implement `assertSafeConstraint` as a small whitelist parser. Permit literals, character classes, `\\d`/`\\w`/`\\s` classes, escaped literals, and simple quantifiers. Reject expression length above 128, groups, alternation, anchors, lookarounds, backreferences, nested quantifiers, and adjacent unbounded quantified atoms without a separating literal. Do not add a runtime dependency.
Build `shape` from segment kinds and constraint source so `:id` and `:name` have the same effective shape.
**Step 4: Run tests and confirm GREEN**
Run:
```bash
npx vitest run test/router.test.ts
npm run typecheck
```
Expected: all router tests pass and TypeScript reports no errors.
**Step 5: Commit**
```bash
git add src/http/router.ts src/http/types.ts test/router.test.ts
git commit -s -m "feat(router): compile safe constrained patterns"
```
### Task 2: Validate request paths and route-table ambiguity
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/app/index.ts`
- Modify: `src/app/types.ts`
- Test: `test/router.test.ts`
- Test: `test/app.test.ts`
**Step 1: Write failing path-policy tests**
Add router tests for the approved normalization:
```typescript
expect(normalizeRequestPath('/users')).toBe('/users');
expect(normalizeRequestPath('/users/')).toBe('/users');
expect(normalizeRequestPath('/')).toBe('/');
expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/);
expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/);
```
Add app-construction tests proving that identical routes and routes that differ only by parameter names fail before serving:
```typescript
expect(() => createApp({ modules: [DuplicateRouteModule] })).toThrow(/ambiguous route.*GET/);
```
Cover the same path under different methods as valid.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/app.test.ts
```
Expected: FAIL because normalization and ambiguity checks are absent.
**Step 3: Implement request normalization**
Add `InvalidRequestPathError` and `normalizeRequestPath(path)` to `src/http/router.ts`. Strip exactly one trailing slash except at root, reject `//`, and call `decodeURIComponent` on every raw segment only to validate encoding. Matching still compares static segments according to the existing encoded-path contract and decodes captured values once.
**Step 4: Implement route-table validation**
Store a `compiled` pattern on each internal `RoutePlan`/`RouteDef`, or expose a shared cache accessor if that avoids duplicating state. During `collectControllers`, compile each joined pattern and compare the candidate's method plus `shape` with existing route plans. Throw an error that includes method, pattern, controller/handler, and conflicting declaration.
Apply the same validation after remote mesh routes join. A remote conflict must name both mesh owner URLs rather than silently selecting registration order.
**Step 5: Run focused and mesh tests**
```bash
npx vitest run test/router.test.ts test/app.test.ts test/mesh/fetch-boot.test.ts test/mesh/integration.test.ts
npm run typecheck
```
Expected: all selected tests pass.
**Step 6: Commit**
```bash
git add src/http/router.ts src/app/index.ts src/app/types.ts test/router.test.ts test/app.test.ts
git commit -s -m "fix(router): reject invalid and ambiguous paths"
```
### Task 3: Add HEAD and OPTIONS to the public decorator API
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/metadata.ts`
- Modify: `src/index.ts`
- Modify: `src/signals.ts`
- Test: `test/metadata.test.ts`
- Test: `test/smoke.test.ts`
**Step 1: Write failing decorator tests**
```typescript
class Methods {
@Head('/resource') head() {}
@Options('/resource') options() {}
}
expect(getRoutes(Methods).map(({ method }) => method)).toEqual(['HEAD', 'OPTIONS']);
```
Add a public-barrel smoke test that imports `Head`, `Options`, and `HttpMethod` from `src/index.ts`.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts
```
Expected: FAIL because the exports do not exist.
**Step 3: Implement decorators and messages**
Extend `HttpMethod`:
```typescript
export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
```
Create buffered `Head` and `Options` decorators through `routeDecorator`, export them from `src/index.ts`, and update `TransportMismatchError`'s buffered-method message. Keep `@Html` restricted to GET/POST and update its rejection text to include HEAD/OPTIONS.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/metadata.test.ts test/smoke.test.ts test/transport-enforcement.test.ts test/views-html.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/metadata.ts src/index.ts src/signals.ts test/metadata.test.ts test/smoke.test.ts
git commit -s -m "feat(router): expose HEAD and OPTIONS decorators"
```
### Task 4: Implement runtime-neutral HEAD, OPTIONS, and path errors
**Skills:** `@superpowers:test-driven-development`, `@security-review`
**Files:**
- Modify: `src/http/router.ts`
- Modify: `src/http/core.ts`
- Modify: `src/http/web.ts`
- Modify: `src/http/server.ts`
- Test: `test/router.test.ts`
- Test: `test/http.test.ts`
- Test: `test/fetch.test.ts`
- Test: `test/parity.test.ts`
- Test: `test/transport-security.test.ts`
**Step 1: Write failing method-semantics tests**
Cover these cases in both Node and `app.fetch`:
```typescript
// Explicit HEAD wins.
// Otherwise buffered GET runs once, retains status/headers, and emits an empty body.
// Streaming GET does not become implicit HEAD.
// Explicit OPTIONS wins.
// Automatic OPTIONS returns 204 and deterministic Allow.
// GET implies HEAD; every existing path implies OPTIONS.
// CORS preflight still runs before explicit/automatic OPTIONS.
// Double slash and malformed encoding return 400 with security headers.
```
Use a canonical expected header such as `GET, HEAD, POST, OPTIONS`.
**Step 2: Run focused tests and confirm RED**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
```
Expected: new assertions fail under the current 405 behavior.
**Step 3: Implement method resolution**
In `src/http/router.ts`, add a stable method order and helpers:
```typescript
export interface ResolvedRoute extends MatchedRoute {
implicitHead: boolean;
}
export function resolveRoute(routes: RouteDef[], method: string, path: string): ResolvedRoute | undefined;
export function allowedMethods(routes: RouteDef[], path: string): HttpMethod[];
```
`resolveRoute` tries explicit method first. For HEAD only, it falls back to a matching buffered GET. `allowedMethods` deduplicates explicit methods, adds HEAD for buffered GET, adds OPTIONS for every existing path, and sorts canonically.
**Step 4: Implement core outcomes**
At the start of `handle`, normalize the path and render `InvalidRequestPathError` as `400`. Preserve the existing CORS-preflight branch. Resolve explicit OPTIONS normally; otherwise return buffered `204` with `allow` and empty body. For an implicit or explicit HEAD route, run the normal pipeline but replace a buffered result body with `''`. Reject a stream outcome for HEAD as a transport mismatch rather than opening a stream.
**Step 5: Align body acquisition in both adapters**
Replace early `matchRoute` calls in `src/http/web.ts` and `src/http/server.ts` with the same normalization and resolution helper used by `handle`. If path validation fails before body acquisition, render `400` through `onError` with injected security/CORS headers. Never read a request body for automatic OPTIONS or an invalid path.
**Step 6: Run focused tests and confirm GREEN**
```bash
npx vitest run test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
npm run typecheck
```
Expected: all selected tests pass with Node/Fetch parity.
**Step 7: Commit**
```bash
git add src/http/router.ts src/http/core.ts src/http/web.ts src/http/server.ts test/router.test.ts test/http.test.ts test/fetch.test.ts test/parity.test.ts test/transport-security.test.ts
git commit -s -m "feat(http): complete HEAD and OPTIONS semantics"
```
### Task 5: Project constraints into OpenAPI and introspection
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/openapi.ts`
- Modify: `src/app/introspect.ts`
- Test: `test/openapi.test.ts`
- Test: `test/graph-viz.test.ts`
**Step 1: Write failing OpenAPI tests**
Add `@Get('/:id(\\d+)')`, explicit `@Head`, and explicit `@Options` routes to the fixture. Assert:
```typescript
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).parameters).toContainEqual(
expect.objectContaining({ name: 'id', schema: { type: 'string', pattern: '\\d+' } }),
);
expect(doc.paths['/api/users/{id}'].head).toBeDefined();
expect(doc.paths['/api/users/{id}'].options).toBeDefined();
```
Assert that automatic HEAD/OPTIONS operations are not invented.
**Step 2: Run tests and confirm RED**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts
```
Expected: constrained template parsing or schema assertions fail.
**Step 3: Implement projection**
Reuse the route compiler's parsed segment data instead of parsing the syntax a second way. Convert params and catch-alls to `{name}`. Add `schema.pattern` only for constrained params. Ensure `inspect`, `explain`, Mermaid, and DOT retain the human-readable original pattern.
**Step 4: Run tests and typecheck**
```bash
npx vitest run test/openapi.test.ts test/graph-viz.test.ts test/app.test.ts
npm run typecheck
```
Expected: all pass.
**Step 5: Commit**
```bash
git add src/openapi.ts src/app/introspect.ts test/openapi.test.ts test/graph-viz.test.ts
git commit -s -m "feat(openapi): document constrained route params"
```
### Task 6: Remove root and website dependency advisories
**Skills:** `@security-review`
**Files:**
- Modify: `package.json`
- Modify: `package-lock.json`
- Modify: `website/package.json`
- Modify: `website/package-lock.json`
- Test: `bench/servers/nestjs-express.ts`
- Test: `bench/servers/nestjs-fastify.ts`
**Step 1: Record the failing audit baseline**
```bash
npm audit
npm --prefix website audit
npm audit --omit=dev
```
Expected: root full audit reports 17 advisories, website reports 3, runtime-only root reports 0.
**Step 2: Apply supported direct updates**
Update root dependencies with explicit commands so the manifests and lockfile agree:
```bash
npm install --save-dev vitest@^3.2.6 \
@nestjs/common@^11.1.28 @nestjs/core@^11.1.28 \
@nestjs/platform-express@^11.1.28 @nestjs/platform-fastify@^11.1.28 \
fastify@^5.11.0 miniflare@^4.20260730.0 \
@eslint/js@^9.39.5 eslint@^9.39.5 prettier@^3.9.6 \
tsx@^4.23.5 typescript-eslint@^8.65.0 ws@^8.21.1
npm --prefix website install astro@^7.1.6 @astrojs/starlight@^0.41.6
```
Do not bump TypeScript, ESLint, or GraphQL across their next major versions.
**Step 3: Add narrow overrides only for unresolved vulnerable transitives**
Run `npm audit --json` and inspect the exact remaining paths. Add the smallest overrides justified by that output, initially:
```json
{
"overrides": {
"@nestjs/platform-fastify": {
"find-my-way": "9.7.0"
},
"autocannon": {
"hyperid": {
"uuid": "11.1.1"
}
}
}
}
```
If npm rejects nested override syntax, express the same ownership with `$` references or the supported nested-object form for the installed npm version. Never add a global override when a package-scoped one works.
**Step 4: Prove compatibility before accepting overrides**
```bash
npm run typecheck
npm test
npm run bench
```
Expected: tests pass; Express, Fastify, Nest Express, and Nest Fastify scenarios start and complete; Autocannon produces all scenario rows. If the UUID override breaks Autocannon, revert only that override and replace/isolate Autocannon in a follow-up commit within this task until the full audit is clean.
**Step 5: Verify clean audits**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
```
Expected: all three commands exit 0 with zero vulnerabilities.
**Step 6: Commit**
```bash
git add package.json package-lock.json website/package.json website/package-lock.json
git commit -s -m "chore(deps): remediate security advisories"
```
### Task 7: Add security and documentation gates to CI
**Skills:** `@security-review`
**Files:**
- Modify: `.github/workflows/ci.yml`
- Modify: `.github/workflows/release.yml`
**Step 1: Define the expected gates**
The CI job must install root and website lockfiles, audit both, build docs, and preserve the existing Node 18 package gate. The GitHub-only release job must audit the root tree immediately after `npm ci` and before `npm publish`.
**Step 2: Update CI**
Add these steps after the root `npm ci`:
```yaml
- run: npm audit
- run: npm ci --prefix website
- run: npm audit --prefix website
- run: npm run docs:build
```
Keep lint, format, complexity, typecheck, test, and build unchanged.
**Step 3: Update the GitHub release gate**
Add `npm audit` after `npm ci` in `.github/workflows/release.yml`. Do not change the tag trigger, Gitea server guard, Node 22 OIDC setup, dist-tag derivation, or `npm publish` command.
Do not modify `stage.yml` or `promote.yml`; their verified GitFlow responsibilities remain:
- Gitea `main` → Verdaccio `stg`;
- Gitea `main` and `v*` tags → GitHub;
- GitHub `v*` → npm OIDC release.
**Step 4: Validate workflow syntax and diff**
```bash
npx prettier --check .github/workflows/ci.yml .github/workflows/release.yml
git diff --check
```
If Prettier does not parse the workflow format in this repo, inspect with `ruby -e "require 'yaml'; YAML.load_file(ARGV[0])" <file>` and record that command instead.
**Step 5: Commit**
```bash
git add .github/workflows/ci.yml .github/workflows/release.yml
git commit -s -m "ci: gate releases on clean dependency audits"
```
### Task 8: Audit and align the complete website documentation
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Review: every page under `website/src/content/docs/`
- Modify: `website/src/content/docs/guides/routing.md`
- Modify: `website/src/content/docs/reference/decorators.md`
- Modify: `website/src/content/docs/guides/openapi.md`
- Modify: any other website page whose API, behavior, example, or cross-link has drifted from the code
- Create: `website/src/content/docs/404.md`
**Step 1: Build a code-backed website documentation inventory**
Compare every website page with the current public exports in `src/index.ts`, app options and methods in `src/app/types.ts`, decorator metadata in `src/metadata.ts`, routing behavior in `src/http/router.ts`, and the executable tests. Search the whole documentation tree for stale method lists, obsolete limitations, old error semantics, old beta/version examples, broken internal links, and examples that no longer typecheck conceptually.
Do not change a claim from memory. Each correction must be supported by code or a passing test.
**Step 2: Update routing documentation from the verified behavior**
Document:
- `@Head` and `@Options`;
- explicit-route priority and automatic fallbacks;
- canonical `Allow` behavior;
- `/path` equals `/path/`;
- `//` and malformed encoding return `400`;
- catch-all must be final;
- `:id(\\d+)`, whole-segment matching, precedence, and the safe-subset restriction;
- the matcher remains linear and a radix tree remains deferred.
Remove the current statement that bare OPTIONS returns 405.
**Step 3: Align cross-cutting website references**
At minimum, verify and correct:
- every buffered-method list to include or intentionally exclude `HEAD`/`OPTIONS` according to the actual API;
- `405`, automatic `OPTIONS`, implicit `HEAD`, CORS-preflight, malformed-path, and security-header descriptions;
- OpenAPI behavior: explicit HEAD/OPTIONS appear as operations, constrained params produce `schema.pattern`, and automatic fallbacks remain absent;
- mesh route-conflict wording after effective-pattern normalization;
- examples and links between routing, decorators, errors, HTML, streaming, security, OpenAPI, and `createApp` reference pages;
- navigation/frontmatter descriptions that still advertise the old router surface.
Keep intentional historical or roadmap statements only when they remain true.
**Step 4: Fix the Starlight 404 warning**
Create the missing `404.md` entry with valid Starlight frontmatter and concise navigation back to the docs index. Run `npm run docs:build` and confirm the line `Entry docs → 404 was not found` disappears.
**Step 5: Validate the whole website documentation tree**
```bash
npm run docs:build
npm --prefix website audit
rg -n 'Not built|bare `OPTIONS`|returns `405`|@Get.*@Post.*@Put.*@Patch.*@Delete' website/src/content/docs
rg -n '\]\(/docs/' website/src/content/docs
git diff --check
```
Expected: all 23+ pages build without the missing-404 warning, the website audit remains clean, obsolete router claims are gone, and every changed claim has a code/test source.
**Step 6: Commit**
```bash
git add website/src/content/docs
git commit -s -m "docs(website): align guides with router behavior"
```
### Task 9: Align package documentation and prepare the August beta
**Skills:** `@writing-clearly-and-concisely`
**Files:**
- Modify: `README.md`
- Modify: `CHANGELOG.md`
- Modify: `src/index.ts`
- Modify: `package.json`
- Modify: `package-lock.json`
**Step 1: Align the package-facing documentation**
Update README routing, roadmap, method, security, and beta-status claims from the same verified behavior documented in the website. Keep README concise and link to the complete website guides rather than duplicating their full reference material.
**Step 2: Bump the beta version consistently**
Run:
```bash
npm version 26.8.0-beta.0 --no-git-tag-version
```
Update `src/index.ts`'s `VERSION` constant and add a `26.8.0-beta.0` CHANGELOG entry covering routes, security remediation, docs, and compatibility. Confirm README's CalVer examples remain accurate.
**Step 3: Verify docs and version consistency**
```bash
npm run docs:build
node -e "const p=require('./package.json'); const l=require('./package-lock.json'); if (p.version !== l.version || p.version !== l.packages[''].version) process.exit(1)"
rg -n '26\.7\.0-beta\.0|Not built|bare `OPTIONS`' README.md CHANGELOG.md src website/src/content/docs
git diff --check
```
Expected: package versions agree, website docs still build, and any old beta string is retained only in historical release examples.
**Step 4: Commit**
```bash
git add README.md CHANGELOG.md src/index.ts package.json package-lock.json
git commit -s -m "docs: document router completeness for beta"
```
### Task 10: Run the complete release-candidate verification
**Skills:** `@superpowers:verification-before-completion`, `@security-review`
**Files:**
- Modify only if a verification failure reveals an in-scope defect.
**Step 1: Run static and Node gates**
```bash
npm run lint
npm run format:check
npm run complexity:check
npm run typecheck
npm run typecheck:bench
npm test
npm run build
```
Expected: every command exits 0. Record the existing lint-warning count separately; introduce no new warnings.
**Step 2: Run multi-runtime gates**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: every installed runtime suite exits 0. If a runtime is unavailable, report the exact missing command; do not claim that suite passed.
**Step 3: Run security, docs, and benchmark gates**
```bash
npm audit
npm audit --omit=dev
npm --prefix website audit
npm run docs:build
npm run bench
```
Expected: zero advisories; docs build without warning; all benchmark scenarios complete.
**Step 4: Inspect the publish artifact without publishing**
```bash
npm pack --dry-run
```
Expected: package contains `dist`, assets, README, CHANGELOG, and LICENSE; version is `26.8.0-beta.0`; no docs worktree, tests, secrets, or local environment files appear.
**Step 5: Review branch and workflow boundaries**
```bash
git status --short --branch
git log --oneline --decorate develop..HEAD
git diff --check develop...HEAD
git diff --stat develop...HEAD
```
Expected: clean `feat/router-security-beta`; all commits carry `Signed-off-by`; no tag, registry publication, `main` merge, or workflow secret change occurred.
**Step 6: Commit any verification-only repair**
Only if Step 1–5 exposed an in-scope defect:
```bash
git add <exact repaired files>
git commit -s -m "fix: address beta verification findings"
```
Re-run the failed gate and the complete related suite after any repair.
@@ -1,166 +0,0 @@
# Observability — Design
**Issue:** [#10](https://github.com/Expressive-Tea/green-tea/issues/10) · **Status:** reviewed, all decisions settled · **Constraint:** no new runtime dependency
---
## The diagnosis is not the one in the issue
#10 says green-tea "ships no logging, metrics or tracing contract today", and asks for an injectable logger, structured output, tracing hooks and metrics as one design. The framing is right; the starting point is wrong, and it changes what the work is.
**The mechanism already exists.** `Bus` (`src/bus.ts`) is an in-process event emitter with 19 emission points already wired through boot, the pipeline, streams, WebSockets, mesh and plugins. Plugins already receive `bus.on` — and only `on`, so isolation is structural (`src/plugin.ts:27`).
What is actually missing is narrower and more serious than "there is no logger":
| # | Finding | Where |
|---|---|---|
| 1 | **No event carries request identity.** Under any concurrency, interleaved `request:step:enter` events cannot be attributed to a request. | `src/pipeline.ts:53,56` |
| 2 | **`durationMs` is declared and never set by anything.** There is no timing in the system at all. | `src/bus.ts:22`, zero writers |
| 3 | **No request-level events exist.** No `started`/`completed`/`failed`, so there is no span for step events to hang from. | — |
| 4 | **A failing step is reported as `name: 'pipeline'`**, losing which step broke. | `src/pipeline.ts:98` |
| 5 | **8 `console.warn` calls in core**, unredirectable. | `src/app/index.ts` ×6, `src/deno.ts`, `src/bun.ts` |
So the real statement of the problem is:
> The event stream exists but is **not correlatable and not measured**, which makes it unusable for production observability regardless of what consumes it.
That is *why* #10 is one design and not six — a sharper reason than the issue had. A logger, a metrics exporter and an OpenTelemetry bridge are not three features; they are three **consumers of one corrected event stream**. Fix correlation and timing once, and all three become adapters outside core. Ship them separately and each grows its own private notion of "which request was that", which is the three-mechanisms failure #10 warned about.
**Consequence for sequencing:** most of this work is in `src/bus.ts` and `src/pipeline.ts`, not in new files.
---
## Decisions
### D1 — The logger is a distinct registration, not an ordinary provider
`createApp({ logger })`, not `@Provider({ provides: 'logger' })`.
The deciding constraint is ordering. `boot:provider:start`/`fail` fire *while* the graph is booting (`src/app/index.ts:639-647`), and the optional-provider failure warning at `src/app/index.ts` logs during that same phase. A provider cannot log its own boot failure, and a logger that only exists after the graph resolves cannot report the graph failing to resolve. Shutdown has the same shape: `closeApp` warns after the graph is gone.
The logger is therefore framework infrastructure with a lifetime wider than the graph.
It is *additionally* exposed as an injectable key so steps and handlers reach it with `@needs('logger')` like anything else. One object, two access paths, no second implementation.
**Default:** structured JSON. Human-readable when the process is interactive, decided once at boot rather than per call. **Never a dependency** — the default writes to `console` behind the same interface everyone else implements, which is what lets the 8 direct `console.warn` calls become logger calls without core gaining a logging library.
### D2 — One emitter. Extend `Bus`; do not add a parallel hook system
Per-category hooks would be a second mechanism competing with an emitter that already has 19 call sites and a plugin contract built on it. `LifecycleEvent` grows; nothing new is introduced.
This also keeps the existing guarantee intact: `emit` swallows listener failures (`src/bus.ts:41`) precisely so observers can never break the pipeline. Observability must not acquire the power to take down a request.
**This is exactly why shutdown teardown does not belong here** — see Task 2.5 in the trust-release plan. A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
### D3 — A step failure emits both `request:step:error` and `request:failed`
They answer different questions — *which step broke* and *did this request fail* — and a tracing exporter needs both: one marks the span, the other marks the trace. Emitting only the outer event is what produces a trace that says a request failed with no indication where.
`request:step:error` must also carry the real step name. Emitting `name: 'pipeline'` (`src/pipeline.ts:98`) is a bug, not a design choice, and it is fixed as part of this.
### D4 — Streams and WebSockets emit lifecycle events only, never per-message
`stream:open`/`close`/`error` already exist and are the right granularity. A per-message event on a high-rate SSE or WebSocket stream is a firehose that costs more than it reports, and the cost lands on the workload least able to absorb it.
Anyone who needs per-message visibility instruments their own handler, where they know the message semantics. Same reasoning that keeps WebSocket upgrades outside the concurrency gate in #21.
### D5 — Request identity is generated with `crypto.randomUUID()`, and inherited when offered
No new dependency is available, so no UUID library. `globalThis.crypto.randomUUID` is present on Node, Deno and Bun (verified locally) and is Web Crypto on workerd.
**To validate during implementation:** Node 18 is the floor in `package.json` and CI's `build` job pins `node-version: '18'`, so a gap there fails CI rather than reaching a user. `test:edge` covers workerd the same way.
An incoming `x-request-id` is adopted rather than replaced — a green-tea service behind a gateway must not start a second identity for the same request. A `traceparent` header, if present, is carried as `traceId` untouched; core parses nothing and implements no propagation spec. That belongs in the OpenTelemetry adapter, which owns W3C Trace Context.
---
## The contract
### Events
Existing, unchanged in name: `boot:provider:start|ok|fail`, `request:step:enter|leave|error`, `stream:open|close|error`, `mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
Added:
```
request:start request:end request:failed
route:matched route:unmatched
graph:resolved graph:failed
```
`route:unmatched` rather than the report's `route.not_found`: a 405 is also an unmatched route and is not a 404, and naming the event after one outcome would misreport the other.
### Payload
`EventPayload` gains the correlation and measurement fields it lacks. Every field stays optional — mesh and boot events have no request to name, and forcing a shape on them would mean inventing values.
```ts
interface EventPayload {
name: string;
scope?: string;
error?: unknown;
durationMs?: number; // declared today, written by nothing — this design makes it real
requestId?: string; // the correlation fix
traceId?: string; // inherited from traceparent when present; never synthesized
route?: string; // the matched pattern, not the raw URL — bounded cardinality for metrics
method?: string;
transport?: Transport;
status?: number;
runtime?: 'node' | 'deno' | 'bun' | 'edge';
}
```
`route` is the **pattern** (`/users/:id`), never the concrete path. A metrics consumer that labels a counter with the raw URL produces unbounded cardinality and takes down the metrics backend rather than the app — the framework should not hand a user that shape by default.
### Metrics
No metrics registry in core, and no new event type for them. Per-step timings come from `durationMs` on the events already defined; a metrics adapter subscribes and aggregates. The graph already knows every node, which is what makes this close to free — but the timing instrumentation is measured before it is declared free, per Trust Release §6, and stays opt-in if the measurement says otherwise.
---
## Out of scope, deliberately
- **OpenTelemetry itself.** A separate `@green-tea/opentelemetry` package. Core exposes the stream; it never imports an exporter, and never depends on one.
- **Log shipping, sampling, redaction.** Consumer concerns. Core hands over structured records.
- **Trace context propagation.** Carried, not parsed. The adapter owns W3C Trace Context.
- **Shutdown teardown for plugins/providers.** Task 2.5, a different guarantee — see D2.
---
### D6 — A request span ends when the handler returns, and stream events carry its `requestId`
A streaming route returns from `handle()` in milliseconds while the connection lives for minutes or hours. `request:end` fires at the handler's return, so latency histograms measure time-to-first-byte and stay meaningful instead of mixing 2 ms buffered requests with hour-long SSE connections in one distribution. Connection duration is already available from `stream:open`/`stream:close`, which now carry the same `requestId` so a consumer can join the two.
This is the same boundary #21 chose for its concurrency gate — release when `handle()` returns, treat long-lived streams like upgrades. Answering it differently in the two places would mean the framework disagreed with itself about when a request is over.
### D7 — Per-step timing is always on, measured at step boundaries
Measured before deciding, on the box `BENCHMARKS.md` was produced on:
| Approach | Cost per step | Share of one request |
|---|---:|---:|
| `performance.now()` ×2 per step | 45.3 ns | 0.44% |
| **`performance.now()` at step boundaries (N+1 calls for N steps)** | **25.2 ns** | **0.25%** |
| `Date.now()` ×1 | 28.6 ns | — |
Baseline: 98,093 req/s ≈ 10.19 µs per request.
Two things follow. `Date.now()` loses on both axes — slower *and* coarser — so `performance.now()` is unambiguous. And a step's end is the next step's start, so a pipeline of N steps needs N+1 timestamps rather than 2N, halving the cost.
At 0.25% per step the overhead sits **below the 0.3% run-to-run CV of the project's own benchmark**, so it is not measurable in the harness that would have to justify a flag. Making it opt-in would buy two code paths and a configuration surface in exchange for something nobody can observe. Always on.
> **Correction, after implementation.** This decision survived; its reasoning did not. The measured cost is **+7.0% of the framework's own per-request work** (~0.29 µs, ~2% over a real socket), and it is *fixed per request* rather than per step — per-step work is skipped entirely when nothing subscribes. "Always on" is still right, and for a better reason: there is nothing per-step left to make optional.
>
> Three earlier figures for this were published before that one and all three were wrong, each from a comparison with more than one variable moving. See Task 7 in the implementation plan for what went wrong and why interleaving is not optional here.
### D8 — Request logging is a `Bus` subscriber, wrapped so a failing logger cannot go silent
The logger is a callable sink either way — the 8 direct diagnostics (shutdown timeout, degraded provider) are not events and need one regardless. The decision is only about request logging, and it goes through the event stream: one path, and it is composable and removable exactly as #10 asks for ("a composable step, not a global middleware").
The cost this closes: `emit` swallows listener failures by design (`src/bus.ts:41`), so a user-supplied logger that throws would stop writing with nobody informed. The built-in subscriber is therefore wrapped to fall back to `console` on failure. The Bus keeps its guarantee — an observer still cannot break a request — without buying it with silence.
---
## Verification this design must survive
`npm run lint && npm run format:check && npm run typecheck && npm test`, plus `test:deno`, `test:bun` and `test:edge` — all four now gate a merge. Per-request instrumentation is on the hot path, so `npm run bench` before and after, with the numbers in the implementation plan.
-166
View File
@@ -1,166 +0,0 @@
# Observability — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Design:** [2026-08-16-observability-design.md](./2026-08-16-observability-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
**Goal:** Make the existing event stream correlatable and measured, then build the logger on top of it as its first consumer. Closes [#10](https://github.com/Expressive-Tea/green-tea/issues/10).
**Architecture:** Most of this lands in `src/bus.ts` and `src/pipeline.ts`. The `Bus` already has 19 emission points; this adds identity, timing and the request-level events those points had nothing to hang from. No new runtime dependency — `reflect-metadata` stays the only one, and the OpenTelemetry bridge lives outside core.
**Tech Stack:** TypeScript, Vitest, Deno/Bun/workerd suites, `performance.now()`, `crypto.randomUUID()`.
---
## Order
Tasks 1–3 are the correction; 4–6 are what consumes it. Do not start 4 before 3 — a logger built on uncorrelated events would need its own notion of request identity, which is the failure the design exists to prevent.
---
### Task 1: Give every request an identity, and carry it
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/http/core.ts` (`NeutralRequest`, `handle`)
- Modify: `src/http/server.ts` (~line 120, the Node call into `handle`)
- Modify: `src/http/web.ts` (~line 178, the Fetch call into `handle`)
- Modify: `src/bus.ts`
- Test: `test/observability.test.ts` (new)
**Step 1:** Extend `EventPayload` with the optional fields from the design: `requestId`, `traceId`, `route`, `method`, `transport`, `status`, `runtime`. All optional — boot and mesh events have no request to name.
**Step 2:** Add `requestId` to `NeutralRequest` (`src/http/core.ts`). Generate it in the **adapters**, not in `handle()`, and here is why that placement matters: both adapters read and size-check the body before they reach `handle()` (`server.ts:107`, `web.ts:143` per the #21 analysis), so a 413 is rejected before `handle()` ever sees the request. Generating inside `handle()` would leave exactly the failures an operator most wants to correlate without an id.
**Step 3:** One shared helper for generation, so the two adapters cannot diverge on the rule: adopt an incoming `x-request-id`, otherwise `crypto.randomUUID()`. Carry `traceparent` through as `traceId` **without parsing it** (D5).
**Step 4:** Write the test that fails first: fire two concurrent requests through `app.fetch`, collect `request:step:enter` from the bus, and assert every event carries a `requestId` and that the two requests' events never share one. This is the defect the whole design exists to fix, so it is the first test.
**Verify:** `crypto.randomUUID` on Node 18 — CI's `build` job pins `node-version: '18'`, and `test:edge` covers workerd. Do not assume; let both run.
### Task 2: Measure steps at their boundaries
**Files:**
- Modify: `src/pipeline.ts` (`runSteps`, ~line 48)
- Test: `test/observability.test.ts`
**Step 1:** Take `performance.now()` once before the loop, then once per iteration — **N+1 timestamps for N steps**, because a step's end is the next step's start. Not two per step. The design measured the difference: 25.2 ns vs 45.3 ns per step (D7).
**Step 2:** Attach `durationMs` to `request:step:leave`. The field has been declared in `EventPayload` since the beginning and written by nothing; this is what makes it real.
**Step 3:** Always on, no flag (D7 — 0.25% of a request, below the benchmark's own 0.3% CV).
**Verify:** a step that sleeps a known interval reports a `durationMs` in that neighbourhood. Assert a range, never an exact value.
### Task 3: Stop losing which step failed
**Files:**
- Modify: `src/pipeline.ts` (`runSteps`, and the catch at ~line 98)
- Test: `test/observability.test.ts`
`request:step:error` currently emits `{ name: 'pipeline' }`, which throws away the one fact it exists to report.
**Step 1:** Wrap each `step.run` inside `runSteps`, emit `request:step:error` with the real step name and `scope`, and rethrow unchanged. Do not swallow.
**Step 2:** `runPipeline`'s existing catch now emits `request:failed` instead of a second `step:error` (D3). Both fire for a failing step, deliberately: one marks the span, the other the trace.
**Verify:** a three-step pipeline whose middle step throws emits `request:step:error` naming *that* step, plus exactly one `request:failed`.
### Task 4: The logger contract
**Files:**
- Create: `src/logger.ts`
- Modify: `src/app/index.ts` (`createApp` options; the 6 `console.warn` calls)
- Modify: `src/deno.ts`, `src/bun.ts` (1 `console.warn` each)
- Modify: `src/index.ts` (export the type)
- Test: `test/logger.test.ts` (new)
**Step 1:** Define the interface. Keep it to the levels core actually uses — resist inventing a hierarchy nobody calls.
**Step 2:** Default implementation: structured JSON, human-readable when the process is interactive, decided **once at boot** rather than per call. It writes through `console`; core gains no logging dependency (D1).
**Step 3:** `createApp({ logger })`. A distinct registration, not a provider — it has to outlive the graph to report the graph failing to boot (D1). Per `AGENTS.md`, a new public option means `src/app/types.ts` too if it appears on `App`.
**Step 4:** Replace all 8 `console.warn` calls. `grep -rn "console\." src/` must return nothing afterwards, which is the check #10 actually asks for.
**Step 5:** Expose the logger under an injectable key so steps and handlers reach it with `@needs('logger')`. One object, two access paths, no second implementation.
### Task 5: Request logging as a subscriber
**Files:**
- Modify: `src/logger.ts`
- Test: `test/logger.test.ts`
**Step 1:** Build request logging as `bus.on(...)` over the corrected stream (D8). Composable and removable, which is what #10 means by "a composable step, not a global middleware".
**Step 2:** Wrap the subscriber so a throwing logger falls back to `console`. `Bus.emit` swallows listener failures by design (`src/bus.ts:41`); without the wrapper a broken user logger stops writing and tells nobody. The Bus keeps its guarantee; it just stops paying for it with silence.
**Verify:** a logger that throws on every call still produces output, and the request still succeeds.
### Task 6: The remaining events
**Files:**
- Modify: `src/bus.ts`, `src/http/core.ts`, `src/app/index.ts`
**Step 1:** Add `request:start|end|failed`, `route:matched|unmatched`, `graph:resolved|failed` to `LifecycleEvent`.
**Step 2:** `request:end` fires **when the handler returns**, not when a stream closes (D6). `stream:open`/`close` carry the same `requestId` so a consumer joins them itself.
**Step 3:** `route:unmatched` covers 404 and 405 both — naming it after one outcome would misreport the other.
**Step 4:** `route` on every payload is the **matched pattern**, never the concrete path. A metrics consumer labelling on raw URLs produces unbounded cardinality and takes down the metrics backend; the framework must not hand anyone that shape by default.
### Task 7: Benchmark, and publish the number — **DONE; D7 was wrong in shape**
**Files:**
- Modify: `BENCHMARKS.md`
D7 predicted ~0.25% **per step**, invisible against the harness's own 0.3% CV.
**Measured: +7.0% of the framework's own per-request work** — 4.074 µs → 4.361 µs, medians of five interleaved rounds, ranges not overlapping. About 0.29 µs, or ~2% of a request over a real socket.
The prediction was wrong in **shape**, not only magnitude. Per-step work is skipped entirely when nothing subscribes (`Bus.hasListeners`), so a deep pipeline pays no more than a shallow one; what remains is a **fixed per-request** cost — generating the request id, reading two headers, and the guard checks. "Always on" survives, for a better reason than it was made with: there is nothing per-step left to make optional.
**Three earlier numbers for this were published and all three were wrong**, which is the more useful lesson: −3.9%, then 0.8%, then −6.8%. Each came from a comparison with more than one variable moving.
- The first two were sequential rather than interleaved. The same code measured at the start and end of one session differed by **12%** as the machine warmed, so run order was indistinguishable from effect — one of them even reported the wrong sign.
- The third compared `7bd11bf` against `HEAD`, which differ by observability **and** three performance fixes pulling the other way. It reported their net as if it were one of them.
The number above compares `7bd11bf` against `523e318`, the last commit before those fixes, alternating round by round.
Two regressions were found and fixed by measuring rather than reasoning, both larger than anything the design anticipated:
- **A second `async` frame in `handle()` cost 0.43 µs/request** — a promise and two microtask ticks, an order of magnitude more than the four `Map` lookups it existed to arrange. `handle()` is no longer `async`.
- **A closure allocated per request inside `correlateRequest`** cost 0.16 µs, 45% of the then-remaining overhead, for a helper capturing nothing.
Recorded here because the lesson generalises: on this path, an extra promise costs more than any amount of bookkeeping, and a hot-path prediction reasoned from primitive costs was off by more than 10×.
### Task 8: Documentation
**Files:**
- Modify: `README.md` (the *Honest scope* paragraph at ~line 246)
- Modify: `website/src/content/docs/` — a new observability guide, plus the `createapp` reference table
`README.md:246` currently opens "**No observability layer, either.**" and links to #10. It is the single most load-bearing sentence in the CTO assessment, and rewriting it is part of this work rather than follow-up. Say what now exists and what still does not — the OpenTelemetry adapter is not in core and should not be implied to be.
Per `AGENTS.md`, new public API needs a note in `README.md`.
> If Phase 4 has already moved the site, the guide lands in the docs repository instead.
---
## Out of scope
`@green-tea/opentelemetry`, log shipping, sampling, redaction, W3C Trace Context parsing, and plugin/provider teardown (Task 2.5 in the trust-release plan — an awaited teardown and a non-blocking observer are opposite guarantees).
---
## Verification
```bash
npm run lint && npm run format:check && npm run complexity:check && npm run typecheck && npm test
npm run test:deno && npm run test:bun && npm run test:edge # all three gate a merge now
npm run bench # hot-path change
grep -rn "console\." src/ # must be empty
```
-350
View File
@@ -1,350 +0,0 @@
# Trust Release Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Close the gaps that four independent evaluations agree on, in the order that makes each one cheap. Prove portability in CI, make derived execution explainable, ship an observability contract, and move the documentation site out of the core repository so it gets its own lifecycle.
**Architecture:** Nothing here adds a runtime dependency. The observability work is a contract plus emission points, with exporters living outside core. The explain work is a resolver over data `explainRoute` already returns. The runtime matrix runs suites that already exist. The docs split moves a directory that is already self-contained.
**Tech Stack:** TypeScript, legacy decorators, Vitest, Deno/Bun/Workers runtimes, JSR, Astro/Starlight, GitHub/Gitea Actions.
---
## Why this order
The four reports in `.specs/reports/` were written independently and converge on one gap. Observability is the only dimension the CTO due diligence marks as risk **Alto** on its own (§5.3, risk register), it is P0 twice in the Trust Release report (§4, §5), and it is a listed con in the lead-dev report (§4). That is GH #10, and it is the largest item here — which is exactly why it is not first. The three phases before it are cheap, unblock evidence, and produce the material that #10's design needs.
Two things the reports demand that had **no issue filed**, both verified against the code rather than taken on the report's word:
- **Runtime matrix in CI.** `package.json:91-93` defines `test:deno`, `test:bun` and `test:edge`. `.github/workflows/ci.yml` runs none of them. `AGENTS.md:23` already warns that `npm test` does not cover the other runtimes — and CI does not close that. The framework's headline claim has no CI evidence. Trust Release §7 (P0), CTO §8.2 and P0-6.
- **`explain()` does not explain causality.** `src/app/introspect.ts:62` returns a flat `chain` with `needs`/`provides` per node, but never the edge from a need to the node that produced it. Trust Release §2 (P0).
One thing that **has** an issue but appears in no report: **#13 circuit breaker**. Neither the CTO report nor the Trust Release report raises it; the nearest item is "rate limiter" under the CTO's security pack (P0-3), which is a different mechanism. The issue itself already says a worked example in the docs might close it outright. It is scheduled last, as documentation.
**API freeze is deliberately not a phase.** `README.md:276` already declares it under `**next**`. It needs the RC boundary, and freezing a public surface before #10 lands would freeze an API that is still missing its observability contract. What this plan adds instead is a stability *contract* — a statement of which areas are volatile today, which promises nothing and commits to no date (Task 6.1).
**Out of scope: #21 and #17.** Both are claimed by `hgshreyas` with the design already settled in the issue threads. Do not touch them.
---
## Phase 0: Unblock releases
### Task 0.1: Scope the audit gate in stage and release
**Files:**
- Modify: `.github/workflows/stage.yml`
- Modify: `.github/workflows/release.yml`
`AGENTS.md:71` states the policy: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. `ci.yml:56-59` implements it. `stage.yml:21` and `release.yml:26` run bare `npm audit`, so a dev-only advisory blocks a publish. This is drift, not a second policy.
That drift is what stopped work twice. The `nanoid` advisory reached the tree through `tsup → postcss → nanoid` — a build-tooling path that ships to nobody.
**Step 1:** In both files, change `npm audit` to `npm audit --omit=dev`, and add a non-blocking full `npm audit` with `continue-on-error: true` after it so the advisory is still visible in the log.
**Step 2:** Carry a comment on the blocking step pointing at the rule, in the voice `ci.yml` already uses — the next person to read it should see a decision, not an omission.
**Verify:** `grep -n "npm audit" .github/workflows/*.yml` — every blocking occurrence carries `--omit=dev`.
---
## Phase 1: Prove portability, and publish to JSR
These are one phase because they are one subject. The type error JSR found is on the `app.fetch` path, which is the path Deno, Bun and edge all use; a runtime matrix would have caught it first. Fixing them together means the matrix has a green baseline to protect.
### Task 1.1: Fix the `BodyInit` hole on the Fetch path
**Skills:** `@superpowers:test-driven-development`
**Files:**
- Modify: `src/http/web.ts`
- Test: `test/` (the Fetch adapter suite)
Gitea #19 reports, from a real `deno publish --dry-run`:
```
TS2345: Argument of type 'string | Buffer<ArrayBufferLike> | null' is not
assignable to parameter of type 'BodyInit | null | undefined'.
--> src/http/web.ts:112:23
```
`Buffer` is not a valid `BodyInit` under Deno's lib. It works at runtime because implementations are forgiving, which is what makes it worth fixing before a user reports it as a bug: it is a genuine typing hole on the runtime-agnostic path, not a JSR formality.
**Step 1:** Write a failing test that drives a `Buffer` body through the Fetch adapter and asserts the response body round-trips byte-for-byte.
**Step 2:** Narrow the body to a real `BodyInit` at the boundary — convert the `Buffer` to a view its type declares, rather than casting the error away. A cast would keep the hole and hide it.
**Step 3:** Confirm the test passes and `npm run typecheck` is clean.
### Task 1.2: Give the slow-type sites explicit return types
**Files:**
- Modify: `src/metadata.ts` (11 sites)
- Modify: `src/params.ts` (6 sites)
Two shapes, both mechanical: `missing-explicit-return-type` on factory functions (`routeDecorator` at `src/metadata.ts:103`, `envelope` at `src/params.ts:35`) and `missing-explicit-type` on the exported constants built from them (`export const Get = routeDecorator('GET', 'buffer')` at `src/metadata.ts:126`).
**Do not pass `--allow-slow-types`.** That flag degrades generated declarations and makes type checking 1.5–2× slower for consumers, in the framework whose central claim is type safety. Shipping it would contradict the pitch on its own install page.
**Step 1:** Annotate the factories first — several of the constant errors resolve on their own once the factory's return type is written down.
**Step 2:** Annotate whatever constants remain.
**Step 3:** `deno publish --dry-run` reports zero slow types, with no flags.
**Verify:** `npm run typecheck` and `npm test` still clean; the public types in `dist/` are unchanged or strictly more precise.
### Task 1.3: Runtime matrix in CI
**Files:**
- Modify: `.github/workflows/ci.yml`
The suites exist and CI ignores them. Add a matrix job that runs `test:deno`, `test:bun` and `test:edge` alongside the Node build.
**Step 1:** Add a job with the three runtimes, each installing its own toolchain. Keep it a separate job from `build` so a Bun failure reports as a Bun failure and does not bury the Node lint output — the same reasoning `ci.yml:53` already applies to the audit step.
**Step 2:** Confirm the forge difference documented at `AGENTS.md:73` does not bite: GitHub reads `pull_request` workflows from the base branch, so this workflow change cannot validate itself and must reach the base before it gates anything.
**Step 3:** Publish the resulting capability matrix. `README.md:273` already claims all four runtimes; the matrix is what turns that claim into evidence.
**Verify:** A deliberate break in shared code fails the Deno job and not only the Node one.
### Task 1.4: Claim the JSR scope and publish
**Files:**
- Modify: `deno.json`
- Modify: `.github/workflows/release.yml`
**Blocked on Diego and not delegable:** `@green-tea` on jsr.io must be claimed with a GitHub account.
**Step 1:** Add `name`, `version` and `exports` to `deno.json`. Decide whether all four entry points (`.`, `./deno`, `./bun`, `./edge`) are exported or only the Deno one.
**Step 2:** Publish from the same `v*` tag that publishes to npm, using GitHub Actions OIDC. `release.yml` already holds `id-token: write` for npm Trusted Publishing, so JSR needs no new secret.
**Step 3:** Nothing here justifies cutting a release on its own — it rides along with the next version cut that has a reason.
---
## Phase 2: The shutdown cluster
Four open issues, all consequences of the `close({ timeoutMs })` contribution that just merged (`3dcf784`). Treated as one deliverable because they are one subject: Trust Release §14 (P1, lifecycle guarantees) and CTO P0-4 (production checklist, shutdown).
Order matters — the bug first, then the API, then the docs that describe the finished API.
### Task 2.1: #20 — `finish()` reads its timer before declaration
A use-before-declare bug. Smallest item in this plan and it is already shipped. Fix it, and leave a test that fails if the ordering regresses.
### Task 2.2: #19 — shutdown deadline settable at `createApp` level
The 10s deadline is hardcoded. Make it configurable at app level, with `close({ timeoutMs })` still overriding per call.
Per `AGENTS.md:81`, a new option on a public interface **must** also change `src/app/types.ts`. An implementation that grows a parameter alone is unreachable for anyone consuming the package.
### Task 2.3: #15 — graceful shutdown is Node-only — **DECIDED, DONE**
**Decision: `app.close()` stays Node-only; each adapter that owns a server offers the same `close({ timeoutMs })`.** The framework's line is *it handles architecture, you handle business*, and draining is owned by whoever holds the handle.
What the runtimes turned out to allow, measured rather than assumed:
| Runtime | Drain | After the deadline |
|---|---|---|
| Node | `server.close()` | `closeAllConnections()` — remainder cut |
| Bun | `stop(false)` | `stop(true)` — remainder cut |
| Deno | `shutdown()` | **returns anyway** — remainder ends with the process |
Deno cannot escalate. Aborting the serve signal while `shutdown()` is pending throws `BadResource: Bad resource ID` from Deno's own listener — uncaught, and fatal under `deno test`. Measured on Deno 2.9: abort alone is clean, abort after shutdown is not. So on Deno the deadline bounds how long `close()` waits, not when connections die, and `runtimes.md` says so in a table rather than averaging the three.
`closeWithDeadline` (`src/http/shutdown.ts`) is shared so the two adapters cannot drift into different meanings of the same `timeoutMs`, and it resolves on its own timer rather than awaiting the force call — Bun's `stop(true)` was measured waiting out a handler with a pending timer, which is the unbounded wait the deadline exists to prevent.
### Task 2.5: Shutdown as an extension point — **OPEN, needs its own design**
Raised while deciding #15: shutdown should emit signals so plugins and providers register their own teardown, instead of every consumer writing `process.on('SIGTERM', …)` by hand. Same principle as the decision above — the framework owns the plumbing.
It does **not** fit the existing `Bus`, and that is the finding worth carrying forward. `Bus.on` takes a synchronous listener (`src/bus.ts:29`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:38`, `catch {}`). That is deliberate — observers must never break the pipeline — but a plugin closing a database connection needs shutdown to *wait for it*. Registering a teardown is not observing an event, and bending `Bus` to do both would cost the guarantee that makes it safe.
So it needs: an await-aware teardown registry, a new surface on `PluginApi` (public API — `src/plugin.ts:19`), and a decision about provider cleanup. That is Trust Release §14 "Graceful lifecycle guarantees" and CTO P0-4, and it belongs in a design document rather than inside a bug-fix cluster. Sequence it with Phase 3, whose observability contract shares the same lifecycle vocabulary.
### Task 2.4: #18 — docs still describe `close()` without the timeout
Last, so it documents the finished API rather than being rewritten twice. If Phase 4 has already run, this lands in the docs repository instead.
---
## Phase 3: Observability (#10)
The one every report puts first, and the only one that needs a design document before code.
### Task 3.1: Design document
**Files:**
- Create: `.specs/2026-XX-XX-green-tea-observability-design.md`
Write the design before any implementation, following the design/plan pairing already in `.specs/`.
The issue is explicit that this is **one design, not six**: an injectable logger, structured output and tracing hooks are the same API decision, and solving them separately leaves three mechanisms that do not fit together.
Inputs to reconcile:
- The scope in GH #10 — injectable logger contract, JSON default with human-readable dev output, request/response logging as a composable step rather than global middleware, hooks an exporter can attach to, metrics export.
- The Trust Release event vocabulary (§4) — `request.*`, `route.*`, `step.*`, `provider.*`, `graph.*`, `websocket.*`, `stream.*` — and its context fields (`requestId`, `traceId`, `route`, `transport`, `step`, `duration`, `status`, `scope`, `runtime`).
- Trust Release §6, graph timing. Per-step timings are close to free because the graph already knows every node, but the instrumentation stays opt-in if overhead is measurable. Measure before deciding.
Hard constraint, restated from `AGENTS.md:11`: **no new runtime dependency.** Core stays on `reflect-metadata` alone. An OpenTelemetry exporter is a separate package (`@green-tea/opentelemetry`), never a core dependency.
Decisions the design must settle rather than leave open:
1. Is the logger a provider like any other, or a distinct registration?
2. Do events go through one emitter or through per-category hooks?
3. Does a step failure emit `step.failed` and `request.failed`, or only the outer one?
4. Do long-lived streams and WebSockets emit per-message events, or only lifecycle ones? (The same reasoning that keeps upgrades out of the #21 gate applies.)
### Task 3.2: Implement to the approved design
Do not start before the design is reviewed. Write the implementation plan from the approved design, as `.specs/` already does for every other subsystem.
### Task 3.3: Rewrite the observability paragraph in `README.md`
`README.md:246` currently reads "**No observability layer, either.**" and points at issue #10. When #10 lands, that paragraph is wrong and it is the single most load-bearing sentence in the CTO's assessment. Rewriting it is part of the work, not follow-up.
`AGENTS.md:83`: new public API needs a note in `README.md`.
---
## Phase 4: Split the documentation site
Verified before scheduling: `website/` is self-contained. 26 source files, no path escaping the directory, and the `@green-tea/core` mentions inside the `.md` files are example code, not build-time imports.
The coupling to core is five lines:
| Location | What |
|---|---|
| `.github/workflows/ci.yml:62-65` | `npm ci --prefix website`, `npm audit --prefix website`, `npm run docs:build` |
| `package.json:100-101` | `docs:dev`, `docs:build` |
Plus two README references to update: `README.md:254` (the docs link) and `README.md:263` (`npm run docs:dev`).
**The real work is not the move.** No workflow anywhere in `.github/workflows/` deploys the site. `website/astro.config.mjs:6` points at `green-tea.expressive-tea.io` and the deploy happens by hand today. The new repository is where that pipeline gets built for the first time.
### Task 4.1: Create the repository and move `website/` with its history
Preserve commit history for the moved directory rather than landing it as one squashed import.
### Task 4.2: Build the deploy pipeline
The thing the docs never had. Build on push to the default branch, deploy to `green-tea.expressive-tea.io`.
### Task 4.3: Remove the website from core
Delete the three `ci.yml` steps, the two `package.json` scripts, and `website/`. Update `README.md:254` and `README.md:263`.
### Task 4.4: Guard the seam the split opens
The split trades CI coupling for drift risk: docs and code can now disagree without anything failing. #18 exists precisely because docs fell behind an API change. Decide what catches that — a link check against the published package, a docs job triggered from core releases, or an explicit accepted risk written down. Do not leave it unstated.
**Resolved 2026-08-17: accepted risk, stated where the rule is read rather than where it is published.** The first pass put it in both READMEs and stopped there, which satisfies the letter of "do not leave it unstated" and little else — the core README's copy sits in *Docs & development*, a section a user reads and a contributor changing an API does not.
What governs behaviour is `AGENTS.md:83` and the pre-PR checklist in `CONTRIBUTING.md`, both of which already carried *"New public API needs a note in `README.md`"* — written before the split and never updated for it, so the two documents that a contributor (or an assistant) actually reads mid-change said nothing about the new repository. Both now name it and say why the rule exists, since a rule without its reason is the first one dropped under time pressure.
**The link check was prototyped and then rejected, on measurement rather than taste.** It had been recommended here as the one worth building; building enough of it to decide showed otherwise.
- Every symbol the pages import is real: **24 distinct imports from `@green-tea/core` across 25 pages, all present** among the package's 101 exports. No bug for it to find today.
- More decisively, **an import check could not have caught #18**. That issue was *"docs still describe `close()` without the timeout"* — the method existed; the **option** was undocumented. Imports are the part that does not drift. Options, option shapes and method signatures are.
- Extending it to options and methods was tried and produced **17 findings, all 17 false** — a regex cannot tell a nested `tls: { key, cert }` from a top-level option, `app.example.com` in a CORS example from an `app.*` call, or prose describing Express's `app.use()` from a green-tea API. A check with that signal-to-noise trains people to ignore it, which is worse than not having one.
- What would genuinely catch #18's class is **type-checking the code blocks** (twoslash / Expressive Code). That requires the documentation repository to depend on `@green-tea/core` and its examples to be complete and compilable — many are deliberately fragments. It buys the guarantee back by spending exactly the independence this split was for.
So the accepted risk stands, now as an informed choice rather than a default. A **docs job triggered from core releases** was the other option and remains the weaker one: it fires after the API has already shipped.
One page is covered by more than a rule: `test/circuit-breaker-recipe.test.ts` executes the recipe published in `guides/circuit-breaker.md`. That is one page of twenty-five, and is not a substitute for the check above.
---
## Phase 4.5: Move the JSR gate off the tag — **run this before Task 2.5's code**
Numbered as an insertion because that is what it is, the same way Task 2.5 was. It is small, and its position is the whole point: **Task 2.5 adds public API** — `Hooks`, `TeardownFn`, `PluginApi.onShutdown` — and exported types are exactly what JSR's slow-types check polices. Writing that surface with no JSR gate on pull requests means learning at release time whether the shape is publishable.
Verified before writing this, because the first reading was wrong: `release.yml:42` **already** runs `deno publish --dry-run`, before publishing to either registry, and its comment already makes the argument — *"JSR checks things npm never looks at — slow types, module analysis — and learning about them after npm has published leaves the tag half-shipped."* Phase 1 already published to JSR, and a dry run passes today, slow-types check included.
The gap is not that the gate is missing. It is **when it runs**: only on a version tag. A change that breaks Deno's type-checker or introduces a slow type lands on `main` in silence and surfaces while cutting a release — the moment `release.yml`'s own npm-audit comment identifies as having the least time to judge a fix. The workflow makes that argument for advisories and not for JSR.
Worth stating plainly: `deno publish --dry-run` type-checks the four entry points with **Deno's** checker and lib, which is not the same pass as `tsc --noEmit -p tsconfig.json`. A second compiler over the same source is a real gate, not a formality — Task 1.1 exists because that second compiler found a hole the first one did not. And JSR serves `src/` directly, so anything it would reject is something a JSR user gets.
### Task 4.5.1: Run the JSR gate on every push and pull request
**Files:**
- Modify: `.github/workflows/ci.yml`
Add `deno publish --dry-run` to the `runtimes` job's Deno leg, which already installs Deno. Measured at **0.68s** against 2.0s for the whole vitest suite — cheap enough that placing it anywhere else is over-thinking.
Leave `release.yml` alone. The tag-time gate stays: it is the one that protects an immutable JSR version, and a gate that runs twice is not a duplication worth removing.
### Task 4.5.2: One command for the whole matrix
**Files:**
- Modify: `package.json`
- Modify: `README.md`
`npm test` is Node-only, deliberately — it is the fast local loop, 2s, and booting Deno, Bun and workerd into it would tax every run to catch what CI already catches on every push. The `runtimes` job means these suites are not unguarded; what is missing is a way for a contributor to run everything with one command before pushing.
Add `test:all` — `npm test` plus `test:deno`, `test:bun`, `test:edge`, and the JSR dry run. Say in `README.md` which one is the fast loop and which one is the pre-push check, so the split reads as a decision rather than an oversight.
### The decorator warning is expected — no task, and no new documentation
Every `deno publish --dry-run` prints:
```
Warning experimentalDecorators compiler option is deprecated and may be removed at any time
```
Whoever adds this gate to CI will see that warning arrive with it and should not treat it as something the gate found. It is **already documented, and better than a new note would manage**: `README.md:233` (*Why legacy decorators*) and `concepts/the-graph.md:43` in the docs repository both carry the reasoning — parameter decorators are deliberately absent from the TC39 Stage 3 proposal, so `handler(@param('id') id: string)` is only expressible with legacy decorators, and Stage 3 means the replacement is not finalized either.
An earlier draft of this phase claimed the framework "depends on `emitDecoratorMetadata`". That is **wrong**, and both documents already say so: argument positions are recorded explicitly, and `grep -rn 'design:type\|design:paramtypes' src/` returns nothing — the flag is set in `tsconfig.json` and `deno.json`, but no `design:*` reflection is read anywhere. Legacy parameter decorators are the only legacy surface this project actually depends on.
Do not turn the warning into an error to force the issue: that breaks releases on someone else's schedule.
---
## Phase 5: Close #13 as documentation
### Task 5.1: Write the circuit-breaker recipe
**Files:**
- Create: a guide page in the docs repository
The issue was opened to decide placement, not to commit to a core implementation, and it answers itself: core adding resilience policy would contradict the one-runtime-dependency rule. A circuit breaker fits a step — it needs whatever provides the client, it produces a guarded caller, and the graph already sequences it correctly.
Write it as a worked example, then close #13 pointing at the page. First real content in the new repository, which is also a live test of the deploy pipeline from Task 4.2.
---
## Phase 6: The stability contract
### Task 6.1: A stability paragraph in `Honest scope`
**Files:**
- Modify: `README.md`
Not a roadmap, and not the API freeze. A statement of which areas are volatile *today* — present state, no dates, no delivery commitment. This is spare-time work by one person and a roadmap it cannot keep would cost more trust than it earns.
`## Honest scope` (`README.md:240`) already carries exactly this voice: mesh is alpha, there is no observability layer, runtimes differ in what they can offer. The stability tiers belong in that section, in that register, as one paragraph.
Roughly the split the Trust Release report proposes in §8 — graph semantics, providers, steps and controllers as the stable candidates; decorator syntax, CLI and plugin APIs as beta; mesh and distributed capabilities as experimental. Verify each claim against the code before writing it down; a stability tier asserted and then broken is worse than none.
`README.md:266-276` keeps its `**next**` line unchanged. API freeze stays declared there and gets planned separately, near the RC.
---
## Verification
Per `AGENTS.md:28`, run before proposing any task as finished:
```bash
npm run lint && npm run format:check && npm run typecheck && npm test
```
And from Phase 1 onward the runtime suites are no longer optional, because CI runs them:
```bash
npm run test:deno && npm run test:bun && npm run test:edge
```
Conventional Commits focused on the *why*, every commit signed off (`git commit -s`), no AI co-authoring attribution.
@@ -1,211 +0,0 @@
# Shutdown teardown — Design
**Task:** 2.5 in the [trust-release plan](./2026-08-16-trust-release-plan.md) · Trust Release §14, CTO P0-4 · **Status:** reviewed, D1–D8 settled · **Constraint:** no new runtime dependency
---
## The diagnosis
An application closing a database connection today writes `process.on('SIGTERM', …)` by hand, because the framework offers nowhere to put that. `closeApp` (`src/app/index.ts:1009`) closes mesh links, streams and the HTTP server, and knows nothing about plugins or providers. `LifecycleEvent` (`src/bus.ts:2`) has no shutdown event at all — a plugin cannot even *observe* that the app is closing, let alone act on it.
The framework owns the plumbing everywhere else. This is the hole.
### Why the existing `Bus` cannot carry it
`Bus.on` takes a synchronous listener (`src/bus.ts:62`) and `emit` neither awaits nor surfaces failures (`src/bus.ts:85`). Both are deliberate: observers must never break the pipeline. A plugin closing a database connection needs shutdown to *wait for it*, and needs its failure to be visible.
The observability design already settled this rather than leaving it open — `D2` of [2026-08-16-observability-design.md](./2026-08-16-observability-design.md):
> **This is exactly why shutdown teardown does not belong here.** A teardown must be *awaited*; an observer must not be. Same word, opposite guarantees, so they get different surfaces.
Conceptually this is still an event — *"the app is closing, do you have anything to do first?"* — and callers may reasonably think of registering as subscribing. Mechanically it is a separate await-aware registry, because bending `Bus` to do both would cost the guarantee that makes `Bus` safe.
### What "isolation is structural" actually protects
`src/plugin.ts:26` reads *"Hand the plugin ONLY on() and add(). No emit, no other scope. Isolation is structural."* That sentence is load-bearing and it is easy to over-read, so this design states what it does and does not cover — verified against the code, because the answer surprised both people in the conversation that produced this document.
**Enforced today:**
- A plugin receives only `bus.on` and `scope.add` — no `emit`, so it cannot fabricate lifecycle events, and no reach into the registry.
- `setRunner` (`src/app/index.ts:320`) throws on duplicate names, so a plugin cannot silently replace an existing provider or step.
- Plugin nodes carry `origin: 'plugin'` and stay attributable in the graph.
**Not enforced today:**
- `runSteps` passes the live context object to every step and merges its output with `Object.assign(context, output)` (`src/pipeline.ts:73-74`). No collision check. A plugin's step can mutate the context directly and can overwrite any key another step provided.
- `mountPlugins` (`src/app/index.ts:161`) runs *before* `provideBuiltins` (`:162`), and `provideBuiltins` skips anything already registered — so a plugin registering a node named `logger` or `rooms` replaces the builtin.
So the guarantee is about the **registration surface**, not about the **runtime context**. Teardown touches neither: it adds a third thing a plugin may register, and never sees a request context. The context-integrity question is real but pre-existing and out of scope here — it is recorded at the end so it is not lost.
---
## Decisions
### D1 — A teardown registry, not a `Bus` event
One list of callbacks, owned by the app, awaited on close. Not a `LifecycleEvent`, for the reason `D2` of the observability design already gives.
The registry is the entire mechanism. Everything below is a door into it.
### D2 — Three doors, one registry: one order, one failure policy
| Door | Who uses it | Shape |
|---|---|---|
| `hooks: [...]` in `createApp` | an application that wants lifecycle participation and nothing else | `onShutdown()` |
| `PluginApi.onShutdown` | a plugin that also extends the graph | `onShutdown()` |
| `dispose()` on a `@Provider` class | the provider that opened the resource | optional method |
Three entry points, **one** registry, **one** order, **one** failure policy. If they ever acquire separate ordering relative to each other, this design has failed and two mechanisms exist again.
The doors differ by intent, not by semantics. Today the only way into the lifecycle is to write a plugin, and a plugin means *"I want to extend the graph"* — someone who only wants to close a connection is forced to declare an extension they do not want.
### D3 — `PluginApi` gains a property; the `Plugin` signature does not change
`Plugin = (api: PluginApi) => void` is untouched. `onShutdown` joins `bus` and `scope` on the object a plugin already receives. Every existing plugin ignores it and behaves identically.
This is why the hooks framing is better than widening the plugin contract directly: it removes the only break the earlier sketch had. See "What breaks" below — the answer is now *nothing at runtime*.
### D4 — Teardown callbacks receive no arguments
```ts
type TeardownFn = () => void | Promise<void>;
```
State lives where the resource was created, and the closure already holds it:
```ts
class MyPlugin {
#db = new Pool();
mount(api: PluginApi) {
api.onShutdown(() => this.#db.end()); // the closure already has it
}
}
```
A provider's `dispose()` is the same picture — the instance holds its own connection.
**Nothing needs to cross scopes**, which is what makes a container reference, an app reference, or any transport mechanism unnecessary here. A bus solves *"tell someone I do not know"*. Teardown is *"run this thing I registered"*. Handing a hook a resolver would make the container reachable from a hook and would be a genuine widening — declined.
If an argument is ever needed, adding one to a callback that receives none is additive. The reverse is not.
### D5 — Order is the reverse of boot
Providers boot in topological order (`bootProviders`, `src/app/index.ts:664`), so they tear down in reverse: if `cache` needs `db`, `cache` closes first. Registration order within the same tier is preserved.
Sequential, not parallel. Reverse-topological order only means something if it is respected, and parallel teardown discards it.
### D6 — A failing teardown is logged and shutdown continues
The failure goes to the injectable `Logger` and `close()` still resolves. One plugin's broken teardown must not strand the remaining ones or hang the process.
This mirrors `Bus`'s philosophy — a subscriber cannot break the system — but with the visibility `Bus` lacks. `Bus` swallows silently because no logger existed when it was written; one exists now.
The counter-argument was weighed and rejected: a `close()` that reports success after losing data is arguably worse than one that fails loudly. It loses because the alternative is worse in the common case — a process that will not exit is a worse operational failure than one that exited with a warning in the log, and the warning is not silent.
### D7 — Triggered from each runtime's real close
`app.close()` returns at its `if (!server)` guard on Deno, Bun and the edge (`src/app/index.ts:1026`). Hanging teardown off `app.close()` would make behaviour differ per runtime, which the multi-runtime constraint forbids.
| Runtime | Entry point |
|---|---|
| Node | `app.close()` → `closeApp` |
| Deno | `serveDeno(app).close()` → `closeWithDeadline` |
| Bun | `serveBun(app).close()` → `closeWithDeadline` |
| edge (workerd) | **none — no shutdown exists** |
`serveDeno` and `serveBun` already receive the app, so their `close()` can run its teardown without the user calling two things. `closeWithDeadline` (`src/http/shutdown.ts`) is already shared by both *"so the two adapters cannot drift into different meanings of the same `timeoutMs`"* — the same argument applies here, and it is why teardown belongs in that shared function rather than in each adapter.
Node, Deno and Bun behave identically. **Edge cannot, and no design fixes it**: workerd never closes, so there is nothing to intercept. A plugin that depends on teardown for correctness is broken there. This is a runtime capability difference and belongs in the `runtimes.md` table beside `@Html` file mode and mesh, not in a footnote.
### D8 — Teardown shares the close budget, and `close()` never exceeds `timeoutMs`
`timeoutMs` is a hard ceiling on the whole of `close()`. That is what it is for, and nothing here is allowed to make `close()` take longer than the caller asked for.
- Drain runs first. Teardown runs after, within the same budget.
- **Unset** (the default): the drain may use the whole of `timeoutMs`, and teardown gets whatever is left — possibly nothing. No reservation is taken from a caller who never asked for one.
- **Set**: it **reserves**. The drain is bounded to `timeoutMs − teardownTimeoutMs`, so teardown is guaranteed its slice.
- `teardownTimeoutMs > timeoutMs` is rejected at `createApp`, not silently clamped.
An earlier draft of this decision said the option "defaults to `timeoutMs`". Read together with the reservation rule that gives the drain `timeoutMs − timeoutMs`, which is zero, and no drain at all. The default is *no reservation*, which is a different statement.
Reserve rather than cap, and the difference is the whole reason this decision exists. A cap only bounds how long teardown *may* run; it does nothing when the drain has already spent the budget, and teardown then gets zero milliseconds and the database does not close. Reserving is what makes `teardownTimeoutMs` a guarantee rather than a ceiling on something that may never run.
---
## The contract
```ts
/** A teardown callback. Receives nothing: state lives in the closure that registered it. */
export type TeardownFn = () => void | Promise<void>;
/** Lifecycle participation without extending the graph. Methods are optional so later
* stages (onBoot, onReady) can join without a breaking change. */
export interface Hooks {
onShutdown?: TeardownFn;
}
/** Unchanged except for the third capability. `Plugin` keeps its signature. */
export interface PluginApi {
bus: { on: Bus['on'] };
scope: ScopeApi;
onShutdown(fn: TeardownFn): void;
}
createApp({
modules: [...],
plugins: [...],
hooks: [...], // new
shutdownTimeoutMs: 10_000, // existing
teardownTimeoutMs: 2_000, // new, optional; <= shutdownTimeoutMs
});
@Provider({ provides: 'db' })
class Db {
provide() { /* ... */ }
async dispose() { /* optional; called if present */ }
}
```
### What this costs internally
`collectProviders` (`src/app/index.ts:345`) constructs each provider with `new ProviderClass()` and captures the instance in a closure. **The instance is never stored anywhere reachable**, and `Container.bindings` is private with no iteration, so there is no handle to call `dispose()` on today.
Keeping provider instances requires a new field on `Registry`. That is internal, not public API, and it is the part nobody sees coming from reading "add `onShutdown` to `PluginApi`".
### What breaks
**At runtime: nothing.** `Plugin`'s signature is unchanged, `Hooks` methods are optional, and `dispose()` is called only if present.
**At compile time: nothing either**, given D3. Widening `PluginApi` would have broken anyone constructing one as a literal — typically a test mock — but `onShutdown` is a required property on an object the framework builds and hands out, never one a user implements. Should that turn out to be wrong for some consumer, it goes in the CHANGELOG with the reason: making it optional would force every plugin to check for it and would turn a capability into a conditional forever.
---
## Out of scope, deliberately
- **`onBoot` / `onReady`.** `Hooks` is shaped as an object of optional methods so they can be added without a breaking change, but only `onShutdown` ships. The shape accommodates them; this design does not build them.
- **Request-scope cleanup.** Request values are recomputed per resolve (`src/container.ts`) and are garbage, not resources. Only app-scope teardown is in scope.
- **Edge teardown.** Not possible. Documented, not worked around.
- **A context argument for teardown callbacks.** D4. Additive later if a real case appears.
- **Context integrity.** A plugin's step can overwrite context keys and can replace the `logger` and `rooms` builtins. Real, pre-existing, unrelated to teardown, and recorded here only so the finding is not lost with this conversation.
---
## Verification this design must survive
1. A plugin registering `onShutdown` has it awaited before `close()` resolves — on Node, Deno and Bun, asserted per runtime rather than once.
2. A provider with `dispose()` has it called; one without is skipped.
3. Reverse-topological order: `cache` needing `db` tears down first.
4. A throwing teardown is logged and the remaining ones still run; `close()` resolves.
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
8. `close()` on an app with no teardown registered costs nothing measurable — this is not a request path, but it is still on the shutdown path of every app that uses none of it.
## Documentation this design changes
All of these now live in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs):
- `guides/plugins.md:7` — states plugins have exactly two capabilities. Becomes three, and the isolation wording needs the precision from the diagnosis above rather than a restatement.
- `guides/runtimes.md:44` — the shutdown table gains teardown, and edge gains its exception.
- `guides/dependency-injection.md:56` — describes what `close()` does; it now does one more thing.
- `README.md` — new public API, per `AGENTS.md:83`.
@@ -1,141 +0,0 @@
# Shutdown teardown — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Design:** [2026-08-17-shutdown-teardown-design.md](./2026-08-17-shutdown-teardown-design.md) — reviewed, D1–D8 settled. Do not re-decide them here.
**Goal:** Give plugins, providers and applications somewhere to put teardown, so closing a database connection stops meaning `process.on('SIGTERM', …)` by hand. Closes Task 2.5 of the [trust-release plan](./2026-08-16-trust-release-plan.md); Trust Release §14, CTO P0-4.
**Architecture:** A new `src/lifecycle.ts` holds the registry and nothing else. `src/plugin.ts` and `src/app/index.ts` gain doors into it; `src/app/index.ts` (`closeApp`) and `src/http/shutdown.ts` (`closeWithDeadline`) gain the call that drains it. No new runtime dependency — `reflect-metadata` stays the only one.
**The thing to keep hold of:** three doors, one registry, one order, one failure policy. Any task that gives a door its own ordering or its own error handling has broken D2, whatever the tests say.
---
## Order
Tasks 1–3 build the mechanism and the doors; nothing observable changes until Task 4 wires it into `close()`. Task 5 is the runtime parity that D7 demands and is the one most likely to surface a surprise, so it does not go last. Documentation is Task 7 because it should describe the finished API rather than be rewritten twice.
---
### Task 1: The registry
**Files:**
- Create: `src/lifecycle.ts`
- Create: `test/lifecycle.test.ts`
The whole mechanism, with no knowledge of plugins, providers, apps or HTTP.
```ts
export type TeardownFn = () => void | Promise<void>;
```
It needs: register a callback, and run everything registered — sequentially, in reverse registration order (D5), awaiting each, catching each (D6), never throwing. A failing callback is reported through the injectable `Logger` and the next one still runs.
Keep the timeout **out** of here. Bounding is the caller's job, and it is already solved twice over by `closeApp` and `closeWithDeadline`; a third implementation is how the three drift into different meanings of the same number.
Tests: order is reverse of registration; a throwing callback is logged and does not stop the rest; a rejecting async callback is treated the same; an empty registry resolves; running twice does not re-run callbacks (`close()` is called twice by more real applications than anyone expects).
### Task 2: The plugin and hook doors
**Files:**
- Modify: `src/plugin.ts`
- Modify: `src/app/index.ts` — `mountPlugins`, `createApp` options
- Modify: `src/app/types.ts` — `Hooks` on the public options
- Modify: `test/plugin.test.ts`
`PluginApi` gains `onShutdown(fn: TeardownFn): void`, bound to the app's registry. `mountPlugin`'s comment at `src/plugin.ts:26` currently says a plugin gets `on()` and `add()` and nothing else; it now gets three things, and the comment says which and why — the isolation wording in the design's diagnosis is the precise version, not "isolation is gone".
`createApp({ hooks })` takes `Hooks[]`, an object of optional methods so `onBoot`/`onReady` can join later without a breaking change. Only `onShutdown` exists now.
Tests: a plugin registering `onShutdown` lands in the registry; a plugin that never calls it behaves exactly as before (D3 — this is the no-break guarantee, so it gets an explicit test rather than an assumption); hooks and plugins interleave in one order rather than running as two groups.
### Task 3: Provider `dispose()`
**Files:**
- Modify: `src/app/index.ts` — `collectProviders`, `Registry`
- Modify: `test/app.test.ts`
`collectProviders` (`src/app/index.ts:345`) builds each provider with `new ProviderClass()` and captures the instance in a closure where nothing can reach it. Keep the instances on `Registry` so a `dispose()` can be called.
Registration order must follow boot order, not declaration order, so that D5's reverse-topological teardown falls out of the registry's reverse-registration rule rather than needing a second sort. That means registering a provider's `dispose()` as it boots in `bootProviders` (`:664`), not when it is collected.
A provider that failed to boot must not have `dispose()` called — it never provided anything. Optional providers that degraded (`degradedProviders`) are exactly this case and already tracked.
Tests: `dispose()` is called; a provider without one is skipped; `cache` needing `db` tears down first; a provider that failed to boot is not disposed.
### Task 4: Drain the registry on close — Node
**Files:**
- Modify: `src/app/index.ts` — `closeApp`
- Modify: `test/app.test.ts`
Teardown runs **after** the server drain and **before** `close()` resolves (D8): in-flight requests may still need the database while draining.
The budget: `timeoutMs` is a hard ceiling on the whole of `close()`. `teardownTimeoutMs` **unset** means no reservation — the drain may use all of `timeoutMs` and teardown gets what is left, possibly nothing. **Set**, it reserves: the drain is bounded to `timeoutMs − teardownTimeoutMs`. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp` rather than being clamped silently.
`closeApp` already arms a timer before `finish` exists, for a reason its comment spells out at length. Read that comment before touching the ordering.
Tests: a registered teardown is awaited before `close()` resolves; a hanging teardown does not let `close()` exceed `timeoutMs`; a slow drain plus a set `teardownTimeoutMs` still leaves teardown its reserved slice; `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
### Task 5: Runtime parity — Deno and Bun
**Files:**
- Modify: `src/http/shutdown.ts` — `closeWithDeadline`
- Modify: `src/deno.ts`, `src/bun.ts`
- Modify: `test/deno/*`, `test/bun/*`
`app.close()` returns at its `if (!server)` guard on Deno and Bun (`src/app/index.ts:1026`), so teardown cannot hang off it without behaviour differing per runtime — which the multi-runtime constraint forbids (D7).
`serveDeno(app)` and `serveBun(app)` already hold the app, so their `close()` runs the teardown and the user calls one thing, not two. It goes in `closeWithDeadline` rather than in each adapter, for the reason that function already exists: so the two cannot drift into different meanings of the same `timeoutMs`.
Deno cannot escalate from graceful to forced — its deadline bounds how long `close()` waits, not when connections die. That asymmetry already exists and this must not make it worse.
These suites are **not** in `npm test`. Run `npm run test:deno` and `npm run test:bun` explicitly, and do not report this task done on the strength of vitest passing.
Tests, per runtime rather than once: a teardown registered on a Deno/Bun app is awaited by that server's `close()`.
### Task 6: Edge — document the hole, do not paper over it
**Files:**
- Modify: `src/edge.ts` — doc comment only
workerd never closes, so there is nothing to intercept and no design fixes it. A plugin depending on teardown for correctness is broken there.
No shim, no fake `close()`, no best-effort call on an unload event that does not exist. The only change is a doc comment stating it, so someone reading `edgeHandler` learns it there rather than in production. The user-facing half is Task 7.
### Task 7: Documentation
**Files:** all in [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs)
- Modify: `src/content/docs/guides/plugins.md` — line 7 says plugins have exactly two capabilities; it is three now, and the isolation sentence needs the design's precision rather than a restatement
- Modify: `src/content/docs/guides/runtimes.md` — the shutdown table gains teardown, and edge gains its row
- Modify: `src/content/docs/guides/dependency-injection.md` — line 56 describes what `close()` does
- Modify: `README.md` in core — new public API, per `AGENTS.md:83`
- Modify: `CHANGELOG.md` in core
Two repositories, one change. This is the first real test of the seam Phase 4 opened, and nothing fails if it is skipped — which is the point of doing it in the same session rather than leaving it to a follow-up.
---
## Out of scope
- `onBoot` / `onReady`. `Hooks` is shaped to accommodate them; this plan does not build them.
- Request-scope cleanup. Request values are recomputed per resolve and are garbage, not resources.
- Edge teardown. Not possible.
- A context argument for teardown callbacks (D4). Additive later if a real case appears.
- Context integrity — a plugin's step can overwrite context keys and replace the `logger` and `rooms` builtins. Real, pre-existing, and recorded in the design's out-of-scope section so it is not lost.
## Verification
The design's list, restated as the gate for calling this done:
1. A plugin's `onShutdown` is awaited before `close()` resolves — asserted on Node, Deno and Bun separately.
2. A provider with `dispose()` has it called; one without is skipped; one that failed to boot is not disposed.
3. Reverse-topological order: `cache` needing `db` tears down first.
4. A throwing teardown is logged, the rest still run, `close()` resolves.
5. A hanging teardown does not make `close()` exceed `timeoutMs`.
6. `teardownTimeoutMs > shutdownTimeoutMs` throws at `createApp`.
7. An existing plugin that never calls `onShutdown` behaves exactly as before.
8. `close()` on an app with no teardown registered costs nothing measurable.
Plus the gates every change here passes: `npm run lint`, `npm run complexity:check`, `npm run typecheck`, `npm test`, and — because Task 5 exists — `npm run test:deno`, `npm run test:bun`, `npm run test:edge`.
@@ -1,89 +0,0 @@
# A teapot that may be absent, declared per teapot
**Status:** planned, 2026-08-18
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
**Mesh stays alpha.**
## The decision
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
away is a degraded checkout; an authorization provider being away is not a degraded anything.
```ts
mesh: {
teapots: [
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
{ url: authUrl, secret }, // 'fail' — the default
],
}
```
## Why `expects` is required for `'degrade'`, and not inferred
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
validation fails the boot anyway — degrading would fail identically, just later.
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
loudly.
It also pushes the developer to state what a service depends on, which is the same discipline the
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
`expects`, naming the teapot.
## Decisions
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
and throws `503`, naming the token and the teapot it belongs to.
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
simply do not exist locally, because a route needs a method and a pattern we were never told. A
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
silent.
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
logged and emitted.
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
instead of a boot manifest.
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
wrong, not a reason to write a second one.
**Note, 2026-09-06: that seam is gone.** `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback were removed along with the remote app-scope binding when the mesh stopped
exporting providers — with nothing cached between requests, there is nothing left to invalidate.
This does not block D6, and it is not the "seam was wrong" case either: a degraded token swaps the
*runner* behind a step node, which is a graph mutation, not a container rebind. It never needed the
seam. Whatever the swap is written on, it is still one mechanism, decided when the work starts.
## Tasks
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
`expects`.
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
3. `degraded()` reporting per D3, plus the warn and the event.
4. Background attempt loop per D4, and adoption per D5/D6.
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
refused, and `'degrade'` without `expects` fails at `createApp`.
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
## Size
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
three runtimes. Not a follow-up to squeeze into another change.
@@ -1,108 +0,0 @@
# Mesh reconnection, with a refusing manifest policy
**Status:** planned, 2026-08-18
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
unusable in production; it does not move the label, because the label is a statement about how much
we know, and we will know more once this runs somewhere real.
## The problem
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
serially and throwing on any failure (`src/app/index.ts:631`):
- a teapot down at boot → the teacup does not start;
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
load-bearing. That is a worse operational property than any gap currently written in the docs.
## Vocabulary
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
words must not be used interchangeably in code, CHANGELOG or docs.
## Decisions
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
`connectLink` becomes "establish, then keep established".
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
configured" with "this dependency is temporarily away".
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
heartbeat, so reconnection never holds a process open on its own.
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
Rationale: the graph was validated at boot against the old manifest and is already running. A token
that vanished cannot be validated away after the fact, and serving requests against a manifest that
no longer backs the graph is how you get a 500 that looks like application code.
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
not spliced in. Documented, not silent.
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
place to be breaking.
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
provider is resolved once at boot and frozen into the container as `() => value`
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
call on the reconnect path, where its failure has nowhere to go. This closes the documented
"app-scope export survives its teapot with a stale value" gap.
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
inline in the reconnect handler — that function is what reconciliation will reuse.
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
cannot exit.
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
not a wait for `timeoutMs`.
## Tasks
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
`mesh:connect` on success (existing events; no new bus contract in alpha).
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
**Note, 2026-09-06:** this no longer exists. When the mesh stopped exporting providers, the
remote app-scope binding went with it, and `invalidateRemoteBindings`, the `rebind` array and the
`onReconnect` callback went with that — there is no cached value left to invalidate, so a
reconnected link is simply usable again on the next RPC. The rest of this plan shipped as
written; only this step has no counterpart in the code.
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
Reconnect defaults **on**. Validate at boot like the other mesh options.
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
where a swappable socket can break.
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
a defect, not a feature.
## Not in this plan
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
@@ -1,710 +0,0 @@
# A mesh that exports steps, not providers
> **For agentic workers:** REQUIRED SUB-SKILL: use `superpowers:subagent-driven-development` or
> `superpowers:executing-plans` to work through this task by task. Steps use `- [ ]` for tracking.
**Status:** planned, 2026-09-06
**Scope:** `src/mesh/protocol.ts`, `src/mesh/teapot.ts`, `src/mesh/teacup.ts`, `src/app/index.ts`,
mesh tests on all runtimes, `README.md`, `CHANGELOG.md`
**Mesh stays alpha.** It remains behind `experimental: true`, and the wire changes without a
protocol bump because of it.
**Goal:** A teapot exports **steps and routes only**. Exporting a `@Provider` becomes a boot error,
and a teapot that is unreachable at boot no longer stops the teacup from starting.
## The problem
`@Provider` is a factory whose value *is* the object — `db`, a client, a pool. That object cannot
cross a wire, and the mesh already knows it: `untransportable` (`src/mesh/protocol.ts:145`) refuses
any class instance, so an exported provider can only ever return plain data. What survives is the
worst half of the idea — `src/app/index.ts:854` registers the remote provider as an **app-scope**
binding, so the teacup resolves it once at boot and answers from that snapshot for the life of the
process. It is a cache the teapot no longer stands behind, wearing the word "provider".
A step is the shape that actually works across the mesh. It runs per request, the teacup sends the
envelope, the teapot resolves its own graph and sends back the result, and the teacup binds it to
the token. Transparent to the caller, and nothing is held.
Two things follow from that, and they are the whole of this plan:
1. **Exporting a provider is not a feature to fix, it is a thing to forbid.** The alternative
already exists and is spelled `@Step({ export: true })`.
2. **The boot no longer needs to block on a teapot.** Blocking existed because an app-scope value
has to be resolved *at boot* — there is no later. A step has nothing but later. A teapot that is
away costs a `503` on the requests that need it, and the app starts.
## Decisions
**D1 — `export: true` on a `@Provider` is a boot error, not a silent no-op.** Turning it into a
warning would leave a running app whose token resolves locally and looks exported. The error names
the replacement, so the message is a fix and not a complaint.
**D2 — No protocol bump.** Removing `ScopeEntry.scope` is a field removal, which the rule in
`src/mesh/protocol.ts:11` would normally make a bump. Mesh is alpha and behind `experimental: true`,
both peers ship from this repo, and a bump would spend the number on a version nobody deployed.
`MESH_PROTOCOL_VERSION` stays `1`.
**D3 — Keep `connectUntilDeadline`; delete only its `throw`.** *This corrects what was said in the
design conversation.* The retry loop is not the boot blocker — the `throw` at the end of it is. The
loop is the co-deploy grace: a teacup that starts two seconds ahead of its teapot waits, gets the
manifest, and has its steps for the process lifetime. Delete the loop and that teacup instead boots
into a graph with no `authorization` node, which is strictly worse than today. So the budget stays;
exhausting it now warns and contributes nothing, instead of failing the boot.
**D4 — A permanent refusal still fails the boot.** `isPermanentRefusal` covers a wrong secret and a
protocol mismatch. Those are configuration errors — the same class as a typo in a token name — and
they will be the same errors in thirty seconds. Failing at boot with the reason beats a `503` at
3am that says nothing about a secret. Only *unreachable* becomes non-fatal.
**D5 — A missing token still fails the boot, through the ordinary validator.** If a teapot is away
and a local step declares `needs: ['authorization']`, `topoSort` throws
`missing dependency: authorization needed by …` (`src/graph.ts:54`). That is not a mesh step to
remove: it is what catches a typo, and tolerating it would let a misspelled token boot clean and
`503` forever. The message gains the teapots that did not connect, so the cause is on the screen.
**D6 — The `expects` / degrade plan survives; its D6 does not.**
`docs/plans/2026-08-18-mesh-degrade-plan.md` is still the right answer for "this teapot may
legitimately be absent", and it is already steps-only. But its D6 reuses
`invalidateRemoteBindings`, which this plan deletes. That seam was app-scope-specific; a degraded
step swaps a runner, not a container binding. Note it there rather than leave a dangling reference.
## File structure
| File | Change |
| --- | --- |
| `src/mesh/protocol.ts` | `Manifest` → `{ steps: string[]; routes: RouteEntry[] }`; drop `ScopeEntry`; update the `manifest` frame and its `SHAPE` row |
| `src/mesh/teapot.ts` | `buildManifest({ steps, routes })` |
| `src/mesh/teacup.ts` | `buildRemote` → `{ steps, routes }` |
| `src/graph.ts` | `topoSort` takes an optional note appended to the missing-dependency error |
| `src/app/index.ts` | forbid provider export; drop the remote-provider loop, `rebind`, `invalidateRemoteBindings`, `exportedProviders`; `connectUntilDeadline` exhaustion becomes non-fatal |
| tests | `test/mesh/*`, `test/deno/mesh*`, `test/bun/mesh*`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs` |
| docs | `README.md` mesh section, `CHANGELOG.md`, the degrade plan's D6 |
## A note on the line numbers
Every `file:line` below is accurate as of `85b6c70` and drifts as tasks land. Locate code by symbol —
`collectProviders`, `spliceRemoteScopes`, `connectUntilDeadline`, `buildMeshControl`, `finalizeGraph`
— and treat the numbers as hints.
---
## Task 1: Forbid exporting a provider
The prohibition lands first and alone, because every later task assumes it. Nothing on the wire
changes yet.
**Files**
- Modify: `src/app/index.ts:440` (`collectProviders`)
- Test: `test/mesh/failure.test.ts`
- [ ] **Step 1: Write the failing test**
```ts
// test/mesh/failure.test.ts
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Module } from '../../src/index';
describe('provider export', () => {
it('refuses to boot when a provider is exported over the mesh', async () => {
@Provider({ provides: 'db', needs: [], export: true } as any)
class Db {
provide() {
return { db: { query: () => [] } };
}
}
@Module({ mountpoint: '/api', providers: [Db] })
class AppModule {}
expect(() => createApp({ modules: [AppModule], mesh: { secret: 's' } })).toThrow(
/provider 'db' cannot be exported/i,
);
});
});
```
- [ ] **Step 2: Run it and watch it fail**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: FAIL — no error is thrown, the app builds.
- [ ] **Step 3: Throw in `collectProviders`**
Replace `src/app/index.ts:440`:
```ts
if (meta.export) registry.exportedProviders.push(meta.provides);
```
with:
```ts
// A provider's value IS the object it builds — a pool, a client, a `db`. That cannot cross a
// wire, and the half of it that could (plain data) arrived as an app-scope binding the teacup
// resolved once and cached for the life of the process. A step is the shape that travels:
// it runs per request, on the teapot, and only its result comes back.
if (meta.export)
throw new Error(
`mesh: provider '${meta.provides}' cannot be exported — a provider is a factory whose value ` +
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
```
- [ ] **Step 4: Run it and watch it pass**
```bash
npx vitest run test/mesh/failure.test.ts -t 'refuses to boot'
```
Expected: PASS.
- [ ] **Step 5: Fix every test that exported a provider**
```bash
npx vitest run test/mesh/
```
Convert any `@Provider({ ..., export: true })` in a fixture to `@Step({ ..., export: true })`.
Check `test/mesh/integration.test.ts`, `test/mesh/envelope.test.ts`, `test/mesh/transport.test.ts`,
`test/mesh/fetch-boot.test.ts`, `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/
git commit -m "feat(mesh)!: refuse to export a provider
A provider's value is the object it builds, which cannot cross a JSON wire.
What did cross became an app-scope binding the teacup resolved once at boot
and served from a cache the teapot no longer stood behind. A step is the
shape that travels; the error says so."
```
---
## Task 2: A manifest of steps and routes
**Files**
- Modify: `src/mesh/protocol.ts` (`ScopeEntry`, `Manifest`, `Frame`, `SHAPE.manifest`)
- Modify: `src/mesh/teapot.ts` (`buildManifest`, and wherever the manifest frame is sent)
- Modify: `src/mesh/teacup.ts` (`buildRemote`)
- Modify: `src/mesh/link.ts` (manifest handling and the refuse-policy comparison)
- Test: `test/mesh/protocol.test.ts`, `test/mesh/teapot.test.ts`, `test/mesh/teacup.test.ts`
**Interfaces**
- Produces: `interface Manifest { steps: string[]; routes: RouteEntry[] }`
- Produces: `buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest`
- Produces: `buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] }`
- Gone: `ScopeEntry`, and the `scopes` field of the `manifest` frame
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/protocol.test.ts
it('encodes a manifest of step names', () => {
const frame = decode(encode({ type: 'manifest', v: 1, steps: ['auth'], routes: [] }));
expect(frame).toEqual({ type: 'manifest', v: 1, steps: ['auth'], routes: [] });
});
it('rejects a manifest whose steps are not an array', () => {
expect(() => decode(JSON.stringify({ type: 'manifest', v: 1, steps: 'auth', routes: [] }))).toThrow(
/steps and routes must be arrays/,
);
});
```
```ts
// test/mesh/teapot.test.ts
it('builds a manifest from step tokens and routes', () => {
expect(buildManifest({ steps: ['auth'], routes: [{ method: 'GET', pattern: '/u/:id' }] })).toEqual({
steps: ['auth'],
routes: [{ method: 'GET', pattern: '/u/:id' }],
});
});
```
```ts
// test/mesh/teacup.test.ts
it('turns every manifest step into a lazy remote node', async () => {
const link = { manifest: { steps: ['auth'], routes: [] }, rpc: async () => ({ ok: true }) } as any;
const { steps, routes } = buildRemote(link);
expect(routes).toEqual([]);
expect(steps.map((s: any) => s.name)).toEqual(['auth']);
expect(await steps[0].run({})).toEqual({ auth: { ok: true } });
});
```
- [ ] **Step 2: Run them and watch them fail**
```bash
npx vitest run test/mesh/protocol.test.ts test/mesh/teapot.test.ts test/mesh/teacup.test.ts
```
Expected: FAIL — `steps` is not a field, `buildManifest` still wants `providers`.
- [ ] **Step 3: Change the protocol**
In `src/mesh/protocol.ts`, delete `ScopeEntry` (`:45-49`) and replace the `Manifest` interface:
```ts
/**
* A mesh server's advertised steps and routes.
*
* Steps only: a provider's value is the object it builds, which cannot cross a JSON wire, so
* exporting one is refused at boot (`collectProviders`). Every entry here is request-scope and
* lazy — the token exists in the teacup's graph, and running it is an RPC.
*/
export interface Manifest {
steps: string[];
routes: RouteEntry[];
}
```
In the `Frame` union, replace the `manifest` member:
```ts
| { type: 'manifest'; v: number; steps: string[]; routes: RouteEntry[] }
```
And its `SHAPE` row:
```ts
manifest: (frame, bad) => {
if (!isNumber(frame.v)) bad('missing protocol version');
if (!Array.isArray(frame.steps) || !Array.isArray(frame.routes)) bad('steps and routes must be arrays');
},
```
Leave `MESH_PROTOCOL_VERSION` at `1` (D2). Leave `untransportable` alone — a step result can still
carry a `Date` or a `Map`.
- [ ] **Step 4: Change `buildManifest`**
In `src/mesh/teapot.ts`, replace the function at `:43-56`:
```ts
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
export function buildManifest(args: { steps: string[]; routes: RouteEntry[] }): Manifest {
return { steps: [...args.steps], routes: args.routes };
}
```
Then follow the type errors: wherever the teapot sends the `manifest` frame it now sends
`steps: manifest.steps` in place of `scopes: manifest.scopes`.
The only other caller is `buildMeshControl` (`src/app/index.ts:1088`). Update it here, not in Task 3
— a task must leave the tree typechecking, and splitting a signature from its only call site across
two commits leaves a broken commit in history:
```ts
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
`exportedProviders` is still destructured on the line above; leave it, Task 3 removes the field.
- [ ] **Step 5: Change `buildRemote`**
In `src/mesh/teacup.ts`, replace the scope loop (`:44-54`):
```ts
/** Turn a link's manifest into local proxy nodes: lazy request-scope steps, and routes. */
export function buildRemote(link: Link): { steps: RemoteScopeNode[]; routes: RemoteRoute[] } {
const steps: RemoteScopeNode[] = link.manifest.steps.map((token) => ({
name: token,
run: async (ctx: any) => ({ [token]: await link.rpc('scope', token, envelopeFrom(ctx)) }),
}));
const routes: RemoteRoute[] = link.manifest.routes.map((route) => ({
method: route.method,
pattern: route.pattern,
handler: async (req: RequestEnvelope) => (await link.rpc('route', route.pattern, req)) as ResponseShape,
}));
return { steps, routes };
}
```
The RPC `kind` stays `'scope'` — renaming it to `'step'` is a wire change with no benefit, and
`resolveScope` on the teapot side resolves both the same way.
- [ ] **Step 6: Update the refuse policy in `link.ts`**
Find the manifest comparison used by `onManifestChange: 'refuse'` and drop the lifetime half of it:
a returned manifest must still contain every step token the link contributed at boot, and every
route by method plus effective shape. There is no `scope` field left to compare (D6 of the reconnect
plan).
- [ ] **Step 7: Typecheck, then run the mesh suite**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS both. A typecheck failure here means a `manifest` frame send or the `buildMeshControl`
call site was missed.
- [ ] **Step 8: Commit**
```bash
git add src/mesh/ test/mesh/
git commit -m "refactor(mesh)!: a manifest carries step names, not scoped tokens
Every exported token is request-scope now, so the lifetime field had one
value and told a reader nothing. No protocol bump: mesh is alpha, both
peers ship from this repo, and the number should mean incompatibility
between deployed versions."
```
---
## Task 3: The teacup stops splicing providers
**Files**
- Modify: `src/app/index.ts:62,427` (`Registry.exportedProviders`)
- Modify: `src/app/index.ts:808` (delete `invalidateRemoteBindings`)
- Modify: `src/app/index.ts:813-856` (`spliceRemoteScopes`)
- Modify: `src/app/index.ts:1078-1088` (`buildMeshControl`)
- Test: `test/mesh/integration.test.ts`
- [ ] **Step 1: Write the failing test**
This file's teapot fixture opens with `@Provider({ provides: 'config', export: true })`
(`test/mesh/integration.test.ts:6`), and `LocalCtl` declares `@needs('config')`. Task 1 already made
that fixture fail at boot, so converting it is not optional — and converting it is the regression
guard, because a step re-runs where the provider was cached:
```ts
// test/mesh/integration.test.ts — replaces the @Provider fixture at :6
let configCalls = 0;
@Step({ provides: 'config', needs: [], export: true })
class Config {
run() {
configCalls += 1;
return { config: { region: 'mx', call: configCalls } };
}
}
```
and add, alongside the existing `/local/who` assertion:
```ts
it('re-runs the RPC on every request rather than caching a boot value', async () => {
// same teapot/teacup pair the '/local/who' test stands up
expect((await hit('/api/local/who')).config.call).toBe(1);
expect((await hit('/api/local/who')).config.call).toBe(2);
});
```
- [ ] **Step 2: Run it — it should already pass, and that is the point**
```bash
npx vitest run test/mesh/integration.test.ts -t 're-runs the RPC'
```
Expected: PASS. This is a regression guard, not a red test. The caching bug was only reachable
through provider export, which Task 1 made impossible — once `config` is a step it lands in the
request-scope bucket and already re-runs. The guard exists so that removing the splice in the next
steps cannot quietly reintroduce a cached remote value. Do not manufacture a red state for it.
- [ ] **Step 3: Delete `exportedProviders`**
Remove the field from the `Registry` interface (`:62`) and its initializer (`:427`). In
`buildMeshControl` (`:1078-1088`):
```ts
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
// ...
const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes });
```
- [ ] **Step 4: Delete the remote-provider splice**
In `spliceRemoteScopes`, delete the `rebind` array (`:829`), the `onReconnect` callback that calls
`invalidateRemoteBindings` (`:838`), and the whole `for (const provider of providers)` block
(`:846-856`). Destructure only what is left:
```ts
const { steps, routes } = buildRemote(link);
```
Then delete `invalidateRemoteBindings` (`:808-810`) and drop the now-unused `container` parameter
from `spliceRemoteScopes` (`:818`) and its call site (`:242`) — `container` was used at `:854` and
nowhere else in the function.
The reconnect handler no longer needs an `onReconnect`. A remote step holds no state between
requests, so a reconnected link is simply usable again on the next RPC.
- [ ] **Step 5: Run the full suite and the typechecker**
```bash
npm run typecheck && npx vitest run test/mesh/
```
Expected: PASS, and no unused-symbol errors.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts test/mesh/
git commit -m "refactor(mesh): drop the remote app-scope binding and its rebind seam
A remote provider was registered app-scope, resolved once, and cached for
the process lifetime; invalidateRemoteBindings existed only to un-cache it
on reconnect. With providers gone from the manifest, both go, and a remote
step needs nothing on reconnect because it holds nothing between requests."
```
---
## Task 4: An unreachable teapot does not stop the boot
**Files**
- Modify: `src/app/index.ts:736-776` (`connectUntilDeadline`)
- Modify: `src/app/index.ts:824-843` (the `try` in `spliceRemoteScopes`)
- Modify: `src/graph.ts:54` (the missing-dependency message)
- Test: `test/mesh/boot-retry.test.ts`
- [ ] **Step 1: Write the failing tests**
```ts
// test/mesh/boot-retry.test.ts
it('boots when a teapot is unreachable and nothing local needs it', async () => {
const app = createApp({
modules: [LocalOnlyModule], // declares no needs on a remote token
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).resolves.toBeUndefined();
});
it('still fails the boot when a local step needs a token the absent teapot owned', async () => {
const app = createApp({
modules: [NeedsAuthModule], // a step with needs: ['auth']
mesh: { secret: 's', teapots: [{ url: 'ws://127.0.0.1:9/x', secret: 's' }], bootTimeoutMs: 300 },
});
await expect(app.ready()).rejects.toThrow(/missing dependency: auth[\s\S]*did not connect/i);
});
it('still fails the boot when the teapot refuses the secret', async () => {
// stand up a teapot with secret 'right', connect with 'wrong'
await expect(app.ready()).rejects.toThrow(/refused/i);
});
```
- [ ] **Step 2: Run them and watch the first two fail**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: the first fails (boot throws on an unreachable teapot), the second fails on the message
(it says `missing dependency: auth` with no mention of the teapot), the third passes already.
- [ ] **Step 3: Make budget exhaustion non-fatal**
In `connectUntilDeadline`, keep the loop, the backoff, the `mesh:boot:retry` event and the
permanent-refusal `throw` (D4). Change the return type to `Promise<Link | undefined>` and replace
the exhaustion branch:
```ts
// The budget is a grace for a co-deploy, not a requirement. Every export is a lazy step or a
// proxied route now, so an absent teapot costs a 503 on the requests that need it — and a
// teacup that refuses to start takes down the half of itself that never needed the teapot.
if (remaining <= 0) {
logger.warn(
`mesh: teapot unreachable after ${attempts} attempt(s) over ${budgetMs}ms ` +
`(${(error as Error).message}) — starting without it; its steps and routes will 503`,
);
return undefined;
}
```
In `spliceRemoteScopes`, skip a link that came back `undefined`, and record its url:
```ts
const link = await connectUntilDeadline(/* … */);
if (!link) {
absent.push(teapot.url);
continue;
}
```
Return `absent` alongside `remoteRoutes` and `meshLinks`.
- [ ] **Step 4: Name the absent teapots in the missing-dependency error**
`topoSort` (`src/graph.ts:46`) is generic and must stay that way. Give it an optional trailing note
instead of mesh knowledge — note the capital S, and that `seedKeys` stays second:
```ts
// src/graph.ts:46
export function topoSort(nodes: GraphNode[], seedKeys: string[], note?: (key: string) => string): GraphNode[] {
```
and at the throw (`src/graph.ts:54`):
```ts
throw new Error(`missing dependency: ${key} needed by ${node.name}${note?.(key) ?? ''}`);
```
The only call site is `finalizeGraph` (`src/app/index.ts:660`), so thread the note through its
signature rather than reaching for a module-level variable:
```ts
// src/app/index.ts:654 — finalizeGraph gains a trailing optional param
function finalizeGraph(
registry: Registry,
logger: Logger,
warnDepth: number | false = DEEP_GRAPH_WARN,
missingNote?: (key: string) => string,
): { orderedProviders: GraphNode[]; orderedSteps: GraphNode[] } {
const { providerNodes, stepNodes, routePlans } = registry;
const ordered = topoSort([...providerNodes, ...stepNodes], ['req', 'params'], missingNote);
```
`finalize` in `createApp` is the closure that calls it; give it the note built from `absent`:
```ts
// Without this the error is `missing dependency: auth needed by getUser` and says nothing about
// the teapot that was away — which is the actual cause every time it is the cause.
const meshNote = absent.length
? () => ` — these teapots did not connect, so their exports are absent: ${absent.join(', ')}`
: undefined;
```
The note is unconditional on the key rather than per-token on purpose: the teacup does not know
which teapot *would* have owned a token it never received a manifest for, and guessing would put a
wrong url in an error. Listing the ones that were away is true and enough.
- [ ] **Step 5: Run them and watch them pass**
```bash
npx vitest run test/mesh/boot-retry.test.ts
```
Expected: PASS, all three.
- [ ] **Step 6: Commit**
```bash
git add src/app/index.ts src/graph.ts test/mesh/boot-retry.test.ts
git commit -m "feat(mesh): an unreachable teapot no longer stops the teacup from booting
Blocking existed for app-scope exports, which have to resolve at boot
because there is no later. Steps and proxied routes are all later. The
grace budget stays -- a co-deploy still waits -- but exhausting it now
warns instead of throwing. A missing token still fails the boot, and the
error now names the teapots that were away."
```
---
## Task 5: The other runtimes
`npm test` does not cover Deno, Bun or the edge, and this change touches `src/mesh/` and
`src/app/index.ts` — exactly the code AGENTS.md says to run them for.
**Files**
- Modify: `test/deno/mesh.test.ts`, `test/deno/mesh-hardening.test.ts`, `test/deno/mesh-interop.test.ts`,
`test/deno/mesh-reconnect.test.ts`, `test/bun/mesh.test.ts`, `test/bun/mesh-reconnect.test.ts`
- Modify: `test/interop/_node-peer.ts`, `test/edge/_worker.mjs`
- [ ] **Step 1: Convert every exported provider in the runtime fixtures to a step**
```bash
grep -rn "export: true" test/deno test/bun test/interop test/edge
```
- [ ] **Step 2: Run each runtime suite**
```bash
npm run test:deno
npm run test:bun
npm run test:edge
```
Expected: PASS on all three. The interop peer and the worker both speak the new manifest, so a
mismatch here means one side was missed.
- [ ] **Step 3: Commit**
```bash
git add test/
git commit -m "test(mesh): steps-only exports across Deno, Bun and the edge"
```
---
## Task 6: Say it in the docs
**Files**
- Modify: `README.md` (mesh section)
- Modify: `CHANGELOG.md` (`[Unreleased]`)
- Modify: `docs/plans/2026-08-18-mesh-degrade-plan.md` (D6)
- [ ] **Step 1: README**
In the mesh section: only `@Step` and routes are exportable; `@Provider` with `export: true` fails
at boot and why; an unreachable teapot no longer blocks the boot, and its steps and routes `503`;
a missing token still fails the boot, and that is deliberate.
- [ ] **Step 2: CHANGELOG**
Under `[Unreleased]`, with no date and no version heading — the heading is written the day the tag
ships, never earlier.
```markdown
### Changed
- **Mesh (alpha): only steps and routes can be exported.** `@Provider({ export: true })` now fails
at boot. A provider's value is the object it builds, which cannot cross a JSON wire; what did
cross became an app-scope binding the teacup resolved once and cached for the life of the
process. Export a `@Step` instead — it runs on the teapot per request and returns its result.
- **Mesh (alpha): an unreachable teapot no longer stops a teacup from booting.** The
`bootTimeoutMs` grace still waits for a co-deploy; exhausting it now warns and starts without
that teapot, whose steps and routes answer `503`. A local step that *needs* an absent token still
fails the boot, and the error names the teapots that did not connect.
- **Mesh (alpha): the manifest carries step names.** The wire changed without a protocol bump,
which alpha permits and a stable version would not.
```
- [ ] **Step 3: Note the broken seam in the degrade plan**
Add one line under its D6: `invalidateRemoteBindings` no longer exists — a degraded step swaps a
runner, not a container binding.
- [ ] **Step 4: The full gate**
```bash
npm run lint && npm run format:check && npm run typecheck && npm test && npm run complexity:check
npm run test:deno && npm run test:bun && npm run test:edge
```
- [ ] **Step 5: Commit**
```bash
git add README.md CHANGELOG.md docs/plans/
git commit -m "docs(mesh): steps and routes are what a teapot exports"
```
---
## Size
Smaller than the reconnect work, and mostly subtraction: roughly 120 lines out, 20 in. No new
subsystem, no new configuration, no background loop. The risk is not in the code but in the wire —
both peers change at once, which alpha allows and which the runtime suites are there to prove.
## Branch
From `develop`, per AGENTS.md — `develop` and `main` refuse direct pushes.
```bash
git fetch origin && git checkout -b feat/mesh-steps-only origin/develop
```
+14 -7
View File
@@ -1,11 +1,18 @@
````markdown
# green-tea example
# green-tea examples
Each file is a runnable app. Run one with `tsx`, which is already a dev dependency:
```bash
npx ts-node example/server.ts # or: npm run build && node dist/example/server.js
curl -H 'x-token: u1' http://localhost:3000/api/users/9
npx tsx example/server.ts # the tour, below
npx tsx example/crud.ts # a CRUD API over an in-memory store, on :3300
npx tsx example/chat.ts # WebSocket rooms, on ws://localhost:4100/chat/:room?token=...
npx tsx example/graphql.ts # GraphQL queries and subscriptions over SSE, on :4200/graphql
```
Demonstrates: typed context contract, graph-derived order, `app.inspect()`,
and a logger plugin that observes the bus without touching the chain.
````
`server.ts` demonstrates the typed context contract, graph-derived order, `app.inspect()`, a
logger plugin that observes the bus without touching the chain, streams, and a mesh teapot and
teacup. Try it with:
```bash
curl -H 'x-token: u1' http://localhost:3000/api/users/9
```
+1
View File
@@ -122,6 +122,7 @@ if (require.main === module) {
console.log('teapot on http://localhost:3002');
const teacupApp = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: `ws://127.0.0.1:3002${MESH_CONTROL_PATH}`, secret: 'demo-secret' }] },
});
teacupApp.listen(3003).then(() => console.log('teacup on http://localhost:3003'));
+1 -1
View File
@@ -1023,7 +1023,7 @@ function assertNeedsSatisfiable(
* never got, because a teapot that did not connect sent no manifest and so nobody knows what it
* would have exported. Its routes 404 like any unregistered path, and a local node that needs one
* of its tokens still fails the boot in finalize(), named. Serving 503 for those tokens instead
* needs an `expects` declaration — see docs/plans/2026-08-18-mesh-degrade-plan.md, still planned.
* needs an `expects` declaration, which is planned and not built.
*/
async function connectUntilDeadline(
mesh: MeshConfig,