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,51 @@
# `@suaveplan/api-db-sqlite-memory` — In-memory SQLite DB adapter for tests
**Package**: `@suaveplan/api-db-sqlite-memory`
**Status**: PROPOSED
**Type**: new-package
**Stage**: 5 (Testing kit + conformance suites) — see umbrella `openspec/changes/api-plugin-foundation/`
## Why
Per design doc §13.2, `createTestHost({ adapters: { db: { engine: "sqlite-memory" } } })` boots a plugin against a real `bun:sqlite` `:memory:` database — production-grade adapter that happens to keep state in process memory. Migrations run, tenant-scoping enforces, prepared statements work; the only thing missing is durability. Tests run in milliseconds.
This adapter implements the same `AdminDatabaseLike` + `TenantScopedDatabaseLike` surfaces as `api-db-adapter` (Stage 4) and passes the same conformance suite — proving the contract is engine-agnostic at the SQLite layer.
## What changes
Net-new package depending on `@suaveplan/api-db` (contract + `./testing` conformance), `@suaveplan/api-types`, `@suaveplan/error`, `zod`, and `bun:sqlite` (Bun built-in — no external dep).
- ADDED: `createSqliteMemoryDb(opts)` — factory returning `{ admin: AdminDatabaseLike; scoped(tenantId): TenantScopedDatabaseLike; close(): void }`.
- ADDED: `SqliteMemoryDbOptions` — Zod schema (`tenantColumn?: string` (default `tenant_id`), `migrationsDir?: string`, `pragmas?: Record<string, string>` (default `{ journal_mode: "WAL", foreign_keys: "ON" }`)).
- ADDED: Tenant-scoped wrapper — same semantics as `api-db-adapter` (`WHERE tenant_id` injection on read, payload injection on write, `DB_SQLITE_MEMORY_TENANT_SCOPE_VIOLATION` on cross-tenant access).
- ADDED: Migration runner — applies SQL files from `migrationsDir` in lexicographic order, records applied versions in `__plugin_migrations` table; idempotent on re-run.
- ADDED: `DB_SQLITE_MEMORY_*` error codes (`DB_SQLITE_MEMORY_TENANT_SCOPE_VIOLATION`, `DB_SQLITE_MEMORY_MIGRATION_FAILED`, `DB_SQLITE_MEMORY_INVALID_OPTIONS`).
- ADDED: Registered in `@suaveplan/api-host/testing`'s adapter table as `engine: "sqlite-memory"`.
## Out of scope
- Persistence — `:memory:` only at this stage. Operators wanting on-disk SQLite use `api-db-adapter` with `engine: "sqlite"`.
- WAL replication — N/A for `:memory:`.
- Surreal-flavoured queries — wrong engine.
## Source mapping
Genesis-original. Source of design intent: `docs/superpowers/specs/2026-05-13-api-plugin-foundation-design.md`.
| Requirement | Design doc section |
|---|---|
| Real SQLite in tests, not a double | §13.2 |
| Same conformance suite as Stage 4 db | §13.4 |
| Registered in `api-host/testing` adapter table | §15 Stage 5 |
## Verification approach
- `src/factory/create-sqlite-memory-db.test.ts` — admin SELECT/INSERT/transaction, prepared statements, pragmas applied.
- `src/factory/create-sqlite-memory-db.spec-conformance.test.ts` — `runDbAdapterConformance("sqlite-memory-direct", ...)`.
- `src/tenant-scoping/tenant-scoping.test.ts` — read injection, write injection, cross-tenant rejection.
- `src/migrations/migrations.test.ts` — forward, idempotent, failure rollback.
- `tests/integration/integration.test.ts` — via `createTestHost`.
## Migration impact
None — additive only.

View File

@@ -0,0 +1,79 @@
<!-- markdownlint-disable MD024 -->
# Capability Spec Delta: api-db-sqlite-memory (api-db-sqlite-memory)
**Package**: `@suaveplan/api-db-sqlite-memory`
**Status**: PROPOSED
## ADDED Requirements
### Requirement: Backed by real bun:sqlite :memory:
The package SHALL open a real `bun:sqlite` `Database(":memory:")` and route every query/execute/prepare through it. No SQL emulation, no in-process query interpreter.
#### Scenario: PRAGMA foreign_keys is honoured
- **WHEN** the adapter is constructed with default pragmas AND a parent/child table pair has a `FOREIGN KEY` constraint AND a child insert references a non-existent parent
- **THEN** the insert fails with the standard SQLite foreign-key violation (proving real SQLite is in the loop)
**Verified by:** `src/factory/create-sqlite-memory-db.test.ts::"PRAGMA foreign_keys is honoured by the real bun:sqlite database"`
---
### Requirement: Admin and tenant-scoped surfaces
The factory SHALL return `{ admin, scoped(tenantId), close }`. The `scoped` wrapper enforces `WHERE tenant_id = $1` on reads and rejects writes whose payload's `tenant_id` differs from the wrapper's bound tenant (or auto-injects when `autoInjectInserts: true`).
#### Scenario: admin reads across tenants
- **WHEN** admin runs `SELECT * FROM users` against a multi-tenant fixture
- **THEN** rows from all tenants are returned
#### Scenario: scoped rejects cross-tenant insert
- **WHEN** `scoped("acme")` attempts `INSERT INTO users (tenant_id) VALUES ('bigcorp')`
- **THEN** the call throws `DB_SQLITE_MEMORY_TENANT_SCOPE_VIOLATION`
**Verified by:** `src/tenant-scoping/tenant-scoping.test.ts::"admin reads across tenants"` AND `src/tenant-scoping/tenant-scoping.test.ts::"scoped rejects cross-tenant insert"`
---
### Requirement: Migration runner
The adapter SHALL run migrations from `migrationsDir` in lexicographic order, record applied versions in `__plugin_migrations`, and remain idempotent on re-run. Failures throw `DB_SQLITE_MEMORY_MIGRATION_FAILED` with the failing file path.
#### Scenario: forward migration applies once
- **WHEN** `runMigrations` is called with a 2-file directory AND `__plugin_migrations` is empty
- **THEN** both files run AND `__plugin_migrations` has 2 rows
#### Scenario: idempotent re-run
- **WHEN** `runMigrations` is called a second time
- **THEN** zero new migrations run AND no error is thrown
**Verified by:** `src/migrations/migrations.test.ts::"applies pending migrations in lexicographic order"` AND `src/migrations/migrations.test.ts::"is idempotent on re-run"`
---
### Requirement: Conforms to Db contract
#### Scenario: conformance suite passes
- **WHEN** `runDbAdapterConformance("sqlite-memory-direct", () => createSqliteMemoryDb(...))` runs
- **THEN** every invariant passes
**Verified by:** `src/factory/create-sqlite-memory-db.spec-conformance.test.ts::"sqlite-memory-direct conforms to Db contract"`
---
### Requirement: Registered in `api-host/testing` adapter table
#### Scenario: createTestHost resolves the engine sentinel
- **WHEN** `createTestHost({ adapters: { db: { engine: "sqlite-memory" } } })`
- **THEN** the resulting `host.db` is an instance produced by this factory
**Verified by:** `tests/integration/integration.test.ts::"createTestHost resolves engine:\"sqlite-memory\" to this adapter"`
<!-- markdownlint-enable MD024 -->

View File

@@ -0,0 +1,68 @@
# Tasks — `@suaveplan/api-db-sqlite-memory`
> Every checkbox MUST reflect work actually done in this change.
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Spec authoring
- [x] 1.1 Read design doc (§13.2, §13.4, §15 Stage 5)
- [x] 1.2 Read `openspec/changes/api-db-adapter/` for Stage 4 parallel
- [x] 1.3 Read `openspec/AGENTS.md` Sections 13 and 14
- [x] 1.4 Draft `proposal.md`
- [x] 1.5 Draft `specs/api-db-sqlite-memory/spec.md`
- [x] 1.6 Every requirement carries `**Verified by:**`
## 2. Implementation
- [ ] 2.1 Scaffold `packages/api/api-db-sqlite-memory/` (deps: api-db, api-types, error, zod)
- [ ] 2.2 `src/options/sqlite-memory-db-options.ts` — Zod schema
- [ ] 2.3 `src/factory/create-sqlite-memory-db.ts` — direct surface (admin + scoped)
- [ ] 2.4 `src/tenant-scoping/tenant-scoping.ts` — read/write injection + rejection
- [ ] 2.5 `src/migrations/migrations.ts` — runner with `__plugin_migrations` table
- [ ] 2.6 `src/error-codes.ts` — `DB_SQLITE_MEMORY_*` codes via `defineCodes`
- [ ] 2.7 `src/index.ts` — explicit named re-exports
- [ ] 2.8 Register this adapter in `@suaveplan/api-host/testing`'s adapter table under `engine: "sqlite-memory"`
## 3. Tests
- [ ] 3.1 `src/factory/create-sqlite-memory-db.test.ts`
- [ ] 3.2 `src/factory/create-sqlite-memory-db.spec-conformance.test.ts` — conformance
- [ ] 3.3 `src/tenant-scoping/tenant-scoping.test.ts`
- [ ] 3.4 `src/migrations/migrations.test.ts`
- [ ] 3.5 `tests/integration/integration.test.ts` — via `createTestHost`
- [ ] 3.6 Every `it(...)` carries `{ timeout: 5000 }`
## 4. Documentation
- [ ] 4.1 Sibling `.md` per implementation `.ts`
- [ ] 4.2 README documents the `:memory:` connection string and the WAL/foreign-keys default pragmas
## 5. Pre-archive verification (5-gate triple)
- [ ] 5.1 `bun run check` — clean
- [ ] 5.2 `bunx turbo lint typecheck test --filter=@suaveplan/api-db-sqlite-memory` — green
- [ ] 5.3 `bunx turbo test:coverage --filter=@suaveplan/api-db-sqlite-memory` — 100/100/100/100
- [ ] 5.4 `bun scripts/openspec-conformance.ts @suaveplan/api-db-sqlite-memory` — exit 0
- [ ] 5.5 `bunx turbo build --filter=@suaveplan/api-db-sqlite-memory` — green
## 6. Pre-archive 7-row checklist
- [ ] 6.1 `expectTypeOf` asserts admin vs scoped surfaces type-distinct (same field name, different type)
- [ ] 6.2 Zod schema at options + manifest boundaries
- [ ] 6.3 Every `DB_SQLITE_MEMORY_*` code thrown by at least one production path
- [ ] 6.4 Strict-mode (`autoInjectInserts` on/off) tested both ways
- [ ] 6.5 OTel instruments (`api.db.query_duration_ms`, `api.db.migrations_applied_total`) asserted with in-memory `MeterProvider`
- [ ] 6.6 Migration idempotency tested
- [ ] 6.7 No retroactive tick
## 7. Archive
- [ ] 7.1 Fold into `openspec/specs/api-db-sqlite-memory/spec.md`
- [ ] 7.2 Move to `openspec/archive/<yyyy-mm-dd>-api-db-sqlite-memory/`
- [ ] 7.3 Tick Stage 5 box in umbrella tasks
- [ ] 7.4 Refresh `MANIFEST.md`