From 02f0473bfc8809b5c1359499c21ce8826f0253fe Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 28 Oct 2026 09:15:30 -0500 Subject: [PATCH] docs: bring the contributor docs and examples in line with the repository CONTRIBUTING said none of the Deno, Bun or edge suites run in CI. They do: the runtimes job runs all three on every push and gates a merge. It now says so, names test:all, and lists the audit step CI runs. The README's benchmark section quoted a ranking against Fastify that went stale with the next measurement. It now explains what the harness measures and why, and leaves every number to BENCHMARKS.md. The install section states the Node 22 floor and that Node 18 and 20 are not supported. The PR template asks which runtime suites were run. The example README pointed at ts-node, which is not a dependency, and a dist path tsup never builds; it now runs each example with tsx. example/server.ts crashed at boot because its teacup lacked experimental: true. docs/plans held agent implementation plans from August and September. Those belong in .specs/, which is not committed, so they leave the repository. The three places that linked the mesh degrade plan now describe the planned expects list instead. Signed-off-by: Diego Resendez --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- .github/PULL_REQUEST_TEMPLATE.md | 1 + CHANGELOG.md | 4 +- CONTRIBUTING.md | 15 +- README.md | 25 +- .../2026-08-02-router-security-beta-design.md | 170 ----- docs/plans/2026-08-02-router-security-beta.md | 679 ----------------- docs/plans/2026-08-16-observability-design.md | 166 ---- docs/plans/2026-08-16-observability-plan.md | 166 ---- docs/plans/2026-08-16-trust-release-plan.md | 350 --------- .../2026-08-17-shutdown-teardown-design.md | 211 ------ .../2026-08-17-shutdown-teardown-plan.md | 141 ---- docs/plans/2026-08-18-mesh-degrade-plan.md | 89 --- docs/plans/2026-08-18-mesh-reconnect-plan.md | 108 --- docs/plans/2026-09-06-mesh-steps-only-plan.md | 710 ------------------ example/README.md | 21 +- example/server.ts | 1 + src/app/index.ts | 2 +- 18 files changed, 49 insertions(+), 2812 deletions(-) delete mode 100644 docs/plans/2026-08-02-router-security-beta-design.md delete mode 100644 docs/plans/2026-08-02-router-security-beta.md delete mode 100644 docs/plans/2026-08-16-observability-design.md delete mode 100644 docs/plans/2026-08-16-observability-plan.md delete mode 100644 docs/plans/2026-08-16-trust-release-plan.md delete mode 100644 docs/plans/2026-08-17-shutdown-teardown-design.md delete mode 100644 docs/plans/2026-08-17-shutdown-teardown-plan.md delete mode 100644 docs/plans/2026-08-18-mesh-degrade-plan.md delete mode 100644 docs/plans/2026-08-18-mesh-reconnect-plan.md delete mode 100644 docs/plans/2026-09-06-mesh-steps-only-plan.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index bfe08f0..d00a80f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -19,7 +19,7 @@ The smallest module and route that shows it: ## Environment - green-tea version: -- Runtime and version: +- Runtime and version: - OS: 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. diff --git a/docs/plans/2026-08-17-shutdown-teardown-design.md b/docs/plans/2026-08-17-shutdown-teardown-design.md deleted file mode 100644 index dc1d19d..0000000 --- a/docs/plans/2026-08-17-shutdown-teardown-design.md +++ /dev/null @@ -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; -``` - -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; - -/** 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`. diff --git a/docs/plans/2026-08-17-shutdown-teardown-plan.md b/docs/plans/2026-08-17-shutdown-teardown-plan.md deleted file mode 100644 index 07d63e8..0000000 --- a/docs/plans/2026-08-17-shutdown-teardown-plan.md +++ /dev/null @@ -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; -``` - -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`. diff --git a/docs/plans/2026-08-18-mesh-degrade-plan.md b/docs/plans/2026-08-18-mesh-degrade-plan.md deleted file mode 100644 index 753d61f..0000000 --- a/docs/plans/2026-08-18-mesh-degrade-plan.md +++ /dev/null @@ -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. diff --git a/docs/plans/2026-08-18-mesh-reconnect-plan.md b/docs/plans/2026-08-18-mesh-reconnect-plan.md deleted file mode 100644 index e9da086..0000000 --- a/docs/plans/2026-08-18-mesh-reconnect-plan.md +++ /dev/null @@ -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. diff --git a/docs/plans/2026-09-06-mesh-steps-only-plan.md b/docs/plans/2026-09-06-mesh-steps-only-plan.md deleted file mode 100644 index 10b98ee..0000000 --- a/docs/plans/2026-09-06-mesh-steps-only-plan.md +++ /dev/null @@ -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` 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 -``` diff --git a/example/README.md b/example/README.md index 68ced80..e98d837 100644 --- a/example/README.md +++ b/example/README.md @@ -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 +``` diff --git a/example/server.ts b/example/server.ts index b0c1b06..70efb1e 100644 --- a/example/server.ts +++ b/example/server.ts @@ -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')); diff --git a/src/app/index.ts b/src/app/index.ts index c819014..2955018 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -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,