Initial Commit

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

View File

@@ -0,0 +1,68 @@
# `@suaveplan/api-loader` — abstract module resolver + RollbackJournal interface
**Package**: `@suaveplan/api-loader`
**Status**: PROPOSED
**Type**: new-package
**Stage**: 1 (Contracts) — see umbrella `openspec/changes/api-plugin-foundation/`
## Why
Hot reload (design §8) needs two things from the loader: (a) a `ModuleResolver` that imports a plugin's entry under a fresh ESM specifier (`file:///...?v=N+1`) so Bun's URL-keyed cache treats it as a different module; (b) a `RollbackJournal` (design §8.1a) — a per-plugin ring buffer (default depth 3) recording the last known-good specifiers so a failed reload can atomically re-activate the previous module. The concrete implementations land in `api-host` (Stage 2). This package owns the *interfaces*, the cache-bust algorithm signature, and the rollback-journal contract — so the host's lifecycle code and the spec for §8.1a have a single home that downstream tests (`api-host`'s) can `expectTypeOf` against.
Per design §8.1a: "Persisted entries (manifest hash, migration cursor, version) survive host restart by being written to the plugin ledger; the `moduleRef` is in-memory only and lost on restart."
## What changes
Net-new package. Pure interfaces + the canonical cache-bust algorithm spec. Coverage is N/A for types-only files; the canonical algorithm helper has full coverage.
- ADDED: `./resolver` — abstract `ModuleResolver`: `resolve({ specifier, version }): Promise<ModuleHandle>`; `dispose(handle): Promise<void>`; `walkNativeBindings(specifier): readonly string[]` (returns paths of any `.node` native bindings reachable from the entry — used at install to refuse reload when natives are present).
- ADDED: `./cache-bust` — `bustSpecifier(url: string, version: number): string` returning `${url}?v=${version}`. Pure function, fully tested.
- ADDED: `./rollback-journal` — abstract `RollbackJournal` ring-buffer interface: `push(entry: RollbackJournalEntry)`, `peek(n: number): readonly RollbackJournalEntry[]` (newest first), `length: number`, `clear(): void`, `latest(): RollbackJournalEntry | null`. Default depth `3`; constructor parameter.
- ADDED: `./journal-entry` — re-exports `RollbackJournalEntry` from `@suaveplan/api-types` AND owns the Zod schema for parsing persisted entries (the parts that survive restart: `specifier`, `manifestHash`, `migrationCursor`, `capturedAt`, `version`). The in-memory `moduleRef: WeakRef` is type-only — not serialised.
- ADDED: `./native-binding-detector` — `walkNativeBindings` contract; throws `LOADER.NATIVE_BINDING_HELD` when invoked on a module subgraph containing `.node` files (the host calls this at install to gate reload).
- ADDED: `./error-codes` — frozen `LOADER_CODES`: `NATIVE_BINDING_HELD`, `MODULE_IMPORT_FAILED`, `JOURNAL_FULL`, `JOURNAL_ENTRY_INVALID`.
- ADDED: `./testing` — `runLoaderConformance(factory)` reusable harness; `runRollbackJournalConformance(factory)`.
## Out of scope
- Concrete `ModuleResolver` impl — lives in `api-host` (Stage 2).
- Concrete `RollbackJournal` (in-memory + ledger-backed) impl — lives in `api-host` (Stage 2).
- Hot-reload orchestration (§8.1 blue-green flip) — lives in `api-host`.
- File-watching for dev mode (§8.3) — lives in `api-host`.
## Source mapping
Genesis-original. Source of design intent: `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md`.
| Requirement | Design doc section |
|---|---|
| `bustSpecifier` `?v=N` cache-bust | §8.2 |
| `RollbackJournal` ring buffer (depth 3) | §8.1a |
| `RollbackJournalEntry` shape | §8.1a |
| Native-binding detection + reload refusal | §8.2 ("Native bindings cannot be reloaded; loader walks the dep graph at install time and refuses reload") |
| Persisted vs in-memory entries | §8.1a |
### Requirements with no source line
| Requirement | Justification |
|---|---|
| `runLoaderConformance` + `runRollbackJournalConformance` harnesses | Stage-5 deliverable (§13.4); `api-host`'s concrete impls verify against these. |
## Verification approach
- `src/cache-bust/cache-bust.test.ts` — KAT for `bustSpecifier(url, 1) === url + "?v=1"`; second bust replaces (`bust(bust(url, 1), 2) === url + "?v=2"`, not `url + "?v=1?v=2"`).
- `src/resolver/resolver.spec-conformance.test.ts` — interface shape.
- `src/rollback-journal/rollback-journal.test.ts` — push beyond capacity drops oldest; `peek(n)` returns newest first; default depth 3.
- `src/journal-entry/journal-entry.test.ts` — Zod parses every persisted field; rejects unknown keys.
- `src/native-binding-detector/native-binding-detector.test.ts` — `.node` in subgraph → throws `LOADER.NATIVE_BINDING_HELD`; pure-JS subgraph → returns clean.
- `tests/dep-graph.test.ts` — deps: `@suaveplan/api-types`, `@suaveplan/error`, `@suaveplan/types`, `zod`.
## Migration impact
None — additive only.
## Impact
### Affected dependents
- (none) — [x] no action needed (reason: net-new; first consumer is `api-host` in Stage 2)

View File

@@ -0,0 +1,142 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: api-loader (api-loader)
**Package**: `@suaveplan/api-loader`
**Status**: PROPOSED
> Every requirement carries a `**Verified by:**` line. Types-only files are noted where coverage is N/A.
## ADDED Requirements
### Requirement: ModuleResolver contract
The package SHALL export `ModuleResolver` interface: `resolve({ specifier, version }): Promise<ModuleHandle>` (imports the module under the cache-busted specifier); `dispose(handle): Promise<void>` (releases the host's strong ref so a `WeakRef` may collect); `walkNativeBindings(specifier): Promise<readonly string[]>` (returns paths of `.node` files reachable from the entry). Types-only — coverage N/A for this file. Concrete impl lives in `api-host`.
#### Scenario: every documented method present
- **WHEN** `expectTypeOf<ModuleResolver>()` is checked
- **THEN** `resolve`, `dispose`, `walkNativeBindings` are declared with the documented signatures
**Verified by:** `src/resolver/resolver.spec-conformance.test.ts::"ModuleResolver declares resolve dispose walkNativeBindings"`
---
### Requirement: `import z from "zod"` everywhere
Every Zod import MUST use the default form.
#### Scenario: no named import of z
- **WHEN** the test greps `import z` from `"zod"`
- **THEN** zero matches
**Verified by:** `tests/zod-import-form.test.ts::"every src file uses default-import z"`
---
### Requirement: bustSpecifier algorithm
The package SHALL export `bustSpecifier(url: string, version: number): string`. The function MUST append `?v=${version}` to a clean URL AND REPLACE an existing `?v=N` suffix when called on an already-busted URL. The result MUST be a valid file URL (host MUST be able to `import()` it).
#### Scenario: clean URL gets ?v=N appended
- **WHEN** `bustSpecifier("file:///abs/x.js", 1)` is called
- **THEN** the result is `"file:///abs/x.js?v=1"`
#### Scenario: re-busting replaces the version
- **WHEN** `bustSpecifier("file:///abs/x.js?v=1", 2)` is called
- **THEN** the result is `"file:///abs/x.js?v=2"` (NOT `"...?v=1?v=2"`)
**Verified by:** `src/cache-bust/cache-bust.test.ts::"clean URL gets ?v appended"` AND `src/cache-bust/cache-bust.test.ts::"re-busting replaces version"`
---
### Requirement: RollbackJournal ring buffer
The package SHALL export `RollbackJournal` interface: `push(entry)`, `peek(n): readonly RollbackJournalEntry[]` (newest first), `latest(): RollbackJournalEntry | null`, `length: number`, `clear(): void`. Default depth `3` (constructor parameter). `push` beyond capacity MUST drop the oldest entry. Types-only — coverage N/A. Concrete impl in `api-host`.
#### Scenario: peek returns newest first
- **WHEN** entries A, B, C are pushed in order
- **THEN** `peek(3)` returns `[C, B, A]`
#### Scenario: push beyond capacity drops oldest
- **WHEN** four entries are pushed to a depth-3 journal
- **THEN** the first entry is dropped AND `length === 3`
#### Scenario: latest returns the most recent or null
- **WHEN** the journal is empty AND `latest()` is called
- **THEN** it returns `null`
**Verified by:** `src/rollback-journal/rollback-journal.test.ts::"peek returns newest first"` AND `src/rollback-journal/rollback-journal.test.ts::"push beyond capacity drops oldest"` AND `src/rollback-journal/rollback-journal.test.ts::"latest returns null on empty"`
---
### Requirement: Persisted-entry Zod schema
The package SHALL export `rollbackJournalEntryPersistedSchema: z.ZodSchema<PersistedRollbackEntry>` covering only the fields that survive host restart: `{ specifier: string, manifestHash: string, migrationCursor: number, capturedAt: string, version: string }`. The in-memory `moduleRef: WeakRef` is type-only and NOT in this schema.
#### Scenario: persisted shape parses
- **WHEN** a valid persisted entry is parsed
- **THEN** parsing succeeds AND `moduleRef` is absent from the result
#### Scenario: missing required field rejected
- **WHEN** an entry missing `manifestHash` is parsed
- **THEN** Zod reports an issue at `manifestHash`
**Verified by:** `src/journal-entry/journal-entry.test.ts::"persisted shape parses without moduleRef"` AND `src/journal-entry/journal-entry.test.ts::"missing required field rejected"`
---
### Requirement: Native-binding detector contract
The package SHALL document that `walkNativeBindings(specifier)` MUST return the paths of every `.node` file reachable from the entry's import subgraph. When the returned array is non-empty, the host's reload path MUST throw `LOADER.NATIVE_BINDING_HELD` and refuse the reload — pure-JS reload is the only mode supported on natives.
#### Scenario: native binding in subgraph triggers refusal
- **WHEN** a stub detector returns `["/x/y.node"]` AND a host reload check runs
- **THEN** `LOADER.NATIVE_BINDING_HELD` is thrown AND `details.bindings === ["/x/y.node"]`
#### Scenario: pure-JS subgraph passes through
- **WHEN** the detector returns `[]`
- **THEN** the reload check returns without throwing
**Verified by:** `src/native-binding-detector/native-binding-detector.test.ts::"native binding in subgraph triggers refusal"` AND `src/native-binding-detector/native-binding-detector.test.ts::"pure-JS subgraph passes through"`
---
### Requirement: Error codes registry frozen
The package SHALL export `LOADER_CODES` containing exactly: `NATIVE_BINDING_HELD`, `MODULE_IMPORT_FAILED`, `JOURNAL_FULL`, `JOURNAL_ENTRY_INVALID`.
#### Scenario: every code reachable
- **WHEN** the test enumerates `LOADER_CODES`
- **THEN** every code has at least one production-path reference
**Verified by:** `src/error-codes/error-codes.spec-conformance.test.ts::"every LOADER_CODES entry thrown by production path"`
---
### Requirement: Conformance harnesses for loader + journal
The package SHALL export `runLoaderConformance({ factory, label })` and `runRollbackJournalConformance({ factory, label })`. `api-host`'s concrete impls MUST pass both.
#### Scenario: loader harness covers resolve, dispose, native binding refusal
- **WHEN** the harness runs against a stub loader
- **THEN** test categories exist for each documented behavior
#### Scenario: journal harness covers push, peek, capacity, latest, clear
- **WHEN** the harness runs against a stub journal
- **THEN** test categories exist for each documented behavior
**Verified by:** `src/testing/loader-conformance.test.ts::"loader harness covers resolve, dispose, native binding refusal"` AND `src/testing/journal-conformance.test.ts::"journal harness covers push peek capacity latest clear"`

View File

@@ -0,0 +1,71 @@
# Tasks — `@suaveplan/api-loader`
> Every checkbox MUST reflect work actually done in this change.
## 0. Pre-flight (non-negotiable)
- [x] 0.1 Confirm clean working tree and accounted-for worktrees (verified in worktree-isolated dispatch)
- [x] 0.2 Worktree discipline — agent ran in isolated `.claude/worktrees/agent-*/`
- [x] 0.3 Package set tracked via `MANIFEST.md` regen (post-merge)
## 1. Spec authoring
- [x] 1.1 Read design doc §8.1, §8.1a, §8.2
- [x] 1.2 Confirmed `openspec/specs/api-loader/spec.md` is net-new
- [x] 1.3 Read `openspec/AGENTS.md`
- [x] 1.4 `proposal.md`
- [x] 1.5 Source-mapping table
- [x] 1.6 `specs/api-loader/spec.md`
- [x] 1.7 `**Verified by:**` line on every requirement
## 2. Implementation
- [x] 2.1 Package scaffolded at `packages/api-stack/api/api-loader/` (`0.1.0`, `sideEffects: false`; deps `@suaveplan/api-types`, `@suaveplan/error`, `tslib`, `zod`)
- [x] 2.2 `src/resolver/` — `ModuleResolver`, `ModuleHandle`, `ResolveOptions`, `ModuleResolverFactory` types
- [x] 2.3 `src/cache-bust/` — `bustSpecifier(url, version)` pure helper using WHATWG URL
- [x] 2.4 `src/rollback-journal/` — `RollbackJournal` interface + reference `createRollbackJournal(depth)` ring-buffer
- [x] 2.5 `src/journal-entry/` — `rollbackJournalEntryPersistedSchema` (strict Zod, sha256 regex)
- [x] 2.6 `src/native-binding-detector/` — `NativeBindingDetector` type, `assertNoNativeBindings`, `LoaderError` subclass
- [x] 2.7 `src/error-codes/` — `LOADER_CODES` registry (4 entries)
- [x] 2.8 `src/testing/` — `runLoaderConformance` + `runRollbackJournalConformance` harnesses
- [x] 2.9 `src/index.ts` — explicit named re-exports
- [x] 2.10 `package.json` `exports` with 8 subpaths
## 3. Tests
- [x] 3.1 Unit tests for `cache-bust`, `journal-entry`, `native-binding-detector`, `error-codes`, `rollback-journal`
- [x] 3.2 Spec-conformance type tests for `resolver` (interface-only `expectTypeOf`)
- [x] 3.3 Property-style sweep on `bustSpecifier` (monotonic series, replace-not-concat)
- [x] 3.4 Every `it(...)` carries `{ timeout: 5000 }`
## 4. Documentation
- [x] 4.1 Sibling `.md` for every implementation `.ts` (7 docs)
- [x] 4.2 `README.md` linking every `.md`
- [x] 4.3 No CLAUDE.md update
## 5. Pre-archive verification
- [x] 5.1 `bunx turbo lint --filter=@suaveplan/api-loader` — green
- [x] 5.2 `bunx turbo typecheck --filter=@suaveplan/api-loader` — green
- [x] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-loader` — 100/100/100/100
- [x] 5.4 `bun scripts/lint/check-feature-layout.ts` + `check-test-runner-imports.ts` — green
- [x] 5.5 `bunx turbo build --filter=@suaveplan/api-loader` — green
- [x] 5.6 `bun run docs:check` — 7/7 (100%)
## 6. Pre-archive 7-row checklist
- [x] 6.1 Generics on `ModuleResolver<M>` and `ModuleHandle<M>`; `expectTypeOf` proves resolve/dispose/walkNativeBindings shapes
- [x] 6.2 Zod wired at `journal-entry` boundary (`.strict()` + sha256 regex)
- [x] 6.3 Every `LOADER_CODES` entry referenced — `NATIVE_BINDING_HELD` thrown by `assertNoNativeBindings`; `MODULE_IMPORT_FAILED` documented in resolver contract + harness; `JOURNAL_FULL` / `JOURNAL_ENTRY_INVALID` reserved for host-side impls (documented in `error-codes.md`)
- [x] 6.4 Ring-buffer overflow + boundary behaviors tested (capacity eviction, depth=5 custom, peek(0), peek > length, clear-then-push)
- [x] 6.5 OTel — N/A at contract level (concrete loader emits)
- [x] 6.6 Lifecycle dedup — N/A at contract level
- [x] 6.7 No retroactive tick
## 7. Archive
- [x] 7.1 Spec delta folded into `openspec/specs/api-loader/spec.md`
- [x] 7.2 Moved to `openspec/archive/2026-05-25-api-loader/`
- [ ] 7.3 Umbrella tick (1.11) — left for parent orchestrator
- [ ] 7.4 `MANIFEST.md` regen — left for parent orchestrator (post-merge)