@happyvertical/smrt-core 0.42.7 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +26 -2
- package/agents/schema-paths.md +29 -15
- package/dist/cascade.d.ts +7 -6
- package/dist/cascade.d.ts.map +1 -1
- package/dist/cascade.js +19 -21
- package/dist/cascade.js.map +1 -1
- package/dist/class.d.ts +10 -0
- package/dist/class.d.ts.map +1 -1
- package/dist/class.js +21 -0
- package/dist/class.js.map +1 -1
- package/dist/decorators/index.d.ts +33 -15
- package/dist/decorators/index.d.ts.map +1 -1
- package/dist/decorators/index.js +16 -11
- package/dist/decorators/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +17 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +20 -1
- package/dist/migrations/differ.d.ts +2 -0
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +75 -0
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/generator.d.ts.map +1 -1
- package/dist/migrations/generator.js +19 -2
- package/dist/migrations/generator.js.map +1 -1
- package/dist/migrations/orchestrate.d.ts.map +1 -1
- package/dist/migrations/orchestrate.js +4 -1
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/object.d.ts +4 -4
- package/dist/object.js +4 -4
- package/dist/object.js.map +1 -1
- package/dist/registry/schema-builder.d.ts +6 -0
- package/dist/registry/schema-builder.d.ts.map +1 -1
- package/dist/registry/schema-builder.js +78 -8
- package/dist/registry/schema-builder.js.map +1 -1
- package/dist/registry.d.ts +5 -7
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +6 -8
- package/dist/registry.js.map +1 -1
- package/dist/scanner/manifest-generator.d.ts.map +1 -1
- package/dist/scanner/manifest-generator.js +62 -18
- package/dist/scanner/manifest-generator.js.map +1 -1
- package/dist/scanner/types.d.ts +5 -1
- package/dist/scanner/types.d.ts.map +1 -1
- package/dist/scanner/types.js.map +1 -1
- package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/base-strategy.js +2 -0
- package/dist/schema/ddl/base-strategy.js.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.d.ts +1 -0
- package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.js +17 -1
- package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
- package/dist/schema/ddl/postgres-strategy.js +1 -1
- package/dist/schema/foreign-key-ddl.d.ts +9 -0
- package/dist/schema/foreign-key-ddl.d.ts.map +1 -0
- package/dist/schema/foreign-key-ddl.js +53 -0
- package/dist/schema/foreign-key-ddl.js.map +1 -0
- package/dist/schema/foreign-key-planner.d.ts +18 -0
- package/dist/schema/foreign-key-planner.d.ts.map +1 -0
- package/dist/schema/foreign-key-planner.js +109 -0
- package/dist/schema/foreign-key-planner.js.map +1 -0
- package/dist/schema/foreign-key-policy.d.ts +21 -0
- package/dist/schema/foreign-key-policy.d.ts.map +1 -0
- package/dist/schema/foreign-key-policy.js +41 -0
- package/dist/schema/foreign-key-policy.js.map +1 -0
- package/dist/schema/generator.d.ts +3 -0
- package/dist/schema/generator.d.ts.map +1 -1
- package/dist/schema/generator.js +54 -10
- package/dist/schema/generator.js.map +1 -1
- package/dist/schema/index.d.ts +3 -0
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema/index.js +4 -1
- package/dist/schema/manifest-schema.d.ts.map +1 -1
- package/dist/schema/manifest-schema.js +20 -3
- package/dist/schema/manifest-schema.js.map +1 -1
- package/dist/schema/schema-aggregator.d.ts +7 -1
- package/dist/schema/schema-aggregator.d.ts.map +1 -1
- package/dist/schema/schema-aggregator.js +54 -9
- package/dist/schema/schema-aggregator.js.map +1 -1
- package/dist/schema/schema-manager.d.ts +1 -6
- package/dist/schema/schema-manager.d.ts.map +1 -1
- package/dist/schema/schema-manager.js +26 -30
- package/dist/schema/schema-manager.js.map +1 -1
- package/dist/schema/types.d.ts +8 -5
- package/dist/schema/types.d.ts.map +1 -1
- package/dist/schema/utils.d.ts.map +1 -1
- package/dist/schema/utils.js +14 -1
- package/dist/schema/utils.js.map +1 -1
- package/dist/schema.js +4 -1
- package/dist/smrt-knowledge.json +18 -8
- package/dist/testing/database.d.ts +11 -1
- package/dist/testing/database.d.ts.map +1 -1
- package/dist/testing/database.js +80 -9
- package/dist/testing/database.js.map +1 -1
- package/package.json +4 -4
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,17 +3,17 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-core",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.43.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "e84a5eedbdf8799a4cef79f9ec3ebc7fd9ca82df0032344c290ac189c3530e6c",
|
|
11
|
+
"packageJson": "cf688370e1f374cf55e0b716bed71998ed6c966f28628b7dd55642561fdeeace",
|
|
12
|
+
"agents": "0f864c4fc9a8c476f387bd3c68199ea06321578a1dab2f36e7866a4ef7dfc001",
|
|
13
13
|
"moduleDoc:agents/change-feed.md": "1530ded9ed605aa9b8a772b3ba4dd992a3f797f4d7c9ede3b3389dd7bfb401fa",
|
|
14
14
|
"moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
|
|
15
15
|
"moduleDoc:agents/generators.md": "2b6ccd5ff557293f2ce84d25cc254ceb518f4c274d93b7e3175985b18f36f564",
|
|
16
|
-
"moduleDoc:agents/schema-paths.md": "
|
|
16
|
+
"moduleDoc:agents/schema-paths.md": "0003296e4d3c8e253eb1be11b60d8b364ed3b1e02efefcee98e9b76aeb58296f",
|
|
17
17
|
"moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
|
|
18
18
|
"moduleDoc:agents/collection-reads.md": "9773b8306e6560a0968514a1c809121bdd63c7e2f74ec0d6e1da0d366420f027",
|
|
19
19
|
"moduleDoc:agents/memory.md": "658cb34f3a499e290c14ba0dd8cf0bf82bcc571da01150b61070abf100894dfc",
|
|
@@ -107,7 +107,8 @@
|
|
|
107
107
|
"getAiUsageSnapshot",
|
|
108
108
|
"listAiUsage",
|
|
109
109
|
"resetAiUsage",
|
|
110
|
-
"summarizeAiUsage"
|
|
110
|
+
"summarizeAiUsage",
|
|
111
|
+
"withDatabase"
|
|
111
112
|
],
|
|
112
113
|
"methodSignatures": [
|
|
113
114
|
{
|
|
@@ -137,6 +138,15 @@
|
|
|
137
138
|
"options?: AiUsageSummaryOptions"
|
|
138
139
|
],
|
|
139
140
|
"returns": "Promise<Record<string, AiUsageStats>>"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"name": "withDatabase",
|
|
144
|
+
"async": true,
|
|
145
|
+
"params": [
|
|
146
|
+
"db: DatabaseInterface",
|
|
147
|
+
"operation: Function"
|
|
148
|
+
],
|
|
149
|
+
"returns": "Promise<T>"
|
|
140
150
|
}
|
|
141
151
|
],
|
|
142
152
|
"surfaces": [],
|
|
@@ -943,7 +953,7 @@
|
|
|
943
953
|
"polymorphicAssociations": 1,
|
|
944
954
|
"uuidColumns": 3
|
|
945
955
|
},
|
|
946
|
-
"agentDoc": "# @happyvertical/smrt-core\n\nORM, code generation, AI integration, and the DispatchBus. Everything else builds on this.\n\nKey surfaces are `SmrtObject`, `SmrtCollection`, `ObjectRegistry`,\n`DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; this file documents\ntheir invariants and source locations, and the module docs below cover the\nper-subsystem semantics.\n\n## Modules\n\nSubsystem semantics live in sibling module docs — read the one for the\nsubsystem you are editing. This file keeps what holds across all of them.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/change-feed.ts` | the adapter-agnostic change-observation spine — `_smrt_changes`, cursors, table versions, generated `_changes` routes, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` + the generated `_events` SSE route | the push companion to the change feed — the signal bus, cross-replica fan-out, the SSE route, and its documented gaps | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/` + `src/vite-plugin/web-collections.ts` | REST/CLI/MCP/web-collection generation, the `manifestHash` emission sites, and generated conditional-GET / ETag v2 semantics | [agents/generators.md](agents/generators.md) |\n| `src/schema/` | the four `SchemaGenerator` entry points, which two reach production, why schema drift stayed invisible, and the #2382 index/tenancy rules | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/data-query.ts` | canonical bounded data-query normalizer and transport-neutral envelope (#2444) | [agents/data-query.md](agents/data-query.md) |\n| `src/collection.ts` | bounded collection reads, projections, latest-related hydration, facets, counts, and read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n\n## SmrtObject Lifecycle\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\n## LearningMemory (#1886)\n\n`LearningMemory` provides tenant-isolated, confidence-scored recall over\n`_smrt_contexts` plus optional injected semantic search. `capture()` reinforces\nsuccesses and decays failures while updating outcome counters; `recall()`\napplies confidence, expiry, time-decay, and hierarchical-scope filters and\nrefreshes `last_used_at`. Detailed persistence and search semantics are in\n[agents/memory.md](agents/memory.md). Keep semantic search behind the\n`SmrtCollection.semanticSearch`-compatible injection boundary.\n\n## SmrtCollection Query\n\n```typescript\nawait collection.list({\n where: { status: 'active', 'price >': 10 },\n limit: 50, offset: 0, orderBy: 'created_at DESC'\n});\n```\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [agents/collection-reads.md](agents/collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\nThis list is the set `@happyvertical/sql`'s `buildWhere` can execute, and\n`convertWhereKeys` accepts nothing outside it — an operator accepted here but\nunknown there fails inside the query builder, after the API said the query was\nvalid (#2276). Two entries were removed for that reason and now reject at the\nAPI boundary: `contains` (never existed in the SQL layer; use `like` with\nexplicit wildcards) and dot-notation JSON paths such as `metadata.userId` (never\nrewritten into an extraction expression, so they reached SQL as qualified column\nreferences). Re-adding either requires the query builder to support it first;\n`src/__tests__/issue-2276-where-contract.test.ts` executes every accepted\noperator against a database to keep the two in step.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [agents/query-bounds.md](agents/query-bounds.md).\n\n## Canonical Bounded Data Queries (#2444)\n\nThe normalizers and fingerprint are the trust boundary for the\ntransport-neutral query envelope; full bounds, schema, and output rules live in\n[agents/data-query.md](agents/data-query.md). Adapters own tenant/principal\naccess and query execution.\n\n## Object Memory & Semantic Search\n\nContext memory and semantic search are persistence primitives inherited by\n`SmrtObject`/`SmrtCollection`; their storage, scope, expiry, and tenant\ninvariants are in [agents/memory.md](agents/memory.md).\n\n## @smrt() Decorator Options\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes, #2357 — see \"Schema paths\"), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n\n## Vite Plugin\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Schema paths (#2382)\n\n`ensureSystemTables(db, typeHint?)` is the public, idempotent provisioning\nboundary for framework-owned `_smrt_*` tables. Call it on a base PostgreSQL\nconnection before opening a caller-owned transaction; its advisory-locked\nbootstrap prevents missing-table probes from poisoning that transaction.\n\nProduction DDL comes from the **manifest** paths\n(`generateSTISchemaFromManifest`/`generateCTISchemaFromManifest`, selected in\n`src/scanner/manifest-generator.ts` → registered `schema` → `db:migrate`). The\n**registry** paths feed `getTestDatabase()` and emit foreign-key indexes\nproduction never gets: the suite runs on a richer schema than it ships.\n\n- Change column/index emission on every shipping path, proven by the path-parity\n test `src/schema/schema-path-parity.test.ts` (#2359; index rules in the module doc). A \"same as migrations\" comment is a claim to check.\n- Every new query predicate ships with its index, or a reason it doesn't.\n- Numeric types, uuid casts, conflict targets, timestamps, migrations: run the\n `test:postgres` lane — SQLite affinity accepts what PostgreSQL rejects.\n- Read `dist/manifest.json`/regenerated schemas for what a decorator produced;\n count across all packages instead of sampling.\n- Tenant scoping is whole-path: every unique constraint and conflict target on a\n tenant-scoped table carries the tenant column, and every read path — not only\n `list()` — is interceptor-aware.\n- Rolling indexes out is part of the change: a bulk `CREATE INDEX` batch needs\n the bounded, concurrent migrate path (#2362, Gotchas), or it takes production\n down on deploy.\n\n## Gotchas\n\n- **Filesystem support is a lazy boundary (#1979)**: `SmrtClass` acquires `options.fs` adapters via `createFilesystemAdapter()` (`src/filesystem-loader.ts`), never a static `@happyvertical/files` import — the files SDK statically pulls @aws-sdk/client-s3 and reaches googleapis, and a static edge here would land it in every downstream SSR bundle. Node/tsx/vite-dev runtimes resolve it on first use; fully-bundled deployments import `@happyvertical/smrt-core/filesystem` at startup. Use `importOptionalDependency()` (`src/lazy-external.ts`) for any similar optional heavyweight dependency.\n- **Never override toJSON()** — handles STI discriminator + meta field extraction. Use `transformJSON()`\n- **Property init order**: TypeScript initializers run first, then `initialize()` applies option values (options win)\n- **No runtime schema creation**: application tables must be prepared explicitly via migrations/tooling; runtime verification is `tableExists()` only (`src/schema/table-verifier.ts`) — no column, type, or index check\n- **PostgreSQL migrate batches are always time-bounded (#2362)**: `MigrationTracker.applyAll({ atomic: true })` emits `SET LOCAL lock_timeout`/`statement_timeout` before any DDL, so a batch blocked on one table cannot hold its earlier locks indefinitely. `postgresSafe: true` adds concurrent-index mode — non-index DDL commits atomically, then index DDL runs `CONCURRENTLY` on a session pinned via `db.acquireSession()` (a pooled `db.query` would not keep the `SET` and the DDL on one connection). That mode is deliberately **not atomic**: unfinished index migrations are recorded `failed`, not `running`, and their `error_message` carries a `[smrt: concurrent-index phase 1 committed]` marker so a reconciling re-run resumes at the index build instead of replaying committed DDL. INVALID indexes are found via `pg_index.indisvalid` (`pg_indexes` reports them as present) and dropped before rebuild. Operational detail: `packages/cli/AGENTS.md`.\n- **Retry logic is transient-only (#2366)**: `db.get()`/`db.upsert()` retry 4× total (initial + 3), but `ErrorUtils.withRetry` classifies via the cause chain (`src/db-errors.ts`) and rethrows deterministic failures immediately — constraint violations, bad input syntax, missing tables, aborted PG tx (`25P02`). `@happyvertical/sql` stringifies the driver text into `context.originalError`, so **never match `error.message`**; use `classifyDatabaseError()` / `isUniqueViolationError()` / `isAbortedTransactionError()`.\n- **Field caching**: `_cachedFields` populated during `Collection.create()` — eliminates async `getFields()` per query\n- **Smart cloning**: arrays/objects shallow-cloned in property init to prevent aliasing (Issue #22)\n- **Table verification cache**: `isTableVerified(dbUrl, tableName)` avoids redundant `tableExists()` calls\n- **Manifest required**: build-time AST scanning creates manifest. Without vitest plugin → \"No field metadata\"\n- **ManifestBuilder fails on scanner errors**: every production manifest path\n must abort before adapting partial scan results. A syntax error or unresolved\n `@smrt()` config spread cannot be allowed to emit a default-open manifest.\n- **Vite plugin loads scanner from `dist/` first**: `src/vite-plugin/import-build-aware.ts` prefers `dist/` when it exists on disk; it only falls back to `src/` on fresh clones. So if you edit `src/scanner/*.ts` or `src/schema/generator.ts` and want those edits reflected in consumer manifest generation, you must rebuild (`pnpm build` or have `pnpm dev` / `pnpm build:watch` running in core). This is intentional — sniffing `.ts` vs `.js` via `import.meta.url` was non-deterministic under tsx and broke 12–13 publishes (#1139).\n- **Bundled registry ownership**: flattened production bundles can rewrite constructor names and make decorator-time stack inference attribute provider code to the consumer. Generated registration repairs identity only from the exact imported constructor plus an explicit package and isolated one-object manifest; never infer ownership from output paths, simple names, or table names. Distinct packages may export the same simple name under qualified keys. The production-consumer gate lives in `packages/bundle-gate/src/__tests__/registry-identity.spec.ts` (#2308).\n",
|
|
956
|
+
"agentDoc": "# @happyvertical/smrt-core\n\nORM, code generation, AI integration, and the DispatchBus. Everything else builds on this.\n\nKey surfaces are `SmrtObject`, `SmrtCollection`, `ObjectRegistry`,\n`DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; this file documents\ntheir invariants and source locations, and the module docs below cover the\nper-subsystem semantics.\n\n## Modules\n\nSubsystem semantics live in sibling module docs — read the one for the\nsubsystem you are editing. This file keeps what holds across all of them.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/change-feed.ts` | the adapter-agnostic change-observation spine — `_smrt_changes`, cursors, table versions, generated `_changes` routes, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` + the generated `_events` SSE route | the push companion to the change feed — the signal bus, cross-replica fan-out, the SSE route, and its documented gaps | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/` + `src/vite-plugin/web-collections.ts` | REST/CLI/MCP/web-collection generation, the `manifestHash` emission sites, and generated conditional-GET / ETag v2 semantics | [agents/generators.md](agents/generators.md) |\n| `src/schema/` | the four `SchemaGenerator` entry points, which two reach production, why schema drift stayed invisible, and the #2382 index/tenancy rules | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/data-query.ts` | canonical bounded data-query normalizer and transport-neutral envelope (#2444) | [agents/data-query.md](agents/data-query.md) |\n| `src/collection.ts` | bounded collection reads, projections, latest-related hydration, facets, counts, and read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n\n## SmrtObject Lifecycle\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\n## LearningMemory (#1886)\n\n`LearningMemory` provides tenant-isolated, confidence-scored recall over\n`_smrt_contexts` plus optional injected semantic search. `capture()` reinforces\nsuccesses and decays failures while updating outcome counters; `recall()`\napplies confidence, expiry, time-decay, and hierarchical-scope filters and\nrefreshes `last_used_at`. Detailed persistence and search semantics are in\n[agents/memory.md](agents/memory.md). Keep semantic search behind the\n`SmrtCollection.semanticSearch`-compatible injection boundary.\n\n## SmrtCollection Query\n\n```typescript\nawait collection.list({\n where: { status: 'active', 'price >': 10 },\n limit: 50, offset: 0, orderBy: 'created_at DESC'\n});\n```\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [agents/collection-reads.md](agents/collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\nThis list is the set `@happyvertical/sql`'s `buildWhere` can execute, and\n`convertWhereKeys` accepts nothing outside it — an operator accepted here but\nunknown there fails inside the query builder, after the API said the query was\nvalid (#2276). Two entries were removed for that reason and now reject at the\nAPI boundary: `contains` (never existed in the SQL layer; use `like` with\nexplicit wildcards) and dot-notation JSON paths such as `metadata.userId` (never\nrewritten into an extraction expression, so they reached SQL as qualified column\nreferences). Re-adding either requires the query builder to support it first;\n`src/__tests__/issue-2276-where-contract.test.ts` executes every accepted\noperator against a database to keep the two in step.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [agents/query-bounds.md](agents/query-bounds.md).\n\n## Canonical Bounded Data Queries (#2444)\n\nThe normalizers and fingerprint are the trust boundary for the\ntransport-neutral query envelope; full bounds, schema, and output rules live in\n[agents/data-query.md](agents/data-query.md). Adapters own tenant/principal\naccess and query execution.\n\n## Object Memory & Semantic Search\n\nContext memory and semantic search are persistence primitives inherited by\n`SmrtObject`/`SmrtCollection`; their storage, scope, expiry, and tenant\ninvariants are in [agents/memory.md](agents/memory.md).\n\n## @smrt() Decorator Options\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes, #2357 — see \"Schema paths\"), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n\n## Vite Plugin\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Schema paths (#2382)\n\n`ensureSystemTables(db, typeHint?)` is the public, idempotent provisioning\nboundary for framework-owned `_smrt_*` tables. Call it on a base PostgreSQL\nconnection before opening a caller-owned transaction; its advisory-locked\nbootstrap prevents missing-table probes from poisoning that transaction.\n\nProduction DDL comes from the **manifest** paths\n(`generateSTISchemaFromManifest`/`generateCTISchemaFromManifest`, selected in\n`src/scanner/manifest-generator.ts` → registered `schema` → `db:migrate`). The\n**registry** paths feed `getTestDatabase()`. Manifest and registry schemas must\nagree on same-package foreign keys as well as columns and indexes:\n`@foreignKey` emits a named physical constraint, while `@crossPackageRef` and\n`@tenantId` remain indexed runtime relationships without physical constraints.\nNatural-key references default to `CASCADE`; ordinary references default to\nimmediate `NO ACTION`, matching `SmrtObject.delete()`.\n\nSame-package archival/audit identifiers that intentionally outlive their\nparent may use `@foreignKey(Target, { constraint: false })`. This explicit\nexception retains relationship loading, indexing, and application-side delete\nmetadata while omitting the physical constraint, schema dependency, and\napp-side cascade/preflight action so the stored identifier survives deletion;\ndocument the retention reason at the field, and keep ordinary same-package\nrelationships constrained.\n\n- Change column/index emission on every shipping path, proven by the path-parity\n test `src/schema/schema-path-parity.test.ts` (#2359; index rules in the module doc). A \"same as migrations\" comment is a claim to check.\n- Every new query predicate ships with its index, or a reason it doesn't.\n- Creation is dependency-planned on every entry point. PostgreSQL defers mutual\n cycle constraints until both tables exist; SQLite keeps cycles inline;\n DuckDB refuses unsupported cycles/actions rather than silently omitting them.\n In particular, generated same-package constraints retain the compatibility\n default `ON UPDATE CASCADE`; DuckDB/JSON cannot enforce that action and must\n return an actionable refusal instead of stripping the clause.\n PostgreSQL deferred adds are idempotent and probe the exact child/parent\n columns for orphans before `NOT VALID` + validation. Rollback drops children\n before parents, removes deferred PostgreSQL cycle constraints first, and\n defers SQLite checks while dropping populated cycles. Schema aggregation that\n deliberately filters a parent also removes the retained child's physical FK.\n- Numeric types, uuid casts, conflict targets, timestamps, migrations: run the\n `test:postgres` lane — SQLite affinity accepts what PostgreSQL rejects.\n- Read `dist/manifest.json`/regenerated schemas for what a decorator produced;\n count across all packages instead of sampling.\n- Tenant scoping is whole-path: every unique constraint and conflict target on a\n tenant-scoped table carries the tenant column, and every read path — not only\n `list()` — is interceptor-aware.\n- Rolling indexes out is part of the change: a bulk `CREATE INDEX` batch needs\n the bounded, concurrent migrate path (#2362, Gotchas), or it takes production\n down on deploy.\n\n## Gotchas\n\n- **Filesystem support is a lazy boundary (#1979)**: `SmrtClass` acquires `options.fs` adapters via `createFilesystemAdapter()` (`src/filesystem-loader.ts`), never a static `@happyvertical/files` import — the files SDK statically pulls @aws-sdk/client-s3 and reaches googleapis, and a static edge here would land it in every downstream SSR bundle. Node/tsx/vite-dev runtimes resolve it on first use; fully-bundled deployments import `@happyvertical/smrt-core/filesystem` at startup. Use `importOptionalDependency()` (`src/lazy-external.ts`) for any similar optional heavyweight dependency.\n- **Transaction-bound instances**: `SmrtClass.withDatabase(db, callback)` temporarily binds an initialized instance (including its public `options.db`) to a supplied transaction database and restores the original binding on success or failure. Use it when domain validation and persistence must share one transaction; never reach into `_db`, and do not use the same instance concurrently during the callback.\n- **Never override toJSON()** — handles STI discriminator + meta field extraction. Use `transformJSON()`\n- **Property init order**: TypeScript initializers run first, then `initialize()` applies option values (options win)\n- **No runtime schema creation**: application tables must be prepared explicitly via migrations/tooling; runtime verification is `tableExists()` only (`src/schema/table-verifier.ts`) — no column, type, or index check\n- **PostgreSQL migrate batches are always time-bounded (#2362)**: `MigrationTracker.applyAll({ atomic: true })` emits `SET LOCAL lock_timeout`/`statement_timeout` before any DDL, so a batch blocked on one table cannot hold its earlier locks indefinitely. `postgresSafe: true` adds concurrent-index mode — non-index DDL commits atomically, then index DDL runs `CONCURRENTLY` on a session pinned via `db.acquireSession()` (a pooled `db.query` would not keep the `SET` and the DDL on one connection). That mode is deliberately **not atomic**: unfinished index migrations are recorded `failed`, not `running`, and their `error_message` carries a `[smrt: concurrent-index phase 1 committed]` marker so a reconciling re-run resumes at the index build instead of replaying committed DDL. INVALID indexes are found via `pg_index.indisvalid` (`pg_indexes` reports them as present) and dropped before rebuild. Operational detail: `packages/cli/AGENTS.md`.\n- **Retry logic is transient-only (#2366)**: `db.get()`/`db.upsert()` retry 4× total (initial + 3), but `ErrorUtils.withRetry` classifies via the cause chain (`src/db-errors.ts`) and rethrows deterministic failures immediately — constraint violations, bad input syntax, missing tables, aborted PG tx (`25P02`). `@happyvertical/sql` stringifies the driver text into `context.originalError`, so **never match `error.message`**; use `classifyDatabaseError()` / `isUniqueViolationError()` / `isAbortedTransactionError()`.\n- **Field caching**: `_cachedFields` populated during `Collection.create()` — eliminates async `getFields()` per query\n- **Smart cloning**: arrays/objects shallow-cloned in property init to prevent aliasing (Issue #22)\n- **Table verification cache**: `isTableVerified(dbUrl, tableName)` avoids redundant `tableExists()` calls\n- **Manifest required**: build-time AST scanning creates manifest. Without vitest plugin → \"No field metadata\"\n- **ManifestBuilder fails on scanner errors**: every production manifest path\n must abort before adapting partial scan results. A syntax error or unresolved\n `@smrt()` config spread cannot be allowed to emit a default-open manifest.\n- **Vite plugin loads scanner from `dist/` first**: `src/vite-plugin/import-build-aware.ts` prefers `dist/` when it exists on disk; it only falls back to `src/` on fresh clones. So if you edit `src/scanner/*.ts` or `src/schema/generator.ts` and want those edits reflected in consumer manifest generation, you must rebuild (`pnpm build` or have `pnpm dev` / `pnpm build:watch` running in core). This is intentional — sniffing `.ts` vs `.js` via `import.meta.url` was non-deterministic under tsx and broke 12–13 publishes (#1139).\n- **Bundled registry ownership**: flattened production bundles can rewrite constructor names and make decorator-time stack inference attribute provider code to the consumer. Generated registration repairs identity only from the exact imported constructor plus an explicit package and isolated one-object manifest; never infer ownership from output paths, simple names, or table names. Distinct packages may export the same simple name under qualified keys. The production-consumer gate lives in `packages/bundle-gate/src/__tests__/registry-identity.spec.ts` (#2308).\n",
|
|
947
957
|
"moduleDocs": [
|
|
948
958
|
{
|
|
949
959
|
"path": "agents/change-feed.md",
|
|
@@ -963,7 +973,7 @@
|
|
|
963
973
|
{
|
|
964
974
|
"path": "agents/schema-paths.md",
|
|
965
975
|
"module": "schema-paths",
|
|
966
|
-
"content": "# smrt-core/schema paths\n\nModule semantics for `src/schema/` — which `SchemaGenerator` entry point reaches\na real database, what each one emits, and the rules that keep them in step.\nPackage orientation, the cross-module invariants, and the traps that apply\nbefore editing anything live in [../AGENTS.md](../AGENTS.md) — read that first;\nits \"Schema paths\" section is the short form of everything below.\n\nWritten from the 2026-08-17 database-layer gap assessment (epic #2382). Symbol\nnames here are stable; the line numbers the assessment quotes are not, so trust\nthis call graph and re-grep before citing a location.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. They do not\nproduce the same schema for the same class.\n\n| Entry point | Selected by | Status |\n|---|---|---|\n| `generateSTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateCTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateSTISchemaFromRegistry` | `src/testing/database.ts` (`getTestDatabase()`), `src/schema/utils.ts` (`generateSchema`; `ensureSchema` only as a fallback) | tests + runtime helpers |\n| `generateSchemaFromRegistry` | the same two callers | tests + runtime helpers |\n\nA fifth entry point, the build-time AST `generateSchema(objectDef)`, existed\nuntil #2380: it fed only the `smrt:schema` virtual module, which had no\nconsumer, had rotted relative to the four paths above (an `idx_`-prefixed\nnaming scheme none of the others use, and no conflict-index emission at all),\nand was deleted rather than wired up. `SchemaOverrideSystem`\n(`schema/override-system.ts`) — unwired, and its two non-generic methods\nhard-coded a schema extension for a project outside this monorepo — was\ndeleted alongside it. See rule 9 and the new rule at the end of this file.\n\nProduction DDL takes the manifest route:\n\n```\n@smrt() class ─▶ scanner ─▶ manifest.json ─▶ generate{STI,CTI}SchemaFromManifest\n ─▶ registered `schema` ─▶ ObjectRegistry.getAllSchemasAsDefinitions()\n ├─▶ smrt db:migrate | db:diff | db:status\n │ (the CLI drives SchemaComparer + MigrationTracker directly)\n └─▶ migrateSmrtSchemas() / getPendingSchemaStatements()\n (src/migrations/orchestrate.ts — exported for programmatic\n use; no in-repo caller outside its own tests)\n```\n\nThe suite takes the registry route. Before #2359 the registry route emitted\nindexes the manifest route did not — per-column foreign-key indexes, and STI\npartial FK indexes filtered by `_meta_type` — so tests ran against a richer\nschema than any deployment received, the manifest STI path populated a\n`fkColumnsByClass` map it never read, and the manifest CTI path had no FK loop\nat all. `src/testing/database.ts`'s \"same as migrations\" comment described an\nintent, not the code.\n\nSince #2359 the two families share one set of index helpers and\n`src/schema/schema-path-parity.test.ts` runs the same fixture manifest through\nthe manifest paths, through `ObjectRegistry.registerFromManifest()` + the\nregistry paths, and through `getAllSchemasAsDefinitions()`, asserting identical\ncolumn and index sets. Extend that fixture with every generator change; a\ndivergence is a bug in the generator, not an exception to add to the test.\n\n### Index rules (#2359)\n\n- **Reference columns are always indexed.** `ensureReferenceColumnIndexes()`\n runs last on every path and gives each `@foreignKey`, `@crossPackageRef` and\n tenant column `<table>_<column>_idx` unless an UNQUALIFIED index (no `WHERE`,\n no JSON path) already leads with it — the `conflictColumns` unique index or an\n `indexed: true` opt-in, or the column's own inline UNIQUE. A partial\n `WHERE _meta_type = …` index does not count: base-class polymorphic queries\n carry no discriminator predicate. `indexed: true` on a reference column is\n redundant. Roll the index wave out to production with\n `smrt db:migrate --postgres-safe` (concurrent-index mode, #2362): a plain\n atomic batch takes SHARE/ACCESS EXCLUSIVE locks for ~230 index builds. STI FK indexes are plain, one per\n column, not per-class partial.\n- **No index on the primary key.** `<table>_id_idx` is gone from every path,\n and `conflictColumns` equal to the PK column set emit no conflict index\n (`ON CONFLICT (id)` binds to the PK constraint). `SchemaComparer` drops the\n legacy non-unique single-column PK index from existing databases without\n `--drop-indexes` when the live table reports that column as its sole primary\n key (never a UNIQUE one — on PostgreSQL that may back a custom-named PRIMARY\n KEY constraint, and `DROP INDEX` on it would fail the atomic batch).\n- **Slug loading keeps its index.** Custom `conflictColumns` replace the\n `(slug, context)` unique index; `loadFromSlug()`/`getId()`/`getSavedId()`\n still filter on slug/context, so a plain `<table>_slug_context_idx` is kept\n (additive; routing those lookups through the conflict key would change which\n row a slug resolves to). The tenant-led default key below counts as serving\n it (`servesSlugLookup()`): a tenant-scoped slug lookup carries the tenant\n predicate (#2365) and is served by the prefix, so no second index.\n- **Tenant-scoped tables key per tenant (#2360).** A tenant-scoped class with\n no explicit `conflictColumns` upserts on, and indexes,\n `(tenant_id, slug, context)` — `(tenant_id, slug, context, _meta_type)` for\n an STI hierarchy — resolved by one rule on both paths:\n `ManifestGenerator.normalizeConflictColumns()` materializes it into\n `decoratorConfig.conflictColumns` for the manifest paths (so the manifest,\n the schema, `smrt-knowledge.json` and the runtime read one value), and\n `ObjectRegistry.getConflictColumns()` derives the same value at runtime from\n the schema owner's `tenantScoped` config (`ObjectRegistry.getTenantColumn()`;\n an STI child resolves through its root; a `@report` class through its\n group/bucket columns; a custom primary key through that key). Explicit\n `conflictColumns` are never rewritten. `src/schema/conflict-target.ts` holds\n the shared helpers. Consequences: the index NAME stays\n `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so the differ\n swaps the columns of an existing global unique in place by name (a superset\n key — creating it cannot fail on existing rows); the tenant-led key also\n serves the tenant column, so `<table>_tenant_id_idx` is no longer emitted\n for those tables (an existing one is an orphan the differ drops only with\n `--drop-indexes`); NULL-tenant rows (`mode: 'optional'` outside a tenant\n context) dedup among themselves through the SDK's null-aware upsert\n (`IS NOT DISTINCT FROM` under a PostgreSQL advisory lock / an in-process\n lock on SQLite) — application-enforced now, where the old global index was\n database-enforced: the tenant-led index treats NULLs as distinct, so raw SQL\n can insert two global rows with one slug, and a raw\n `ON CONFLICT (slug, context…)` against such a table no longer binds (use\n `WHERE NOT EXISTS`, plus an advisory lock on PostgreSQL). Emitting\n `NULLS NOT DISTINCT` on PostgreSQL ≥ 15 (the SDK already detects it) would\n restore the database arbiter — a follow-up. The `save()` path serializes an\n unset tenant field as an explicit `NULL` whatever its registered type,\n because the SDK rejects an upsert whose conflict column is missing from the\n row.\n- **Rolling the tenant-led key out (#2360).** There is no mixed-version state:\n new code against the old index fails every NEW-object create on a\n tenant-scoped default-key table (PostgreSQL 42P10, SQLite \"ON CONFLICT\n clause does not match…\"), and old code against the new index fails the same\n way, because the conflict target must match the unique index's column set\n exactly; only persisted objects (upsert on `id`) keep saving. Deploy the code\n and run `smrt db:migrate` in the same maintenance step. The plan is one\n `DROP INDEX` + `CREATE UNIQUE INDEX` per table under the SAME name (a\n superset key, so the build cannot fail when the old same-name index was a\n valid UNIQUE over the subset key; a #1165-class table whose old index was\n non-unique or missing may hold duplicates that a superset UNIQUE rejects —\n `db:diff` shows which tables' old index is non-unique or missing; dedupe\n those rows before migrating). Atomic mode swaps every table in one\n transaction: `DROP INDEX` takes ACCESS EXCLUSIVE and holds it until commit,\n which blocks ALL access to those tables — reads included — for the batch;\n size `statementTimeout` for the largest tenant-scoped table. That is the\n maintenance window this rollout requires anyway (no mixed-version state), so\n run this wave — the #2359 index wave included — in atomic mode inside it;\n the \"roll out with `--postgres-safe`\" advice above applies to a #2359-only\n wave, because `--postgres-safe` runs the two statements sequentially per\n table, so each table has NO conflict index between them and a failed rebuild\n leaves it without one until the re-run. The recreate has no automatic\n DOWN: reverting the code means re-creating the old index by hand. And\n legacy NULL-tenant rows fork rather than get adopted — a tenant-context save\n whose slug matches a `(NULL, slug, ctx)` row now inserts `(tenant, slug,\n ctx)` beside it, and that tenant no longer sees the legacy row — so backfill\n `tenant_id` (anytown: `SET tenant_id = context::uuid`) BEFORE this release.\n Ingestion that relied on natural-key dedup across tenants now inserts one\n row per tenant (release note).\n- **STI `@field({ unique: true })` is enforced through indexes** (the differ can\n add an index to an existing table, never a column constraint): a full\n `<table>_<col>_unique_idx` when the STI base declares it, one\n `<table>_<col>_<class>_unique_idx WHERE _meta_type = '<qualified>'` per class\n when only descendants do — uniqueness per concrete class, not across the\n subtree. DuckDB/JSON have no partial indexes, so the descendant-scoped shape\n (`isStiSubtypeUniqueIndex`) is not emitted there — degrading it to a full\n UNIQUE would constrain every subtype; the DDL strategy and the differ both\n skip it, while other partial indexes keep degrading to full ones as before. Remember the\n framework serializes an unset text field as `''`, so a unique optional text\n field must be `nullable: true` with a `null` initializer or every unset row\n collides.\n- **Every class in an STI hierarchy carries the schema of the one shared\n table**, generated from the root base (`ManifestGenerator.generateSchemas()`\n resolves the root through `findSTIBaseInfo`), so a child never treats its own\n descendant-only unique field as base-declared.\n\n`src/schema/utils.ts` sits in between, and the two exports differ:\n\n- `generateSchema()` (reached from `SmrtCollection.generateSchema()`) always\n rebuilds from the registry and writes the result back into the registry,\n replacing whatever the manifest registered for that class.\n- `ensureSchema()` (reached from the deprecated `smrt db:setup`) is\n manifest-first: it takes `ObjectRegistry.getSchema()` plus the merged\n `getAllSchemasAsDefinitions()` table definition, and only falls back to\n `generateSchema()` when no schema is registered at all.\n\nSo a normal build keeps the manifest schema through `db:setup`, and a\nregistry-derived schema is a dev/test artifact. `smrt-content` shows what one\nlooks like: `packages/content/src/hooks.server.ts` `bootstrapSchema()` calls\n`generateSchema()` for every registered class and then `ensureSchema()` from the\nSvelteKit `handle` hook on any `/api/*` request, so that process holds\nregistry-derived schemas rather than the manifest ones. It reaches only that\npackage's own `vite dev` app — the library build excludes the file and the\npackage never exports it — but it is the shape to recognize. Check which route a\nprocess actually took before trusting a reproduction.\n\n## Why the drift stayed invisible\n\nEvery drift oracle compares a database with the same artifact that dropped the\nindex:\n\n- `verifyPersistenceTable()` (`src/schema/table-verifier.ts`) calls\n `db.tableExists()` and nothing else. \"Runtime verifies schema\" has always meant\n existence-only — no column, type, constraint, or index comparison.\n- `smrt doctor` never opens a database connection.\n- `db:status` and `db:diff` diff the live database against\n `getAllSchemasAsDefinitions()`, i.e. the manifest projection.\n\nAn index the manifest never emitted is \"in sync\" by construction. That is how a\nproduction database reached 164 unindexed `tenant_id` columns while `db:status`\nreported no drift (#2356 → #2359). The assessment's other counts — 196/231\n`@foreignKey` and 91/92 `@crossPackageRef` columns with no production index,\n238/238 tables carrying a redundant index on the primary key, zero DB-level\nforeign-key constraints on any engine — come from regenerating every package's\nschema against a live database, so re-measure rather than quote them once the\nepic's fixes land.\n\n## Rules\n\n### 1. Verify against the production path, not the test path\n\nAny change to column or index emission goes on **all** paths that ship and is\nproven by the path-parity test (`src/schema/schema-path-parity.test.ts`, #2359)\n— extend its fixture; a green suite otherwise proves the registry paths only.\nRead the call graph before believing a comment: \"same as migrations\" was wrong\nfor years.\n\n### 2. Every new query predicate ships with its index\n\nCollection methods, poll loops, auth lookups, junction right-side filters, and\npolymorphic owner lookups all count — or write down why the predicate does not\nneed one. For list workloads, EXPLAIN on a PostgreSQL snapshot; the measured\nspread on the assessed workload was 21 ms → 0.1 ms.\n\n### 3. Run the PostgreSQL lane\n\nAnything touching numeric types, uuid casts, upsert conflict targets, timestamps,\nor migrations runs the package's `test:postgres` script:\n\n```bash\npnpm --filter @happyvertical/smrt-<pkg> test:postgres\n```\n\ncore, cli, users, sales, marketing, analytics, and vitest carry the lane.\nSQLite's type affinity accepts values PostgreSQL rejects — a money field declared\n`number = 0` compiles to INTEGER and only fails on PG (#2361).\n\n### 4. Read the built artifact, not the source\n\nWhat a decorator produced is in `dist/manifest.json` and in regenerated schemas:\n`integer` vs `decimal`, the actual index list, the actual conflict columns. When\nthe question is \"how many tables/columns/indexes\", regenerate and count across\nevery package; do not sample a few and extrapolate.\n\n### 5. Index intent belongs on both the constraint and the read path\n\nA conflict target is not automatically a unique index, and a unique index is not\nautomatically the index a read path uses. Custom `conflictColumns` used to\nreplace the `(slug, context)` index while `loadFromSlug`/`getId` still queried\nslug+context, and STI dropped `@field({ unique: true })` — both fixed in #2359,\nsee \"Index rules\" above. Check the pair, not the declaration.\n\n### 6. Multi-tenancy is a whole-path property\n\nEvery unique constraint and every conflict target on a tenant-scoped table\nincludes the tenant column — otherwise a second tenant's `save()` of the same\nnatural key updates the first tenant's row through `DO UPDATE SET` (#2360; the\ndefault key now does, see \"Index rules\" — an explicit `conflictColumns` that\nomits the tenant column is the class author's own key and is not rewritten).\nAnd every read path is interceptor-aware: hydration\n(`loadFromId`/`loadFromSlug`), get-by-slug, vector search, and collection\nmemory, not only `list()` (#2365).\n\n### 7. Retry only transient errors\n\nClassify through the cause chain (SQLSTATE), never on a message substring, and\nnever retry inside an aborted PostgreSQL transaction (`25P02`). Test the\ncontract end to end against a real database, not only the classifier (#2366).\n\n### 8. Thread new decorator options through every config-rebuild site\n\nA new `@smrt()` or `@field()` option that affects schema must reach the\n`SchemaGeneratorConfig` type in `src/schema/generator.ts` and every site that\nrebuilds that config — `src/schema/utils.ts` and `src/testing/database.ts` — or\nit is silently dropped on the paths that rebuild it (#2357).\n\n### 9. Delete or wire dead paths, and write docs to what the code does\n\nDead code that looks canonical misleads the next agent: the AST `generateSchema`\npath, `SchemaOverrideSystem`, and the never-emitted `triggers: []` all read as\nsupported surfaces (#2380). Documentation follows the implementation, not the\nintent — say \"verifies the table exists\" when that is what runs.\n\n### 10. Untracked \"known limitation\" comments are bugs nobody will read\n\nFile the issue and link it from the comment. A `products` comment explaining why\na conflict-column change was refrained from sat there for months — and\nmisdescribed the failure mode the whole time.\n\n### 11. Consumer repair scripts are signals\n\nDownstream repair tooling (anytown's `db-repair-plan.ts` carried column-type\nrepairs, missing STI columns and indexes, and `tenant_id` backfills since April)\nis the consumer-side record of framework gaps. Mine it during triage.\n\n### 12. Try to falsify before filing, and treat operations as correctness\n\nRe-verify a finding at source before it becomes an issue — one assessment\ncandidate claimed conflict indexes past two columns were narrowed to two\ncolumns, when only the index *name* is shortened. And an index fix that ships\nwithout a bounded-timeout, `CONCURRENTLY`-capable migrate path can take\nproduction down on rollout (#2362).\n\n### 13. Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), the default list ordering (rule 18\nbelow), and single columns opted in with `@field({ indexed: true })`. A list\nworkload's access path is composite, so declare it:\n\n```ts\n@smrt({\n indexes: [\n { name: 'contents_tenant_id_publish_date_idx',\n columns: ['tenantId', 'publish_date'] },\n ],\n})\n```\n\n`columns` takes field names or column names in access-path order — filter\ncolumns first, sort column last. Declare columns, not a direction: PostgreSQL\nscans a btree either way, so an ascending index also serves the matching\n`ORDER BY ... DESC` as an ordered scan with no Sort node. `unique` and `where`\n(partial index) are honoured.\n\n`appendDeclaredIndexes()` runs first on all four entry points, ahead of\n`ensureDefaultListOrderingIndex()` (rule 18) and `ensureReferenceColumnIndexes()`,\nso a declared composite leading with the tenant column (or any reference column)\nreplaces the automatic standalone index rather than duplicating it.\nUnknown columns, malformed entries, and a name collision with a different index\nall fail generation — a silently dropped index only surfaces later as a\nproduction slowdown. Rule 8 above is why this works at runtime at all.\n\n### 14. Relationship targets resolve to a class name on both paths\n\n`@foreignKey`/`@oneToMany`/`@manyToMany` accept a class, a name string, or a\n`() => Target` thunk. The decorator invokes the thunk and throws when the target\ncannot be resolved (never `related: ''`); the scanner unwraps the same thunk\nfrom raw source (never `related: '() => Target'`). An unresolved target silently\ncosts the relationship edge, `loadRelated()`, and the FK-derived index (#2379).\nA thunk resolves at decoration time, so a target declared later in the same\nmodule is still in its temporal dead zone — use the string form there.\n\n### 15. A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced only on an empty table;\n on a populated one it is added nullable and the `NOT NULL` is reported as a\n manual follow-up on every engine.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1). The #2370 rebuild (rule 15) consumes\n only `type_upgrade` placeholders today; extending it to rewrite constraints\n would lift this.\n- Defaults compare through `canonicalizeDefault()`, which folds engine\n renderings (`'x'::text`, `CAST('t' AS BOOLEAN)`, `CURRENT_TIMESTAMP` vs\n `now()`) by manifest type; an unclassifiable rendering skips the comparison\n rather than risking a false positive that would churn every run. The\n round-trip test (create from each DDL strategy → compare → zero changes) in\n `src/migrations/__tests__/issue-2369-*.test.ts` guards this.\n\n### 16. `schema.ddl` is a preview, not the table\n\n`SchemaDefinition.ddl` / `manifest.json` `schema.ddl` is the engine-neutral\nCREATE TABLE string from `SchemaGenerator.generateSQL()` with no engine: no\nindexes, no triggers, abstract `REAL`/`JSON`/`UUID`/`TIMESTAMP`. It is kept for\nbackward compatibility only. Everything that needs an executable table renders\n`columns` + `indexes` through `getDDLStrategy(engine)` — `db:migrate`\n(`migrations/orchestrate.ts`), `MigrationGenerator` (default\n`materializeStructuredSchema: true`; `false` is a deprecated opt-out),\n`SchemaAggregator`, and `createIsolatedTestDbFromManifest` in smrt-vitest, the\nlast two via `src/schema/manifest-schema.ts` (`collectManifestTables` /\n`renderCollectedManifestTable`). The cached string is merged in only for a\ntable whose contributors expose no structured columns (hand-authored\nmanifests); table constraints that exist only in the string are dropped with a\nwarning, as `db:migrate` drops them. Do not add a new consumer of the\nstring, and do not write a private CREATE INDEX renderer — the retired ones\ndropped `where` and `jsonPath` (#2358). Every DDL strategy also spells out\n`PRIMARY KEY NOT NULL`: SQLite lets a bare non-INTEGER PRIMARY KEY hold NULL.\n\n### 17. The merged table shape is registration-order independent (#2372)\n\n`getAllSchemas()` and `getAllSchemasAsDefinitions()` fold every class that\nshares a physical table — the whole STI hierarchy — into one shape. Both route\nthrough `buildMergedTableSchemas()`, which groups contributors by table and\nthen merges them in a **deterministic** order: the STI base first, then\nancestors before descendants, then by qualified name.\n\nThat order matters because the first contributor seeds the table: it supplies\nthe fallback base columns, the `idType`, the conflict columns and the cached\nDDL, and its columns win every merge conflict. When registration order decided\nit, an STI child that carries no manifest `schema` — the external- and\nconsumer-manifest case — seeded the table from bare fallback columns and the\nbase class's richer ones were skipped when it registered later, yielding\n`context TEXT` instead of `context TEXT NOT NULL DEFAULT ''` and timestamps\nwith no NOT NULL/DEFAULT. The shipped content manifest lists `Article` before\n`Content`, so the losing order was the one that shipped, and the differ\ncompares types only, so the weak fresh-create was never repaired.\n\nTwo invariants keep the two assembly paths agreeing:\n\n- `createBaseColumns()` mirrors what `generateSchemaFromManifest` /\n `generateSTISchemaFromManifest` emit for the same table, so a table built\n from runtime field metadata alone has the same NOT NULL/DEFAULT shape as one\n built from a manifest. Note `_meta_type` is `TEXT NOT NULL` with **no**\n default, matching the generator.\n- `fieldsToColumns()` reads `required`, `default`, and `description` from the\n top level *or* `_meta`. Registry fields normalize them into `_meta`\n (`manifest-field-merge.ts`), so reading only the top level silently dropped\n NOT NULL and DEFAULT for every registry-sourced field.\n\nSTI columns stay nullable regardless of the field's `required` flag\n(`fieldsToColumns(fields, { stiUnionColumns: true })`): the table holds the\nunion of all subtypes' fields, so a column only one subtype declares is never\npopulated on a sibling's row. Declared defaults are still emitted. This matches\n`generateSTISchemaFromManifest`, which sets `notNull: false` on every non-system\nSTI column.\n\nWhen adding a class-level input to the merged shape, take it from the seeding\ncontributor rather than \"whichever class arrives first\", and cover it with a\nchild-first/base-first equality test.\n\n### 18. The generator owns the index for its own default ordering (#2363)\n\nEvery generated list surface — REST, MCP, the SvelteKit list route — pages with\n`ORDER BY created_at DESC, <pk> ASC` (`DEFAULT_LIST_ORDER_BY`, #2367), and\nuntil #2363 no schema path indexed `created_at` (the AST path, deleted in\n#2380, indexed `updated_at`), so the framework's own default page was a\nsequential scan plus a top-N sort. `ensureDefaultListOrderingIndex()` now runs\non all four entry points and emits:\n\n- `(<tenant column>, created_at)` on a tenant-scoped table — the tenancy\n interceptor puts `tenant_id = ?` in front of every list, so the tenant column\n leads and `created_at` orders within it. This composite **replaces** the\n standalone tenant index from #2359: a B-tree serves every prefix of its\n column list, so `ensureDefaultListOrderingIndex()` is called first and\n `ensureReferenceColumnIndexes()` then sees the column as already served. The\n tenant column is found by `referenceKind === 'tenantId'`, never by the\n `tenant_id` spelling — `@smrt({ tenantScoped: { field } })` renames it.\n- `(created_at)` otherwise.\n\nThree deliberate omissions, so nobody \"fixes\" them later:\n\n- **No `DESC`.** `IndexDefinition` carries no per-column direction and\n PostgreSQL scans a B-tree backwards just as cheaply.\n- **No primary-key tiebreak column.** The default order mixes directions\n (`created_at DESC, id ASC`), so no single-direction index satisfies the whole\n key; the leading columns already turn a full sort into an index scan plus an\n incremental sort over rows sharing a timestamp.\n- **Not scoped per STI subtype.** `(_meta_type, created_at)` would serve a\n child collection's list but not the base class's polymorphic one, which\n carries no discriminator predicate — the same reasoning that keeps STI\n reference indexes plain (#2359). One unqualified index per shared table.\n\nAn existing UNQUALIFIED index that already leads with the same columns\nsuppresses it — a partial or JSON-path index never counts. That is how a\ndeclared `@smrt({ indexes: [...] })` composite (#2357) takes over: declaring\n`(tenant_id, created_at, status)` replaces the generated pair, while declaring\na different sort column such as `(tenant_id, publish_date)` sits **beside** it,\nbecause that index cannot order the default page. Declared indexes are appended\nbefore this helper for exactly that reason; anything that appends an index in\nfuture goes in the same slot, ahead of `ensureDefaultListOrderingIndex()` and\n`ensureReferenceColumnIndexes()`.\n\n### 19. One conflict-target rule, applied on every producer\n\n`save()` upserts on `ObjectRegistry.getConflictColumns()`; the schema must\ncarry exactly one unique index over those columns (or they must be the\nprimary key). Keep the derivation in `src/schema/conflict-target.ts` and let\nevery producer call it — the three manifest pipelines share\n`ManifestGenerator.applyGenerationPasses()` since #2360 because\n`ManifestBuilder` had silently skipped the report passes for months. When you\nadd a way for the key to vary (a new decorator option, a new class kind),\nthread it through `getConflictColumns()`, `normalizeConflictColumns()` and the\ngenerator's `resolveConflictTarget()` together, and extend the parity test's\n\"unique index == conflict target\" assertion; a key the runtime uses and the\nschema does not index is a hard PostgreSQL error (42P10) on the first save,\nand a key the schema indexes without the tenant column is the silent\ncross-tenant overwrite this rule exists for.\n\n### 20. Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates any identifier past 63 **bytes** and reports nothing;\nSQLite and DuckDB do not, so the entire test suite was blind to it. The 66-byte\n`content_contribution_revisions_contribution_id_revision_number_idx` shipped\nthat way — only the differ's signature-equivalence check kept it from emitting\n`add_index` on every run. Two names agreeing for 63 bytes is the real hazard:\n`CREATE INDEX IF NOT EXISTS` no-ops against the wrong index, and the second\nindex is never created.\n\n`schema/index-utils.ts` owns the guard, and it splits by who owns the name:\n\n- **Generated index, trigger and PL/pgSQL function names** →\n `shortenIdentifier()`. Deterministic `<head>_<digest><suffix>`, digest taken\n over the **full** original so a shared prefix still yields distinct names, and\n a recognised suffix (`_idx`, `_unique_idx`, `_key`, `_pkey`) preserved.\n- **Hand-declared `@smrt({ indexes: [{ name }] })`** → `assertIdentifierFits()`,\n a hard error in `validateDeclaredIndex()`. Renaming what a developer wrote is\n worse than refusing it, and `SchemaComparer` matches indexes **by name**\n first, so a 70-byte declaration could never match the 63-byte index\n PostgreSQL stored and `db:migrate` would emit `add_index` forever.\n- **Table and column names** → deliberately **not** guarded. PostgreSQL\n truncates identifiers *consistently on every reference*: `CREATE TABLE\n \"<80 bytes>\"` and a later `SELECT ... FROM \"<the same 80 bytes>\"` both resolve\n to the same stored 63-byte name, so one long name round-trips fine end to end.\n `smrt-users` depends on this — it ships an intentional 80-byte\n `@smrt({ tableName })` (`permission_policy_table_name_that_is_far_too_long…`)\n and derives unique Postgres RLS policy names from it. An earlier revision of\n this rule hard-errored here on the theory that the runtime resolves tables by\n name and would break; that theory is wrong for the reason above, and the error\n broke `packages/users`. The residual collision risk is over a name the\n developer chose, not one the generator manufactured.\n\n`enforceIdentifierLimits()` is the single call site per path, placed **after**\n`ensureReferenceColumnIndexes()` — nothing may lengthen a name after it. Doing\nthe shortening at the end rather than at each `indexes.push()` is safe because\nthe digest covers the whole original name, so entries distinct before shortening\nstay distinct after; the helper still throws if two ever collide. The migrate\nleg's `withConflictIndex()` (`registry/schema-builder.ts`) and the PostgreSQL\ntrigger-function name call `shortenIdentifier()` directly, because they compose\na name outside the generator's index list. Note that an over-long *table* name\nstill yields in-limit, distinct *index* names, because the shortening runs over\nthe whole composed name.\n\nThe digest is FNV-1a, not `node:crypto`: `index-utils.ts` is re-exported from\n`schema/utils.ts`, which exists to keep Node built-ins out of browser bundles.\nIt only has to be *stable* — a shortened name that changed between releases\nwould make every deployment drop and recreate the index — so the parity and\nunit tests pin the literal output rather than recomputing it. Unpaired\nsurrogates are folded to U+FFFD before both counting and hashing, so the digest\nis taken over exactly the bytes the driver transmits.\n\nExisting databases migrate **by name swap, without a rebuild**: the live index\nstill carries the name PostgreSQL truncated it to, the manifest now carries the\nshortened one, and the differ claims it by signature (columns + uniqueness +\npredicate), emitting nothing — including under `includeDroppedIndexes`. See\n`migrations/__tests__/index-drift.test.ts` and the PostgreSQL lane test\n`schema/issue-2374-identifier-length-postgres.optional.test.ts`.\n\nOut of scope, deliberately: constraint names PostgreSQL invents for itself. A\nCTI table's inline `UNIQUE` produces an implicit `<table>_<column>_key`, which\ncan exceed 63 bytes even when the table and column each fit. SMRT never names\nit, and PostgreSQL disambiguates its own truncations by appending a counter\nrather than collapsing them, so there is no silent-collision hazard there.\n\n### 21. The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Referential integrity lives in `delete()`, not in the DDL\n\nNo schema path emits a `FOREIGN KEY` clause on any engine — grep `schema/ddl/*`,\n`schema-manager.ts` and `differ.ts` for `REFERENCES` and you get nothing. That is\na deliberate position, not an oversight: emitting constraints changes delete\nsemantics for every consumer, requires topological table ordering in both\nmigrate paths (neither orders today), and needs a plan for the orphans already in\nproduction databases. Emitting them is tracked separately.\n\nWhat `@foreignKey(..., { onDelete })` therefore means is *application* behaviour,\napplied by `SmrtObject.delete()` through `src/cascade.ts` (#2371):\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Anything else, including every `@tenantId()` field | `NO ACTION` — the row is left alone |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and keeps its pre-#2371\nbehaviour unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field — found in review before this\nlanded (originally reachable, untested, and undocumented).\n\nProperties to keep if you touch that module:\n\n- **The plan is registry-derived and rebuilt per delete.** Registration is\n incremental — manifests load lazily and tests register classes between cases —\n so a cached plan would silently skip a table that registered later. Cache it\n only behind an invalidation hook that every registration path calls.\n- **A class with nothing pointing at it skips the transaction entirely — but\n `CascadePlan.isEmpty` requires no polymorphic association class anywhere in\n the process, not just no typed references.** `buildCascadePlan()` pushes\n *every* registered `SmrtPolymorphicAssociation` subclass into\n `plan.polymorphic` unconditionally (`cascade.ts` around\n `isPolymorphicAssociationClass`): a `metaType` column can point at any class\n at runtime, so there is no static metadata to scope it by the target being\n deleted. One registered polymorphic class anywhere makes `isEmpty` false for\n every delete in that process — do not read \"the common case skips the\n transaction\" as \"most deletes in a real app skip it\"; in a multi-package app\n that registers even one polymorphic association, almost none do.\n `runCascadeDelete()` builds the plan for `getResolvedQualifiedName()` (not the\n bare constructor name — two packages can register the same simple name).\n- **Cascaded rows are removed set-based.** Their `beforeDelete`/`afterDelete`\n hooks and interceptors do not run and no change-feed tombstone is written for\n them, which is exactly what a DB-level `ON DELETE CASCADE` does. Only the\n object `delete()` was called on runs the lifecycle. Do not \"improve\" this into\n a per-row model delete without deciding what that means for sync consumers.\n- **Everything is one transaction where the adapter has one**, including the\n object's own `DELETE`, whenever there is anything to cascade. The `RESTRICT`\n checks run first, before any mutation, so a refusal costs nothing; the\n transaction is what makes a refusal *deeper* in the graph safe.\n- **`_smrt_embeddings` and `_smrt_contexts` are matched by id *and* a\n class-name candidate set, not id alone.** Their class columns store the\n *runtime* constructor name, which for an STI hierarchy is a concrete\n subclass rather than the class the cascade planned from — id-alone matching\n looked STI-safe, but let two unrelated classes using `idType: 'text'`\n (non-UUID, not guaranteed globally unique) collide on a shared id value and\n delete each other's rows (review fix). `ownerClassCandidates()` expands to\n every STI hierarchy member of the class the ids actually belong to, in both\n qualified and simple form. A failure to clean them is logged, never raised —\n an application database may predate the table, and losing derived rows must\n not fail a valid delete.\n\n`_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals` and the dispatch tables are\ndeliberately **not** cascaded. They are append-only logs; the change feed in\nparticular receives the delete's own tombstone, so cascading it would erase the\nrecord that tells sync clients the row is gone.\n\n### 22. System tables get a retention policy, not just a prune function (#2375)\n\nFour framework-owned tables grow with traffic and nothing used to remove a row:\n`_smrt_changes` (one per save/delete), `_smrt_ai_usage` (one per AI call, and\npersistence is on by default), `_smrt_contexts` (whose `expires_at` nothing\nenforced) and `_smrt_dispatch` (an operator-only `dispatch:cleanup`).\n`src/system/retention.ts` is now the single place that bounds them.\n\n- **`runRetentionSweep(db, policy)` is the entry point.** It runs the four\n built-in tasks in a fixed order, then every task other packages contributed\n via `registerRetentionTask()` — `@happyvertical/smrt-jobs` registers\n `_smrt_jobs`/`_smrt_job_events`, `@happyvertical/smrt-users` registers\n session/magic-link/CLI-auth expiry. A task that throws is recorded on its own\n result and the sweep continues; a missing table reports `unavailable`, so a\n sweep is safe against a partially bootstrapped database.\n- **A contributed task only exists in a process that loaded its package.** Both\n packages register on import from their entry point, and the registry lives on\n `globalThis` (like `ObjectRegistry`) so a duplicated `smrt-core` resolution\n cannot split it. `smrt db:prune` optionally imports both packages for exactly\n this reason — a project that installs neither correctly gets neither task.\n- **Defaults are opt-out, not opt-in.** `DEFAULT_RETENTION_POLICY` covers the\n four built-in tables (changes 30 days, AI usage 90 days, dispatch 30 days\n completed / 90 days failed, contexts strictly by their own `expires_at`), and\n those are the ones `smrt.configure({ retention })` tunes. Contributed tasks\n carry their own defaults and their own window options —\n `DEFAULT_JOB_RETENTION` (7 days terminal / 30 days failed / 30 days events,\n set through `registerJobRetentionTasks()` or the runner's `retention.jobs`),\n and expired credentials, which have no window because an expired credential\n has nothing worth retaining. Every task, built-in or contributed, can be\n turned off: a table set to `false`, a task set to `false` under `tasks`, or\n `enabled: false` for the whole sweep — through `smrt.configure`,\n `smrt db:prune --skip`, or the runner's `retention` config.\n- **Contributed task names are prefixed with the owning package's short name**\n (`jobs-records`, `jobs-events`, `users-sessions`, …) because the registry is\n one process-global namespace.\n- **Scheduling lives outside core.** A running `TaskRunner` sweeps every six\n hours (`retention: false` opts out) and `smrt db:prune` is the cron entry\n point. The first runner sweep is one interval after `start()`, never at\n start: a crash-looping worker must not become a delete loop.\n- **Every prune counts before it deletes.** `rowCount` is not reliably\n populated across the engines SMRT supports, so counting is both what gives a\n usable figure and what lets `dryRun` preview the *same* predicate rather than\n an approximation of it. Count and delete are two statements and deliberately\n not one transaction — a maintenance pass must not hold a write lock over a\n large delete — so the figure is approximate under concurrent writers. Where\n two bounds can select the same row (`pruneChangeFeed`, `pruneAiUsage`), the\n second bound excludes what the first already accounted for, so a dry run does\n not count an entry twice.\n- **Every retention predicate ships with its index** (rule 2 applies to\n maintenance SQL too): `_smrt_contexts(expires_at)`,\n `_smrt_ai_usage(tenant_id, created_at)` — which is also the subscriptions\n billing meter's range scan — `_smrt_dispatch(status, processed_at)` and\n `(status, updated_at)` come from the system DDL, so they reach existing\n databases through the `SMRT_SCHEMA_VERSION` bump that replays it.\n `_smrt_jobs(status, completed_at)` comes from\n `ensureJobsSystemTableCompatibility()` instead, because `_smrt_jobs` is\n generated from a decorated class and does not exist yet when bootstrap runs;\n the jobs collection calls that path on every `initialize()`.\n- **Expiry enforcement is prune-side only.** `recall()`/`recallAll()` keep\n their documented \"expiry is not applied at read time\" contract — changing it\n would change read semantics for existing callers, which is a different issue\n from bounding storage. `LearningMemory` filters expired rows itself.\n\n### 23. Dead generation surfaces were deleted, not wired (#2380)\n\nRule 9 named three surfaces that read as canonical but were not: the AST\n`generateSchema(objectDef)` entry point, `SchemaOverrideSystem`, and the\nnever-emitted `triggers: []`. Resolution, so a future agent does not re-open\nwhat was deliberately decided:\n\n- **The AST path is gone.** `SchemaGenerator.generateSchema(objectDef)` and its\n AST-only private helpers (`generateIndexes`, `generateTriggers`,\n `extractDependencies`, `generateVersion`, `getTableName`,\n `extractPackageName`) were deleted from `schema/generator.ts`, along with\n their sole caller, `generateSchemaModule()` in `vite-plugin/index.ts`, and the\n `smrt:schema` / `@happyvertical/smrt-virt-schema` virtual module registration\n that fed. Nothing else called it — grep the deleted method's exact name\n before assuming a caller was missed; the path-parity fixture and every other\n rule above already speak only of the four surviving entry points.\n- **`SchemaOverrideSystem` is gone**, file and all\n (`schema/override-system.ts` no longer exists). It was never called from\n anywhere in this repository outside its own now-deleted exports, and two of\n its five public methods (`createPraecoContentOverride`,\n `createPraecoMeetingOverride`) hard-coded a schema extension for a\n consuming project outside this monorepo — scaffolding that never belonged in\n the framework, not a generic feature with a missing caller. `SchemaOverride`\n (the type) went with it; `ColumnDefinition`/`IndexDefinition`/\n `TriggerDefinition`, which it merely referenced, did not.\n- **The DDL-strategy trigger machinery was kept, not deleted.**\n `TriggerDefinition`, `SchemaDefinition.triggers`, and every DDL strategy's\n `generateTriggers()` / `generateTriggerStatement()` / `supportsTriggers()`\n (`schema/ddl/*.ts`) are real, engine-uniform, directly-tested rendering code\n that runs on **every** table creation via `strategy.generateTriggers(schema)`\n — unlike the AST path, this is not an orphaned call graph. It is kept for the\n same reason rule 16 keeps the cached `schema.ddl` string: `SchemaDefinition`\n is part of the shape third-party tooling and published manifests may already\n depend on, and `EngineSpecificDDL`/`MultiEngineDDL` (`schema/ddl/types.ts`)\n carry `triggers` as part of that same contract. Deleting a published field is\n a different (and unjustified) risk from deleting a virtual module nothing\n ever imported.\n- **What changed is what is documented, not what runs.** `schema.triggers` is\n now explicitly documented (`schema/types.ts`) as always `[]` on every schema\n a `@smrt()` class can produce, and why: there is no `@smrt()`/`@field()`\n option that populates it (unlike `indexes`, #2357), `updated_at` is\n maintained at the application layer (`SmrtObject.save()`), and\n `migrations/differ.ts` never diffs triggers — so even a hand-populated one\n would only apply to a newly `CREATE TABLE`d table and never retrofit an\n existing one. Wiring live trigger emission was considered and rejected for\n this issue: it is a migration-rollout feature (retrofitting 238+ existing\n production tables needs the same `SMRT_SCHEMA_VERSION`-replay or differ\n support rule 21/rule 22's system-table work required), not a cleanup, and\n nothing in the epic depended on it the way #2359 depended on FK indexes\n actually shipping.\n- **`_smrt_signals` and `ObjectRegistry.persistToDatabase()`/`loadFromDatabase()`**\n — named in the original finding alongside triggers — were already handled by\n #2376 before this issue landed: see rule 21 and `system/schema.ts`'s\n `RETIRED_SYSTEM_TABLES`. Nothing further to do there.\n- **The two config-rebuild-site comments** (`schema/utils.ts`,\n `testing/database.ts`) rule 8 requires were already in place, added by\n #2357/#2360; the `testing/database.ts` \"same as migrations\" overclaim rule 1\n quotes was already corrected by #2359, and doctor's `experimentalDecorators`\n check was already fixed by #2368/#2399 (see `packages/cli/AGENTS.md`\n Gotchas). Re-verify against current source before repeating any of these —\n the epic's PRs landed across one evening and a stale assessment line is not\n proof a fix is still needed.\n"
|
|
976
|
+
"content": "# smrt-core/schema paths\n\nModule semantics for `src/schema/` — which `SchemaGenerator` entry point reaches\na real database, what each one emits, and the rules that keep them in step.\nPackage orientation, the cross-module invariants, and the traps that apply\nbefore editing anything live in [../AGENTS.md](../AGENTS.md) — read that first;\nits \"Schema paths\" section is the short form of everything below.\n\nWritten from the 2026-08-17 database-layer gap assessment (epic #2382). Symbol\nnames here are stable; the line numbers the assessment quotes are not, so trust\nthis call graph and re-grep before citing a location.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. They do not\nproduce the same schema for the same class.\n\n| Entry point | Selected by | Status |\n|---|---|---|\n| `generateSTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateCTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateSTISchemaFromRegistry` | `src/testing/database.ts` (`getTestDatabase()`), `src/schema/utils.ts` (`generateSchema`; `ensureSchema` only as a fallback) | tests + runtime helpers |\n| `generateSchemaFromRegistry` | the same two callers | tests + runtime helpers |\n\nA fifth entry point, the build-time AST `generateSchema(objectDef)`, existed\nuntil #2380: it fed only the `smrt:schema` virtual module, which had no\nconsumer, had rotted relative to the four paths above (an `idx_`-prefixed\nnaming scheme none of the others use, and no conflict-index emission at all),\nand was deleted rather than wired up. `SchemaOverrideSystem`\n(`schema/override-system.ts`) — unwired, and its two non-generic methods\nhard-coded a schema extension for a project outside this monorepo — was\ndeleted alongside it. See rule 9 and the new rule at the end of this file.\n\nProduction DDL takes the manifest route:\n\n```\n@smrt() class ─▶ scanner ─▶ manifest.json ─▶ generate{STI,CTI}SchemaFromManifest\n ─▶ registered `schema` ─▶ ObjectRegistry.getAllSchemasAsDefinitions()\n ├─▶ smrt db:migrate | db:diff | db:status\n │ (the CLI drives SchemaComparer + MigrationTracker directly)\n └─▶ migrateSmrtSchemas() / getPendingSchemaStatements()\n (src/migrations/orchestrate.ts — exported for programmatic\n use; no in-repo caller outside its own tests)\n```\n\nThe suite takes the registry route. Before #2359 the registry route emitted\nindexes the manifest route did not — per-column foreign-key indexes, and STI\npartial FK indexes filtered by `_meta_type` — so tests ran against a richer\nschema than any deployment received, the manifest STI path populated a\n`fkColumnsByClass` map it never read, and the manifest CTI path had no FK loop\nat all. `src/testing/database.ts`'s \"same as migrations\" comment described an\nintent, not the code.\n\nSince #2359 the two families share one set of index helpers and\n`src/schema/schema-path-parity.test.ts` runs the same fixture manifest through\nthe manifest paths, through `ObjectRegistry.registerFromManifest()` + the\nregistry paths, and through `getAllSchemasAsDefinitions()`, asserting identical\ncolumn and index sets. Extend that fixture with every generator change; a\ndivergence is a bug in the generator, not an exception to add to the test.\n\n### Index rules (#2359)\n\n- **Reference columns are always indexed.** `ensureReferenceColumnIndexes()`\n runs last on every path and gives each `@foreignKey`, `@crossPackageRef` and\n tenant column `<table>_<column>_idx` unless an UNQUALIFIED index (no `WHERE`,\n no JSON path) already leads with it — the `conflictColumns` unique index or an\n `indexed: true` opt-in, or the column's own inline UNIQUE. A partial\n `WHERE _meta_type = …` index does not count: base-class polymorphic queries\n carry no discriminator predicate. `indexed: true` on a reference column is\n redundant. Roll the index wave out to production with\n `smrt db:migrate --postgres-safe` (concurrent-index mode, #2362): a plain\n atomic batch takes SHARE/ACCESS EXCLUSIVE locks for ~230 index builds. STI FK indexes are plain, one per\n column, not per-class partial.\n- **No index on the primary key.** `<table>_id_idx` is gone from every path,\n and `conflictColumns` equal to the PK column set emit no conflict index\n (`ON CONFLICT (id)` binds to the PK constraint). `SchemaComparer` drops the\n legacy non-unique single-column PK index from existing databases without\n `--drop-indexes` when the live table reports that column as its sole primary\n key (never a UNIQUE one — on PostgreSQL that may back a custom-named PRIMARY\n KEY constraint, and `DROP INDEX` on it would fail the atomic batch).\n- **Slug loading keeps its index.** Custom `conflictColumns` replace the\n `(slug, context)` unique index; `loadFromSlug()`/`getId()`/`getSavedId()`\n still filter on slug/context, so a plain `<table>_slug_context_idx` is kept\n (additive; routing those lookups through the conflict key would change which\n row a slug resolves to). The tenant-led default key below counts as serving\n it (`servesSlugLookup()`): a tenant-scoped slug lookup carries the tenant\n predicate (#2365) and is served by the prefix, so no second index.\n- **Tenant-scoped tables key per tenant (#2360).** A tenant-scoped class with\n no explicit `conflictColumns` upserts on, and indexes,\n `(tenant_id, slug, context)` — `(tenant_id, slug, context, _meta_type)` for\n an STI hierarchy — resolved by one rule on both paths:\n `ManifestGenerator.normalizeConflictColumns()` materializes it into\n `decoratorConfig.conflictColumns` for the manifest paths (so the manifest,\n the schema, `smrt-knowledge.json` and the runtime read one value), and\n `ObjectRegistry.getConflictColumns()` derives the same value at runtime from\n the schema owner's `tenantScoped` config (`ObjectRegistry.getTenantColumn()`;\n an STI child resolves through its root; a `@report` class through its\n group/bucket columns; a custom primary key through that key). Explicit\n `conflictColumns` are never rewritten. `src/schema/conflict-target.ts` holds\n the shared helpers. Consequences: the index NAME stays\n `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so the differ\n swaps the columns of an existing global unique in place by name (a superset\n key — creating it cannot fail on existing rows); the tenant-led key also\n serves the tenant column, so `<table>_tenant_id_idx` is no longer emitted\n for those tables (an existing one is an orphan the differ drops only with\n `--drop-indexes`); NULL-tenant rows (`mode: 'optional'` outside a tenant\n context) dedup among themselves through the SDK's null-aware upsert\n (`IS NOT DISTINCT FROM` under a PostgreSQL advisory lock / an in-process\n lock on SQLite) — application-enforced now, where the old global index was\n database-enforced: the tenant-led index treats NULLs as distinct, so raw SQL\n can insert two global rows with one slug, and a raw\n `ON CONFLICT (slug, context…)` against such a table no longer binds (use\n `WHERE NOT EXISTS`, plus an advisory lock on PostgreSQL). Emitting\n `NULLS NOT DISTINCT` on PostgreSQL ≥ 15 (the SDK already detects it) would\n restore the database arbiter — a follow-up. The `save()` path serializes an\n unset tenant field as an explicit `NULL` whatever its registered type,\n because the SDK rejects an upsert whose conflict column is missing from the\n row.\n- **Rolling the tenant-led key out (#2360).** There is no mixed-version state:\n new code against the old index fails every NEW-object create on a\n tenant-scoped default-key table (PostgreSQL 42P10, SQLite \"ON CONFLICT\n clause does not match…\"), and old code against the new index fails the same\n way, because the conflict target must match the unique index's column set\n exactly; only persisted objects (upsert on `id`) keep saving. Deploy the code\n and run `smrt db:migrate` in the same maintenance step. The plan is one\n `DROP INDEX` + `CREATE UNIQUE INDEX` per table under the SAME name (a\n superset key, so the build cannot fail when the old same-name index was a\n valid UNIQUE over the subset key; a #1165-class table whose old index was\n non-unique or missing may hold duplicates that a superset UNIQUE rejects —\n `db:diff` shows which tables' old index is non-unique or missing; dedupe\n those rows before migrating). Atomic mode swaps every table in one\n transaction: `DROP INDEX` takes ACCESS EXCLUSIVE and holds it until commit,\n which blocks ALL access to those tables — reads included — for the batch;\n size `statementTimeout` for the largest tenant-scoped table. That is the\n maintenance window this rollout requires anyway (no mixed-version state), so\n run this wave — the #2359 index wave included — in atomic mode inside it;\n the \"roll out with `--postgres-safe`\" advice above applies to a #2359-only\n wave, because `--postgres-safe` runs the two statements sequentially per\n table, so each table has NO conflict index between them and a failed rebuild\n leaves it without one until the re-run. The recreate has no automatic\n DOWN: reverting the code means re-creating the old index by hand. And\n legacy NULL-tenant rows fork rather than get adopted — a tenant-context save\n whose slug matches a `(NULL, slug, ctx)` row now inserts `(tenant, slug,\n ctx)` beside it, and that tenant no longer sees the legacy row — so backfill\n `tenant_id` (anytown: `SET tenant_id = context::uuid`) BEFORE this release.\n Ingestion that relied on natural-key dedup across tenants now inserts one\n row per tenant (release note).\n- **STI `@field({ unique: true })` is enforced through indexes** (the differ can\n add an index to an existing table, never a column constraint): a full\n `<table>_<col>_unique_idx` when the STI base declares it, one\n `<table>_<col>_<class>_unique_idx WHERE _meta_type = '<qualified>'` per class\n when only descendants do — uniqueness per concrete class, not across the\n subtree. DuckDB/JSON have no partial indexes, so the descendant-scoped shape\n (`isStiSubtypeUniqueIndex`) is not emitted there — degrading it to a full\n UNIQUE would constrain every subtype; the DDL strategy and the differ both\n skip it, while other partial indexes keep degrading to full ones as before. Remember the\n framework serializes an unset text field as `''`, so a unique optional text\n field must be `nullable: true` with a `null` initializer or every unset row\n collides.\n- **Every class in an STI hierarchy carries the schema of the one shared\n table**, generated from the root base (`ManifestGenerator.generateSchemas()`\n resolves the root through `findSTIBaseInfo`), so a child never treats its own\n descendant-only unique field as base-declared.\n\n`src/schema/utils.ts` sits in between, and the two exports differ:\n\n- `generateSchema()` (reached from `SmrtCollection.generateSchema()`) always\n rebuilds from the registry and writes the result back into the registry,\n replacing whatever the manifest registered for that class.\n- `ensureSchema()` (reached from the deprecated `smrt db:setup`) is\n manifest-first: it takes `ObjectRegistry.getSchema()` plus the merged\n `getAllSchemasAsDefinitions()` table definition, and only falls back to\n `generateSchema()` when no schema is registered at all.\n\nSo a normal build keeps the manifest schema through `db:setup`, and a\nregistry-derived schema is a dev/test artifact. `smrt-content` shows what one\nlooks like: `packages/content/src/hooks.server.ts` `bootstrapSchema()` calls\n`generateSchema()` for every registered class and then `ensureSchema()` from the\nSvelteKit `handle` hook on any `/api/*` request, so that process holds\nregistry-derived schemas rather than the manifest ones. It reaches only that\npackage's own `vite dev` app — the library build excludes the file and the\npackage never exports it — but it is the shape to recognize. Check which route a\nprocess actually took before trusting a reproduction.\n\n## Why the drift stayed invisible\n\nEvery drift oracle compares a database with the same artifact that dropped the\nindex:\n\n- `verifyPersistenceTable()` (`src/schema/table-verifier.ts`) calls\n `db.tableExists()` and nothing else. \"Runtime verifies schema\" has always meant\n existence-only — no column, type, constraint, or index comparison.\n- `smrt doctor` never opens a database connection.\n- `db:status` and `db:diff` diff the live database against\n `getAllSchemasAsDefinitions()`, i.e. the manifest projection.\n\nAn index the manifest never emitted is \"in sync\" by construction. That is how a\nproduction database reached 164 unindexed `tenant_id` columns while `db:status`\nreported no drift (#2356 → #2359). The assessment's other counts — 196/231\n`@foreignKey` and 91/92 `@crossPackageRef` columns with no production index,\n238/238 tables carrying a redundant index on the primary key, zero DB-level\nforeign-key constraints on any engine — come from regenerating every package's\nschema against a live database, so re-measure rather than quote them once the\nepic's fixes land.\n\n## Rules\n\n### 1. Verify against the production path, not the test path\n\nAny change to column or index emission goes on **all** paths that ship and is\nproven by the path-parity test (`src/schema/schema-path-parity.test.ts`, #2359)\n— extend its fixture; a green suite otherwise proves the registry paths only.\nRead the call graph before believing a comment: \"same as migrations\" was wrong\nfor years.\n\n### 2. Every new query predicate ships with its index\n\nCollection methods, poll loops, auth lookups, junction right-side filters, and\npolymorphic owner lookups all count — or write down why the predicate does not\nneed one. For list workloads, EXPLAIN on a PostgreSQL snapshot; the measured\nspread on the assessed workload was 21 ms → 0.1 ms.\n\n### 3. Run the PostgreSQL lane\n\nAnything touching numeric types, uuid casts, upsert conflict targets, timestamps,\nor migrations runs the package's `test:postgres` script:\n\n```bash\npnpm --filter @happyvertical/smrt-<pkg> test:postgres\n```\n\ncore, cli, users, sales, marketing, analytics, and vitest carry the lane.\nSQLite's type affinity accepts values PostgreSQL rejects — a money field declared\n`number = 0` compiles to INTEGER and only fails on PG (#2361).\n\n### 4. Read the built artifact, not the source\n\nWhat a decorator produced is in `dist/manifest.json` and in regenerated schemas:\n`integer` vs `decimal`, the actual index list, the actual conflict columns. When\nthe question is \"how many tables/columns/indexes\", regenerate and count across\nevery package; do not sample a few and extrapolate.\n\n### 5. Index intent belongs on both the constraint and the read path\n\nA conflict target is not automatically a unique index, and a unique index is not\nautomatically the index a read path uses. Custom `conflictColumns` used to\nreplace the `(slug, context)` index while `loadFromSlug`/`getId` still queried\nslug+context, and STI dropped `@field({ unique: true })` — both fixed in #2359,\nsee \"Index rules\" above. Check the pair, not the declaration.\n\n### 6. Multi-tenancy is a whole-path property\n\nEvery unique constraint and every conflict target on a tenant-scoped table\nincludes the tenant column — otherwise a second tenant's `save()` of the same\nnatural key updates the first tenant's row through `DO UPDATE SET` (#2360; the\ndefault key now does, see \"Index rules\" — an explicit `conflictColumns` that\nomits the tenant column is the class author's own key and is not rewritten).\nAnd every read path is interceptor-aware: hydration\n(`loadFromId`/`loadFromSlug`), get-by-slug, vector search, and collection\nmemory, not only `list()` (#2365).\n\n### 7. Retry only transient errors\n\nClassify through the cause chain (SQLSTATE), never on a message substring, and\nnever retry inside an aborted PostgreSQL transaction (`25P02`). Test the\ncontract end to end against a real database, not only the classifier (#2366).\n\n### 8. Thread new decorator options through every config-rebuild site\n\nA new `@smrt()` or `@field()` option that affects schema must reach the\n`SchemaGeneratorConfig` type in `src/schema/generator.ts` and every site that\nrebuilds that config — `src/schema/utils.ts` and `src/testing/database.ts` — or\nit is silently dropped on the paths that rebuild it (#2357).\n\n### 9. Delete or wire dead paths, and write docs to what the code does\n\nDead code that looks canonical misleads the next agent: the AST `generateSchema`\npath, `SchemaOverrideSystem`, and the never-emitted `triggers: []` all read as\nsupported surfaces (#2380). Documentation follows the implementation, not the\nintent — say \"verifies the table exists\" when that is what runs.\n\n### 10. Untracked \"known limitation\" comments are bugs nobody will read\n\nFile the issue and link it from the comment. A `products` comment explaining why\na conflict-column change was refrained from sat there for months — and\nmisdescribed the failure mode the whole time.\n\n### 11. Consumer repair scripts are signals\n\nDownstream repair tooling (anytown's `db-repair-plan.ts` carried column-type\nrepairs, missing STI columns and indexes, and `tenant_id` backfills since April)\nis the consumer-side record of framework gaps. Mine it during triage.\n\n### 12. Try to falsify before filing, and treat operations as correctness\n\nRe-verify a finding at source before it becomes an issue — one assessment\ncandidate claimed conflict indexes past two columns were narrowed to two\ncolumns, when only the index *name* is shortened. And an index fix that ships\nwithout a bounded-timeout, `CONCURRENTLY`-capable migrate path can take\nproduction down on rollout (#2362).\n\n### 13. Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), the default list ordering (rule 18\nbelow), and single columns opted in with `@field({ indexed: true })`. A list\nworkload's access path is composite, so declare it:\n\n```ts\n@smrt({\n indexes: [\n { name: 'contents_tenant_id_publish_date_idx',\n columns: ['tenantId', 'publish_date'] },\n ],\n})\n```\n\n`columns` takes field names or column names in access-path order — filter\ncolumns first, sort column last. Declare columns, not a direction: PostgreSQL\nscans a btree either way, so an ascending index also serves the matching\n`ORDER BY ... DESC` as an ordered scan with no Sort node. `unique` and `where`\n(partial index) are honoured.\n\n`appendDeclaredIndexes()` runs first on all four entry points, ahead of\n`ensureDefaultListOrderingIndex()` (rule 18) and `ensureReferenceColumnIndexes()`,\nso a declared composite leading with the tenant column (or any reference column)\nreplaces the automatic standalone index rather than duplicating it.\nUnknown columns, malformed entries, and a name collision with a different index\nall fail generation — a silently dropped index only surfaces later as a\nproduction slowdown. Rule 8 above is why this works at runtime at all.\n\n### 14. Relationship targets resolve to a class name on both paths\n\n`@foreignKey`/`@oneToMany`/`@manyToMany` accept a class, a name string, or a\n`() => Target` thunk. The decorator invokes the thunk and throws when the target\ncannot be resolved (never `related: ''`); the scanner unwraps the same thunk\nfrom raw source (never `related: '() => Target'`). An unresolved target silently\ncosts the relationship edge, `loadRelated()`, and the FK-derived index (#2379).\nA thunk resolves at decoration time, so a target declared later in the same\nmodule is still in its temporal dead zone — use the string form there.\n\n### 15. A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced only on an empty table;\n on a populated one it is added nullable and the `NOT NULL` is reported as a\n manual follow-up on every engine.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1). The #2370 rebuild (rule 15) consumes\n only `type_upgrade` placeholders today; extending it to rewrite constraints\n would lift this.\n- Defaults compare through `canonicalizeDefault()`, which folds engine\n renderings (`'x'::text`, `CAST('t' AS BOOLEAN)`, `CURRENT_TIMESTAMP` vs\n `now()`) by manifest type; an unclassifiable rendering skips the comparison\n rather than risking a false positive that would churn every run. The\n round-trip test (create from each DDL strategy → compare → zero changes) in\n `src/migrations/__tests__/issue-2369-*.test.ts` guards this.\n\n### 16. `schema.ddl` is a preview, not the table\n\n`SchemaDefinition.ddl` / `manifest.json` `schema.ddl` is the engine-neutral\nCREATE TABLE string from `SchemaGenerator.generateSQL()` with no engine: no\nindexes, no triggers, abstract `REAL`/`JSON`/`UUID`/`TIMESTAMP`. It is kept for\nbackward compatibility only. Everything that needs an executable table renders\n`columns` + `indexes` through `getDDLStrategy(engine)` — `db:migrate`\n(`migrations/orchestrate.ts`), `MigrationGenerator` (default\n`materializeStructuredSchema: true`; `false` is a deprecated opt-out),\n`SchemaAggregator`, and `createIsolatedTestDbFromManifest` in smrt-vitest, the\nlast two via `src/schema/manifest-schema.ts` (`collectManifestTables` /\n`renderCollectedManifestTable`). The cached string is merged in only for a\ntable whose contributors expose no structured columns (hand-authored\nmanifests); table constraints that exist only in the string are dropped with a\nwarning, as `db:migrate` drops them. Do not add a new consumer of the\nstring, and do not write a private CREATE INDEX renderer — the retired ones\ndropped `where` and `jsonPath` (#2358). Every DDL strategy also spells out\n`PRIMARY KEY NOT NULL`: SQLite lets a bare non-INTEGER PRIMARY KEY hold NULL.\n\n### 17. The merged table shape is registration-order independent (#2372)\n\n`getAllSchemas()` and `getAllSchemasAsDefinitions()` fold every class that\nshares a physical table — the whole STI hierarchy — into one shape. Both route\nthrough `buildMergedTableSchemas()`, which groups contributors by table and\nthen merges them in a **deterministic** order: the STI base first, then\nancestors before descendants, then by qualified name.\n\nThat order matters because the first contributor seeds the table: it supplies\nthe fallback base columns, the `idType`, the conflict columns and the cached\nDDL, and its columns win every merge conflict. When registration order decided\nit, an STI child that carries no manifest `schema` — the external- and\nconsumer-manifest case — seeded the table from bare fallback columns and the\nbase class's richer ones were skipped when it registered later, yielding\n`context TEXT` instead of `context TEXT NOT NULL DEFAULT ''` and timestamps\nwith no NOT NULL/DEFAULT. The shipped content manifest lists `Article` before\n`Content`, so the losing order was the one that shipped, and the differ\ncompares types only, so the weak fresh-create was never repaired.\n\nTwo invariants keep the two assembly paths agreeing:\n\n- `createBaseColumns()` mirrors what `generateSchemaFromManifest` /\n `generateSTISchemaFromManifest` emit for the same table, so a table built\n from runtime field metadata alone has the same NOT NULL/DEFAULT shape as one\n built from a manifest. Note `_meta_type` is `TEXT NOT NULL` with **no**\n default, matching the generator.\n- `fieldsToColumns()` reads `required`, `default`, and `description` from the\n top level *or* `_meta`. Registry fields normalize them into `_meta`\n (`manifest-field-merge.ts`), so reading only the top level silently dropped\n NOT NULL and DEFAULT for every registry-sourced field.\n\nSTI columns stay nullable regardless of the field's `required` flag\n(`fieldsToColumns(fields, { stiUnionColumns: true })`): the table holds the\nunion of all subtypes' fields, so a column only one subtype declares is never\npopulated on a sibling's row. Declared defaults are still emitted. This matches\n`generateSTISchemaFromManifest`, which sets `notNull: false` on every non-system\nSTI column.\n\nWhen adding a class-level input to the merged shape, take it from the seeding\ncontributor rather than \"whichever class arrives first\", and cover it with a\nchild-first/base-first equality test.\n\n### 18. The generator owns the index for its own default ordering (#2363)\n\nEvery generated list surface — REST, MCP, the SvelteKit list route — pages with\n`ORDER BY created_at DESC, <pk> ASC` (`DEFAULT_LIST_ORDER_BY`, #2367), and\nuntil #2363 no schema path indexed `created_at` (the AST path, deleted in\n#2380, indexed `updated_at`), so the framework's own default page was a\nsequential scan plus a top-N sort. `ensureDefaultListOrderingIndex()` now runs\non all four entry points and emits:\n\n- `(<tenant column>, created_at)` on a tenant-scoped table — the tenancy\n interceptor puts `tenant_id = ?` in front of every list, so the tenant column\n leads and `created_at` orders within it. This composite **replaces** the\n standalone tenant index from #2359: a B-tree serves every prefix of its\n column list, so `ensureDefaultListOrderingIndex()` is called first and\n `ensureReferenceColumnIndexes()` then sees the column as already served. The\n tenant column is found by `referenceKind === 'tenantId'`, never by the\n `tenant_id` spelling — `@smrt({ tenantScoped: { field } })` renames it.\n- `(created_at)` otherwise.\n\nThree deliberate omissions, so nobody \"fixes\" them later:\n\n- **No `DESC`.** `IndexDefinition` carries no per-column direction and\n PostgreSQL scans a B-tree backwards just as cheaply.\n- **No primary-key tiebreak column.** The default order mixes directions\n (`created_at DESC, id ASC`), so no single-direction index satisfies the whole\n key; the leading columns already turn a full sort into an index scan plus an\n incremental sort over rows sharing a timestamp.\n- **Not scoped per STI subtype.** `(_meta_type, created_at)` would serve a\n child collection's list but not the base class's polymorphic one, which\n carries no discriminator predicate — the same reasoning that keeps STI\n reference indexes plain (#2359). One unqualified index per shared table.\n\nAn existing UNQUALIFIED index that already leads with the same columns\nsuppresses it — a partial or JSON-path index never counts. That is how a\ndeclared `@smrt({ indexes: [...] })` composite (#2357) takes over: declaring\n`(tenant_id, created_at, status)` replaces the generated pair, while declaring\na different sort column such as `(tenant_id, publish_date)` sits **beside** it,\nbecause that index cannot order the default page. Declared indexes are appended\nbefore this helper for exactly that reason; anything that appends an index in\nfuture goes in the same slot, ahead of `ensureDefaultListOrderingIndex()` and\n`ensureReferenceColumnIndexes()`.\n\n### 19. One conflict-target rule, applied on every producer\n\n`save()` upserts on `ObjectRegistry.getConflictColumns()`; the schema must\ncarry exactly one unique index over those columns (or they must be the\nprimary key). Keep the derivation in `src/schema/conflict-target.ts` and let\nevery producer call it — the three manifest pipelines share\n`ManifestGenerator.applyGenerationPasses()` since #2360 because\n`ManifestBuilder` had silently skipped the report passes for months. When you\nadd a way for the key to vary (a new decorator option, a new class kind),\nthread it through `getConflictColumns()`, `normalizeConflictColumns()` and the\ngenerator's `resolveConflictTarget()` together, and extend the parity test's\n\"unique index == conflict target\" assertion; a key the runtime uses and the\nschema does not index is a hard PostgreSQL error (42P10) on the first save,\nand a key the schema indexes without the tenant column is the silent\ncross-tenant overwrite this rule exists for.\n\n### 20. Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates any identifier past 63 **bytes** and reports nothing;\nSQLite and DuckDB do not, so the entire test suite was blind to it. The 66-byte\n`content_contribution_revisions_contribution_id_revision_number_idx` shipped\nthat way — only the differ's signature-equivalence check kept it from emitting\n`add_index` on every run. Two names agreeing for 63 bytes is the real hazard:\n`CREATE INDEX IF NOT EXISTS` no-ops against the wrong index, and the second\nindex is never created.\n\n`schema/index-utils.ts` owns the guard, and it splits by who owns the name:\n\n- **Generated index, trigger and PL/pgSQL function names** →\n `shortenIdentifier()`. Deterministic `<head>_<digest><suffix>`, digest taken\n over the **full** original so a shared prefix still yields distinct names, and\n a recognised suffix (`_idx`, `_unique_idx`, `_key`, `_pkey`) preserved.\n- **Hand-declared `@smrt({ indexes: [{ name }] })`** → `assertIdentifierFits()`,\n a hard error in `validateDeclaredIndex()`. Renaming what a developer wrote is\n worse than refusing it, and `SchemaComparer` matches indexes **by name**\n first, so a 70-byte declaration could never match the 63-byte index\n PostgreSQL stored and `db:migrate` would emit `add_index` forever.\n- **Table and column names** → deliberately **not** guarded. PostgreSQL\n truncates identifiers *consistently on every reference*: `CREATE TABLE\n \"<80 bytes>\"` and a later `SELECT ... FROM \"<the same 80 bytes>\"` both resolve\n to the same stored 63-byte name, so one long name round-trips fine end to end.\n `smrt-users` depends on this — it ships an intentional 80-byte\n `@smrt({ tableName })` (`permission_policy_table_name_that_is_far_too_long…`)\n and derives unique Postgres RLS policy names from it. An earlier revision of\n this rule hard-errored here on the theory that the runtime resolves tables by\n name and would break; that theory is wrong for the reason above, and the error\n broke `packages/users`. The residual collision risk is over a name the\n developer chose, not one the generator manufactured.\n\n`enforceIdentifierLimits()` is the single call site per path, placed **after**\n`ensureReferenceColumnIndexes()` — nothing may lengthen a name after it. Doing\nthe shortening at the end rather than at each `indexes.push()` is safe because\nthe digest covers the whole original name, so entries distinct before shortening\nstay distinct after; the helper still throws if two ever collide. The migrate\nleg's `withConflictIndex()` (`registry/schema-builder.ts`) and the PostgreSQL\ntrigger-function name call `shortenIdentifier()` directly, because they compose\na name outside the generator's index list. Note that an over-long *table* name\nstill yields in-limit, distinct *index* names, because the shortening runs over\nthe whole composed name.\n\nThe digest is FNV-1a, not `node:crypto`: `index-utils.ts` is re-exported from\n`schema/utils.ts`, which exists to keep Node built-ins out of browser bundles.\nIt only has to be *stable* — a shortened name that changed between releases\nwould make every deployment drop and recreate the index — so the parity and\nunit tests pin the literal output rather than recomputing it. Unpaired\nsurrogates are folded to U+FFFD before both counting and hashing, so the digest\nis taken over exactly the bytes the driver transmits.\n\nExisting databases migrate **by name swap, without a rebuild**: the live index\nstill carries the name PostgreSQL truncated it to, the manifest now carries the\nshortened one, and the differ claims it by signature (columns + uniqueness +\npredicate), emitting nothing — including under `includeDroppedIndexes`. See\n`migrations/__tests__/index-drift.test.ts` and the PostgreSQL lane test\n`schema/issue-2374-identifier-length-postgres.optional.test.ts`.\n\nOut of scope, deliberately: constraint names PostgreSQL invents for itself. A\nCTI table's inline `UNIQUE` produces an implicit `<table>_<column>_key`, which\ncan exceed 63 bytes even when the table and column each fit. SMRT never names\nit, and PostgreSQL disambiguates its own truncations by appending a counter\nrather than collapsing them, so there is no silent-collision hazard there.\n\n### 21. The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Same-package referential integrity uses two matching rails\n\n`@foreignKey(Target)` emits a physical database constraint when the target is\nin the same package and applies the same action through `SmrtObject.delete()`\nin `src/cascade.ts`. A shared delete-action resolver keeps both paths aligned;\nthe established generated `ON UPDATE CASCADE` default remains unchanged:\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Ordinary same-package reference | `NO ACTION` — deletion is refused while references remain |\n| Every `@tenantId()` field | Excluded from physical constraints and delete cascades |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and therefore defaults to\nimmediate `NO ACTION` unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field.\n\n`@crossPackageRef()` remains runtime-only: it registers relationship loading\nand indexes but deliberately emits no physical constraint, avoiding circular\npackage DDL. Tenant markers follow the same non-constraint rule because a\ntenant is a scope, not an ownership edge.\n\nEvery schema creation entry point uses the same deterministic dependency\nplanner. Parents are created before children. SQLite keeps cycle constraints\ninline because it can create them safely. PostgreSQL creates mutually dependent\ntables first and adds their named constraints afterward. DuckDB refuses cycles,\nself-references, `CASCADE`, and `SET NULL` with an actionable error because its\ncurrent ALTER/constraint support cannot enforce those shapes safely.\n\nFor existing tables, PostgreSQL checks the exact child table/column against the\nexact referenced table/column before adding a constraint as `NOT VALID` and\nthen validating it. If orphans exist (or the probe cannot run), migration stops\nwith detector and repair SQL. SQLite requires a deliberate table rebuild;\nDuckDB reports the unsupported ALTER path. Neither engine treats an unsupported\nconstraint addition as a successful no-op.\n\nProperties to keep if you touch that module:\n\n- **The plan is registry-derived and rebuilt per delete.** Registration is\n incremental — manifests load lazily and tests register classes between cases —\n so a cached plan would silently skip a table that registered later. Cache it\n only behind an invalidation hook that every registration path calls.\n- **A class with nothing pointing at it skips the transaction entirely — but\n `CascadePlan.isEmpty` requires no polymorphic association class anywhere in\n the process, not just no typed references.** `buildCascadePlan()` pushes\n *every* registered `SmrtPolymorphicAssociation` subclass into\n `plan.polymorphic` unconditionally (`cascade.ts` around\n `isPolymorphicAssociationClass`): a `metaType` column can point at any class\n at runtime, so there is no static metadata to scope it by the target being\n deleted. One registered polymorphic class anywhere makes `isEmpty` false for\n every delete in that process — do not read \"the common case skips the\n transaction\" as \"most deletes in a real app skip it\"; in a multi-package app\n that registers even one polymorphic association, almost none do.\n `runCascadeDelete()` builds the plan for `getResolvedQualifiedName()` (not the\n bare constructor name — two packages can register the same simple name).\n- **Cascaded rows are removed set-based.** Their `beforeDelete`/`afterDelete`\n hooks and interceptors do not run and no change-feed tombstone is written for\n them, which is exactly what a DB-level `ON DELETE CASCADE` does. Only the\n object `delete()` was called on runs the lifecycle. Do not \"improve\" this into\n a per-row model delete without deciding what that means for sync consumers.\n- **Everything is one transaction where the adapter has one**, including the\n object's own `DELETE`, whenever there is anything to cascade. The `RESTRICT`\n checks run first, before any mutation, so a refusal costs nothing; the\n transaction is what makes a refusal *deeper* in the graph safe.\n- **`_smrt_embeddings` and `_smrt_contexts` are matched by id *and* a\n class-name candidate set, not id alone.** Their class columns store the\n *runtime* constructor name, which for an STI hierarchy is a concrete\n subclass rather than the class the cascade planned from — id-alone matching\n looked STI-safe, but let two unrelated classes using `idType: 'text'`\n (non-UUID, not guaranteed globally unique) collide on a shared id value and\n delete each other's rows (review fix). `ownerClassCandidates()` expands to\n every STI hierarchy member of the class the ids actually belong to, in both\n qualified and simple form. A failure to clean them is logged, never raised —\n an application database may predate the table, and losing derived rows must\n not fail a valid delete.\n\n`_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals` and the dispatch tables are\ndeliberately **not** cascaded. They are append-only logs; the change feed in\nparticular receives the delete's own tombstone, so cascading it would erase the\nrecord that tells sync clients the row is gone.\n\n### 22. System tables get a retention policy, not just a prune function (#2375)\n\nFour framework-owned tables grow with traffic and nothing used to remove a row:\n`_smrt_changes` (one per save/delete), `_smrt_ai_usage` (one per AI call, and\npersistence is on by default), `_smrt_contexts` (whose `expires_at` nothing\nenforced) and `_smrt_dispatch` (an operator-only `dispatch:cleanup`).\n`src/system/retention.ts` is now the single place that bounds them.\n\n- **`runRetentionSweep(db, policy)` is the entry point.** It runs the four\n built-in tasks in a fixed order, then every task other packages contributed\n via `registerRetentionTask()` — `@happyvertical/smrt-jobs` registers\n `_smrt_jobs`/`_smrt_job_events`, `@happyvertical/smrt-users` registers\n session/magic-link/CLI-auth expiry. A task that throws is recorded on its own\n result and the sweep continues; a missing table reports `unavailable`, so a\n sweep is safe against a partially bootstrapped database.\n- **A contributed task only exists in a process that loaded its package.** Both\n packages register on import from their entry point, and the registry lives on\n `globalThis` (like `ObjectRegistry`) so a duplicated `smrt-core` resolution\n cannot split it. `smrt db:prune` optionally imports both packages for exactly\n this reason — a project that installs neither correctly gets neither task.\n- **Defaults are opt-out, not opt-in.** `DEFAULT_RETENTION_POLICY` covers the\n four built-in tables (changes 30 days, AI usage 90 days, dispatch 30 days\n completed / 90 days failed, contexts strictly by their own `expires_at`), and\n those are the ones `smrt.configure({ retention })` tunes. Contributed tasks\n carry their own defaults and their own window options —\n `DEFAULT_JOB_RETENTION` (7 days terminal / 30 days failed / 30 days events,\n set through `registerJobRetentionTasks()` or the runner's `retention.jobs`),\n and expired credentials, which have no window because an expired credential\n has nothing worth retaining. Every task, built-in or contributed, can be\n turned off: a table set to `false`, a task set to `false` under `tasks`, or\n `enabled: false` for the whole sweep — through `smrt.configure`,\n `smrt db:prune --skip`, or the runner's `retention` config.\n- **Contributed task names are prefixed with the owning package's short name**\n (`jobs-records`, `jobs-events`, `users-sessions`, …) because the registry is\n one process-global namespace.\n- **Scheduling lives outside core.** A running `TaskRunner` sweeps every six\n hours (`retention: false` opts out) and `smrt db:prune` is the cron entry\n point. The first runner sweep is one interval after `start()`, never at\n start: a crash-looping worker must not become a delete loop.\n- **Every prune counts before it deletes.** `rowCount` is not reliably\n populated across the engines SMRT supports, so counting is both what gives a\n usable figure and what lets `dryRun` preview the *same* predicate rather than\n an approximation of it. Count and delete are two statements and deliberately\n not one transaction — a maintenance pass must not hold a write lock over a\n large delete — so the figure is approximate under concurrent writers. Where\n two bounds can select the same row (`pruneChangeFeed`, `pruneAiUsage`), the\n second bound excludes what the first already accounted for, so a dry run does\n not count an entry twice.\n- **Every retention predicate ships with its index** (rule 2 applies to\n maintenance SQL too): `_smrt_contexts(expires_at)`,\n `_smrt_ai_usage(tenant_id, created_at)` — which is also the subscriptions\n billing meter's range scan — `_smrt_dispatch(status, processed_at)` and\n `(status, updated_at)` come from the system DDL, so they reach existing\n databases through the `SMRT_SCHEMA_VERSION` bump that replays it.\n `_smrt_jobs(status, completed_at)` comes from\n `ensureJobsSystemTableCompatibility()` instead, because `_smrt_jobs` is\n generated from a decorated class and does not exist yet when bootstrap runs;\n the jobs collection calls that path on every `initialize()`.\n- **Expiry enforcement is prune-side only.** `recall()`/`recallAll()` keep\n their documented \"expiry is not applied at read time\" contract — changing it\n would change read semantics for existing callers, which is a different issue\n from bounding storage. `LearningMemory` filters expired rows itself.\n\n### 23. Dead generation surfaces were deleted, not wired (#2380)\n\nRule 9 named three surfaces that read as canonical but were not: the AST\n`generateSchema(objectDef)` entry point, `SchemaOverrideSystem`, and the\nnever-emitted `triggers: []`. Resolution, so a future agent does not re-open\nwhat was deliberately decided:\n\n- **The AST path is gone.** `SchemaGenerator.generateSchema(objectDef)` and its\n AST-only private helpers (`generateIndexes`, `generateTriggers`,\n `extractDependencies`, `generateVersion`, `getTableName`,\n `extractPackageName`) were deleted from `schema/generator.ts`, along with\n their sole caller, `generateSchemaModule()` in `vite-plugin/index.ts`, and the\n `smrt:schema` / `@happyvertical/smrt-virt-schema` virtual module registration\n that fed. Nothing else called it — grep the deleted method's exact name\n before assuming a caller was missed; the path-parity fixture and every other\n rule above already speak only of the four surviving entry points.\n- **`SchemaOverrideSystem` is gone**, file and all\n (`schema/override-system.ts` no longer exists). It was never called from\n anywhere in this repository outside its own now-deleted exports, and two of\n its five public methods (`createPraecoContentOverride`,\n `createPraecoMeetingOverride`) hard-coded a schema extension for a\n consuming project outside this monorepo — scaffolding that never belonged in\n the framework, not a generic feature with a missing caller. `SchemaOverride`\n (the type) went with it; `ColumnDefinition`/`IndexDefinition`/\n `TriggerDefinition`, which it merely referenced, did not.\n- **The DDL-strategy trigger machinery was kept, not deleted.**\n `TriggerDefinition`, `SchemaDefinition.triggers`, and every DDL strategy's\n `generateTriggers()` / `generateTriggerStatement()` / `supportsTriggers()`\n (`schema/ddl/*.ts`) are real, engine-uniform, directly-tested rendering code\n that runs on **every** table creation via `strategy.generateTriggers(schema)`\n — unlike the AST path, this is not an orphaned call graph. It is kept for the\n same reason rule 16 keeps the cached `schema.ddl` string: `SchemaDefinition`\n is part of the shape third-party tooling and published manifests may already\n depend on, and `EngineSpecificDDL`/`MultiEngineDDL` (`schema/ddl/types.ts`)\n carry `triggers` as part of that same contract. Deleting a published field is\n a different (and unjustified) risk from deleting a virtual module nothing\n ever imported.\n- **What changed is what is documented, not what runs.** `schema.triggers` is\n now explicitly documented (`schema/types.ts`) as always `[]` on every schema\n a `@smrt()` class can produce, and why: there is no `@smrt()`/`@field()`\n option that populates it (unlike `indexes`, #2357), `updated_at` is\n maintained at the application layer (`SmrtObject.save()`), and\n `migrations/differ.ts` never diffs triggers — so even a hand-populated one\n would only apply to a newly `CREATE TABLE`d table and never retrofit an\n existing one. Wiring live trigger emission was considered and rejected for\n this issue: it is a migration-rollout feature (retrofitting 238+ existing\n production tables needs the same `SMRT_SCHEMA_VERSION`-replay or differ\n support rule 21/rule 22's system-table work required), not a cleanup, and\n nothing in the epic depended on it the way #2359 depended on FK indexes\n actually shipping.\n- **`_smrt_signals` and `ObjectRegistry.persistToDatabase()`/`loadFromDatabase()`**\n — named in the original finding alongside triggers — were already handled by\n #2376 before this issue landed: see rule 21 and `system/schema.ts`'s\n `RETIRED_SYSTEM_TABLES`. Nothing further to do there.\n- **The two config-rebuild-site comments** (`schema/utils.ts`,\n `testing/database.ts`) rule 8 requires were already in place, added by\n #2357/#2360; the `testing/database.ts` \"same as migrations\" overclaim rule 1\n quotes was already corrected by #2359, and doctor's `experimentalDecorators`\n check was already fixed by #2368/#2399 (see `packages/cli/AGENTS.md`\n Gotchas). Re-verify against current source before repeating any of these —\n the epic's PRs landed across one evening and a stale assessment line is not\n proof a fix is still needed.\n"
|
|
967
977
|
},
|
|
968
978
|
{
|
|
969
979
|
"path": "agents/data-query.md",
|
|
@@ -8,8 +8,9 @@ export interface TestDatabaseOptions {
|
|
|
8
8
|
* - 'sqlite': SQLite database
|
|
9
9
|
* - 'json': JSON adapter (stores data as JSON files with DuckDB for querying)
|
|
10
10
|
* - 'duckdb': Native DuckDB database
|
|
11
|
+
* - 'postgres': PostgreSQL database (normally supplied through `db`)
|
|
11
12
|
*/
|
|
12
|
-
type?: 'sqlite' | 'json' | 'duckdb';
|
|
13
|
+
type?: 'sqlite' | 'json' | 'duckdb' | 'postgres';
|
|
13
14
|
/**
|
|
14
15
|
* Database URL (default: ':memory:')
|
|
15
16
|
* Use ':memory:' for in-memory databases (fastest for tests)
|
|
@@ -31,7 +32,16 @@ export interface TestDatabaseOptions {
|
|
|
31
32
|
* System tables include _smrt_contexts, _smrt_migrations, etc.
|
|
32
33
|
*/
|
|
33
34
|
includeSystemTables?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Explicitly omit physical FK constraints for adapter/query tests whose
|
|
37
|
+
* subject is unrelated to referential enforcement. Defaults to `false`.
|
|
38
|
+
* This is required (and deliberately noisy at the call site) when a DuckDB
|
|
39
|
+
* fixture uses generated `ON UPDATE CASCADE`, which DuckDB cannot enforce.
|
|
40
|
+
*/
|
|
41
|
+
omitForeignKeyConstraints?: boolean;
|
|
34
42
|
}
|
|
43
|
+
/** Resolve the DDL dialect used when preparing an existing test database. */
|
|
44
|
+
export declare function resolveTestDatabaseDDLEngine(type: TestDatabaseOptions['type'], db: DatabaseInterface, inferFromDatabase?: boolean): 'sqlite' | 'json' | 'duckdb' | 'postgres';
|
|
35
45
|
/**
|
|
36
46
|
* Creates an in-memory test database with schemas pre-created
|
|
37
47
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../src/testing/database.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../src/testing/database.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAqJ5D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,QAAQ,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,CAAC;IAEjD;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,EAAE,CAAC,EAAE,iBAAiB,CAAC;IAEvB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAEnB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAE9B;;;;;OAKG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED,6EAA6E;AAC7E,wBAAgB,4BAA4B,CAC1C,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,EAAE,EAAE,iBAAiB,EACrB,iBAAiB,UAAQ,GACxB,QAAQ,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,CAwC3C;AA4DD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAsB,eAAe,CACnC,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,iBAAiB,CAAC,CA+M5B"}
|
package/dist/testing/database.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { schemaForeignKeys } from "../schema/foreign-key-ddl.js";
|
|
1
2
|
import { detectEngine } from "../schema/ddl/index.js";
|
|
2
3
|
import { getSystemTableDDL } from "../system/schema.js";
|
|
3
4
|
import { ensurePostgresChangeFeedAppendFunction } from "../change-feed.js";
|
|
@@ -5,6 +6,7 @@ import { ensureLegacySystemTableCompatibility } from "../system/compatibility.js
|
|
|
5
6
|
import { SchemaGenerator } from "../schema/generator.js";
|
|
6
7
|
import { isCollectionRegistration, resolveCollectionItemClassName, resolveRelatedRegistration } from "../registry/collection-resolution.js";
|
|
7
8
|
import { ObjectRegistry } from "../registry.js";
|
|
9
|
+
import { planForeignKeyCreation } from "../schema/foreign-key-planner.js";
|
|
8
10
|
import { getDatabase } from "@happyvertical/sql";
|
|
9
11
|
//#region src/testing/database.ts
|
|
10
12
|
function resolveSTIBaseRegistration(className, stiBaseName) {
|
|
@@ -54,6 +56,29 @@ function resolveCollectionSchemaClassName(className, registered) {
|
|
|
54
56
|
}
|
|
55
57
|
return className;
|
|
56
58
|
}
|
|
59
|
+
/** Resolve the DDL dialect used when preparing an existing test database. */
|
|
60
|
+
function resolveTestDatabaseDDLEngine(type, db, inferFromDatabase = false) {
|
|
61
|
+
if (!inferFromDatabase) return type ?? "sqlite";
|
|
62
|
+
const configuredDb = db;
|
|
63
|
+
if (typeof configuredDb.inferSchemaFromJSON === "function" || typeof configuredDb.getTableLoadErrors === "function") return "json";
|
|
64
|
+
if (typeof configuredDb.exportTable === "function") {
|
|
65
|
+
if (typeof configuredDb.getTableSchema === "function" && typeof configuredDb.alterTable?.addColumn === "function") return "duckdb";
|
|
66
|
+
return "json";
|
|
67
|
+
}
|
|
68
|
+
return detectEngine(db.url || configuredDb.config?.url || "", configuredDb.type || configuredDb.config?.type);
|
|
69
|
+
}
|
|
70
|
+
function omitTestForeignKeyConstraints(schema) {
|
|
71
|
+
const foreignKeyTargets = new Set(schemaForeignKeys(schema).map((foreignKey) => foreignKey.referencesTable));
|
|
72
|
+
return {
|
|
73
|
+
...schema,
|
|
74
|
+
columns: Object.fromEntries(Object.entries(schema.columns).map(([name, column]) => [name, column.foreignKey ? {
|
|
75
|
+
...column,
|
|
76
|
+
foreignKey: void 0
|
|
77
|
+
} : column])),
|
|
78
|
+
foreignKeys: [],
|
|
79
|
+
dependencies: schema.dependencies.filter((dependency) => !foreignKeyTargets.has(dependency))
|
|
80
|
+
};
|
|
81
|
+
}
|
|
57
82
|
function resolveRequestedSchemaClassName(className) {
|
|
58
83
|
const registered = ObjectRegistry.getClass(className);
|
|
59
84
|
if (!registered) return className;
|
|
@@ -116,9 +141,9 @@ function resolveRequestedSchemaClassNames(classNames) {
|
|
|
116
141
|
* ```
|
|
117
142
|
*/
|
|
118
143
|
async function getTestDatabase(options = {}) {
|
|
119
|
-
const { type
|
|
144
|
+
const { type, url = ":memory:", db: existingDb, classes, includeSystemTables = true, omitForeignKeyConstraints = false } = options;
|
|
120
145
|
const db = existingDb ?? await getDatabase({
|
|
121
|
-
type,
|
|
146
|
+
type: type ?? "sqlite",
|
|
122
147
|
url,
|
|
123
148
|
__smrtSkipVitestSchemaPreparation: true
|
|
124
149
|
});
|
|
@@ -126,13 +151,14 @@ async function getTestDatabase(options = {}) {
|
|
|
126
151
|
const classNames = resolveRequestedSchemaClassNames(classes ?? ObjectRegistry.getQualifiedClassNames());
|
|
127
152
|
if (classNames.length === 0) return db;
|
|
128
153
|
const schemaGenerator = new SchemaGenerator();
|
|
129
|
-
const ddlEngine = type
|
|
130
|
-
const
|
|
154
|
+
const ddlEngine = resolveTestDatabaseDDLEngine(type, db, existingDb !== void 0);
|
|
155
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
156
|
+
const authoritativeSchemas = ObjectRegistry.getAllSchemasAsDefinitions();
|
|
131
157
|
for (const className of classNames) {
|
|
132
158
|
const registered = ObjectRegistry.getClass(className);
|
|
133
159
|
if (isSTIChild(className)) continue;
|
|
134
160
|
const tableName = ObjectRegistry.getTableName(className);
|
|
135
|
-
if (!tableName ||
|
|
161
|
+
if (!tableName || schemas.has(tableName)) continue;
|
|
136
162
|
const fields = await ObjectRegistry.getAllFields(className);
|
|
137
163
|
const strategy = ObjectRegistry.getTableStrategy(className);
|
|
138
164
|
const runtimeSchemaConfig = {
|
|
@@ -142,20 +168,65 @@ async function getTestDatabase(options = {}) {
|
|
|
142
168
|
registry: ObjectRegistry
|
|
143
169
|
};
|
|
144
170
|
const schema = strategy === "sti" ? await schemaGenerator.generateSTISchemaFromRegistry(className, tableName, fields, runtimeSchemaConfig) : schemaGenerator.generateSchemaFromRegistry(className, tableName, fields, runtimeSchemaConfig);
|
|
171
|
+
const authoritativeSchema = authoritativeSchemas[tableName];
|
|
172
|
+
const effectiveColumns = authoritativeSchema ? Object.fromEntries(Object.entries(schema.columns).map(([name, column]) => {
|
|
173
|
+
const manifestColumn = authoritativeSchema.columns[name];
|
|
174
|
+
return [name, manifestColumn ? {
|
|
175
|
+
...column,
|
|
176
|
+
foreignKey: manifestColumn.foreignKey
|
|
177
|
+
} : column];
|
|
178
|
+
})) : schema.columns;
|
|
179
|
+
const effectiveForeignKeys = schemaForeignKeys({
|
|
180
|
+
columns: effectiveColumns,
|
|
181
|
+
foreignKeys: []
|
|
182
|
+
});
|
|
183
|
+
const effectiveSchema = {
|
|
184
|
+
...schema,
|
|
185
|
+
columns: effectiveColumns,
|
|
186
|
+
foreignKeys: effectiveForeignKeys,
|
|
187
|
+
dependencies: effectiveForeignKeys.map((foreignKey) => foreignKey.referencesTable).filter((dependency) => dependency !== tableName)
|
|
188
|
+
};
|
|
189
|
+
schemas.set(tableName, {
|
|
190
|
+
schema: omitForeignKeyConstraints ? omitTestForeignKeyConstraints(effectiveSchema) : effectiveSchema,
|
|
191
|
+
className
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
const addDependencies = (schema) => {
|
|
195
|
+
for (const foreignKey of schemaForeignKeys(schema)) {
|
|
196
|
+
if (schemas.has(foreignKey.referencesTable)) continue;
|
|
197
|
+
const dependency = authoritativeSchemas[foreignKey.referencesTable];
|
|
198
|
+
if (!dependency) continue;
|
|
199
|
+
const effectiveDependency = omitForeignKeyConstraints ? omitTestForeignKeyConstraints(dependency) : dependency;
|
|
200
|
+
schemas.set(dependency.tableName, {
|
|
201
|
+
schema: effectiveDependency,
|
|
202
|
+
className: dependency.tableName
|
|
203
|
+
});
|
|
204
|
+
addDependencies(effectiveDependency);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
for (const { schema } of [...schemas.values()]) addDependencies(schema);
|
|
208
|
+
const tablePlan = planForeignKeyCreation([...schemas.values()].map(({ schema }) => schema), ddlEngine);
|
|
209
|
+
const ddlStrategy = (await import("../schema/ddl/index.js")).getDDLStrategy(ddlEngine);
|
|
210
|
+
for (const schema of tablePlan.schemas) {
|
|
211
|
+
const className = schemas.get(schema.tableName)?.className ?? "unknown";
|
|
145
212
|
const ddl = schemaGenerator.generateSQL(schema, ddlEngine);
|
|
146
213
|
try {
|
|
147
214
|
await db.query(ddl);
|
|
148
|
-
|
|
149
|
-
const indexStatements = (await import("../schema/ddl/index.js")).getDDLStrategy(ddlEngine).generateIndexes(schema);
|
|
215
|
+
const indexStatements = ddlStrategy.generateIndexes(schema);
|
|
150
216
|
for (const indexSQL of indexStatements) try {
|
|
151
217
|
await db.query(indexSQL);
|
|
152
218
|
} catch (indexError) {
|
|
153
219
|
console.warn(`[getTestDatabase] Warning: Failed to create index: ${indexError instanceof Error ? indexError.message : String(indexError)} (SQL: ${indexSQL})`);
|
|
154
220
|
}
|
|
155
221
|
} catch (error) {
|
|
156
|
-
throw new Error(`[getTestDatabase] Failed to create table '${tableName}' for class '${className}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
222
|
+
throw new Error(`[getTestDatabase] Failed to create table '${schema.tableName}' for class '${className}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
157
223
|
}
|
|
158
224
|
}
|
|
225
|
+
for (const statement of tablePlan.deferredStatements) try {
|
|
226
|
+
await db.query(statement);
|
|
227
|
+
} catch (error) {
|
|
228
|
+
throw new Error(`[getTestDatabase] Failed to add deferred foreign-key constraint: ${error instanceof Error ? error.message : String(error)} (SQL: ${statement})`, { cause: error });
|
|
229
|
+
}
|
|
159
230
|
return db;
|
|
160
231
|
}
|
|
161
232
|
/**
|
|
@@ -179,6 +250,6 @@ async function initializeSystemTables(db) {
|
|
|
179
250
|
await ensurePostgresChangeFeedAppendFunction(db);
|
|
180
251
|
}
|
|
181
252
|
//#endregion
|
|
182
|
-
export { getTestDatabase };
|
|
253
|
+
export { getTestDatabase, resolveTestDatabaseDDLEngine };
|
|
183
254
|
|
|
184
255
|
//# sourceMappingURL=database.js.map
|