Skip to content

Latest commit

 

History

History
271 lines (223 loc) · 28 KB

MISALIGNMENTS.md

File metadata and controls

271 lines (223 loc) · 28 KB

Misalignments & Fix Tasks

This document compares the intended system with the code on branch feat/oauth-widget @ 7fc3266. The intended system is defined by the README, the design draft, .agents/skills/, and the decisions in QUESTION_ANSWERS.md, which were refined in a follow-up review.

Priorities:

  • P1: breaks the stated purpose (GDPR compliance, partner integration).
  • P2: correctness or developer-experience problem.
  • P3: docs and skill hygiene.

Each task has a stable ID (e.g. AUTH-1). The documentation site refers to these IDs.

Status (2026-11-03): implemented on feat/oauth-widget (uncommitted). [x] = done, [~] = partly done (see note). Remaining work and new findings are in §7.


0. Decisions (target state)

# Decision
D1 Each partner self-hosts its own CMP. The clause list is per partner, and the partner is the data controller for its instance. There is no multi-tenant "partner" model.
D2 Consent read access: GET /consent and GET /consent/:clause_id are admin-only. GET /consent/:clause_id/:orcid requires an ORCID JWT whose sub equals :orcid, so end users read only their own decision. There are no API keys.
D3 Webhooks (admin-managed) notify APICURON and the partner's own systems: HMAC-signed, at-least-once delivery, retries, and a delivery log.
D4 Widget distribution: consent-lib publishes two npm packages with the same version. @biocomputingup/apicuron-consent is the Angular 14 library; @biocomputingup/apicuron-consent-wc is the prebuilt widget.js. The backend pins the -wc package and serves it at /widget/widget.js.
D5 Supported widget: <ac-consent-gather>, one element per clause. <ac-apicuron-consent> is deprecated.
D6 Production deployment: docker-compose.prod.yml with a backend image (node dist/main), the dashboard as static nginx, and KurrentDB on the internal network only. TLS is handled by the partner's reverse proxy.
D7 ORCID sandbox is turned on by an explicit ORCID_SANDBOX flag, not inferred from a hostname.
D8 First admin: created on the dashboard's setup page, or with npm run create-admin. The command can also add more admins.
D9 Docs have two audiences: partner developers (who set up, deploy and integrate) and administrators. Contributor docs live in the README and .agents/skills.
D10 APICURON is a webhook receiver that the partner's admin registers.

1. Product / architecture

# Intended Actual Priority
1.1 Consent changes are pushed to subscribers, including APICURON (D3, D10) No webhooks or outbound notifications exist. P1
1.2 Consent reads are access-controlled (D2) All three GET /consent* routes have no auth. consent-manager.controller.ts only applies Swagger decorators, so anyone can list every ORCID iD and its decisions. (It was believed an auth check existed, but none does.) P1
1.3 Per-partner self-hosting (D1) Confirmed by the README ("deployed on the scientific resource's infrastructure"). The code is single-tenant, so nothing to fix, but it is blocked by 1.6. —
1.4 The query interface returns the latest consolidated record Reads come from an asynchronously updated SQLite projection (eventually consistent). The dashboard works around this with safetyDelay. P2
1.5 Users can see what they agreed to The widget only links tosUrl/privacyPolicyUrl, and consent events don't record the clause version. P2
1.6 Portable production deployment (D6) The KurrentDB connection string is hardcoded (backend/src/app.module.ts:24). Only dev images exist, and build:wc uses --configuration=development. P1
1.7 The widget is served by the backend at a matching version, and also usable as an npm library (D4) widget.js is written to consent-lib/projects/apicuron-consent-wc/demo/. Nothing serves it and nothing is published to npm. P1

Tasks: access control (D2)

  • AUTH-1 · P1 Add @Authenticated() (admin) to GET /consent and GET /consent/:clause_id.
  • AUTH-2 · P1 Add @OrcidAuthenticated() to GET /consent/:clause_id/:orcid. Return 403 when req.user.sub !== :orcid. The widget already sends its Bearer token: check consent-client.service.ts.
  • AUTH-3 · P2 Send the admin token from the dashboard Overview page (the interceptor already does this; verify it).

Tasks: webhooks (D3, D10)

  • HOOK-1 · P1 Add a SQLite table webhooks: id, url, secret, events[], optional clauses[] filter, enabled, created_by, created_at. Add a Drizzle migration.
  • HOOK-2 · P1 Add an admin API: GET/POST /webhooks, PUT/DELETE /webhooks/:id, POST /webhooks/:id/rotate-secret, POST /webhooks/:id/test (sends a ping event). Return the secret only once, on create or rotate.
  • HOOK-3 · P1 Add a dispatcher driven by a KurrentDB persistent subscription on $ce-clause.
    • It maps UserGrantedConsent, UserRevokedConsent and (opt-in) ClauseCreated/ClauseModified/ClauseDeleted to the payload { id, type, occurredAt, data: { orcid, clauseIdentifier, status } }.
    • id is the KurrentDB event id.
    • Done differently: a @Reactor (catch-up subscription with a persisted checkpoint) writes to a SQLite outbox (webhook_deliveries), and WebhookDispatcherService sends from it. Same at-least-once guarantee, the delivery log comes for free, and no server-side persistent-subscription group is needed.
  • HOOK-4 · P1 Sign <X-CMP-Timestamp>.<raw body> with HMAC-SHA256 using the per-webhook secret. Send the headers X-CMP-Signature: sha256=<hex>, X-CMP-Event, X-CMP-Delivery and X-CMP-Timestamp.
  • HOOK-5 · P1 Retry with exponential backoff on non-2xx or a 10 s timeout, for up to ~24h, and park the delivery when retries run out. Delivery is at-least-once, and receivers dedupe on id.
  • HOOK-6 · P2 Add a webhook_deliveries log table and GET /webhooks/:id/deliveries.
  • HOOK-7 · P2 Add a dashboard Webhooks page: CRUD, secret reveal and rotation, test ping, delivery log.

Tasks: deployment (D6)

  • DEPLOY-1 · P1 Add a KURRENTDB_CONNECTION_STRING env var, defaulting to the current value.
  • DEPLOY-2 · P1 Give the backend a multi-stage Dockerfile with prod target: npm ci → nest build → node dist/main, running as non-root.
  • DEPLOY-3 · P1 Give the dashboard a multi-stage Dockerfile: ng build → nginx:alpine. An entrypoint writes /config.json ({ "apiUrl": "$API_URL" }), and the dashboard loads it at startup through APP_INITIALIZER instead of environment.apiUrl.
    • Uses provideAppInitializer + AppConfigService; the nginx entrypoint is frontend/dashboard/docker/40-write-config.sh.
  • DEPLOY-4 · P1 Add docker-compose.prod.yml:
    • backend and dashboard services
    • kurrentdb with no published ports, on an internal network
    • named volumes kurrentdb-data and backend-data (SQLite at DB_FILE_PATH=data/data.sqlite)
    • backend and dashboard published on 127.0.0.1:3000 and 127.0.0.1:8080 only, for the reverse proxy
    • a healthcheck-gated depends_on
  • DEPLOY-5 · P2 Make CORS configurable with CORS_ORIGINS, which the dashboard origin and the partner site need.
  • DEPLOY-6 · P2 Add a production build:wc (--configuration=production).

Tasks: widget distribution (D4, D5)

  • WIDGET-1 · P1 Make consent-lib publish @biocomputingup/apicuron-consent, the Angular 14 library built with ng-packagr (dist/apicuron-consent).
  • WIDGET-2 · P1 Add a -wc package (e.g. consent-lib/packages/apicuron-consent-wc/) containing widget.js, a package.json and a manifest ({ version, apiCompat }). Point scripts/build.js at it instead of demo/.
  • [~] WIDGET-3 · P1 Add a release workflow (GitHub Actions) that publishes both packages with the same version.
    • Workflow ready, not run: .github/workflows/release-consent-lib.yml (tag consent-lib-vX.Y.Z). The first publish needs the NPM_TOKEN secret, ownership of the @biocomputingup npm scope, and a license decision (§7).
  • [~] WIDGET-4 · P1 Make the backend depend on the pinned @biocomputingup/apicuron-consent-wc. Serve it at /widget/widget.js with ServeStaticModule, which is already a dependency (@nestjs/serve-static). Log the widget version at startup.
    • Partly done: WidgetModule resolves the installed package (or WIDGET_DIR) and serves /widget/widget.js + /widget/manifest.json, logging the version. The dependency is not yet added to backend/package.json, because the package isn't on npm and npm ci would fail. Add the pinned dependency after the first release (see §7).
  • WIDGET-5 · P2 Make the widget default api-url to the origin of its own <script src> (document.currentScript), so partners only need the script tag and the element.
  • WIDGET-6 · P2 Deprecate <ac-apicuron-consent>: log a console warning, remove it from the demo, and make demo/index.html show <ac-consent-gather>.

Tasks: consistency and evidence

  • DATA-1 · P2 Record the clause version (or a hash of name + description) in UserGrantedConsent/UserRevokedConsent.
  • DATA-2 · P2 Document eventual consistency in the skills and the API docs, or offer read-your-write (return the stream revision on write).
    • Documented (docs Core concepts, Query consent; cmp-kurrent-cqrs skill). Read-your-write was not implemented.

2. Backend vs. the cmp-backend / cmp-kurrent-cqrs skills

# Skill says Actual Priority
2.1 The key dirs include src/permission-manager It doesn't exist. Clauses live in src/clause-manager, auth in src/auth and src/admin-auth. P3
2.2 It uses the @biocomputingup/nestjs-kurrent package It is a local library at backend/libs/nestjs-kurrent, imported through path mapping. P3
2.3 "The backend is fully tested" consent-manager has no specs. The only e2e test is the scaffold GET / test. P2
2.4 Commands validate input There is no global ValidationPipe, and the revoke and clause bodies are untyped inline objects. P2
2.5 Uses "clause" naming throughout Leftover names remain: PermissionDeletedEvent, userPermissionsDto, and the widget's permission_* aliases. P3

Tasks

  • SKILL-1 · P3 In cmp-kurrent-cqrs: replace permission-manager with clause-manager and list auth/admin-auth. Describe the projector and SQLite read model, plus the webhook dispatcher (HOOK-3).
  • SKILL-2 · P3 In cmp-backend: say that nestjs-kurrent is a local lib, and describe the CLI, the automatic migrations, and ORCID_SANDBOX.
  • BE-1 · P2 Add a global ValidationPipe({ whitelist: true, transform: true }), and DTOs for revoke and for clause create/modify.
  • BE-2 · P2 Make grant and revoke bodies symmetric: { orcidId, clauseIdentifier }.
  • BE-3 · P2 Add consent-manager.controller.spec.ts and an e2e test that grants and then queries, including the ACL from D2.
  • BE-4 · P3 Rename the remaining permission* symbols to clause*.

3. Backend correctness / hygiene

  • BE-5 · P1 Fail at startup when JWT_SECRET is missing. Today it falls back to 'fallback-secret-key-for-dev' (src/auth/auth.module.ts).
  • BE-6 · P2 Log startup errors and exit non-zero. Today bootstrap().catch(() => {}) in main.ts swallows them.
  • BE-7 · P2 Type the admin JWT sub as a string. Controllers currently type it as number.
  • BE-8 · P2 Stop /orcid/oauth/callback from posting to '*'. Restrict postMessage to CORS_ORIGINS.
  • BE-9 · P2 Make drizzle.config.ts read DB_FILE_PATH. Drop encryptionKey: 'mysecretkey', or wire it into the runtime client as well.
  • BE-10 · P3 Remove dead code:
    • clause-manager/users.controller.ts
    • admin-auth/auth.guard.ts
    • orcid/orcid-authenticated.decorator.ts (a duplicate)
    • the empty DatabaseService
    • the typeorm and @nestjs/typeorm dependencies
    • leftover console.log calls

4. Configuration / setup

# Issue Priority
4.1 .env.example lists ORCID_API_URL three times. ORCID_OAUTH_URL/ORCID_BASE_URL are never read. Sandbox mode is inferred from the ORCID_API_URL hostname (D7). P2
4.2 PORT and KURRENT_ENABLE_SUBSCRIPTIONS are read by the code but missing from .env.example. P3
4.3 The KurrentDB healthcheck curls https://node1.kurrentdb, but the node is insecure and named kurrentdb. depends_on doesn't wait for health. P2
4.4 The dev compose file never installs node_modules. P2
4.5 The create-admin CLI has no npm script. It calls setup() even when the passwords differ, and it can't add a second admin (D8). P2
4.6 The dashboard Dockerfile uses Node 22, but .nvmrc says 24. P3

Tasks

  • CONF-1 · P2 Add ORCID_SANDBOX=true|false (default false). It selects the sandbox API/OAuth/authorize URLs and replaces the hostname check in OrcidService. Remove ORCID_API_URL/ORCID_OAUTH_URL/ORCID_BASE_URL from .env.example, or keep ORCID_API_URL only as an advanced override.
    • When ORCID_SANDBOX is unset, a sandbox ORCID_API_URL still enables sandbox mode, with a deprecation warning, so existing .env files keep working.
  • CONF-2 · P2 Rewrite .env.example with one comment per variable:
    • JWT_SECRET, DB_FILE_PATH, PORT
    • KURRENTDB_CONNECTION_STRING, CORS_ORIGINS
    • ORCID_SANDBOX, ORCID_CLIENT_ID, ORCID_CLIENT_SECRET, ORCID_REDIRECT_URI
    • API_URL (dashboard)
  • CONF-3 · P2 Add npm run create-admin, so it runs as docker compose exec backend npm run create-admin. Add an AdminAuthService.createAdmin() that works even when admins already exist, keep setup() first-admin-only, and re-prompt when the passwords don't match.
  • CONF-4 · P2 Fix the healthcheck (curl -f http://localhost:2113/health/live) and use condition: service_healthy.
  • CONF-5 · P2 Have the dev containers run npm ci when node_modules is missing.
  • CONF-6 · P3 Align the dashboard Dockerfile's Node version with .nvmrc.

5. Frontend vs. the cmp-consent-lib / cmp-dashboard / cmp-architecture skills

# Skill says Actual Priority
5.1 .nvmrc is at /frontend/.nvmrc It is at frontend/consent-lib/.nvmrc (16). Dashboard and docs use 24. P3
5.2 cmp-architecture says to run watch:app in /frontend and refers to a cmp-frontend skill The command has to run in frontend/consent-lib. cmp-frontend doesn't exist, and the dashboard and docs aren't mentioned. P3
5.3 The lib has three parts Three projects exist (consent-widget, the demo, is unnamed in the skill), and two custom elements are registered. P3
5.4 Sidebar is dumb, with @Input/@Output It has no inputs or outputs, and decorator and signal APIs are mixed. P3
5.5 Components rely on AuthService The Overview page decodes the JWT itself, and the guards call HttpClient directly. P3
5.6 The dashboard manages users and clauses The Users page is a placeholder. There is no clause editing and no Webhooks page. P2
5.7 The widget component is finished The WIP <ac-consent-gather> still has leftovers. P2

Tasks

  • SKILL-3 · P3 Fix cmp-architecture: correct the paths and Node versions per app, reference cmp-consent-lib/cmp-dashboard, and mention frontend/docs and widget distribution (D4).
  • SKILL-4 · P3 Fix cmp-consent-lib: correct the .nvmrc path, list both elements (the legacy one deprecated), and describe the npm packages and release flow.
  • SKILL-5 · P3 Update cmp-dashboard for Angular 22, standalone components and signals. Move JWT decoding into AuthService.currentUser(), and route guard HTTP calls through a service.
  • FE-1 · P2 Finish the WIP in <ac-consent-gather>:
    • Use or remove lib/icons/orcid-logo.component.ts.
    • Make fetchUserConsentStatus(orcid?) use its argument.
    • Dedupe the fallback config in the input setters.
  • FE-2 · P2 Dashboard: implement the Users page (decisions per ORCID iD), clause editing (PUT /clauses/:id) and the Webhooks page (HOOK-7).
  • FE-3 · P2 Dashboard: load apiUrl from runtime /config.json (DEPLOY-3), and drop the unused environment.prod.ts.
  • FE-4 · P3 Remove dead code:
    • the serve:ssr:consent-widget script
    • window.apicuronConsentW
    • the unused AConsentProviders import
    • the commented-out WrapperComponent

Suggested alternative components (optional, not committed)

These would sit alongside <ac-consent-gather> for use cases beyond collecting consent for a single clause:

  • <ac-consent-status>: a read-only badge showing the signed-in user's status for a clause, e.g. on contribution pages.
  • <ac-consent-center>: a "my consents" panel listing every clause with grant/revoke toggles, for user profile or settings pages. It needs GET /clauses and a per-user GET /consent/me endpoint.
  • Headless JS client (@biocomputingup/apicuron-consent-client): the ORCID popup flow plus the consent API calls without any UI, for partners with their own design system or a non-Angular framework.

6. Repo / docs hygiene

  • DOC-1 · P3 Move contributor documentation (local development, Node versions, scripts, ORCID_SANDBOX) into the root README.md and skills. The docs site targets partner developers and admins only (D9).
  • DOC-2 · P3 skills-lock.json lists angular-new-app, which isn't installed. Install it or remove it.
    • Removed angular-new-app from skills-lock.json.
  • DOC-3 · P3 cmp.code-workspace references frontend/tsconfig.json, which doesn't exist. Point it at each sub-project.
  • DOC-4 · P3 Replace the stock frontend/dashboard/README.md with a pointer to the docs.

7. Implementation notes, new findings & remaining work

Bugs found and fixed during implementation

  • Subscription checkpoints used the wrong unit (libs/nestjs-kurrent/src/subscriptions/stream-subscription.ts). Checkpoints were taken from commitPosition (a global log position), but passed back as fromRevision (a revision of $ce-clause). With persisted checkpoints, a restarted subscription would have waited forever. Fixed: checkpoints now use resolved.link?.revision ?? event.revision. Covered by test/webhook-restart.e2e-spec.ts.
  • Checkpoints were never persisted (in-memory default): projections replayed from scratch on every start, and reactors would miss events emitted while the server was down. Added SqliteCheckpointStore.
  • SQLITE_BUSY when projections and reactors wrote concurrently. The library now processes them sequentially: projections first, then reactors.
  • GET /consent returned 500 whenever a decision existed: the clause's BigInt version can't be serialized to JSON. The dashboard Overview could never show data.
  • GET /consent/:clause_id listed revoked users without a status, so partners couldn't filter on it. It now returns { orcid, status, timestamp }.
  • Dashboard Overview compared the numeric status with 'Granted'/'Revoked' strings and read clause.title instead of clause.name.
  • GET /clauses?includeDeleted=false included deleted clauses, because without a ValidationPipe the query value was the truthy string "false". Fixed by BE-1.
  • npm run start:prod pointed at dist/main, but the build outputs dist/src/main.js (because libs/ is compiled too).
  • The KurrentDB gRPC client was never disposed and shutdown hooks weren't enabled, so docker stop didn't flush checkpoints.
  • The create-clause modal accepted _, which the backend rejects.

Remaining / follow-ups

  • REL-1 · P1 License set to GPL-3.0-or-later. Added LICENSE (GPL v3 text); license fields in all package.json files; LICENSE is shipped in both npm packages.
  • REL-2 · P1 Publish the first consent-lib-v0.1.0 release (needs the NPM_TOKEN secret and the @biocomputingup scope), then add "@biocomputingup/apicuron-consent-wc": "0.1.0" to backend/package.json (completes WIDGET-3/WIDGET-4). Until then, mount a local build with WIDGET_DIR. Owner: maintainer (deferred).
  • DB-1 · P2 SQLITE_BUSY on concurrent writes. Resolved by switching to better-sqlite3 (option G below): one synchronous connection per process, WAL, 5 s busy timeout. Verified on the running server: 200 concurrent admin writes during a full read-model replay plus 200 writes from a second process gave 0 failures.
  • FE-5 · P3 <ac-consent-gather> loaded /clauses three times on initialisation. Loading is now deferred by a microtask and deduplicated per (apiUrl, clause); the server text is no longer overwritten by the config fallback. Verified in Chrome: one request.
  • BE-11 · P3 ESLint:
    • Config: added ignores (dist, coverage, drizzle); made no-floating-promises and no-unsafe-argument errors in application code; no-unused-vars with _ prefixes. Tests relax only mock-related rules (unbound-method, no-unsafe-*, no-explicit-any, require-await). npm run lint:check is --max-warnings=0.
    • Result: 239 problems → 0, and tsc --noEmit is clean as well (the pre-existing repository.spec.ts error is fixed).
    • Code fixes: typed define-model (no this: any), User decorator and AuthGuard request types, the clause query, ConsentStatus reverse map, await of a non-promise in stream-subscription.ts. Test mocks now mimic the client's streaming readStream. Type-level wildcards (Decider<infer S, any, …>, EventDefinition<any, …>) keep any with a justified, line-scoped disable: these types are invariant, so unknown doesn't type-check.
    • Not covered: frontend/consent-lib and frontend/dashboard have no ESLint setup (see LINT-1).
  • E2E-1 · P3 Tested against the real ORCID sandbox with the .env application credentials, in headless Chrome over the DevTools protocol (11/11 checks):
    • OAuth config; the authorize popup (client_id, redirect_uri, random state).
    • A page-initiated redirect to the CMP callback: postMessage → code exchange → ORCID invalid_grant, shown in the widget.
    • Grant and revoke through the UI with a signed-in session; registry search and verify.
    • Not automatable: typing a password into ORCID's sign-in page (it needs a sandbox user account, which .env doesn't contain).
  • SEC-1 · P1 (found during E2E-1) The widget accepted ORCID_AUTH_CODE messages from any window and sent no OAuth state, which allowed login CSRF. Now: a random state round-trip (the callback page echoes it), plus event.source === popup and event.origin === callback origin checks. Unit-tested and verified in the browser.
  • FE-6 · P3 (found during E2E-1) Sign-in errors showed Angular's generic "Http failure response …" instead of the backend's message.
  • LINT-1 · P3 Add ESLint (angular-eslint) to frontend/dashboard (Angular 22) and frontend/consent-lib (Angular 14, needs angular-eslint 14.x), and add them to CI.

DB-1 analysis: SQLITE_BUSY on concurrent writes

Measured with @libsql/client 0.15 against a local file:

Scenario Result
HTTP-style write while a projector-style interactive transaction is open SQLITE_BUSY immediately
Sustained: projector transactions (200) + concurrent HTTP writes (200) 200/200 HTTP writes failed, with or without WAL
Same workload with atomic batch() instead of interactive transactions 0 failures
PRAGMA busy_timeout set on the client no effect: each interactive transaction hands its connection off, and the next statement opens a fresh connection with default settings
Native driver opened with timeout (what patching the client would give) still SQLITE_BUSY, after blocking the event loop for the whole timeout
Reads during an open write transaction fine, even without WAL

Why: libsql executes local SQL synchronously. An interactive transaction holds the write lock across awaits, and every other write in the same process uses a second connection. A busy wait cannot work in-process: the waiting call blocks the event loop, so the lock holder (same process) can never commit. Today this is rare in normal operation, but during a read-model replay (e.g. after deleting the SQLite file) practically every admin write fails.

Options

Option Pros Cons
A Patch @libsql/client (patch-package) to pass timeout One-line patch Does not work in-process (measured): it freezes the server for the timeout and still fails. Also a maintenance burden on every upgrade.
B Replace the projector's interactive transactions with atomic db.batch([...]) (3 places in ClauseProjector; their read-then-write logic becomes INSERT … ON CONFLICT DO NOTHING + upsert) Removes the root cause: a batch runs as one synchronous call, so nothing can interleave in-process (measured 0 failures). Small, local change; same atomicity. Simpler SQL. Batches can't branch on intermediate reads, so the logic must be expressible as upserts (it is today). Future code must follow the "no interactive transactions" rule (document it in the skill / lint it). Other processes (e.g. the CLI running alongside the server) can still collide, rarely.
C App-level async write lock (mutex) around every write and transaction Eliminates in-process conflicts for any write shape, including future complex transactions Touches every write call site (or needs a DB-client proxy). Must be reentrant (AsyncLocalStorage) to avoid self-deadlock. Serialises all writes (fine at this scale). More code to maintain.
D Retry SQLITE_BUSY with async backoff (await sleep) at write call sites Simple. Also covers cross-process conflicts (CLI vs. server). Treats symptoms; under a long replay, retries can still exhaust. Needs wrapping each write path; adds latency jitter.
E Enable WAL Persistent and cheap; better read/write concurrency in general Doesn't solve writer-vs-writer (measured: still 200/200). Adds -wal/-shm files to back up together.
F Move the read model to PostgreSQL No single-writer limitation; standard ops tooling Another container for every partner; large migration (drizzle dialect, migrations, tests); contradicts the lightweight self-hosting goal.

Original recommendation (superseded by G): B, plus D only in the create-admin CLI (the one cross-process writer). B fixes the cause with the smallest change and no new moving parts. Add the rule "no interactive transactions on the SQLite read model; use batch" to the cmp-kurrent-cqrs skill. C is the fallback if future features genuinely need read-modify-write transactions.

Decision: G. Switch the driver to better-sqlite3 (raised by the maintainer after this analysis).

Option Pros Cons
G better-sqlite3 with WAL and a busy timeout One connection for the process's lifetime, never handed off, so the busy timeout stays in force. Transactions are synchronous: they finish before any other JavaScript runs, so in-process writes can't collide. WAL plus the busy timeout covers the CLI writing alongside the server, so D isn't needed. Transactions must be written without await (3 places converted). A native module (prebuilt for the Debian images). Drops libsql's remote (Turso) option, which nothing used. WAL adds -wal/-shm files, so backups must use VACUUM INTO or stop the backend (documented in Deploy).

Measured with G:

  • Synthetic: 200 synchronous transactions interleaved with 200 writes in the same process, plus 200 writes from a second process. 0 SQLITE_BUSY.
  • Real server: 200 concurrent POST /clauses during a full projection replay, plus 200 inserts from a second process. All returned 201, all 200 were projected, 0 busy errors.