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.
| # | 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. |
| # | 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 |
- AUTH-1 · P1 Add
@Authenticated()(admin) toGET /consentandGET /consent/:clause_id. - AUTH-2 · P1 Add
@OrcidAuthenticated()toGET /consent/:clause_id/:orcid. Return 403 whenreq.user.sub !== :orcid. The widget already sends its Bearer token: checkconsent-client.service.ts. - AUTH-3 · P2 Send the admin token from the dashboard Overview page (the interceptor already does this; verify it).
- HOOK-1 · P1 Add a SQLite table
webhooks:id,url,secret,events[], optionalclauses[]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 apingevent). 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,UserRevokedConsentand (opt-in)ClauseCreated/ClauseModified/ClauseDeletedto the payload{ id, type, occurredAt, data: { orcid, clauseIdentifier, status } }. idis the KurrentDB event id.- Done differently: a
@Reactor(catch-up subscription with a persisted checkpoint) writes to a SQLite outbox (webhook_deliveries), andWebhookDispatcherServicesends from it. Same at-least-once guarantee, the delivery log comes for free, and no server-side persistent-subscription group is needed.
- It maps
- HOOK-4 · P1 Sign
<X-CMP-Timestamp>.<raw body>with HMAC-SHA256 using the per-webhook secret. Send the headersX-CMP-Signature: sha256=<hex>,X-CMP-Event,X-CMP-DeliveryandX-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_deliverieslog table andGET /webhooks/:id/deliveries. - HOOK-7 · P2 Add a dashboard Webhooks page: CRUD, secret reveal and rotation, test ping, delivery log.
- DEPLOY-1 · P1 Add a
KURRENTDB_CONNECTION_STRINGenv var, defaulting to the current value. - DEPLOY-2 · P1 Give the backend a multi-stage Dockerfile with
prodtarget: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 throughAPP_INITIALIZERinstead ofenvironment.apiUrl.- Uses
provideAppInitializer+AppConfigService; the nginx entrypoint isfrontend/dashboard/docker/40-write-config.sh.
- Uses
- DEPLOY-4 · P1 Add
docker-compose.prod.yml:backendanddashboardserviceskurrentdbwith no published ports, on an internal network- named volumes
kurrentdb-dataandbackend-data(SQLite atDB_FILE_PATH=data/data.sqlite) - backend and dashboard published on
127.0.0.1:3000and127.0.0.1:8080only, 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).
- WIDGET-1 · P1 Make
consent-libpublish@biocomputingup/apicuron-consent, the Angular 14 library built with ng-packagr (dist/apicuron-consent). - WIDGET-2 · P1 Add a
-wcpackage (e.g.consent-lib/packages/apicuron-consent-wc/) containingwidget.js, apackage.jsonand a manifest ({ version, apiCompat }). Pointscripts/build.jsat it instead ofdemo/. - [~] 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(tagconsent-lib-vX.Y.Z). The first publish needs theNPM_TOKENsecret, ownership of the@biocomputingupnpm scope, and a license decision (§7).
- Workflow ready, not run:
- [~] WIDGET-4 · P1 Make the backend depend on the pinned
@biocomputingup/apicuron-consent-wc. Serve it at/widget/widget.jswithServeStaticModule, which is already a dependency (@nestjs/serve-static). Log the widget version at startup.- Partly done:
WidgetModuleresolves the installed package (orWIDGET_DIR) and serves/widget/widget.js+/widget/manifest.json, logging the version. The dependency is not yet added tobackend/package.json, because the package isn't on npm andnpm ciwould fail. Add the pinned dependency after the first release (see §7).
- Partly done:
- WIDGET-5 · P2 Make the widget default
api-urlto 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 makedemo/index.htmlshow<ac-consent-gather>.
- 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-cqrsskill). Read-your-write was not implemented.
- Documented (docs Core concepts, Query consent;
| # | 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 |
- SKILL-1 · P3 In
cmp-kurrent-cqrs: replacepermission-managerwithclause-managerand listauth/admin-auth. Describe the projector and SQLite read model, plus the webhook dispatcher (HOOK-3). - SKILL-2 · P3 In
cmp-backend: say thatnestjs-kurrentis a local lib, and describe the CLI, the automatic migrations, andORCID_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.tsand an e2e test that grants and then queries, including the ACL from D2. - BE-4 · P3 Rename the remaining
permission*symbols toclause*.
- BE-5 · P1 Fail at startup when
JWT_SECRETis 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(() => {})inmain.tsswallows them. - BE-7 · P2 Type the admin JWT
subas a string. Controllers currently type it asnumber. - BE-8 · P2 Stop
/orcid/oauth/callbackfrom posting to'*'. RestrictpostMessagetoCORS_ORIGINS. - BE-9 · P2 Make
drizzle.config.tsreadDB_FILE_PATH. DropencryptionKey: 'mysecretkey', or wire it into the runtime client as well. - BE-10 · P3 Remove dead code:
clause-manager/users.controller.tsadmin-auth/auth.guard.tsorcid/orcid-authenticated.decorator.ts(a duplicate)- the empty
DatabaseService - the
typeormand@nestjs/typeormdependencies - leftover
console.logcalls
| # | 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 |
- CONF-1 · P2 Add
ORCID_SANDBOX=true|false(defaultfalse). It selects the sandbox API/OAuth/authorize URLs and replaces the hostname check inOrcidService. RemoveORCID_API_URL/ORCID_OAUTH_URL/ORCID_BASE_URLfrom.env.example, or keepORCID_API_URLonly as an advanced override.- When
ORCID_SANDBOXis unset, a sandboxORCID_API_URLstill enables sandbox mode, with a deprecation warning, so existing.envfiles keep working.
- When
- CONF-2 · P2 Rewrite
.env.examplewith one comment per variable:JWT_SECRET,DB_FILE_PATH,PORTKURRENTDB_CONNECTION_STRING,CORS_ORIGINSORCID_SANDBOX,ORCID_CLIENT_ID,ORCID_CLIENT_SECRET,ORCID_REDIRECT_URIAPI_URL(dashboard)
- CONF-3 · P2 Add
npm run create-admin, so it runs asdocker compose exec backend npm run create-admin. Add anAdminAuthService.createAdmin()that works even when admins already exist, keepsetup()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 usecondition: service_healthy. - CONF-5 · P2 Have the dev containers run
npm ciwhennode_modulesis missing. - CONF-6 · P3 Align the dashboard Dockerfile's Node version with
.nvmrc.
| # | 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 |
- SKILL-3 · P3 Fix
cmp-architecture: correct the paths and Node versions per app, referencecmp-consent-lib/cmp-dashboard, and mentionfrontend/docsand widget distribution (D4). - SKILL-4 · P3 Fix
cmp-consent-lib: correct the.nvmrcpath, list both elements (the legacy one deprecated), and describe the npm packages and release flow. - SKILL-5 · P3 Update
cmp-dashboardfor Angular 22, standalone components and signals. Move JWT decoding intoAuthService.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.
- Use or remove
- 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
apiUrlfrom runtime/config.json(DEPLOY-3), and drop the unusedenvironment.prod.ts. - FE-4 · P3 Remove dead code:
- the
serve:ssr:consent-widgetscript window.apicuronConsentW- the unused
AConsentProvidersimport - the commented-out
WrapperComponent
- the
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 needsGET /clausesand a per-userGET /consent/meendpoint.- 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.
- DOC-1 · P3 Move contributor documentation (local development, Node versions, scripts,
ORCID_SANDBOX) into the rootREADME.mdand skills. The docs site targets partner developers and admins only (D9). - DOC-2 · P3
skills-lock.jsonlistsangular-new-app, which isn't installed. Install it or remove it.- Removed
angular-new-appfromskills-lock.json.
- Removed
- DOC-3 · P3
cmp.code-workspacereferencesfrontend/tsconfig.json, which doesn't exist. Point it at each sub-project. - DOC-4 · P3 Replace the stock
frontend/dashboard/README.mdwith a pointer to the docs.
- Subscription checkpoints used the wrong unit (
libs/nestjs-kurrent/src/subscriptions/stream-subscription.ts). Checkpoints were taken fromcommitPosition(a global log position), but passed back asfromRevision(a revision of$ce-clause). With persisted checkpoints, a restarted subscription would have waited forever. Fixed: checkpoints now useresolved.link?.revision ?? event.revision. Covered bytest/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_BUSYwhen projections and reactors wrote concurrently. The library now processes them sequentially: projections first, then reactors.GET /consentreturned 500 whenever a decision existed: the clause's BigIntversioncan't be serialized to JSON. The dashboard Overview could never show data.GET /consent/:clause_idlisted 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 readclause.titleinstead ofclause.name. GET /clauses?includeDeleted=falseincluded deleted clauses, because without aValidationPipethe query value was the truthy string"false". Fixed by BE-1.npm run start:prodpointed atdist/main, but the build outputsdist/src/main.js(becauselibs/is compiled too).- The KurrentDB gRPC client was never disposed and shutdown hooks weren't enabled, so
docker stopdidn't flush checkpoints. - The create-clause modal accepted
_, which the backend rejects.
- REL-1 · P1 License set to GPL-3.0-or-later. Added
LICENSE(GPL v3 text);licensefields in allpackage.jsonfiles;LICENSEis shipped in both npm packages. - REL-2 · P1 Publish the first
consent-lib-v0.1.0release (needs theNPM_TOKENsecret and the@biocomputingupscope), then add"@biocomputingup/apicuron-consent-wc": "0.1.0"tobackend/package.json(completes WIDGET-3/WIDGET-4). Until then, mount a local build withWIDGET_DIR. Owner: maintainer (deferred). - DB-1 · P2
SQLITE_BUSYon concurrent writes. Resolved by switching tobetter-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/clausesthree 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); madeno-floating-promisesandno-unsafe-argumenterrors in application code;no-unused-varswith_prefixes. Tests relax only mock-related rules (unbound-method,no-unsafe-*,no-explicit-any,require-await).npm run lint:checkis--max-warnings=0. - Result: 239 problems → 0, and
tsc --noEmitis clean as well (the pre-existingrepository.spec.tserror is fixed). - Code fixes: typed
define-model(nothis: any),Userdecorator andAuthGuardrequest types, the clause query,ConsentStatusreverse map,awaitof a non-promise instream-subscription.ts. Test mocks now mimic the client's streamingreadStream. Type-level wildcards (Decider<infer S, any, …>,EventDefinition<any, …>) keepanywith a justified, line-scoped disable: these types are invariant, sounknowndoesn't type-check. - Not covered:
frontend/consent-libandfrontend/dashboardhave no ESLint setup (see LINT-1).
- Config: added ignores (
- E2E-1 · P3 Tested against the real ORCID sandbox with the
.envapplication 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 → ORCIDinvalid_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
.envdoesn't contain).
- SEC-1 · P1 (found during E2E-1) The widget accepted
ORCID_AUTH_CODEmessages from any window and sent no OAuthstate, which allowed login CSRF. Now: a randomstateround-trip (the callback page echoes it), plusevent.source === popupandevent.origin === callback originchecks. 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) tofrontend/dashboard(Angular 22) andfrontend/consent-lib(Angular 14, needs angular-eslint 14.x), and add them to CI.
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 /clausesduring a full projection replay, plus 200 inserts from a second process. All returned201, all 200 were projected, 0 busy errors.