@happyvertical/smrt-core 0.60.9 → 0.60.10
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/browser-entry.md +10 -0
- package/agents/change-feed.md +33 -0
- package/agents/object-runtime.md +8 -0
- package/agents/schema-paths.md +6 -0
- package/dist/browser.d.ts +2 -1
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +3 -2
- package/dist/cascade.d.ts +17 -3
- package/dist/cascade.d.ts.map +1 -1
- package/dist/cascade.js +30 -15
- package/dist/cascade.js.map +1 -1
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +8 -4
- package/dist/collection.js.map +1 -1
- package/dist/embedded-write-queue.d.ts +18 -7
- package/dist/embedded-write-queue.d.ts.map +1 -1
- package/dist/embedded-write-queue.js +40 -10
- package/dist/embedded-write-queue.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +25 -7
- 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 +39 -7
- package/dist/migrations/differ.d.ts +4 -0
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +25 -9
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/orchestrate.d.ts +1 -1
- package/dist/migrations/orchestrate.d.ts.map +1 -1
- package/dist/migrations/orchestrate.js +5 -14
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/native-duckdb.d.ts.map +1 -1
- package/dist/native-duckdb.js +5 -1
- package/dist/native-duckdb.js.map +1 -1
- package/dist/object.d.ts +26 -0
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +215 -55
- package/dist/object.js.map +1 -1
- package/dist/schema/generator.d.ts.map +1 -1
- package/dist/schema/generator.js +8 -4
- package/dist/schema/generator.js.map +1 -1
- package/dist/scripts/browser-entry-evaluation.mjs +63 -8
- package/dist/scripts/browser-unbundled-dev.mjs +5 -2
- package/dist/scripts/fixtures/browser-pglite-cascade.ts +107 -0
- package/dist/scripts/fixtures/pglite-peer/package.json +9 -0
- package/dist/scripts/fixtures/pglite-peer/peer.js +1 -0
- package/dist/scripts/fixtures/pglite-peer/pnpm-lock.yaml +22 -0
- package/dist/scripts/fixtures/pglite-peer/pnpm-workspace.yaml +1 -0
- package/dist/smrt-knowledge.json +19 -11
- package/dist/smrt-knowledge.okf.md +181 -0
- package/dist/sync-device.d.ts +6 -0
- package/dist/sync-device.d.ts.map +1 -0
- package/dist/sync-device.js +18 -0
- package/dist/sync-device.js.map +1 -0
- package/dist/sync-tombstones.d.ts +30 -0
- package/dist/sync-tombstones.d.ts.map +1 -0
- package/dist/sync-tombstones.js +112 -0
- package/dist/sync-tombstones.js.map +1 -0
- package/dist/system/schema.d.ts +5 -1
- package/dist/system/schema.d.ts.map +1 -1
- package/dist/system/schema.js +21 -4
- package/dist/system/schema.js.map +1 -1
- package/package.json +11 -11
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,21 +3,21 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-core",
|
|
6
|
-
"packageVersion": "0.60.
|
|
6
|
+
"packageVersion": "0.60.10",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "39728637e314fcaecf79e945fa35936a91160cffe4bf6ef065f332e42ab3accf",
|
|
11
|
+
"packageJson": "1a6cb3804811d59176b4f02ff474560472ef0fe1ef82922646aa037bbdc59aff",
|
|
12
12
|
"agents": "796e85343e7361fcb0874e904e709190189ffae4ca644d90d59b1bd2d1384b40",
|
|
13
|
-
"moduleDoc:agents/object-runtime.md": "
|
|
13
|
+
"moduleDoc:agents/object-runtime.md": "25716b05497ae5718a3bfbcbee8b986cf158b684d27be87b8236b0528fce2c24",
|
|
14
14
|
"moduleDoc:agents/revision-guard.md": "f6ea32a6860964c98aba14b93587f40b33c8f7d0deccb2c54d21bff45db3da42",
|
|
15
15
|
"moduleDoc:agents/collection-reads.md": "39acea7faf3505d38bfb999e414f4c4c6f964ec7c3d19cc52993302c29223029",
|
|
16
16
|
"moduleDoc:agents/query-bounds.md": "3a0601ddaf2bea4e90e3f22e16a2eb3508a6fb8c019e3fb2c1f930c90a377cd5",
|
|
17
17
|
"moduleDoc:agents/data-query.md": "726ef89560d4143d03bfc26943a993ecaa0b42b47e64e861d9de08ee17f1981b",
|
|
18
|
-
"moduleDoc:agents/schema-paths.md": "
|
|
18
|
+
"moduleDoc:agents/schema-paths.md": "f35f2a43241e71fe5b83fd3552f9d3f99f9b68a6307fa5200a4fb548171af864",
|
|
19
19
|
"moduleDoc:agents/deployment-phases.md": "e1036073f31d54db95de95e498c74cddce5e47f367d56ccc00aad69f4e5a28e1",
|
|
20
|
-
"moduleDoc:agents/change-feed.md": "
|
|
20
|
+
"moduleDoc:agents/change-feed.md": "3cb20313d338a510db8938c61832d93a7dbf3de27632b79af1d5b65b1e4365fc",
|
|
21
21
|
"moduleDoc:agents/change-signals.md": "a2dbe7077483b5a19bd5ea9589b5a08fe847377c8e05d01d57f813c6d9cbc28b",
|
|
22
22
|
"moduleDoc:agents/generators.md": "e1de88e8486534e0d70ddd578be13a73d4296a5c337ab2db74cd46b565092667",
|
|
23
23
|
"moduleDoc:agents/build-knowledge.md": "999cd57a28a521f2931d67dfb76eb35386aec6ad21a9642ccf6ba3f80e061961",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"moduleDoc:agents/recipes.md": "528dfe91b1e54d210bfbfa4d7de3420e0e897d55954c678089413851357e4275",
|
|
30
30
|
"moduleDoc:agents/cookbook.md": "20c256f4f6219f9b2add6365ef930e0bb3eda37e7866ddbc4bdd466830f76e4f",
|
|
31
31
|
"moduleDoc:agents/cookbook-engine.md": "f8e6869021b6cc214fe34da20b73a83509abc10bab71299ea9668b47a1c4307d",
|
|
32
|
-
"moduleDoc:agents/browser-entry.md": "
|
|
32
|
+
"moduleDoc:agents/browser-entry.md": "1244034d8b4d9a157fa80e08690ff2f547aabc11e6752f66e3a36072387104a3",
|
|
33
33
|
"moduleDoc:agents/test-types.md": "37c009ae2bd21001d83bba6cfab2047465fe32d5443de12661e24ba7d4e2d613"
|
|
34
34
|
},
|
|
35
35
|
"exports": [
|
|
@@ -752,6 +752,7 @@
|
|
|
752
752
|
"getSlug",
|
|
753
753
|
"hasBaseJunctionLifecycle",
|
|
754
754
|
"hasStaleEmbeddings",
|
|
755
|
+
"hydrateSyncMetadata",
|
|
755
756
|
"initialize",
|
|
756
757
|
"is",
|
|
757
758
|
"isRelatedLoaded",
|
|
@@ -929,6 +930,13 @@
|
|
|
929
930
|
"async": true,
|
|
930
931
|
"returns": "Promise<boolean>"
|
|
931
932
|
},
|
|
933
|
+
{
|
|
934
|
+
"name": "hydrateSyncMetadata",
|
|
935
|
+
"params": [
|
|
936
|
+
"row: Record<string, unknown>"
|
|
937
|
+
],
|
|
938
|
+
"returns": "void"
|
|
939
|
+
},
|
|
932
940
|
{
|
|
933
941
|
"name": "initialize",
|
|
934
942
|
"async": true,
|
|
@@ -1154,7 +1162,7 @@
|
|
|
1154
1162
|
{
|
|
1155
1163
|
"path": "agents/object-runtime.md",
|
|
1156
1164
|
"module": "object-runtime",
|
|
1157
|
-
"content": "# Object and collection runtime\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\nModels declaring `audit: true` use transactional collection CRUD with trusted\n`SmrtCollectionOptions.auditTrail` identity and writer. `collection.update()` checks\nregistered mutable fields; audited creates refuse natural-key overwrites.\nDirect object writes and custom overrides need explicit service recording.\nCascade reuse of a no-savepoint transaction requires an active framework-owned\ntransaction handle; raw caller transactions retain the ordinary delete limitation.\nSee [audit contract](../../../docs/content/audit-trail.md).\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- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws\n `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or\n delete to an earlier snapshot. Remote guarded deletes bind the same predicate\n into the final `DELETE`; embedded adapters compare inside the shared write queue\n before cascading. That queue serializes same-process saves, deletes, and full\n `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this\n public CAS ordering contract. PostgreSQL predicate:\n [revision-guard.md](revision-guard.md).\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\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- `normalizePersistenceData(data)` is the synchronous final derived-column hook:\n shared save preparation passes read-only snake-case row data after the complete polymorphic\n `toJSON()` / `transformJSON()` chain and UUID coercion, then merges the returned\n columns before every insert/update/upsert branch. Declare permitted snake-case\n columns with `getPersistenceDerivedColumns()`, preserving super declarations.\n Declarations must name registered schema fields; framework identity, tenant,\n revision, STI metadata and natural conflict columns are always rejected.\n Undeclared return keys reject before persistence. The hook receives a frozen\n shallow row copy. Derive only the declared columns; do not perform I/O.\n Preserve `super` results. It does not alter plain/public serialization;\n use `transformJSON()` for that existing contract. Ordinary saves and eligible\n junction batches share this preparation. A custom normalization override makes\n a junction ineligible for batching, preserving its virtual per-row save path.\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\nRelationship I/O resolves canonical source and target identities, not the public\ndisplay names. `relationship-loader.ts` owns target manifest hydration and inverse\nselection for lazy, eager, junction and latest-related reads. An unresolved exact\nconstructor or ambiguous target fails before querying or caching a foreign peer;\nlegacy external string targets retain manifest discovery. Junction column naming\nconventions still use display names. Cached reads retain their tenant rechecks.\n\n\n## Plain-object serialization\n\n`toPlainObject()` materializes the `toJSON()` / `transformJSON()` result directly,\nwithout an intermediate JSON string for ordinary payloads. Native `JSON.rawJSON()`\nliterals are decoded once with `JSON.parse()`. Nested hooks and JSON omission/coercion\nrules still apply. The active ancestor stack rejects cycles while allowing\nshared siblings, which become independent plain copies. Arrays skip boxed-value\nbrand checks; other objects use intrinsic brand checks without reading user\n`Symbol.toStringTag` getters. Customize the payload through `transformJSON()`.\nThe focused `to-plain-object.test.ts` suite compares legacy output and reports\nwarmed, interleaved per-row timings without a flaky timing assertion.\n\n`pnpm --filter @happyvertical/smrt-core test:browser` bundles the production\n`src/plain-json.ts` helper and executes it in Chromium with `process` and\n`JSON.isRawJSON` unavailable. It is an opt-in local/browser release gate rather\nthan part of the default core suite: it requires the repository's\n`playwright-core` dependency and an installed Chromium binary. Set\n`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/path/to/chromium` to use an installed\nexecutable; otherwise Playwright's managed Chromium is used. The normal test\nsuite covers the same helper through `toPlainObject()` on Node.\n\n## SmrtCollection Query\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [collection-reads.md](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\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\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\n`convertWhereKeys` must accept only operators executable by the SQL builder.\n`contains` and dot-notation JSON paths reject at the boundary; use `like` with\nexplicit wildcards. Adding operators requires SQL support first.\n`src/__tests__/issue-2276-where-contract.test.ts` executes the accepted set.\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 [query-bounds.md](query-bounds.md).\n\n\n## Junction reads and compatible writes\n\n`byLeft(id, { relationship: 'attachment', limit: 20, offset: 40 })` and\n`byRight()` forward `limit`/`offset` to the collection's existing bounds parser;\nother options remain field filters. Pagination is read-only: `detach()` still\nrequires field filters and never deletes a page. Cursor pagination is not part\nof this API; callers can use deterministic limit/offset pages.\n\n`setLinks()` preserves replacement semantics: even retained right IDs get new\njunction IDs/timestamps and delete/create change entries. `detach()` and\n`setLinks()` batch compatible models automatically. Within 100 removed + added\nrows and 900 inserted bind values, a warm SQLite/DuckDB/PostgreSQL operation uses\nconstant framework SQL: one snapshot, grouped owned-memory cleanup and delete,\none multi-row natural-key upsert, and one feed append per nonempty mutation\nphase. Bootstrap, retries, and caller-defined work are excluded. The read\nsnapshot and in-memory work remain proportional to link count.\n\nEligibility is deliberately conservative and rechecked each call: base runtime\nmethods/accessors and collection create/attach behavior, one non-STI table,\ncompiler-owned declarative validators, no validated cross-package references,\nno embedding generation, no incoming typed references, non-NULL unique\nconflict values with no duplicate input conflict keys, and explicit consent\nfrom every mutation interceptor. Otherwise the original virtual per-row path\nruns. Larger sets retain that fallback; there is no truncated replacement.\nPolymorphic association cleanup remains grouped through the owning cascade API\nand invalidates every affected table. JSON export adapters retain their ordinary\nlifecycle; unrecognized transaction-only DuckDB handles also fall back.\nThe tenancy interceptor consents only without directory dispatch/custom error\ncallbacks. Tenant checks and auto-population still run per row. The change-feed\ninterceptor appends every row and preserves tenant IDs and tombstones.\n\nBulk lifecycle preparation and completion are owned by `SmrtObject`; collection\ninitialization shares `createUnsaved()` with `create()`. Additional interceptors\nmay supply `bulkMutation.compatible()` only if grouped before/persist/after\nphases preserve their behavior and before hooks have no side effects beyond\ninstance/context mutation. Preparation can discover an unsupported shape and\nfall back; before hooks must tolerate that rehearsal. Unknown interceptors never\nopt in implicitly.\nThe compiler marks its own callback-free validators by function identity.\n\nThe whole replacement remains nontransactional unless the caller supplies a\ntransaction. A delete group is atomic with its owned-memory cleanup and each\nmulti-row insert is atomic, so database failure can leave the deletion phase\ncommitted without new links. No per-row prefix is promised for a failed batch.\nThe batch delete reuses an existing DuckDB transaction when the SDK explicitly\nrefuses savepoint nesting before running any work; it never replays a callback.\nThe legacy fallback retains its existing detectable nested-transaction refusal\nfor ordinary deletes inside caller-owned DuckDB transactions\n([#2824](https://github.com/happyvertical/smrt/issues/2824)).\nPublic ordinary `save()` still owns revision CAS; batches only create new\ninstances and never use this path to overwrite a loaded revision.\n\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- Tenancy (`dispatch/tenant-resolver.ts`): `emit` stamps the server-derived\n tenant; no context stores `tenant_id` NULL (global). Under an active tenant,\n processing (`process`/`retry`/`cleanup`) matches that tenant plus global rows,\n but inspection reads (`list`/`get`) match that tenant only — global rows are\n system-only because their payload may belong to another tenant (#3301). Emit\n tenant-owned deliveries inside the tenant context so the owner can see them.\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- Columns win over `_meta_data` (#3238): `formatDataJs` never lets a meta key\n shadow a column the row carries, except a field the class declares\n `@meta()` (a same-named column then belongs to an STI sibling). `id`, tenant-ownership and `_`-prefixed\n keys (`isReservedMetaDataKey`, inherited tenant fields included) are dropped\n from the blob on hydration and save, object or JSON text (`sanitizeMetaData`).\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n- Multi-level STI collections read their own discriminator and every registered descendant, never sibling branches. Decorate every intermediate with `@smrt()`; registration rejects an undecorated intermediate beneath an STI root.\n- `@smrt({ abstract: true })` makes a registered STI type readable but prevents saving an instance with its own discriminator. A base collection can still create a concrete descendant by passing that descendant's `_meta_type`. Generated surfaces expose only `list` and `get` for abstract models, including when custom actions were explicitly included.\n- Set `validateSubtype: true` on a foreign key or cross-package reference targeting an STI child when it must reject sibling rows. Save checks through the child's collection, and `loadRelated()` rejects a stored sibling row. The physical FK targets the shared root table, so the collection's discriminator and tenant read scope provide the subtype check. Saves fail when the subtype target cannot be loaded, even if ordinary cross-package validation is disabled.\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## Mandatory persisted write predicates\n\n`CollectionInterceptor.writeGuard` supplies trusted column predicates that callers\ncannot override through patches or save options. Core conjoins these with CAS\nconditions at the final mutation. Guarded new rows insert without unconditional\nupsert fallback; existing natural-key targets update conditionally, with zero rows\nfailing closed. Embedded adapter checks execute inside the shared write queue;\nPostgreSQL uses the final SQL predicate. Guarded policies disable bulk shortcuts\nunless explicitly compatible. Preserve this enforcement in save, claimRevision,\ndelete and natural-key adoption paths, including transaction-bound executors.\n\nMandatory write guards preserve natural-key identity: only the row found and\nowner-checked by the natural-key lookup can be adopted for a conditional update.\nAn unmatched natural key uses INSERT, even if its explicit primary key names an\nexisting row. Duplicate IDs therefore fail without changing foreign/global rows,\nincluding NULL-bearing natural keys on PostgreSQL.\n\n`requireInsertOnSave({ preserveDerivedSlug: true })` opts a model into new-identity\nwrites while retaining generated-name slug disambiguation. Explicit natural-key\ncollisions fail with the ordinary unique-constraint error; the create path of\n`getOrUpsert` cannot override this policy. Loaded objects still update by ID and\nrun their model guards. The default without options remains strict INSERT for\nevery initial save, including generated slugs. Once requested, that stricter\npolicy cannot be relaxed by a later opt-in call from the model.\n"
|
|
1165
|
+
"content": "# Object and collection runtime\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\nModels declaring `audit: true` use transactional collection CRUD with trusted\n`SmrtCollectionOptions.auditTrail` identity and writer. `collection.update()` checks\nregistered mutable fields; audited creates refuse natural-key overwrites.\nDirect object writes and custom overrides need explicit service recording.\nCascade reuse of a no-savepoint transaction requires an active framework-owned\ntransaction handle; raw caller transactions retain the ordinary delete limitation.\nSee [audit contract](../../../docs/content/audit-trail.md).\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- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws\n `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or\n delete to an earlier snapshot. Remote guarded deletes bind the same predicate\n into the final `DELETE`; embedded adapters compare inside the shared write queue\n before cascading. That queue serializes same-process saves, deletes, and full\n `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this\n public CAS ordering contract. PostgreSQL predicate:\n [revision-guard.md](revision-guard.md).\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\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- `normalizePersistenceData(data)` is the synchronous final derived-column hook:\n shared save preparation passes read-only snake-case row data after the complete polymorphic\n `toJSON()` / `transformJSON()` chain and UUID coercion, then merges the returned\n columns before every insert/update/upsert branch. Declare permitted snake-case\n columns with `getPersistenceDerivedColumns()`, preserving super declarations.\n Declarations must name registered schema fields; framework identity, tenant,\n revision, STI metadata and natural conflict columns are always rejected.\n Undeclared return keys reject before persistence. The hook receives a frozen\n shallow row copy. Derive only the declared columns; do not perform I/O.\n Preserve `super` results. It does not alter plain/public serialization;\n use `transformJSON()` for that existing contract. Ordinary saves and eligible\n junction batches share this preparation. A custom normalization override makes\n a junction ineligible for batching, preserving its virtual per-row save path.\n Junction batches write new rows in one statement. Known collisions take\n the per-row path. A late untracked collision updates the existing row in\n place, while a tracked collision rolls back all additions. Callers still\n own the transaction for an atomic remove-and-add replacement.\n- PostgreSQL nullable natural-key upserts recheck an initial miss on the\n bound transaction under a per-key advisory lock. A late same-owner match\n keeps its original ID and creation time. An unloaded write to a tracked\n match fails without committing.\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\nRelationship I/O resolves canonical source and target identities, not the public\ndisplay names. `relationship-loader.ts` owns target manifest hydration and inverse\nselection for lazy, eager, junction and latest-related reads. An unresolved exact\nconstructor or ambiguous target fails before querying or caching a foreign peer;\nlegacy external string targets retain manifest discovery. Junction column naming\nconventions still use display names. Cached reads retain their tenant rechecks.\n\n\n## Plain-object serialization\n\n`toPlainObject()` materializes the `toJSON()` / `transformJSON()` result directly,\nwithout an intermediate JSON string for ordinary payloads. Native `JSON.rawJSON()`\nliterals are decoded once with `JSON.parse()`. Nested hooks and JSON omission/coercion\nrules still apply. The active ancestor stack rejects cycles while allowing\nshared siblings, which become independent plain copies. Arrays skip boxed-value\nbrand checks; other objects use intrinsic brand checks without reading user\n`Symbol.toStringTag` getters. Customize the payload through `transformJSON()`.\nThe focused `to-plain-object.test.ts` suite compares legacy output and reports\nwarmed, interleaved per-row timings without a flaky timing assertion.\n\n`pnpm --filter @happyvertical/smrt-core test:browser` bundles the production\n`src/plain-json.ts` helper and executes it in Chromium with `process` and\n`JSON.isRawJSON` unavailable. It is an opt-in local/browser release gate rather\nthan part of the default core suite: it requires the repository's\n`playwright-core` dependency and an installed Chromium binary. Set\n`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/path/to/chromium` to use an installed\nexecutable; otherwise Playwright's managed Chromium is used. The normal test\nsuite covers the same helper through `toPlainObject()` on Node.\n\n## SmrtCollection Query\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [collection-reads.md](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\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\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\n`convertWhereKeys` must accept only operators executable by the SQL builder.\n`contains` and dot-notation JSON paths reject at the boundary; use `like` with\nexplicit wildcards. Adding operators requires SQL support first.\n`src/__tests__/issue-2276-where-contract.test.ts` executes the accepted set.\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 [query-bounds.md](query-bounds.md).\n\n\n## Junction reads and compatible writes\n\n`byLeft(id, { relationship: 'attachment', limit: 20, offset: 40 })` and\n`byRight()` forward `limit`/`offset` to the collection's existing bounds parser;\nother options remain field filters. Pagination is read-only: `detach()` still\nrequires field filters and never deletes a page. Cursor pagination is not part\nof this API; callers can use deterministic limit/offset pages.\n\n`setLinks()` preserves replacement semantics: even retained right IDs get new\njunction IDs/timestamps and delete/create change entries. `detach()` and\n`setLinks()` batch compatible models automatically. Within 100 removed + added\nrows and 900 inserted bind values, a warm SQLite/DuckDB/PostgreSQL operation uses\nconstant framework SQL: one snapshot, grouped owned-memory cleanup and delete,\none multi-row natural-key upsert, and one feed append per nonempty mutation\nphase. Bootstrap, retries, and caller-defined work are excluded. The read\nsnapshot and in-memory work remain proportional to link count.\n\nEligibility is deliberately conservative and rechecked each call: base runtime\nmethods/accessors and collection create/attach behavior, one non-STI table,\ncompiler-owned declarative validators, no validated cross-package references,\nno embedding generation, no incoming typed references, non-NULL unique\nconflict values with no duplicate input conflict keys, and explicit consent\nfrom every mutation interceptor. Otherwise the original virtual per-row path\nruns. Larger sets retain that fallback; there is no truncated replacement.\nPolymorphic association cleanup remains grouped through the owning cascade API\nand invalidates every affected table. JSON export adapters retain their ordinary\nlifecycle; unrecognized transaction-only DuckDB handles also fall back.\nThe tenancy interceptor consents only without directory dispatch/custom error\ncallbacks. Tenant checks and auto-population still run per row. The change-feed\ninterceptor appends every row and preserves tenant IDs and tombstones.\n\nBulk lifecycle preparation and completion are owned by `SmrtObject`; collection\ninitialization shares `createUnsaved()` with `create()`. Additional interceptors\nmay supply `bulkMutation.compatible()` only if grouped before/persist/after\nphases preserve their behavior and before hooks have no side effects beyond\ninstance/context mutation. Preparation can discover an unsupported shape and\nfall back; before hooks must tolerate that rehearsal. Unknown interceptors never\nopt in implicitly.\nThe compiler marks its own callback-free validators by function identity.\n\nThe whole replacement remains nontransactional unless the caller supplies a\ntransaction. A delete group is atomic with its owned-memory cleanup and each\nmulti-row insert is atomic, so database failure can leave the deletion phase\ncommitted without new links. No per-row prefix is promised for a failed batch.\nThe batch delete reuses an existing DuckDB transaction when the SDK explicitly\nrefuses savepoint nesting before running any work; it never replays a callback.\nThe legacy fallback retains its existing detectable nested-transaction refusal\nfor ordinary deletes inside caller-owned DuckDB transactions\n([#2824](https://github.com/happyvertical/smrt/issues/2824)).\nPublic ordinary `save()` still owns revision CAS; batches only create new\ninstances and never use this path to overwrite a loaded revision.\n\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- Tenancy (`dispatch/tenant-resolver.ts`): `emit` stamps the server-derived\n tenant; no context stores `tenant_id` NULL (global). Under an active tenant,\n processing (`process`/`retry`/`cleanup`) matches that tenant plus global rows,\n but inspection reads (`list`/`get`) match that tenant only — global rows are\n system-only because their payload may belong to another tenant (#3301). Emit\n tenant-owned deliveries inside the tenant context so the owner can see them.\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- Columns win over `_meta_data` (#3238): `formatDataJs` never lets a meta key\n shadow a column the row carries, except a field the class declares\n `@meta()` (a same-named column then belongs to an STI sibling). `id`, tenant-ownership and `_`-prefixed\n keys (`isReservedMetaDataKey`, inherited tenant fields included) are dropped\n from the blob on hydration and save, object or JSON text (`sanitizeMetaData`).\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n- Multi-level STI collections read their own discriminator and every registered descendant, never sibling branches. Decorate every intermediate with `@smrt()`; registration rejects an undecorated intermediate beneath an STI root.\n- `@smrt({ abstract: true })` makes a registered STI type readable but prevents saving an instance with its own discriminator. A base collection can still create a concrete descendant by passing that descendant's `_meta_type`. Generated surfaces expose only `list` and `get` for abstract models, including when custom actions were explicitly included.\n- Set `validateSubtype: true` on a foreign key or cross-package reference targeting an STI child when it must reject sibling rows. Save checks through the child's collection, and `loadRelated()` rejects a stored sibling row. The physical FK targets the shared root table, so the collection's discriminator and tenant read scope provide the subtype check. Saves fail when the subtype target cannot be loaded, even if ordinary cross-package validation is disabled.\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## Mandatory persisted write predicates\n\n`CollectionInterceptor.writeGuard` supplies trusted column predicates that callers\ncannot override through patches or save options. Core conjoins these with CAS\nconditions at the final mutation. Guarded new rows insert without unconditional\nupsert fallback; existing natural-key targets update conditionally, with zero rows\nfailing closed. Embedded adapter checks execute inside the shared write queue;\nPostgreSQL uses the final SQL predicate. Guarded policies disable bulk shortcuts\nunless explicitly compatible. Preserve this enforcement in save, claimRevision,\ndelete and natural-key adoption paths, including transaction-bound executors.\n\nMandatory write guards preserve natural-key identity: only the row found and\nowner-checked by the natural-key lookup can be adopted for a conditional update.\nAn unmatched natural key uses INSERT, even if its explicit primary key names an\nexisting row. Duplicate IDs therefore fail without changing foreign/global rows,\nincluding NULL-bearing natural keys on PostgreSQL.\n\n`requireInsertOnSave({ preserveDerivedSlug: true })` opts a model into new-identity\nwrites while retaining generated-name slug disambiguation. Explicit natural-key\ncollisions fail with the ordinary unique-constraint error; the create path of\n`getOrUpsert` cannot override this policy. Loaded objects still update by ID and\nrun their model guards. The default without options remains strict INSERT for\nevery initial save, including generated slugs. Once requested, that stricter\npolicy cannot be relaxed by a later opt-in call from the model.\n"
|
|
1158
1166
|
},
|
|
1159
1167
|
{
|
|
1160
1168
|
"path": "agents/revision-guard.md",
|
|
@@ -1179,7 +1187,7 @@
|
|
|
1179
1187
|
{
|
|
1180
1188
|
"path": "agents/schema-paths.md",
|
|
1181
1189
|
"module": "schema-paths",
|
|
1182
|
-
"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;\nit links the relevant runtime and generation contracts.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. Their columns and indexes must agree 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\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\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 default keys** are `(tenant_id, slug, context)`, plus `_meta_type`\n for STI. `ManifestGenerator.normalizeConflictColumns()` and\n `ObjectRegistry.getConflictColumns()` share `src/schema/conflict-target.ts`:\n resolve tenant fields through the schema owner/STI root, report group/bucket\n columns through the report, and custom PKs through their key. Explicit\n `conflictColumns` remain unchanged. The manifest, schema, knowledge, and\n runtime must carry the same value.\n Names remain `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so\n migration replaces a same-name global unique with tenant-led columns. That\n prefix serves tenant and tenant-scoped slug reads; a legacy standalone tenant\n index is dropped only with `--drop-indexes`.\n- **Widening an explicit key** (e.g. `['key']` → `['tenant_id', 'key']`,\n #3126) renames its index, so migration adds the new unique and\n `SchemaComparer` drops the superseded one without `--drop-indexes`: a UNIQUE\n index named `conflictIndexName()` for its own columns, with no predicate,\n whose columns are a strict subset of a declared UNIQUE index. It is a pure\n relaxation (every row satisfies the wider key) and otherwise would keep\n rejecting rows the model allows. The maintenance-window rule below applies.\n DuckDB has no partial indexes, so its indexes count as predicate-free, and\n its quoted index columns (`\"key\"`) are unquoted before comparison (#3305 M1).\n- **Optional NULL tenants** retain the SDK's NULL-equal upsert identity. Generated\n framework conflict indexes with nullable keys carry `nullsNotDistinct: true`;\n PostgreSQL 15+ creates `UNIQUE NULLS NOT DISTINCT`, enabling warm single-statement\n native upserts. Earlier PostgreSQL, SQLite and DuckDB retain adapter fallback\n semantics. Existing ordinary indexes are upgraded only through the explicit\n [NULL-equal maintenance migration](null-equal-indexes.md). Optional business\n unique fields remain NULLS DISTINCT; this marker is not inferred from them.\n- **Tenant-key rollout requires a maintenance window.** Old code/new indexes\n and new code/old indexes both fail new-object saves because conflict column\n sets must match exactly; persisted ID-based saves still work. Backfill legacy\n NULL tenants first or scoped ingestion creates separate rows and cannot see\n the old global ones. Cross-tenant natural-key dedup now creates one row per\n tenant. Deploy code and migrate together in atomic mode: each table drops\n and recreates its same-name unique index, holding ACCESS EXCLUSIVE locks\n (including against reads) until commit. Size `statementTimeout` for the\n largest table. A valid old subset unique guarantees the superset build;\n missing/nonunique old indexes may contain duplicates and need dedup first.\n Include the reference-index wave in that atomic window. `--postgres-safe` is\n suitable for an additive reference-index-only wave, but a key replacement\n leaves a per-table gap between drop/build and a failed build leaves no arbiter\n until rerun. There is no automatic DOWN; reverting code requires deliberately\n recreating its old indexes.\n\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\n## Verification\n\nExtend `src/schema/schema-path-parity.test.ts` for every generator change;\nmanifest, registry, and merged migration schemas must agree. Inspect regenerated\n`dist/manifest.json` and schemas across affected packages, not only decorators.\nRuntime `verifyPersistenceTable()` checks table existence only. Database drift\nchecks compare with generated artifacts; they cannot detect an omission shared\nby those artifacts. Use `smrt doctor --db` / `db:status --parity` for live parity.\n\nEvery new query predicate needs its index or an explicit reason none is needed.\nRun `pnpm --filter @happyvertical/smrt-core test:postgres` for numeric types,\nUUID casts, conflict targets, timestamps, or migrations. Schema-affecting options\nmust reach `SchemaGeneratorConfig` and both config rebuild sites:\n`src/schema/utils.ts` and `src/testing/database.ts`.\n\nTenant uniqueness and conflict targets must include the tenant column; explicit\n`conflictColumns` are author-owned and never rewritten. All reads, including\nhydration, slug lookup, vector search, and memory, remain interceptor-aware.\nRetry only transient errors classified through the cause chain; never retry an\naborted PostgreSQL transaction (`25P02`).\n\n### Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), default list ordering, 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()` (default ordering below) 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. Keep both config rebuild sites aligned.\n\n### STI subclasses declare indexes on the shared table (#3299)\n\n`@smrt({ indexes })` on an STI **descendant** is emitted on the shared table\nby `appendStiSubclassDeclaredIndexes()` (both STI entry points, after the\nbase's declarations; `getAllSchemasAsDefinitions()` and `getTestDatabase()`\ninherit it). It goes through the same validation as a base declaration: known\ncolumns, the 63-byte name limit, and errors on a collision. A UNIQUE\ndeclaration is scoped to the declaring subtype with\n`WHERE _meta_type = '<qualified class>'`, so siblings sharing the column are\nnot constrained. As with `@field({ unique })` on a descendant, each class in\nthe declaring class's own subtree gets a partial copy\n(`<declared name, cut to 52>_<10-hex digest>`), so uniqueness holds per\nconcrete class there too, not across the subtree. DuckDB/JSON skip these\nrather than widen them. A subclass UNIQUE with its own `where` is refused; declare a\ncombined predicate on the base. A plain subclass index stays unqualified, so\npolymorphic reads can use it. Columns are emitted exactly as declared and are\nnever tenant-prefixed, as with explicit `conflictColumns`: put `tenant_id`\nfirst for a tenant-local key (`['tenantId', 'rampEventId']`). Leave it out\nonly for a reviewed global identity (#3305 dispositions).\n\nMigration: `db:migrate` adds the new index by name. A UNIQUE index fails\nclosed (the migration rolls back) when existing rows already duplicate the\nkey. Find and repair those rows first, scoped to the subtype\n(`_meta_type = '<qualified class>'`), and never by deleting history to make\nthe index fit. With `db:migrate --postgres-safe` it is built `CONCURRENTLY`.\nA failed concurrent build leaves an INVALID index, which the next run drops\nand rebuilds after the data is repaired.\n\n### 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.\nRuntime decorators retain the resolved constructor alongside the display name.\nInverse lookup and cascade planning resolve that constructor when queried, so\nthe target may register after its child without binding to a same-name class\nin another package. String targets prefer the declaring package; ambiguous\nunqualified targets never match an unrelated package's inverse edge.\nRegistry schema generation and the merged migration schema resolve the same\ncanonical target before selecting both its table and identifier type. The\nmanifest generator resolves unqualified targets in the declaring package.\nKeep the merged schema in parity tests: `getTestDatabase()` preserves its\nauthoritative FK metadata over the generated columns, so testing only the\nstandalone generator cannot prove the constraint that reaches the database.\nWith an explicit `classes` list, `getTestDatabase()` builds that authoritative\nschema with `getAllSchemasAsDefinitions({ tables })`: only the requested tables\nand their foreign-key closure are merged and ownership-checked\n(`CONFIG_TABLE_NAME_COLLISION` still fires for any of them), so an unrelated\ncollision elsewhere in the registry cannot abort the setup. The implicit list\nchecks every registered table (#3956).\n\nField decorator registration retains constructor ownership separately from the\nsimple-name inspection view. Custom decorators should pass the callback's\nconstructor as `registerFieldDecorator`'s fourth argument. Omit it only for\nintentional legacy string-only metadata; that legacy metadata still composes\nwith constructor-owned options, but mirrored public decorator fields do not.\n\n### Decorator-only field types agree on both paths (#4295)\n\nA compiled model registered without a manifest entry sees only `@field()`\noptions, never the initializer or annotation the scanner reads. Without an\nexplicit `type`, a boolean `default` infers `boolean` on both paths\n(`inferDecoratorOnlyFieldType` in `src/registry/class-registration.ts`, step\n3.7 of the scanner's `ManifestAdapter.inferFieldType`); anything else falls\nback to `text`. Numbers are never inferred at runtime (`0` and `0.0` are the\nsame value), so a runtime-only numeric field must declare\n`type: 'integer' | 'decimal'`. Loading the manifest later still replaces the\ndecorator-only type. A database whose column was built from the old TEXT\nexpectation is not auto-cast; parity reports the drift for an explicit\nmigration.\n\n### 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### Explicit SQLite NOT NULL relaxation (#4413)\n\n`relaxColumns: true` / `smrt db:migrate --relax-columns` also supports removing\nan ordinary inline `NOT NULL` clause on a manifest-declared column. The local\napplication entry point forwards `smrt app migrate --relax-columns` under its\nexisting operation lock and refuses a live application writer. The programmatic\n`migrateSmrtSchemas` / `getPendingSchemaStatements` entry points accept the same\nexplicit `relaxColumns` option. Defaults remain advisory; this does not relax\norphan columns or change SQLite defaults/tightening behavior.\n\nThe rebuild preserves live DDL, indexes/triggers and assigned rowids. Named\nNOT NULL constraints, `ON CONFLICT`, AUTOINCREMENT tables, primary/generated target columns, missing\nclauses and tables shadowing every rowid alias refuse rather than guessing.\nA nullable-relaxation rebuild emits `PRAGMA foreign_keys = OFF` as a tracker\nhandoff: `MigrationTracker` suspends FK enforcement **before** opening its\ntransaction, verifies suspension on both the base and transaction connection,\nand checks `PRAGMA foreign_key_check` before commit. This avoids inbound FK\n`ON DELETE` actions and preserves referencing rows. An active borrowed transaction\nthat cannot suspend enforcement, a mismatched transaction connection or an\nadapter without transactions refuses. FK and legacy rename settings are restored\nin `finally`, including after rollback. Run this maintenance operation with\nexclusive access to the SQLite connection. Type-only rebuilds retain the older\ninbound-FK refusal described above.\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 inline only on an empty\n table. On a populated one it needs a per-row `backfill` (#3008,\n `ColumnDefinition.backfill` from `@field({ backfill })`): PostgreSQL/DuckDB\n run `ADD COLUMN` (nullable) → `UPDATE … SET col = (backfill) WHERE col IS\n NULL` → `SET DEFAULT` (deferred, if declared) → `SET NOT NULL` → the unique\n index; SQLite adds it through the table rebuild (`sqliteBackfillPlaceholderSql`\n → `planSqliteTableRebuilds` appends `\"col\" TYPE NOT NULL` and copies\n `(backfill)`), one rebuild per table for every such column. The differ first\n probes `WHERE (backfill) IS NULL` on the live rows. With no default and no\n backfill, or with a backfill that yields NULL or will not evaluate, the\n column is **not added**: a manual `alter_column` (`mismatch.actual ===\n REQUIRED_COLUMN_NOT_ADDED`) names table and column, and `compareTable`\n withholds `add_index`/`add_foreign_key` changes on it. The same backfill\n repairs nullability drift (an existing nullable column holding NULLs).\n A backfill for a single-column unique target is also probed for duplicate\n values and refused by name. Partial unique indexes are exempt from that\n probe only where `supportsPartialIndexes()` holds (SQLite/PostgreSQL);\n DuckDB/JSON build them as full indexes, so they are probed there (#3015).\n DuckDB refuses `ALTER COLUMN` while any index depends on the table, so its\n `SET NOT NULL` is bracketed by `DROP INDEX`/recreate from `duckdb_indexes().sql`.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1), except a NOT NULL tightening with a\n declared `backfill`, which the rebuild performs (`COALESCE(col, backfill)`\n in the copy). The rebuild otherwise consumes `type_upgrade` placeholders.\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### `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### 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\nThe first contributor supplies fallback columns, `idType`, conflict columns,\ncached DDL, and wins column conflicts. Keep base-first ordering even when a\nchild without manifest schema registers first.\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### Default list ordering indexes\n\nAll four generators index `DEFAULT_LIST_ORDER_BY` (`created_at DESC, <pk> ASC`):\n`ensureDefaultListOrderingIndex()` emits `(tenant column, created_at)` when\nscoped, otherwise `(created_at)`. Resolve tenant columns by `referenceKind ===\n'tenantId'`, not spelling. The tenant-leading pair also serves the reference\nindex requirement.\n\nOnly an unqualified, non-JSON-path index with the same leading columns suppresses\nit. Append declared composites first, then default ordering, then reference\nindexes. `(tenant_id, created_at, status)` replaces the default pair;\n`(tenant_id, publish_date)` does not. Emit one plain index per STI table, since\nbase polymorphic reads lack `_meta_type` predicates.\n\nDo not add direction or PK columns by inference: `IndexDefinition` has no\nper-column directions, backward B-tree scans serve descending timestamps, and\nthe mixed-direction PK tie-break still needs incremental sorting within equal\ntimestamps.\n\n### 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### Tenant OWNERSHIP, not tenant scope, leads the default key\n\nA class with a `tenantId` field is tenant-owned even when it declares no\ntenancy — consumers register such classes with the tenancy interceptor at\nruntime (Anytown's Ludis `League`/`Team`, smrt-users `Group`/`Role`/…), which\ncore never reads. `resolveOwnershipTenantColumn()` (declared tenant column,\nelse `tenant_id`) leads the default natural key on every producer:\n`ObjectRegistry.getOwnershipTenantColumn()` / `getConflictColumns()`,\n`normalizeConflictColumns()`, the generator's `resolveConflictTarget()` and the\nregistry schema-builder. The tenancy read policy is still never inferred\n(`getTenantScopedConfig()` stays undefined). Explicit `conflictColumns` are\nnever rewritten. Old code's `ON CONFLICT (slug, context)` and new code's\n`ON CONFLICT (tenant_id, slug, context)` each need their own unique index, so\nthe inferred tenant-led key is named by the custom-key rule\n(`<table>_tenant_id_slug_idx`; only a DECLARED tenant column keeps\n`<table>_slug_context_idx`) and `smrt db:migrate` builds it BESIDE the legacy\nglobal unique (expand). The differ keeps the legacy index\n(`isLegacyNaturalKeyIndex()`, exempt from the #3126 superseded-index sweep and\nfrom `--drop-indexes`) until `--drop-legacy-natural-key` /\n`DiffOptions.dropLegacyNaturalKey` (contract). `db:status` exits 1 while the\ntenant-led unique is missing and warns while the legacy one survives\n(`cli/src/commands/tenant-natural-keys.ts`). Deploy order and locking:\n`docs/content/core.md` (\"Upgrading an existing database\"). The implicit\n`tenant_id` column never makes a foreign key identifying\n(`resolveForeignKeyDeleteAction({ columnName })`): a tenant FK stays\n`NO ACTION`, so deleting a tenant does not cascade through tenant-owned tables.\n\nThe save path backs this up where the key still omits the owner (an explicit\nkey, or a live table not yet migrated) — `SmrtObject.writeNaturalKeyRow()`. The\nrow a NEW object's conflict target matches is read directly, bypassing read\ninterceptors. A different owner on any ownership column\n(`ObjectRegistry.getOwnershipColumns()`: `tenant_id`, the declared tenant\ncolumn, `@tenantId` fields and runtime registrations reported through\n`ObjectRegistry.registerOwnershipColumnSource()` — the tenancy package reports\n`registerTenantScopedClass(…, { field })` columns) raises\n`TenantIsolationError.naturalKeyOwnedElsewhere()` (`TENANT_ISOLATION_VIOLATION`,\nnever retried, never naming the other owner), also under `withSystemContext()`;\nNULL — or an ownership column the save leaves unset — counts as an owner. A\nsame-owner row is adopted by id (keeping its `created_at`, applied to the\ninstance only after the write succeeds), so `DO UPDATE SET` never rewrites a\nprimary key (no `ON UPDATE CASCADE` churn). Adoption needs an explicit natural\nkey: when the match is only through a slug `getSlug()` derived from\n`name`/`title`/`label` (a human value, not an identity), the new object keeps\nits id, moves to the first free `<base>-2` … `<base>-9` (one `slug IN (…)`\nprobe; then `<base>-<8 id chars>`) and INSERTs — whoever owns the taken row, so\nit is never refused. `getOrUpsert()`'s create path opts back into adoption\n(`_adoptNaturalKey`): a miss on a non-key field updates the row the derived\nslug names instead of adding `<slug>-2`. On PostgreSQL with no NULL conflict\nvalue the write is `INSERT … ON CONFLICT (…) DO NOTHING RETURNING id` first, so\na new key costs one statement and no pre-read, and concurrent first creates\nnever collapse: the loser re-reads and adopts (explicit key) or moves (derived\nslug, then straight to the id suffix), bounded retries. Embedded engines\n(serialized by the in-process write queue) and NULL-bearing keys read first.\nThe junction batch path falls back to per-item saves when\nits conflict target omits an ownership column present in the row (`tenant_id`,\nthe declared tenant column, or any `@tenantId`-marked field), and when any new\nitem's natural key already names a row the batch is not removing; its\n`DO UPDATE SET` never lists `id`, `created_at` or an ownership column. Strict\ninserts (`_insertOnly`) check NULL-bearing keys the same way, because NULLs\nare distinct in the unique index on SQLite, DuckDB and PostgreSQL < 15.\n\nA save with no owner (`tenantId: null`, typically under `withSystemContext()`)\nis deliberately NOT refused when a tenant row shares its slug under the\ntenant-led key: it lands as a separate global row, the global-default /\ntenant-override shape #2360 keeps. Refusing it would need a cross-owner read on\nevery global save and would break that pattern. A model that needs a slug\nunique across every owner declares explicit `conflictColumns` without the\ntenant column; then the guard refuses the colliding save instead.\n\n### Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates identifiers beyond 63 bytes; two generated names sharing\nthat prefix can make `CREATE INDEX IF NOT EXISTS` silently skip an index.\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** are not guarded: PostgreSQL truncates their\n declarations and references consistently. `smrt-users` tests intentionally\n long table names; collision risk remains with the author.\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### The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`SmrtClass` coalesces concurrent system-table initialization through completion\nof bootstrap, deferred compatibility, and vector setup (#3944). In-flight work\nis shared only by the same database handle. Distinct handles at the same URL\nretain database-level coordination: a caller-owned transaction may finish its\ninitialization statements before its tables become visible to another handle.\nAll same-handle waiters observe failure; the pending entry is removed so a fresh\ninstance can retry. Existing completed-success cache identities are unchanged.\nProvision system tables on a base connection before caller-owned transactions;\nconstructor initialization still preserves PostgreSQL's transaction lock lifetime.\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\nOn PostgreSQL `db:migrate` converges a live SMRT-owned constraint whose only\ndrift is its action (#3023, `SchemaComparer.findReplaceableForeignKey()`):\nbuild-then-swap via `renderForeignKeyReplaceStatements()` — staged\n`<name>_smrt_new` added `NOT VALID` and validated before the old constraint is\ndropped and the staged one renamed; `--postgres-safe` runs the VALIDATE and the\nswap outside the batch transaction. A change toward `CASCADE` / `SET NULL` /\n`SET DEFAULT` still applies (the manifest declares it) but carries a\n`warning` advisory that `db:diff`, `db:status` and `db:migrate` print as\nDESTRUCTIVE.\n\n### Deletes inside a caller-owned transaction\n\n`runCascadeDelete()` owns the cascade's atomic scope through\n`runInOwningCascadeTransaction()` in `src/cascade.ts` (#2824). A root handle opens\nits own transaction. A transaction handle on an engine with savepoints nests.\nWhen the engine refuses to nest (`NestedTransactionError`, raised by the SDK before\nthe callback runs), the cascade joins the enclosing transaction. This happens for\nframework-owned handles, for caller-owned **native DuckDB** transactions\n(`db.transaction()` scopes and `beginTransaction()` handles passed to\n`withDatabase()`), and for the bulk junction path (#2818). A transaction handle\ncounts as native DuckDB only after core has seen its root, through\n`initialize()`, `withDatabase()` or a framework transaction. Otherwise the\nhandle is never treated as native by guesswork, and the delete keeps the\n`NestedTransactionError` refusal. The caller's commit or\nrollback then decides the outcome of the cascade, the owned `_smrt_contexts` and\n`_smrt_embeddings` cleanup, and the target row.\n\nThere is no savepoint, so a cascade that fails part-way cannot be undone on its\nown. On native DuckDB the framework therefore aborts the joined transaction\n(`SELECT error(...)`) before rethrowing, but only if the cascade has already\nissued a write. The SDK's DuckDB `delete()` reports a constant affected count,\nand the owned-row cleanup always runs. In practice, then, any failure after the\ndepth-0 RESTRICT / NO ACTION preflight aborts the transaction. That includes a\nrevision or write-guard conflict on the row itself, even one that changed no\nrows. DuckDB then rejects every later statement with \"transaction\nis aborted\", and its `COMMIT` persists nothing. A caller that swallows the error\ntherefore cannot commit a half-applied cascade, and the callback is never\nreplayed. By contrast, a refusal raised before the first write, such as the\nRESTRICT / NO ACTION preflight, leaves the caller's transaction usable.\nJSON-adapter caller transactions keep the detectable\n`NestedTransactionError` refusal, because nothing can poison them.\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\nSame-package archival identifiers may explicitly use `@foreignKey(Target, {\nconstraint: false })`: preserve relationship loading and indexing, but omit\nphysical constraints, schema dependencies, and application cascade/preflight\nso the identifier survives parent deletion. Document the retention reason at\nthe field; ordinary references remain constrained.\n\nFor a same-package relationship whose semantics are portable but whose physical\nconstraint shape is not, `@foreignKey(Target, { constraint: { engines: [...] } })`\nis the public exception. The allowlist scopes physical DDL and dependency\nplanning only. Relationship metadata, UUID representation, derived indexes, and\nthe application delete rail remain canonical on every engine. Empty or unknown\nengine lists fail closed; unannotated unsupported DuckDB cycles and actions keep\ntheir actionable refusal.\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\nRollback drops children before parents, removes deferred PostgreSQL cycle\nconstraints first, and defers SQLite checks while dropping populated cycles.\nAggregation that filters a parent also removes a retained child's physical FK.\nPostgreSQL deferred constraint adds are idempotent. Generated `ON UPDATE\nCASCADE` remains the default; DuckDB/JSON must refuse unsupported actions\nrather than silently stripping them.\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. The probe uses distinct child/parent aliases and, when both\nmanifest columns are UUIDs, bases its guarded casts on both live column types:\nmatching live types compare directly, while a legacy text side is shape-checked\nbefore casting. This keeps a self-reference or malformed legacy value from\ninvalidating the query. An orphan stops migration with detector SQL and an\nexecutable repair suggestion: nullable FKs are cleared, while required FKs\nrequire an explicit operator decision to reassign the reference or deliberately\nremove a child row after preserving its required data. A probe failure is\nsurfaced as a database/framework error, never misreported as orphan data.\nWhen the referenced parent is absent but scheduled for creation by the same\n`compare()` batch (#3240), PostgreSQL first proves the entire existing child\ntable empty instead of querying the absent parent. Nonempty children are blocked\nwithout executable repair SQL: create and populate the parent deliberately,\nthen rerun the ordinary orphan preflight. The exception never applies to a\nstandalone `compareTable()` or an undeclared missing parent, and incompatible\ncolumn types, missing target columns, and existing conflicting constraints stay\nblocked. Planned-parent and newly added child-column types are compared using\nthe PostgreSQL DDL mapping (for example, `TIMESTAMP` becomes `TIMESTAMPTZ`,\n`INTEGER` becomes `BIGINT`); existing columns retain their live physical types. `NOT VALID` plus `VALIDATE CONSTRAINT` remains the authoritative check;\na writer racing the preflight causes the atomic migration to roll back.\nSQLite emits inline `REFERENCES` when adding a new nullable column with no\nnon-NULL default or backfill (#3795): existing rows receive NULL and the database\nenforces subsequent writes. An existing-column constraint or another column\nshape still requires a deliberate table rebuild. DuckDB reports the unsupported ALTER\npath. Neither engine treats an unsupported constraint addition as a successful\nno-op.\n\n**Counting orphans is a separate, read-only concern (#2753).**\n`renderForeignKeyOrphanDetector({ limitOne: true })` makes the probe a gate;\n`schema/foreign-key-orphan-report.ts`'s `collectForeignKeyOrphanCounts()` runs\nthe identical predicate as `COUNT(*)` (via the same function's `countOnly`\noption, so the FROM/JOIN/WHERE clause is never duplicated) for every\nmanifest-declared foreign key, and reports child/parent table and column, the\nlive count, and child-column nullability. A relationship whose child or parent\ntable does not exist live is skipped and reported separately rather than\nfailing the whole run. It never repairs anything — the CLI surface is\n`smrt db:orphans` (`packages/cli/src/commands/db-orphans.ts`), and `db:status`\nprints a compact per-foreign-key summary when any count is nonzero.\n\n**Diagnostics are latency-bound, not query-bound.** Each `getTableSchema()` is\nfive catalog round trips, so `compare()` and the orphan report read each table\nat most once per run, with bounded concurrency on PostgreSQL\n(`schema/bounded-concurrency.ts`: 8 introspections, 4 data-scanning probes; 1\nelsewhere). `compare()` reads partial-index predicates in one `pg_indexes`\nquery, and `db:status` seeds the orphan report with\n`SchemaComparer.getLiveSchemaSnapshot()`. Never add a per-table or\nper-relationship query to these paths without batching or bounding it.\n\n**Partial apply and opt-in orphan disposition (#2748).** The batch an\nunflagged `db:migrate` attempts already excludes every blocked change (a\nFK-with-orphans, a manual `type_upgrade`/`alter_column`) — those never leave\n`SchemaDiff.changes` as executable SQL, so they never enter the atomic\ntracker batch on their own. `--apply-unblocked` adds a second, opt-in\nsafety layer on top of that exclusion: the CLI partitions the remaining\n\"safe\" bucket by *dependency*, not just by whether a change is individually\nblocked. `computeBlockedColumns()` (`packages/cli/src/commands/\ndb-migrate-actions.ts`) reads every manual intervention's blocked\n`table.column` identity; `partitionUnblockedMigrations()` then withholds any\n`add_index`/`add_foreign_key`/`alter_column`/`drop_column` that reads or\nwrites one of those columns (an index on a column whose type upgrade is\nblocked, or a FK whose child *or* parent column is blocked) and applies\neverything else through the normal transaction/tracker path. Off by\ndefault: without the flag, the batch stays exactly what it always was.\n\nThe FK-orphan advisory branch in `compareForeignKeys()` (`migrations/\ndiffer.ts`) tags its `SchemaChange` with `orphanBlocked: true` and\n`orphanNullable` (mirroring `renderForeignKeyOrphanRepair()`'s own\nnullable/not-nullable branch) so a caller can identify this specific\nmanual-intervention reason without parsing `advisory.message`. `db:migrate\n--null-orphans` reads that tag: for a nullable child column it runs the\ndiffer's own suggested `UPDATE ... SET <column> = NULL` (from\n`advisory.suggestedSql[1]`, the exact statement the differ already\nrendered — never re-derived), then rebuilds the `ADD CONSTRAINT NOT VALID` +\n`VALIDATE CONSTRAINT` pair via the shared `renderForeignKeyAddStatements()`\nhelper (`schema/foreign-key-ddl.ts`, also used by the differ's own safe-add\nbranch) and adds it through the normal tracker path. A NOT NULL child column\nkeeps the unconditional \"Manual repair required\" refusal — nulling isn't an\noption and the flag never deletes rows. `planOrphanDispositions()` fails\nclosed (routes to \"not nullable\"/no-op) if an orphan-blocked change is\nmissing its `foreignKey` definition or its `advisory.suggestedSql` pair, on\nthe same \"report and withhold rather than guess\" principle as the rest of\nthis gate.\n\n`getForeignKeyOrphanOptions()`'s `nullable` reads BOTH sides: the manifest\nAND the live column (`dbSchema.columns[...].notNull`), never the manifest\nalone (review, #2748). A manifest relaxed to nullable while the live column\nhas not converged yet — the same drift `--relax-columns` handles for plain\ncolumns — would otherwise report `nullable: true` from the manifest side\nonly, and `--null-orphans` would attempt an `UPDATE` PostgreSQL rejects\noutright (`23502`), failing the whole atomic batch instead of refusing just\nthat one relationship. Nullable only when both sides agree; a real\nNOT NULL on either side keeps the unconditional refusal.\n\n### Pre-R11 `text` ids converge to `uuid` before any FK statement (#2608)\n\nPostgreSQL FK columns must have matching physical types. Legacy text IDs may\nmeet newer native UUID references; neither SQLite (text UUID by design) nor\nDuckDB (no in-place type rewrite) emits this convergence.\n\n**The runtime guard fails closed.** `SchemaManager.ensurePostgresForeignKey()`\nreads both live column types and refuses to emit `ADD CONSTRAINT` when they\ndisagree, naming both columns, both live types, and the repair. It deliberately\nskips the orphan probe in that case: across mismatched types the probe answers\na question about casted values, not about the constraint being refused, and it\nhas to run again after the columns converge anyway.\n\n**The differ converges the columns.** `planUuidConvergence()`\n(`src/schema/uuid-convergence.ts`) groups every manifest relationship that\ndeclares UUID on both sides into connected components and converges a component\nonly when the live database already proves the target shape — at least one\nmember is native `uuid`. A component that is `text` on *every* side is the\ntolerated pre-R11 deployment and is left alone; its foreign keys are\ntype-compatible today, and the R11 uuid/text equivalence in\n`migrations/differ.ts` keeps it out of the column diff.\n\nConverge entire relationship components, including siblings and self-references;\nan unreferenced legacy text ID retains its UUID/text equivalence tolerance.\n\nThe planner never coerces data. Before emitting anything it probes each column\nit would rewrite for values that are not uuid-shaped (the same `~*` canonical\npattern the orphan probe uses) and refuses the whole component — with the count\nand a sample value — if any exist, if the probe cannot run, if a member carries\nsome third physical type, or if a live foreign key still constrains a column\nthat must change. `@happyvertical/sql` introspection does not expose live\nPostgreSQL constraint names, so SMRT cannot drop and re-add those constraints\nfor you: drop them deliberately, rerun the migration to converge, and let SMRT\nre-add the manifest constraints.\n\nRefusals are reported, not silent. Each one becomes a warning advisory with no\nexecutable SQL, so it reaches `unactionableChanges` / `hasManualDrift` and\n`db:status` shows **blocked: incompatible column types** instead of *pending*.\nThe same check runs per relationship in `compareForeignKeys`, so a foreign key\nwhose live types will still disagree after this run's conversions is reported\nblocked rather than emitted as pending DDL that cannot succeed.\n\nThe planner also inspects tables the manifest no longer declares. A live\nforeign key from an orphan table onto a column that must convert still blocks\n`ALTER COLUMN … TYPE`, so the differ introspects every existing table — not\nonly the manifest ones — whenever there is at least one conversion candidate,\nand reports the dependency instead of emitting DDL PostgreSQL would reject. An\nalready-converged database has no candidates and pays nothing.\n\nOrdering is a contract. Conversions carry `SchemaChange.phase =\n'pre_foreign_key'`, and the orchestrator emits them **before every CREATE TABLE\nand every foreign-key statement in the batch**. Both halves matter:\n`planForeignKeyCreation()` only defers the constraints inside a mutual cycle,\nso an acyclic new child table keeps its foreign key *inline in `CREATE TABLE`*\n— a brand-new `uuid` child pointing at a legacy `text` parent fails exactly\nlike an existing one, before the parent could be converted. Conversions only\never rewrite columns that already exist, so leading the batch is always safe. A\nlive `DEFAULT` on a converting column is dropped first (PostgreSQL refuses\n`ALTER COLUMN … TYPE` when the default cannot be cast); the ordinary default\ncomparison re-establishes the manifest default on the next run.\n\nThere are **two** batch builders and both order on that marker:\n`collectStatementsFromDiff()` in `migrations/orchestrate.ts` (used by\n`getPendingSchemaStatements` / `migrateSmrtSchemas`) and the tracker batch\n`db:migrate` assembles by hand in `@happyvertical/smrt-cli`\n(`commands/utilities.ts`). `partitionSchemaChanges()` carries\n`SchemaChange.phase` onto `MigrationAction.phase` so the CLI can partition the\nsame way, in both the applied batch and the `--dry-run` preview. If you add a\nthird consumer, order it the same way.\n\nConvergence entries carry the manifest column definition. Every `type_upgrade`\nconsumer reads `SchemaChange.column` — `partitionSchemaChanges()` in\n`@happyvertical/smrt-cli` skips an entry without one — so a conversion missing\nit would drop out of the `db:migrate` batch while `compareForeignKeys()` still\nassumed the converged type. Refused convergences carry the same column plus an\nadvisory and no SQL, and the CLI routes them to the report-only advisories\nrather than to manual interventions or the tracker.\n\nThe uuid wording is gated on the manifest. Both the runtime guard and the\nstatus planner reach their incompatible-type branch for *any* mismatched pair,\nnot only uuid/text. A `USING …::uuid` repair is suggested only when the\nmanifest declares UUID on both sides **and** a live side is actually `text`;\notherwise the diagnostic names the two live types and asks the operator to\nalign them deliberately.\n\nThe conversion is one-time and idempotent: once the column is native `uuid`,\nthe component is uniformly UUID and the planner emits nothing.\n\n### Application cascade invariants (`src/cascade.ts`)\n\n- Rebuild the registry-derived plan on every delete; manifests register lazily.\n Caching requires invalidation across every registration path.\n- Plan from `getResolvedQualifiedName()`. Every registered polymorphic\n association class participates, since its runtime target can be any class;\n `CascadePlan.isEmpty` requires no such class anywhere and no typed references.\n Only an empty plan skips the transaction.\n- Cascades are set-based: child hooks/interceptors and change-feed tombstones do\n not run. Only the explicitly deleted object runs its lifecycle. RESTRICT\n checks precede mutations; the parent DELETE and cascades share one transaction\n where supported, so deeper refusals roll back.\n- Derived `_smrt_embeddings` / `_smrt_contexts` cleanup matches IDs AND\n `ownerClassCandidates()` (qualified and simple STI member names), never IDs\n alone: unrelated text-ID classes can collide. Cleanup failures are logged,\n not raised, because these tables may not exist in older databases.\n- Never cascade append-only `_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals`,\n or dispatch logs; deleting change tombstones would break sync.\n\n### Retention (`src/system/retention.ts`)\n\n`runRetentionSweep(db, policy)` runs five built-ins in fixed order (`changes`,\n`ai-usage`, `contexts`, `dispatch`, `run-once-claims`), then\n`registerRetentionTask()` contributions. A failed task records its result and\ncontinues; a missing table is `unavailable`. The `globalThis` registry avoids\nsplit registrations under duplicate core resolution; package tasks exist only\nafter importing the package. CLI prune optionally imports jobs/users.\n\nDefaults are opt-out: changes 30 days, AI usage 90 days, completed dispatch 30\ndays/failed dispatch 90 days, contexts by `expires_at`, run-once claims 30\ndays on `completed_at` (#3080; `in_progress` rows never match — the window is\na replay deadline for `runOnce()`, not just disk hygiene, see\n`agents/run-once.md`). `smrt.configure({ retention })` tunes built-ins;\ncontributed tasks own their defaults/options.\nJobs defaults are 7 days terminal, 30 failed, 30 events via\n`registerJobRetentionTasks()` or runner `retention.jobs`; expired credentials\nhave no extra window. Disable a table/task with `false` or the whole policy with\n`enabled: false`; CLI `--skip` and runner configuration expose these controls.\nTask names use package prefixes (`jobs-records`, `users-sessions`).\n\nCore does not schedule sweeps. TaskRunner runs every six hours, first one\ninterval after start; `retention: false` opts out. `smrt db:prune` supports cron.\nEvery prune counts then deletes using the same predicate; `rowCount` is not\nportable. The two statements deliberately are not transactional, so counts are\napproximate under concurrency. Overlapping change/AI-usage bounds exclude rows\nalready counted, including dry runs.\n\nRetention indexes belong in system DDL and its versioned replay:\n`_smrt_contexts(expires_at)`, `_smrt_ai_usage(tenant_id, created_at)`, dispatch\n`(status, processed_at)` / `(status, updated_at)`, and\n`_smrt_run_once_claims(status, completed_at)`. Jobs `(status, completed_at)`\nbelongs in `ensureJobsSystemTableCompatibility()` on each collection initialize,\nsince decorated jobs tables do not exist at bootstrap.\n\nExpiry remains prune-side for object/collection `recall()`/`recallAll()`;\n`LearningMemory` separately filters it at read time.\n\n## Supported generation surfaces\n\nThe four entry points above are the supported generator paths. The unused AST\n`generateSchema(objectDef)`, `smrt:schema` / `@happyvertical/smrt-virt-schema`\nvirtual modules, and project-specific `SchemaOverrideSystem` were removed.\n\nKeep published `SchemaDefinition.triggers`, `TriggerDefinition`, and the DDL\nstrategies' trigger renderers: they support hand-authored new-table schemas.\nGenerated `@smrt()` schemas always emit `triggers: []`; no decorator populates\nit, `save()` maintains `updated_at`, and the differ never retrofits triggers.\nAdding live trigger generation requires a migration rollout design.\n`_smrt_signals` and database-persisted registry APIs are retired; see\n`RETIRED_SYSTEM_TABLES` in `src/system/schema.ts`.\n\n## PostgreSQL migration execution\n\n`MigrationTracker.applyAll({ atomic: true })` sets local lock/statement timeouts\nbefore any DDL. `postgresSafe: true` commits non-index DDL atomically, then runs\nindexes CONCURRENTLY on `db.acquireSession()` so settings and DDL share a\nconnection. This mode is not atomic. Unfinished indexes are `failed`, not\n`running`; `[smrt: concurrent-index phase 1 committed]` in `error_message`\nallows reruns to resume index work without replaying committed DDL. Inspect\n`pg_index.indisvalid` and drop INVALID indexes before rebuild (`pg_indexes`\nalone cannot detect them). Operational commands: `packages/cli/AGENTS.md`.\n\n### Subclass conflict identities (#3456)\n\nAn STI child's explicit `conflictColumns` owns a partial unique index restricted\nto its qualified discriminator. The root conflict index excludes these children;\nregistry and manifest paths emit the same predicates. Natural-key lookups include\nthat scope, PostgreSQL atomic inserts include the index predicate, and adopted\nrows update by id. Bulk writes use per-item guards for these targets. Normal\nmigrations replace the root index by name and add the child index; repair any\nexisting duplicate child natural keys before migrating. Stop old writers for this\nindex migration and load the complete consumer manifest on every shared-table\nwriter before resuming: a provider-only manifest lacks the child predicates.\nDuckDB/JSON reject\nthese schemas because partial unique conflict identities cannot be enforced.\n\n## Consumer physical table bindings (#3660)\n\n`smrt.tableNames` maps exact qualified model identities to deployment-local\nphysical tables. `registry/table-mappings.ts` projects schemas for both runtime\n`getSchema()` reads and merged migration planning, including index names and\nrelationship targets. Never remap by a raw old table name: two unrelated models\nmay own that name in their respective packages. Bind STI roots only; sensitive\nmodels are refused. Well-formed bindings may precede model registration;\npartial registries never need unrelated models merely to satisfy configuration.\nRuntime object/collection getters recheck ownership even for cached table\nnames; validation is memoized by registry generation and binding configuration.\nConfiguration must load before first database use and stay\nfixed for that process. This is not an implicit data migration; see\n[consumer table bindings](../../../docs/content/table-bindings.md).\n"
|
|
1190
|
+
"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;\nit links the relevant runtime and generation contracts.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. Their columns and indexes must agree 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\nThe migration differ and CREATE TABLE planner share adapter-aware engine\nselection. A native in-memory DuckDB handle can report `:memory:` and expose\n`exportTable`, so use the native and JSON adapter discriminators before URL\ninference. For native DuckDB the differ reads inline UNIQUE constraints from\n`duckdb_constraints()` because the adapter index list omits them.\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\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 default keys** are `(tenant_id, slug, context)`, plus `_meta_type`\n for STI. `ManifestGenerator.normalizeConflictColumns()` and\n `ObjectRegistry.getConflictColumns()` share `src/schema/conflict-target.ts`:\n resolve tenant fields through the schema owner/STI root, report group/bucket\n columns through the report, and custom PKs through their key. Explicit\n `conflictColumns` remain unchanged. The manifest, schema, knowledge, and\n runtime must carry the same value.\n Names remain `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so\n migration replaces a same-name global unique with tenant-led columns. That\n prefix serves tenant and tenant-scoped slug reads; a legacy standalone tenant\n index is dropped only with `--drop-indexes`.\n- **Widening an explicit key** (e.g. `['key']` → `['tenant_id', 'key']`,\n #3126) renames its index, so migration adds the new unique and\n `SchemaComparer` drops the superseded one without `--drop-indexes`: a UNIQUE\n index named `conflictIndexName()` for its own columns, with no predicate,\n whose columns are a strict subset of a declared UNIQUE index. It is a pure\n relaxation (every row satisfies the wider key) and otherwise would keep\n rejecting rows the model allows. The maintenance-window rule below applies.\n DuckDB has no partial indexes, so its indexes count as predicate-free, and\n its quoted index columns (`\"key\"`) are unquoted before comparison (#3305 M1).\n- **Optional NULL tenants** retain the SDK's NULL-equal upsert identity. Generated\n framework conflict indexes with nullable keys carry `nullsNotDistinct: true`;\n PostgreSQL 15+ creates `UNIQUE NULLS NOT DISTINCT`, enabling warm single-statement\n native upserts. Earlier PostgreSQL, SQLite and DuckDB retain adapter fallback\n semantics. Existing ordinary indexes are upgraded only through the explicit\n [NULL-equal maintenance migration](null-equal-indexes.md). Optional business\n unique fields remain NULLS DISTINCT; this marker is not inferred from them.\n- **Tenant-key rollout requires a maintenance window.** Old code/new indexes\n and new code/old indexes both fail new-object saves because conflict column\n sets must match exactly; persisted ID-based saves still work. Backfill legacy\n NULL tenants first or scoped ingestion creates separate rows and cannot see\n the old global ones. Cross-tenant natural-key dedup now creates one row per\n tenant. Deploy code and migrate together in atomic mode: each table drops\n and recreates its same-name unique index, holding ACCESS EXCLUSIVE locks\n (including against reads) until commit. Size `statementTimeout` for the\n largest table. A valid old subset unique guarantees the superset build;\n missing/nonunique old indexes may contain duplicates and need dedup first.\n Include the reference-index wave in that atomic window. `--postgres-safe` is\n suitable for an additive reference-index-only wave, but a key replacement\n leaves a per-table gap between drop/build and a failed build leaves no arbiter\n until rerun. There is no automatic DOWN; reverting code requires deliberately\n recreating its old indexes.\n\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\n## Verification\n\nExtend `src/schema/schema-path-parity.test.ts` for every generator change;\nmanifest, registry, and merged migration schemas must agree. Inspect regenerated\n`dist/manifest.json` and schemas across affected packages, not only decorators.\nRuntime `verifyPersistenceTable()` checks table existence only. Database drift\nchecks compare with generated artifacts; they cannot detect an omission shared\nby those artifacts. Use `smrt doctor --db` / `db:status --parity` for live parity.\n\nEvery new query predicate needs its index or an explicit reason none is needed.\nRun `pnpm --filter @happyvertical/smrt-core test:postgres` for numeric types,\nUUID casts, conflict targets, timestamps, or migrations. Schema-affecting options\nmust reach `SchemaGeneratorConfig` and both config rebuild sites:\n`src/schema/utils.ts` and `src/testing/database.ts`.\n\nTenant uniqueness and conflict targets must include the tenant column; explicit\n`conflictColumns` are author-owned and never rewritten. All reads, including\nhydration, slug lookup, vector search, and memory, remain interceptor-aware.\nRetry only transient errors classified through the cause chain; never retry an\naborted PostgreSQL transaction (`25P02`).\n\n### Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), default list ordering, 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()` (default ordering below) 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. Keep both config rebuild sites aligned.\n\n### STI subclasses declare indexes on the shared table (#3299)\n\n`@smrt({ indexes })` on an STI **descendant** is emitted on the shared table\nby `appendStiSubclassDeclaredIndexes()` (both STI entry points, after the\nbase's declarations; `getAllSchemasAsDefinitions()` and `getTestDatabase()`\ninherit it). It goes through the same validation as a base declaration: known\ncolumns, the 63-byte name limit, and errors on a collision. A UNIQUE\ndeclaration is scoped to the declaring subtype with\n`WHERE _meta_type = '<qualified class>'`, so siblings sharing the column are\nnot constrained. As with `@field({ unique })` on a descendant, each class in\nthe declaring class's own subtree gets a partial copy\n(`<declared name, cut to 52>_<10-hex digest>`), so uniqueness holds per\nconcrete class there too, not across the subtree. DuckDB/JSON skip these\nrather than widen them. A subclass UNIQUE with its own `where` is refused; declare a\ncombined predicate on the base. A plain subclass index stays unqualified, so\npolymorphic reads can use it. Columns are emitted exactly as declared and are\nnever tenant-prefixed, as with explicit `conflictColumns`: put `tenant_id`\nfirst for a tenant-local key (`['tenantId', 'rampEventId']`). Leave it out\nonly for a reviewed global identity (#3305 dispositions).\n\nMigration: `db:migrate` adds the new index by name. A UNIQUE index fails\nclosed (the migration rolls back) when existing rows already duplicate the\nkey. Find and repair those rows first, scoped to the subtype\n(`_meta_type = '<qualified class>'`), and never by deleting history to make\nthe index fit. With `db:migrate --postgres-safe` it is built `CONCURRENTLY`.\nA failed concurrent build leaves an INVALID index, which the next run drops\nand rebuilds after the data is repaired.\n\n### 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.\nRuntime decorators retain the resolved constructor alongside the display name.\nInverse lookup and cascade planning resolve that constructor when queried, so\nthe target may register after its child without binding to a same-name class\nin another package. String targets prefer the declaring package; ambiguous\nunqualified targets never match an unrelated package's inverse edge.\nRegistry schema generation and the merged migration schema resolve the same\ncanonical target before selecting both its table and identifier type. The\nmanifest generator resolves unqualified targets in the declaring package.\nKeep the merged schema in parity tests: `getTestDatabase()` preserves its\nauthoritative FK metadata over the generated columns, so testing only the\nstandalone generator cannot prove the constraint that reaches the database.\nWith an explicit `classes` list, `getTestDatabase()` builds that authoritative\nschema with `getAllSchemasAsDefinitions({ tables })`: only the requested tables\nand their foreign-key closure are merged and ownership-checked\n(`CONFIG_TABLE_NAME_COLLISION` still fires for any of them), so an unrelated\ncollision elsewhere in the registry cannot abort the setup. The implicit list\nchecks every registered table (#3956).\n\nField decorator registration retains constructor ownership separately from the\nsimple-name inspection view. Custom decorators should pass the callback's\nconstructor as `registerFieldDecorator`'s fourth argument. Omit it only for\nintentional legacy string-only metadata; that legacy metadata still composes\nwith constructor-owned options, but mirrored public decorator fields do not.\n\n### Decorator-only field types agree on both paths (#4295)\n\nA compiled model registered without a manifest entry sees only `@field()`\noptions, never the initializer or annotation the scanner reads. Without an\nexplicit `type`, a boolean `default` infers `boolean` on both paths\n(`inferDecoratorOnlyFieldType` in `src/registry/class-registration.ts`, step\n3.7 of the scanner's `ManifestAdapter.inferFieldType`); anything else falls\nback to `text`. Numbers are never inferred at runtime (`0` and `0.0` are the\nsame value), so a runtime-only numeric field must declare\n`type: 'integer' | 'decimal'`. Loading the manifest later still replaces the\ndecorator-only type. A database whose column was built from the old TEXT\nexpectation is not auto-cast; parity reports the drift for an explicit\nmigration.\n\n### 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### Explicit SQLite NOT NULL relaxation (#4413)\n\n`relaxColumns: true` / `smrt db:migrate --relax-columns` also supports removing\nan ordinary inline `NOT NULL` clause on a manifest-declared column. The local\napplication entry point forwards `smrt app migrate --relax-columns` under its\nexisting operation lock and refuses a live application writer. The programmatic\n`migrateSmrtSchemas` / `getPendingSchemaStatements` entry points accept the same\nexplicit `relaxColumns` option. Defaults remain advisory; this does not relax\norphan columns or change SQLite defaults/tightening behavior.\n\nThe rebuild preserves live DDL, indexes/triggers and assigned rowids. Named\nNOT NULL constraints, `ON CONFLICT`, AUTOINCREMENT tables, primary/generated target columns, missing\nclauses and tables shadowing every rowid alias refuse rather than guessing.\nA nullable-relaxation rebuild emits `PRAGMA foreign_keys = OFF` as a tracker\nhandoff: `MigrationTracker` suspends FK enforcement **before** opening its\ntransaction, verifies suspension on both the base and transaction connection,\nand checks `PRAGMA foreign_key_check` before commit. This avoids inbound FK\n`ON DELETE` actions and preserves referencing rows. An active borrowed transaction\nthat cannot suspend enforcement, a mismatched transaction connection or an\nadapter without transactions refuses. FK and legacy rename settings are restored\nin `finally`, including after rollback. Run this maintenance operation with\nexclusive access to the SQLite connection. Type-only rebuilds retain the older\ninbound-FK refusal described above.\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 inline only on an empty\n table. On a populated one it needs a per-row `backfill` (#3008,\n `ColumnDefinition.backfill` from `@field({ backfill })`): PostgreSQL/DuckDB\n run `ADD COLUMN` (nullable) → `UPDATE … SET col = (backfill) WHERE col IS\n NULL` → `SET DEFAULT` (deferred, if declared) → `SET NOT NULL` → the unique\n index; SQLite adds it through the table rebuild (`sqliteBackfillPlaceholderSql`\n → `planSqliteTableRebuilds` appends `\"col\" TYPE NOT NULL` and copies\n `(backfill)`), one rebuild per table for every such column. The differ first\n probes `WHERE (backfill) IS NULL` on the live rows. With no default and no\n backfill, or with a backfill that yields NULL or will not evaluate, the\n column is **not added**: a manual `alter_column` (`mismatch.actual ===\n REQUIRED_COLUMN_NOT_ADDED`) names table and column, and `compareTable`\n withholds `add_index`/`add_foreign_key` changes on it. The same backfill\n repairs nullability drift (an existing nullable column holding NULLs).\n A backfill for a single-column unique target is also probed for duplicate\n values and refused by name. Partial unique indexes are exempt from that\n probe only where `supportsPartialIndexes()` holds (SQLite/PostgreSQL);\n DuckDB/JSON build them as full indexes, so they are probed there (#3015).\n DuckDB refuses `ALTER COLUMN` while any index depends on the table, so its\n `SET NOT NULL` is bracketed by `DROP INDEX`/recreate from `duckdb_indexes().sql`.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1), except a NOT NULL tightening with a\n declared `backfill`, which the rebuild performs (`COALESCE(col, backfill)`\n in the copy). The rebuild otherwise consumes `type_upgrade` placeholders.\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### `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### 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\nThe first contributor supplies fallback columns, `idType`, conflict columns,\ncached DDL, and wins column conflicts. Keep base-first ordering even when a\nchild without manifest schema registers first.\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### Default list ordering indexes\n\nAll four generators index `DEFAULT_LIST_ORDER_BY` (`created_at DESC, <pk> ASC`):\n`ensureDefaultListOrderingIndex()` emits `(tenant column, created_at)` when\nscoped, otherwise `(created_at)`. Resolve tenant columns by `referenceKind ===\n'tenantId'`, not spelling. The tenant-leading pair also serves the reference\nindex requirement.\n\nOnly an unqualified, non-JSON-path index with the same leading columns suppresses\nit. Append declared composites first, then default ordering, then reference\nindexes. `(tenant_id, created_at, status)` replaces the default pair;\n`(tenant_id, publish_date)` does not. Emit one plain index per STI table, since\nbase polymorphic reads lack `_meta_type` predicates.\n\nDo not add direction or PK columns by inference: `IndexDefinition` has no\nper-column directions, backward B-tree scans serve descending timestamps, and\nthe mixed-direction PK tie-break still needs incremental sorting within equal\ntimestamps.\n\n### 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### Tenant OWNERSHIP, not tenant scope, leads the default key\n\nA class with a `tenantId` field is tenant-owned even when it declares no\ntenancy — consumers register such classes with the tenancy interceptor at\nruntime (Anytown's Ludis `League`/`Team`, smrt-users `Group`/`Role`/…), which\ncore never reads. `resolveOwnershipTenantColumn()` (declared tenant column,\nelse `tenant_id`) leads the default natural key on every producer:\n`ObjectRegistry.getOwnershipTenantColumn()` / `getConflictColumns()`,\n`normalizeConflictColumns()`, the generator's `resolveConflictTarget()` and the\nregistry schema-builder. The tenancy read policy is still never inferred\n(`getTenantScopedConfig()` stays undefined). Explicit `conflictColumns` are\nnever rewritten. Old code's `ON CONFLICT (slug, context)` and new code's\n`ON CONFLICT (tenant_id, slug, context)` each need their own unique index, so\nthe inferred tenant-led key is named by the custom-key rule\n(`<table>_tenant_id_slug_idx`; only a DECLARED tenant column keeps\n`<table>_slug_context_idx`) and `smrt db:migrate` builds it BESIDE the legacy\nglobal unique (expand). The differ keeps the legacy index\n(`isLegacyNaturalKeyIndex()`, exempt from the #3126 superseded-index sweep and\nfrom `--drop-indexes`) until `--drop-legacy-natural-key` /\n`DiffOptions.dropLegacyNaturalKey` (contract). `db:status` exits 1 while the\ntenant-led unique is missing and warns while the legacy one survives\n(`cli/src/commands/tenant-natural-keys.ts`). Deploy order and locking:\n`docs/content/core.md` (\"Upgrading an existing database\"). The implicit\n`tenant_id` column never makes a foreign key identifying\n(`resolveForeignKeyDeleteAction({ columnName })`): a tenant FK stays\n`NO ACTION`, so deleting a tenant does not cascade through tenant-owned tables.\n\nThe save path backs this up where the key still omits the owner (an explicit\nkey, or a live table not yet migrated) — `SmrtObject.writeNaturalKeyRow()`. The\nrow a NEW object's conflict target matches is read directly, bypassing read\ninterceptors. A different owner on any ownership column\n(`ObjectRegistry.getOwnershipColumns()`: `tenant_id`, the declared tenant\ncolumn, `@tenantId` fields and runtime registrations reported through\n`ObjectRegistry.registerOwnershipColumnSource()` — the tenancy package reports\n`registerTenantScopedClass(…, { field })` columns) raises\n`TenantIsolationError.naturalKeyOwnedElsewhere()` (`TENANT_ISOLATION_VIOLATION`,\nnever retried, never naming the other owner), also under `withSystemContext()`;\nNULL — or an ownership column the save leaves unset — counts as an owner. A\nsame-owner row is adopted by id (keeping its `created_at`, applied to the\ninstance only after the write succeeds), so `DO UPDATE SET` never rewrites a\nprimary key (no `ON UPDATE CASCADE` churn). Adoption needs an explicit natural\nkey: when the match is only through a slug `getSlug()` derived from\n`name`/`title`/`label` (a human value, not an identity), the new object keeps\nits id, moves to the first free `<base>-2` … `<base>-9` (one `slug IN (…)`\nprobe; then `<base>-<8 id chars>`) and INSERTs — whoever owns the taken row, so\nit is never refused. `getOrUpsert()`'s create path opts back into adoption\n(`_adoptNaturalKey`): a miss on a non-key field updates the row the derived\nslug names instead of adding `<slug>-2`. On PostgreSQL with no NULL conflict\nvalue the write is `INSERT … ON CONFLICT (…) DO NOTHING RETURNING id` first, so\na new key costs one statement and no pre-read, and concurrent first creates\nnever collapse: the loser re-reads and adopts (explicit key) or moves (derived\nslug, then straight to the id suffix), bounded retries. Embedded engines\n(serialized by the in-process write queue) and NULL-bearing keys read first.\nThe junction batch path falls back to per-item saves when\nits conflict target omits an ownership column present in the row (`tenant_id`,\nthe declared tenant column, or any `@tenantId`-marked field), and when any new\nitem's natural key already names a row the batch is not removing; its\n`DO UPDATE SET` never lists `id`, `created_at` or an ownership column. Strict\ninserts (`_insertOnly`) check NULL-bearing keys the same way, because NULLs\nare distinct in the unique index on SQLite, DuckDB and PostgreSQL < 15.\n\nA save with no owner (`tenantId: null`, typically under `withSystemContext()`)\nis deliberately NOT refused when a tenant row shares its slug under the\ntenant-led key: it lands as a separate global row, the global-default /\ntenant-override shape #2360 keeps. Refusing it would need a cross-owner read on\nevery global save and would break that pattern. A model that needs a slug\nunique across every owner declares explicit `conflictColumns` without the\ntenant column; then the guard refuses the colliding save instead.\n\n### Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates identifiers beyond 63 bytes; two generated names sharing\nthat prefix can make `CREATE INDEX IF NOT EXISTS` silently skip an index.\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** are not guarded: PostgreSQL truncates their\n declarations and references consistently. `smrt-users` tests intentionally\n long table names; collision risk remains with the author.\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### The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`SmrtClass` coalesces concurrent system-table initialization through completion\nof bootstrap, deferred compatibility, and vector setup (#3944). In-flight work\nis shared only by the same database handle. Distinct handles at the same URL\nretain database-level coordination: a caller-owned transaction may finish its\ninitialization statements before its tables become visible to another handle.\nAll same-handle waiters observe failure; the pending entry is removed so a fresh\ninstance can retry. Existing completed-success cache identities are unchanged.\nProvision system tables on a base connection before caller-owned transactions;\nconstructor initialization still preserves PostgreSQL's transaction lock lifetime.\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\nOn PostgreSQL `db:migrate` converges a live SMRT-owned constraint whose only\ndrift is its action (#3023, `SchemaComparer.findReplaceableForeignKey()`):\nbuild-then-swap via `renderForeignKeyReplaceStatements()` — staged\n`<name>_smrt_new` added `NOT VALID` and validated before the old constraint is\ndropped and the staged one renamed; `--postgres-safe` runs the VALIDATE and the\nswap outside the batch transaction. A change toward `CASCADE` / `SET NULL` /\n`SET DEFAULT` still applies (the manifest declares it) but carries a\n`warning` advisory that `db:diff`, `db:status` and `db:migrate` print as\nDESTRUCTIVE.\n\n### Deletes inside a caller-owned transaction\n\n`runCascadeDelete()` owns the cascade's atomic scope through\n`runInOwningCascadeTransaction()` in `src/cascade.ts` (#2824). A root handle opens\nits own transaction. A transaction handle on an engine with savepoints nests.\nWhen the engine refuses to nest (`NestedTransactionError`, raised by the SDK before\nthe callback runs), the cascade joins the enclosing transaction. This happens for\nframework-owned handles, for caller-owned **native DuckDB** transactions\n(`db.transaction()` scopes and `beginTransaction()` handles passed to\n`withDatabase()`), and for the bulk junction path (#2818). A transaction handle\ncounts as native DuckDB only after core has seen its root, through\n`initialize()`, `withDatabase()` or a framework transaction. Otherwise the\nhandle is never treated as native by guesswork, and the delete keeps the\n`NestedTransactionError` refusal. The caller's commit or\nrollback then decides the outcome of the cascade, the owned `_smrt_contexts` and\n`_smrt_embeddings` cleanup, and the target row.\n\nThere is no savepoint, so a cascade that fails part-way cannot be undone on its\nown. On native DuckDB the framework therefore aborts the joined transaction\n(`SELECT error(...)`) before rethrowing, but only if the cascade has already\nissued a write. The SDK's DuckDB `delete()` reports a constant affected count,\nand the owned-row cleanup always runs. In practice, then, any failure after the\ndepth-0 RESTRICT / NO ACTION preflight aborts the transaction. That includes a\nrevision or write-guard conflict on the row itself, even one that changed no\nrows. DuckDB then rejects every later statement with \"transaction\nis aborted\", and its `COMMIT` persists nothing. A caller that swallows the error\ntherefore cannot commit a half-applied cascade, and the callback is never\nreplayed. By contrast, a refusal raised before the first write, such as the\nRESTRICT / NO ACTION preflight, leaves the caller's transaction usable.\nJSON-adapter caller transactions keep the detectable\n`NestedTransactionError` refusal, because nothing can poison them.\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\nSame-package archival identifiers may explicitly use `@foreignKey(Target, {\nconstraint: false })`: preserve relationship loading and indexing, but omit\nphysical constraints, schema dependencies, and application cascade/preflight\nso the identifier survives parent deletion. Document the retention reason at\nthe field; ordinary references remain constrained.\n\nFor a same-package relationship whose semantics are portable but whose physical\nconstraint shape is not, `@foreignKey(Target, { constraint: { engines: [...] } })`\nis the public exception. The allowlist scopes physical DDL and dependency\nplanning only. Relationship metadata, UUID representation, derived indexes, and\nthe application delete rail remain canonical on every engine. Empty or unknown\nengine lists fail closed; unannotated unsupported DuckDB cycles and actions keep\ntheir actionable refusal.\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\nRollback drops children before parents, removes deferred PostgreSQL cycle\nconstraints first, and defers SQLite checks while dropping populated cycles.\nAggregation that filters a parent also removes a retained child's physical FK.\nPostgreSQL deferred constraint adds are idempotent. Generated `ON UPDATE\nCASCADE` remains the default; DuckDB/JSON must refuse unsupported actions\nrather than silently stripping them.\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. The probe uses distinct child/parent aliases and, when both\nmanifest columns are UUIDs, bases its guarded casts on both live column types:\nmatching live types compare directly, while a legacy text side is shape-checked\nbefore casting. This keeps a self-reference or malformed legacy value from\ninvalidating the query. An orphan stops migration with detector SQL and an\nexecutable repair suggestion: nullable FKs are cleared, while required FKs\nrequire an explicit operator decision to reassign the reference or deliberately\nremove a child row after preserving its required data. A probe failure is\nsurfaced as a database/framework error, never misreported as orphan data.\nWhen the referenced parent is absent but scheduled for creation by the same\n`compare()` batch (#3240), PostgreSQL first proves the entire existing child\ntable empty instead of querying the absent parent. Nonempty children are blocked\nwithout executable repair SQL: create and populate the parent deliberately,\nthen rerun the ordinary orphan preflight. The exception never applies to a\nstandalone `compareTable()` or an undeclared missing parent, and incompatible\ncolumn types, missing target columns, and existing conflicting constraints stay\nblocked. Planned-parent and newly added child-column types are compared using\nthe PostgreSQL DDL mapping (for example, `TIMESTAMP` becomes `TIMESTAMPTZ`,\n`INTEGER` becomes `BIGINT`); existing columns retain their live physical types. `NOT VALID` plus `VALIDATE CONSTRAINT` remains the authoritative check;\na writer racing the preflight causes the atomic migration to roll back.\nSQLite emits inline `REFERENCES` when adding a new nullable column with no\nnon-NULL default or backfill (#3795): existing rows receive NULL and the database\nenforces subsequent writes. An existing-column constraint or another column\nshape still requires a deliberate table rebuild. DuckDB reports the unsupported ALTER\npath. Neither engine treats an unsupported constraint addition as a successful\nno-op.\n\n**Counting orphans is a separate, read-only concern (#2753).**\n`renderForeignKeyOrphanDetector({ limitOne: true })` makes the probe a gate;\n`schema/foreign-key-orphan-report.ts`'s `collectForeignKeyOrphanCounts()` runs\nthe identical predicate as `COUNT(*)` (via the same function's `countOnly`\noption, so the FROM/JOIN/WHERE clause is never duplicated) for every\nmanifest-declared foreign key, and reports child/parent table and column, the\nlive count, and child-column nullability. A relationship whose child or parent\ntable does not exist live is skipped and reported separately rather than\nfailing the whole run. It never repairs anything — the CLI surface is\n`smrt db:orphans` (`packages/cli/src/commands/db-orphans.ts`), and `db:status`\nprints a compact per-foreign-key summary when any count is nonzero.\n\n**Diagnostics are latency-bound, not query-bound.** Each `getTableSchema()` is\nfive catalog round trips, so `compare()` and the orphan report read each table\nat most once per run, with bounded concurrency on PostgreSQL\n(`schema/bounded-concurrency.ts`: 8 introspections, 4 data-scanning probes; 1\nelsewhere). `compare()` reads partial-index predicates in one `pg_indexes`\nquery, and `db:status` seeds the orphan report with\n`SchemaComparer.getLiveSchemaSnapshot()`. Never add a per-table or\nper-relationship query to these paths without batching or bounding it.\n\n**Partial apply and opt-in orphan disposition (#2748).** The batch an\nunflagged `db:migrate` attempts already excludes every blocked change (a\nFK-with-orphans, a manual `type_upgrade`/`alter_column`) — those never leave\n`SchemaDiff.changes` as executable SQL, so they never enter the atomic\ntracker batch on their own. `--apply-unblocked` adds a second, opt-in\nsafety layer on top of that exclusion: the CLI partitions the remaining\n\"safe\" bucket by *dependency*, not just by whether a change is individually\nblocked. `computeBlockedColumns()` (`packages/cli/src/commands/\ndb-migrate-actions.ts`) reads every manual intervention's blocked\n`table.column` identity; `partitionUnblockedMigrations()` then withholds any\n`add_index`/`add_foreign_key`/`alter_column`/`drop_column` that reads or\nwrites one of those columns (an index on a column whose type upgrade is\nblocked, or a FK whose child *or* parent column is blocked) and applies\neverything else through the normal transaction/tracker path. Off by\ndefault: without the flag, the batch stays exactly what it always was.\n\nThe FK-orphan advisory branch in `compareForeignKeys()` (`migrations/\ndiffer.ts`) tags its `SchemaChange` with `orphanBlocked: true` and\n`orphanNullable` (mirroring `renderForeignKeyOrphanRepair()`'s own\nnullable/not-nullable branch) so a caller can identify this specific\nmanual-intervention reason without parsing `advisory.message`. `db:migrate\n--null-orphans` reads that tag: for a nullable child column it runs the\ndiffer's own suggested `UPDATE ... SET <column> = NULL` (from\n`advisory.suggestedSql[1]`, the exact statement the differ already\nrendered — never re-derived), then rebuilds the `ADD CONSTRAINT NOT VALID` +\n`VALIDATE CONSTRAINT` pair via the shared `renderForeignKeyAddStatements()`\nhelper (`schema/foreign-key-ddl.ts`, also used by the differ's own safe-add\nbranch) and adds it through the normal tracker path. A NOT NULL child column\nkeeps the unconditional \"Manual repair required\" refusal — nulling isn't an\noption and the flag never deletes rows. `planOrphanDispositions()` fails\nclosed (routes to \"not nullable\"/no-op) if an orphan-blocked change is\nmissing its `foreignKey` definition or its `advisory.suggestedSql` pair, on\nthe same \"report and withhold rather than guess\" principle as the rest of\nthis gate.\n\n`getForeignKeyOrphanOptions()`'s `nullable` reads BOTH sides: the manifest\nAND the live column (`dbSchema.columns[...].notNull`), never the manifest\nalone (review, #2748). A manifest relaxed to nullable while the live column\nhas not converged yet — the same drift `--relax-columns` handles for plain\ncolumns — would otherwise report `nullable: true` from the manifest side\nonly, and `--null-orphans` would attempt an `UPDATE` PostgreSQL rejects\noutright (`23502`), failing the whole atomic batch instead of refusing just\nthat one relationship. Nullable only when both sides agree; a real\nNOT NULL on either side keeps the unconditional refusal.\n\n### Pre-R11 `text` ids converge to `uuid` before any FK statement (#2608)\n\nPostgreSQL FK columns must have matching physical types. Legacy text IDs may\nmeet newer native UUID references; neither SQLite (text UUID by design) nor\nDuckDB (no in-place type rewrite) emits this convergence.\n\n**The runtime guard fails closed.** `SchemaManager.ensurePostgresForeignKey()`\nreads both live column types and refuses to emit `ADD CONSTRAINT` when they\ndisagree, naming both columns, both live types, and the repair. It deliberately\nskips the orphan probe in that case: across mismatched types the probe answers\na question about casted values, not about the constraint being refused, and it\nhas to run again after the columns converge anyway.\n\n**The differ converges the columns.** `planUuidConvergence()`\n(`src/schema/uuid-convergence.ts`) groups every manifest relationship that\ndeclares UUID on both sides into connected components and converges a component\nonly when the live database already proves the target shape — at least one\nmember is native `uuid`. A component that is `text` on *every* side is the\ntolerated pre-R11 deployment and is left alone; its foreign keys are\ntype-compatible today, and the R11 uuid/text equivalence in\n`migrations/differ.ts` keeps it out of the column diff.\n\nConverge entire relationship components, including siblings and self-references;\nan unreferenced legacy text ID retains its UUID/text equivalence tolerance.\n\nThe planner never coerces data. Before emitting anything it probes each column\nit would rewrite for values that are not uuid-shaped (the same `~*` canonical\npattern the orphan probe uses) and refuses the whole component — with the count\nand a sample value — if any exist, if the probe cannot run, if a member carries\nsome third physical type, or if a live foreign key still constrains a column\nthat must change. `@happyvertical/sql` introspection does not expose live\nPostgreSQL constraint names, so SMRT cannot drop and re-add those constraints\nfor you: drop them deliberately, rerun the migration to converge, and let SMRT\nre-add the manifest constraints.\n\nRefusals are reported, not silent. Each one becomes a warning advisory with no\nexecutable SQL, so it reaches `unactionableChanges` / `hasManualDrift` and\n`db:status` shows **blocked: incompatible column types** instead of *pending*.\nThe same check runs per relationship in `compareForeignKeys`, so a foreign key\nwhose live types will still disagree after this run's conversions is reported\nblocked rather than emitted as pending DDL that cannot succeed.\n\nThe planner also inspects tables the manifest no longer declares. A live\nforeign key from an orphan table onto a column that must convert still blocks\n`ALTER COLUMN … TYPE`, so the differ introspects every existing table — not\nonly the manifest ones — whenever there is at least one conversion candidate,\nand reports the dependency instead of emitting DDL PostgreSQL would reject. An\nalready-converged database has no candidates and pays nothing.\n\nOrdering is a contract. Conversions carry `SchemaChange.phase =\n'pre_foreign_key'`, and the orchestrator emits them **before every CREATE TABLE\nand every foreign-key statement in the batch**. Both halves matter:\n`planForeignKeyCreation()` only defers the constraints inside a mutual cycle,\nso an acyclic new child table keeps its foreign key *inline in `CREATE TABLE`*\n— a brand-new `uuid` child pointing at a legacy `text` parent fails exactly\nlike an existing one, before the parent could be converted. Conversions only\never rewrite columns that already exist, so leading the batch is always safe. A\nlive `DEFAULT` on a converting column is dropped first (PostgreSQL refuses\n`ALTER COLUMN … TYPE` when the default cannot be cast); the ordinary default\ncomparison re-establishes the manifest default on the next run.\n\nThere are **two** batch builders and both order on that marker:\n`collectStatementsFromDiff()` in `migrations/orchestrate.ts` (used by\n`getPendingSchemaStatements` / `migrateSmrtSchemas`) and the tracker batch\n`db:migrate` assembles by hand in `@happyvertical/smrt-cli`\n(`commands/utilities.ts`). `partitionSchemaChanges()` carries\n`SchemaChange.phase` onto `MigrationAction.phase` so the CLI can partition the\nsame way, in both the applied batch and the `--dry-run` preview. If you add a\nthird consumer, order it the same way.\n\nConvergence entries carry the manifest column definition. Every `type_upgrade`\nconsumer reads `SchemaChange.column` — `partitionSchemaChanges()` in\n`@happyvertical/smrt-cli` skips an entry without one — so a conversion missing\nit would drop out of the `db:migrate` batch while `compareForeignKeys()` still\nassumed the converged type. Refused convergences carry the same column plus an\nadvisory and no SQL, and the CLI routes them to the report-only advisories\nrather than to manual interventions or the tracker.\n\nThe uuid wording is gated on the manifest. Both the runtime guard and the\nstatus planner reach their incompatible-type branch for *any* mismatched pair,\nnot only uuid/text. A `USING …::uuid` repair is suggested only when the\nmanifest declares UUID on both sides **and** a live side is actually `text`;\notherwise the diagnostic names the two live types and asks the operator to\nalign them deliberately.\n\nThe conversion is one-time and idempotent: once the column is native `uuid`,\nthe component is uniformly UUID and the planner emits nothing.\n\n### Application cascade invariants (`src/cascade.ts`)\n\n- Rebuild the registry-derived plan on every delete; manifests register lazily.\n Caching requires invalidation across every registration path.\n- Plan from `getResolvedQualifiedName()`. Every registered polymorphic\n association class participates, since its runtime target can be any class;\n `CascadePlan.isEmpty` requires no such class anywhere and no typed references.\n Only an empty plan skips the transaction.\n- Cascades are set-based: child hooks/interceptors and change-feed tombstones do\n not run. Only the explicitly deleted object runs its lifecycle. RESTRICT\n checks precede mutations; the parent DELETE and cascades share one transaction\n where supported, so deeper refusals roll back.\n- Derived `_smrt_embeddings` / `_smrt_contexts` cleanup matches IDs AND\n `ownerClassCandidates()` (qualified and simple STI member names), never IDs\n alone: unrelated text-ID classes can collide. Cleanup failures are logged,\n not raised, because these tables may not exist in older databases.\n- Never cascade append-only `_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals`,\n or dispatch logs; deleting change tombstones would break sync.\n\n### Retention (`src/system/retention.ts`)\n\n`runRetentionSweep(db, policy)` runs five built-ins in fixed order (`changes`,\n`ai-usage`, `contexts`, `dispatch`, `run-once-claims`), then\n`registerRetentionTask()` contributions. A failed task records its result and\ncontinues; a missing table is `unavailable`. The `globalThis` registry avoids\nsplit registrations under duplicate core resolution; package tasks exist only\nafter importing the package. CLI prune optionally imports jobs/users.\n\nDefaults are opt-out: changes 30 days, AI usage 90 days, completed dispatch 30\ndays/failed dispatch 90 days, contexts by `expires_at`, run-once claims 30\ndays on `completed_at` (#3080; `in_progress` rows never match — the window is\na replay deadline for `runOnce()`, not just disk hygiene, see\n`agents/run-once.md`). `smrt.configure({ retention })` tunes built-ins;\ncontributed tasks own their defaults/options.\nJobs defaults are 7 days terminal, 30 failed, 30 events via\n`registerJobRetentionTasks()` or runner `retention.jobs`; expired credentials\nhave no extra window. Disable a table/task with `false` or the whole policy with\n`enabled: false`; CLI `--skip` and runner configuration expose these controls.\nTask names use package prefixes (`jobs-records`, `users-sessions`).\n\nCore does not schedule sweeps. TaskRunner runs every six hours, first one\ninterval after start; `retention: false` opts out. `smrt db:prune` supports cron.\nEvery prune counts then deletes using the same predicate; `rowCount` is not\nportable. The two statements deliberately are not transactional, so counts are\napproximate under concurrency. Overlapping change/AI-usage bounds exclude rows\nalready counted, including dry runs.\n\nRetention indexes belong in system DDL and its versioned replay:\n`_smrt_contexts(expires_at)`, `_smrt_ai_usage(tenant_id, created_at)`, dispatch\n`(status, processed_at)` / `(status, updated_at)`, and\n`_smrt_run_once_claims(status, completed_at)`. Jobs `(status, completed_at)`\nbelongs in `ensureJobsSystemTableCompatibility()` on each collection initialize,\nsince decorated jobs tables do not exist at bootstrap.\n\nExpiry remains prune-side for object/collection `recall()`/`recallAll()`;\n`LearningMemory` separately filters it at read time.\n\n## Supported generation surfaces\n\nThe four entry points above are the supported generator paths. The unused AST\n`generateSchema(objectDef)`, `smrt:schema` / `@happyvertical/smrt-virt-schema`\nvirtual modules, and project-specific `SchemaOverrideSystem` were removed.\n\nKeep published `SchemaDefinition.triggers`, `TriggerDefinition`, and the DDL\nstrategies' trigger renderers: they support hand-authored new-table schemas.\nGenerated `@smrt()` schemas always emit `triggers: []`; no decorator populates\nit, `save()` maintains `updated_at`, and the differ never retrofits triggers.\nAdding live trigger generation requires a migration rollout design.\n`_smrt_signals` and database-persisted registry APIs are retired; see\n`RETIRED_SYSTEM_TABLES` in `src/system/schema.ts`.\n\n## PostgreSQL migration execution\n\n`MigrationTracker.applyAll({ atomic: true })` sets local lock/statement timeouts\nbefore any DDL. `postgresSafe: true` commits non-index DDL atomically, then runs\nindexes CONCURRENTLY on `db.acquireSession()` so settings and DDL share a\nconnection. This mode is not atomic. Unfinished indexes are `failed`, not\n`running`; `[smrt: concurrent-index phase 1 committed]` in `error_message`\nallows reruns to resume index work without replaying committed DDL. Inspect\n`pg_index.indisvalid` and drop INVALID indexes before rebuild (`pg_indexes`\nalone cannot detect them). Operational commands: `packages/cli/AGENTS.md`.\n\n### Subclass conflict identities (#3456)\n\nAn STI child's explicit `conflictColumns` owns a partial unique index restricted\nto its qualified discriminator. The root conflict index excludes these children;\nregistry and manifest paths emit the same predicates. Natural-key lookups include\nthat scope, PostgreSQL atomic inserts include the index predicate, and adopted\nrows update by id. Bulk writes use per-item guards for these targets. Normal\nmigrations replace the root index by name and add the child index; repair any\nexisting duplicate child natural keys before migrating. Stop old writers for this\nindex migration and load the complete consumer manifest on every shared-table\nwriter before resuming: a provider-only manifest lacks the child predicates.\nDuckDB/JSON reject\nthese schemas because partial unique conflict identities cannot be enforced.\n\n## Consumer physical table bindings (#3660)\n\n`smrt.tableNames` maps exact qualified model identities to deployment-local\nphysical tables. `registry/table-mappings.ts` projects schemas for both runtime\n`getSchema()` reads and merged migration planning, including index names and\nrelationship targets. Never remap by a raw old table name: two unrelated models\nmay own that name in their respective packages. Bind STI roots only; sensitive\nmodels are refused. Well-formed bindings may precede model registration;\npartial registries never need unrelated models merely to satisfy configuration.\nRuntime object/collection getters recheck ownership even for cached table\nnames; validation is memoized by registry generation and binding configuration.\nConfiguration must load before first database use and stay\nfixed for that process. This is not an implicit data migration; see\n[consumer table bindings](../../../docs/content/table-bindings.md).\n"
|
|
1183
1191
|
},
|
|
1184
1192
|
{
|
|
1185
1193
|
"path": "agents/deployment-phases.md",
|
|
@@ -1189,7 +1197,7 @@
|
|
|
1189
1197
|
{
|
|
1190
1198
|
"path": "agents/change-feed.md",
|
|
1191
1199
|
"module": "change-feed",
|
|
1192
|
-
"content": "# smrt-core/change feed\n\nModule semantics for `src/change-feed.ts`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Change Feed (#1758)\n\nAdapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):\n\n- `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing; they compare JSON values structurally and key-order-insensitively via `src/utils/json-equal.ts`, #4604); subscribers must tolerate spurious entries — they are convergent.\n- Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry (a jittered pause of at most 40 ms between attempts, so two tight-loop writers cannot starve one another — #3062) — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).\n- Staged appends (PostgreSQL, #2649): `MAX+1` costs a *wait* — the loser of a primary-key race waits for the winner's whole transaction — so an append inside a caller transaction that already wrote rows would let a long write transaction and an ordinary concurrent request form a real lock cycle (`40P01`, found downstream in willgriffin/willgriffin.dev#457). `_smrt_append_change` therefore checks `pg_current_xact_id_if_assigned()` (PostgreSQL 13+): when the caller already has a transaction id it stages the entry in `_smrt_changes_pending` (identity key, conflicts with nothing, never waits, still rolled back with the caller) and `appendChange()` returns **`null`** instead of a sequence. `_smrt_drain_changes()` moves *committed* staged rows into `_smrt_changes` with contiguous `MAX(seq)+row_number()` sequences under a **try-only** advisory lock, so the drain never waits either. Draining is driven from JavaScript, never inside the append helper: an entry sequenced invisibly server-side would get no live `_events` signal while the append's own signal carried a higher sequence, and a subscriber resuming from that `Last-Event-ID` would skip it permanently. `drainChangeFeed(db)` is called best-effort by `getChangesSince()`, by `pruneChangeFeed()`, and by the append path itself (throttled to one drain per 250 ms per database, bypassed immediately after this process staged an append). The append path issues ONE drain statement (a single bounded pass) and nothing else — the caller may own the surrounding transaction, and a second statement there could fail and abort it behind the feed's own error-swallowing (#2026); the helper's whole body, preflight included, sits inside its exception boundary for the same reason. It still settles that drain's signals in order without spending a statement: a drain that allocated anything assigns a transaction id, so an append that then takes the DIRECT path proves the drain committed, and its signals publish ahead of the append's own; a deferred append proves nothing and queues them. Signals for drained entries publish only after a follow-up probe proves the drain committed, so an uncommitted drain can never advertise a sequence a rollback releases for reuse. `getChangesSince()` additionally holds back everything the handle's own drains allocated while a transaction id is still assigned at read time (a per-handle watermark, so later reads in the same transaction keep holding back), and `bootstrapSystemTables()` refreshes the helpers before its schema-version fast return so an already-stamped database does not keep the deadlocking function. Consequences: the cursor guarantee is unchanged (one `MAX+1` writer at a time, only over committed work), but a staged entry becomes visible one drain after its transaction commits, its log position is drain order rather than statement order, and it publishes its live `_events` signal at drain time (post-commit — the old pre-commit signal could describe a rolled-back write). SQLite/DuckDB keep the direct insert unchanged. Residual: an append issued as a transaction's *first* statement still allocates inline — it holds no row locks then, so it cannot close a cycle, but it can make other direct appenders wait for that commit; issue explicit `bumpChangeFeed()` calls after the write or outside the transaction. A deployment that writes only through transactions and reads the feed from a connection that cannot write must schedule `drainChangeFeed()` on a writable one.\n- Tenant typing (#3297): on PostgreSQL `_smrt_changes.tenant_id`, `_smrt_changes_pending.tenant_id` and the dispatch tables' `tenant_id` are native `uuid` on fresh installs (TEXT elsewhere, and on existing installs until `smrt db:migrate-uuid` converts them in a maintenance window). The helpers (marker `smrt-change-feed-helpers:v5`) coerce each tenant id to the LIVE column type through `jsonb_populate_record(NULL::<table>, …)`, so one body serves TEXT, uuid and the mixed state mid-conversion, and `_smrt_drain_changes()` returns `drained_tenant_id` as text. v5 bodies also carry the v4 marker so an older process's probe keeps them during a rolling upgrade; `db:migrate-uuid` installs them in its own transaction before converting. Upgrade every writer before converting: an older process that reinstalls its v4 drain cannot return a uuid tenant id. Tenant ids written here must be UUIDs (or NULL); `_smrt_ai_usage.tenant_id` and `_smrt_run_once_claims.tenant_id` stay TEXT (caller-supplied scope strings).\n- `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).\n- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table **plus that table's staged-but-undrained count**, so a staged write still moves the ETag and cannot false-304 a client; the sum is monotonic because draining `n` staged rows raises the table's `MAX(seq)` by at least `n`, and both terms are read in ONE statement — separate reads let a drain be counted twice, minting a version a later write re-mints; replica-stable, with no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.\n- Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.\n- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable. The age bound is a **prefix** bound — everything below the oldest entry still inside the window — because `created_at` and `seq` are not co-monotonic (writer clocks skew, and a staged entry carries its stage-time stamp into a later-assigned sequence); deleting by timestamp alone could punch a hole in the middle of the retained run, where `since < floor - 1` cannot see it and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.\n\n\n## Credential-bearing tables are never disclosed (#2937)\n\n`src/change-feed-sensitivity.ts` is a leaf module (it imports nothing, so\n`change-feed.ts`, `change-signals.ts` and the registry can all consult it\nwithout a cycle) holding the tables whose **row id or payload is a secret**. A\ntable joins it two ways: by name, via the baseline\n`CHANGE_FEED_CREDENTIAL_TABLES` (`sessions`, `users_cli_auth_requests`,\n`users_magic_link_tokens`, `magic_link_tokens`, `api_keys`,\n`nostr_identities`), or because a class declared `@smrt({ sensitive: true })`\nand registration pushed its resolved table name across\n(`declareChangeFeedSensitiveTable`, called from both the decorator and the\nmanifest-stub registration paths). Both are needed: the declaration is the\npackage's own contract but only binds in a process where that package\nregistered, while the name baseline is all the read path has when serving a\ndatabase another process writes. The set is **monotonic** — `sensitive: false`\nis not an opt-out and nothing removes a name — so a consumer whose domain\ntable is named `sessions` loses feed coverage for it and must rename it via\n`@smrt({ tableName })`.\n\n`isChangeFeedObservableTable()` ANDs the sensitivity check with\n`CHANGE_FEED_EXCLUDED_TABLES`, and the refusal is enforced at four points, not\none: the interceptor write path; `appendChange`/`appendChanges`, the lowest\nwrite API, so `bumpChangeFeed()` and any other escape hatch are covered (a\nrefused append returns `null`, indistinguishable from a staged one);\n`deliverLocally` in `change-signals.ts`, which also catches a signal broadcast\nby a peer replica running an older build; and **`getChangesSince()`**. The\nread-side refusal is what makes upgrading sufficient — rows an earlier version\nalready wrote stay in the log but are never served. A caller-named sensitive\ntable is dropped from the `tables` filter rather than erroring, so nothing\nconfirms the table exists, and a request naming *only* sensitive tables gets\nan empty page rather than an unfiltered one. Filtered rows never hold the\ncursor back: an exhaustive page still advances to the served horizon.\n\nThe PostgreSQL drain also refuses them (#2982). Every drain passes the live\nsensitive set to `_smrt_drain_changes(limit, excluded_tables)`. Under the drain\nlock it deletes staged rows for those tables before allocating any sequence,\nand its batch skips any that commit afterwards. Entries an older replica staged,\nor that were staged before an upgrade, therefore never reach `_smrt_changes`.\nThe single-argument `_smrt_drain_changes(limit)` remains as a compatibility\nentry point for older replicas during a rollout. It delegates with no\nexclusions, which is the old behaviour; its output stays covered by the read,\nsignal and retention refusals above. The bootstrap and raw-handle probes require\nboth overloads, so an upgraded database installs the new one before current code\ncalls it. A newly created two-argument drain inherits the compat drain's\nreconciled EXECUTE grants, so a hardened ACL with no PUBLIC EXECUTE carries\nover. The compat drain has its own exception boundary. The purge is bounded per\npass, like the sequencing batch.\n\nIn a permissions-managed deployment the migration owner installs the helpers\nbefore current replicas boot. Permission plans must come from the current CLI:\nan older planner reports the two-argument overload as an unsupported routine.\n\n`pruneChangeFeed()` additionally deletes sensitive rows below the horizon on\nevery sweep, ahead of either retention bound, so credentials do not sit at rest\nfor the retention window. That deletes from the middle of the retained run,\nwhich the age bound goes to lengths to avoid — permissible only because these\nrows are unservable on every read path, so no page ever contained them and no\ncursor can fall into the gap. It **does** move `floor`, and usually will: a\nsession is created before the first domain write and re-saved on every request,\nso the lowest retained sequences are typically credential rows. `floor` is read\nlive (`MIN(seq)`) on every `getChangesSince` and never cached, so the only\nconsequence is that a cursor below the new floor is answered `resyncRequired`\nand refetches — including a `since=0` client on a never-pruned feed. Extra\nresyncs, never a missed change. The horizon does not move, because the newest\nentry is retained even when it is sensitive; that preserves \"a non-empty feed\nis never emptied\" and means one credential row can linger until the next write\nmoves the horizon past it.\n\nBecause a non-observable table appends nothing, it also has no ETag source:\n`getTableVersion()` would pin at whatever an older build last wrote and then\nfall back to the global horizon, which moves only on unrelated traffic — so a\nconditional GET could answer `304` for a revoked API key or a rotated session.\n`getTableVersion()` therefore returns a deliberately **unrepeatable** value for\nsuch a table — 48 bits of `crypto` randomness per call, not a per-process\ncounter, because two replicas' clock-seeded counters drift through each other\nand the ETag carries no per-process entropy — so no *concrete* `If-None-Match`\ncan match and every such read is a full 200. It is the single point every ETag\npath goes through (the runtime `APIGenerator`, the generated\n`conditionalVersionedRead`, and route files an older generator already\nemitted), so no call site needs a special case. A wildcard `If-None-Match: *`\nstill 304s; the read paths evaluate it only after the payload is built, so it\ndistinguishes nothing an unconditional request would not.\n\nSTI sensitivity is table-wide. Manifest generation and registration refuse a\nhierarchy mixing classes declaring `sensitive: true` with classes omitting it or\ndeclaring false (`CONFIG_STI_MIXED_SENSITIVITY`, #3456). Mark every class sensitive\nor put the sensitive and public models on separate tables. This preserves the\nhistorical-read and live-signal protections without introducing a discriminator\ninto old feed rows. A uniformly sensitive hierarchy declares its shared table;\nthe authoritative write-path check still verifies the instance's actual table.\n\nScope note: the generated `_changes`/`_events` routes — both the SvelteKit\nroutes and the runtime REST generator's — authorize on an authenticated\nprincipal plus tenant scoping (`getTenantScopedChangesSince`, fail-closed) by\ndefault. A consumer-supplied table/row authorization seam beyond that —\n`change-feed-authz.ts` (#3020, below) — is optional and off until registered.\n\n## Consumer table/row authorization seam (#3020)\n\nTenant scoping keeps one tenant from seeing another's rows, but it cannot\nexpress \"table X is readable by some principals of the tenant but not others\"\nor \"principal P only sees their own rows of table X\" (e.g. a bay-tablet\nstation versus the back office). `?tables=` on `_changes` was always a\nclient-chosen filter, never enforcement — a table the client did not ask for\nwas withheld only because it did not ask, not because it could not have.\n\n`src/change-feed-authz.ts` closes that gap with two independent, optional\nhooks, dependency-inverted onto `globalThis` exactly like\n`resolveDispatchTenantScope` (`dispatch/tenant-resolver.ts`), so a consumer\nregisters them once with no change to the generated \"DO NOT EDIT\" route files.\nBoth hooks are evaluated identically by **every** transport — the generated\nSvelteKit `_changes`/`_events` routes AND the runtime REST generator's\n`_changes`/`_events` (`generators/changes-route.ts`, `generators/events-route.ts`)\n— so a consumer serving both cannot register a hook that protects one and\nleaks through the other:\n\n- `setChangeFeedAuthorizer(authorizeChangeFeed)` — table-level.\n `authorizeChangeFeed({ locals, request, tables }) => allowedTables` returns\n the tables the requester may read from the feed at all; the result is\n INTERSECTED with the client's `?tables=` filter (never unioned), so a table\n the hook does not name is never queried, let alone returned.\n- `setChangeFeedEntryVisibility(isChangeFeedEntryVisible)` — row-level, for\n scope narrower than a whole table. Applied per entry, after the table\n filter, before anything is serialized — including a live `_events` signal.\n\n`locals` is SvelteKit's `event.locals`; `request` is SvelteKit's\n`event.request` or, on REST, the `authMiddleware`-processed `Request`. REST\nhas no `locals` concept, so REST routes pass `locals: undefined` and a\nREST-hosting consumer identifies the principal from `request` instead\n(whatever the `authMiddleware` attached — headers, a decoded token, etc.).\nEvery generated route supplies `request`.\n\nBoth hooks are optional and independent; unregistered, every transport\nbehaves exactly as before (tenant-scoped only). A hook that throws or returns\nsomething other than the documented shape fails closed to \"authorizes\nnothing\" for that call — same posture as a throwing `resolveDispatchTenantScope`\nresolver, and the same 200-empty-page shape the sensitivity filter above\nalready gives a request naming only tables it may not see (never a 5xx, which\nwould tell a caller its own hook is broken — indistinguishable from \"denied\"\nfrom the caller's side).\n\nEvery filter narrows the *returned* `changes`; nothing ever touches\n`cursor`/`resyncRequired`/`resyncCursor` — mirrors the sensitivity filter's\n\"filters affect what is returned, never how the cursor advances\" and for the\nsame reason: a client must advance past a denied entry without re-polling it\nforever, and the entry's row id/timing must never be inferable from a stalled\ncursor. Table denial sets `getChangesSince`'s explicit `denyAllTables: true`\noption rather than passing an empty `tables` array, because `getChangesSince`\ntreats an omitted/empty `tables` as \"no filter\" and would otherwise widen the\nread. `denyAllTables` skips the `table_name IN (...)` clause (and the query)\nentirely — an earlier version instead passed a guaranteed-no-match sentinel\ntable name through that clause, which broke on PostgreSQL (it rejects a NUL\nbyte in a text parameter, turning a denied request into a 500 instead of the\nrequired 200 empty page, #3020 P1 follow-up). `denyAllTables` still runs every\nresync/pruned-cursor check unfiltered first, so the real horizon computation\nruns and the cursor still advances — it just matches zero rows.\n`change-feed-authz.ts`'s `isChangeFeedDenyAll()` is the one place that decides\n\"empty allow-list\" (deny all) vs. \"no hook registered\" (no filter); both\n`readAuthorized()` (pull side) and `buildChangeEventStream()`'s catch-up loop\n(push side) call it rather than re-deriving the distinction. With NO hook\nregistered, `resolveAuthorizedChangeFeedTables()` normalizes an explicit empty\nrequested `tables: []` to `undefined` before that decision runs: `?tables=`\nwith nothing in it is documented as equivalent to an omitted filter, and\nwithout a hook there is no authorized answer to narrow anything with — feeding\n`[]` through unchanged would let `isChangeFeedDenyAll()` read it as \"deny\nevery table\" and silently break the promised unchanged default (#3020\nfollow-up). Once a hook IS registered, its own answer is what decides\ndeny-all, exactly as above.\n\nA registered hook's returned table list is also validated for USABLE\nstrings, not just string-typed ones: any entry that is empty or contains a\nNUL byte fails the whole call closed to `[]` (deny all), the same posture as\na non-array or non-string result. This closes the same NUL-byte hazard the\n`denyAllTables` sentinel removal above fixed for a *synthesized* value — here\nthe NUL byte would come from the hook's OWN answer, which otherwise flows\nstraight into the ordinary `table_name IN (...)` clause and 500s on\nPostgreSQL (#3020 Copilot follow-up).\n\n`getAuthorizedChangesSince()` / `getAuthorizedTenantScopedChangesSince()` wrap\n`getChangesSince()` / `getTenantScopedChangesSince()` with both hooks applied;\nBOTH `_changes` routes (SvelteKit's `vite-plugin/changes-route.ts` and REST's\n`generators/changes-route.ts` `handleChangesRoute`) call the tenant-scoped\nvariant, and `buildChangeEventStream()` (`change-signals.md`) — shared by\nBOTH `_events` routes — applies the same hooks to catch-up replay and live\nsignal delivery, resolving the table allow-list ONCE at connection open\n(mirrors captured tenant scope).\n\n## Compatible bulk mutations (#2818)\n\n`appendChanges(db, entries)` validates all inputs before writing and returns one\nsequence (or PostgreSQL staged `null`) per entry in input order. A nonempty batch\nuses one client SQL statement and one set-based insert. The PostgreSQL\n`_smrt_append_changes(jsonb)` helper chooses the staged/direct path once before\nits own writes assign a transaction ID, and retains the same exception isolation\nas the single-row helper. Bootstrap refreshes its body marker and runtime grants\ninclude this exact helper signature.\n\nThe registered feed interceptor explicitly supports grouped lifecycle completion.\n`recordInstanceChanges()` retains observable-table filtering, row/tenant IDs,\nper-row operations, and best-effort failure handling. It publishes each direct\nsequence in order; staged entries publish through the existing committed drain.\nA batch is never replaced with a table-level bump or a single aggregate event.\nThe junction caller bounds its batch; the low-level append API does not split\none logical append into partially committed chunks.\n"
|
|
1200
|
+
"content": "# smrt-core/change feed\n\nModule semantics for `src/change-feed.ts`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Change Feed (#1758)\n\nAdapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):\n\n- `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing; they compare JSON values structurally and key-order-insensitively via `src/utils/json-equal.ts`, #4604); subscribers must tolerate spurious entries — they are convergent.\n- Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry (a jittered pause of at most 40 ms between attempts, so two tight-loop writers cannot starve one another — #3062) — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).\n- Staged appends (PostgreSQL, #2649): `MAX+1` costs a *wait* — the loser of a primary-key race waits for the winner's whole transaction — so an append inside a caller transaction that already wrote rows would let a long write transaction and an ordinary concurrent request form a real lock cycle (`40P01`, found downstream in willgriffin/willgriffin.dev#457). `_smrt_append_change` therefore checks `pg_current_xact_id_if_assigned()` (PostgreSQL 13+): when the caller already has a transaction id it stages the entry in `_smrt_changes_pending` (identity key, conflicts with nothing, never waits, still rolled back with the caller) and `appendChange()` returns **`null`** instead of a sequence. `_smrt_drain_changes()` moves *committed* staged rows into `_smrt_changes` with contiguous `MAX(seq)+row_number()` sequences under a **try-only** advisory lock, so the drain never waits either. Draining is driven from JavaScript, never inside the append helper: an entry sequenced invisibly server-side would get no live `_events` signal while the append's own signal carried a higher sequence, and a subscriber resuming from that `Last-Event-ID` would skip it permanently. `drainChangeFeed(db)` is called best-effort by `getChangesSince()`, by `pruneChangeFeed()`, and by the append path itself (throttled to one drain per 250 ms per database, bypassed immediately after this process staged an append). The append path issues ONE drain statement (a single bounded pass) and nothing else — the caller may own the surrounding transaction, and a second statement there could fail and abort it behind the feed's own error-swallowing (#2026); the helper's whole body, preflight included, sits inside its exception boundary for the same reason. It still settles that drain's signals in order without spending a statement: a drain that allocated anything assigns a transaction id, so an append that then takes the DIRECT path proves the drain committed, and its signals publish ahead of the append's own; a deferred append proves nothing and queues them. Signals for drained entries publish only after a follow-up probe proves the drain committed, so an uncommitted drain can never advertise a sequence a rollback releases for reuse. `getChangesSince()` additionally holds back everything the handle's own drains allocated while a transaction id is still assigned at read time (a per-handle watermark, so later reads in the same transaction keep holding back), and `bootstrapSystemTables()` refreshes the helpers before its schema-version fast return so an already-stamped database does not keep the deadlocking function. Consequences: the cursor guarantee is unchanged (one `MAX+1` writer at a time, only over committed work), but a staged entry becomes visible one drain after its transaction commits, its log position is drain order rather than statement order, and it publishes its live `_events` signal at drain time (post-commit — the old pre-commit signal could describe a rolled-back write). SQLite/DuckDB keep the direct insert unchanged. Residual: an append issued as a transaction's *first* statement still allocates inline — it holds no row locks then, so it cannot close a cycle, but it can make other direct appenders wait for that commit; issue explicit `bumpChangeFeed()` calls after the write or outside the transaction. A deployment that writes only through transactions and reads the feed from a connection that cannot write must schedule `drainChangeFeed()` on a writable one.\n- Tenant typing (#3297): on PostgreSQL `_smrt_changes.tenant_id`, `_smrt_changes_pending.tenant_id` and the dispatch tables' `tenant_id` are native `uuid` on fresh installs (TEXT elsewhere, and on existing installs until `smrt db:migrate-uuid` converts them in a maintenance window). The helpers (marker `smrt-change-feed-helpers:v5`) coerce each tenant id to the LIVE column type through `jsonb_populate_record(NULL::<table>, …)`, so one body serves TEXT, uuid and the mixed state mid-conversion, and `_smrt_drain_changes()` returns `drained_tenant_id` as text. v5 bodies also carry the v4 marker so an older process's probe keeps them during a rolling upgrade; `db:migrate-uuid` installs them in its own transaction before converting. Upgrade every writer before converting: an older process that reinstalls its v4 drain cannot return a uuid tenant id. Tenant ids written here must be UUIDs (or NULL); `_smrt_ai_usage.tenant_id` and `_smrt_run_once_claims.tenant_id` stay TEXT (caller-supplied scope strings).\n- `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).\n- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table **plus that table's staged-but-undrained count**, so a staged write still moves the ETag and cannot false-304 a client; the sum is monotonic because draining `n` staged rows raises the table's `MAX(seq)` by at least `n`, and both terms are read in ONE statement — separate reads let a drain be counted twice, minting a version a later write re-mints; replica-stable, with no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.\n- Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.\n- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable. The age bound is a **prefix** bound — everything below the oldest entry still inside the window — because `created_at` and `seq` are not co-monotonic (writer clocks skew, and a staged entry carries its stage-time stamp into a later-assigned sequence); deleting by timestamp alone could punch a hole in the middle of the retained run, where `since < floor - 1` cannot see it and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.\n\n\n## Durable row sync metadata (#4673)\n\nConfigure the current local writer with `setDatabaseSyncDeviceId(db, uuid)`.\nAn ordinary row stays untracked until a trusted caller opts in with\n`object.save({ trackSync: true })` or applies an incoming revision. Subsequent\nlocal saves and timestamp claims advance the counter and stamp the configured\ndevice. Tracked creates require a supplied ID and strict insert. Load an\nexisting tracked row by ID to update it.\n\nA trusted replay supplies `save({ sync: { originDeviceId, revision } })` with\na positive safe-integer revision. A replay advances the row only when its\nrevision is higher, or when the revision is equal and its device ID sorts\nafter the stored ID. Core still uses the local `updated_at` compare-and-swap\npredicate. The caller supplies the authenticated actor and tenant context.\nThis API is separate from the generated `sync/apply` protocol.\n\n`delete()` physically removes a tracked row and records its next sync revision\nin `_smrt_sync_tombstones` in the same transaction. Tracked cascade deletes do\nthe same. A tracked SET NULL reference stays live and advances its writer,\nrevision and timestamp. A trusted incoming `delete({ sync: { originDeviceId,\nrevision } })` can record a deletion for an ID that has never been present\nlocally. The ledger stores the physical table, row ID, qualified model and\ntenant, and remains available after change-feed retention. Its entries\nrepresent tombstones. Ordinary model reads only see live rows. A new identity\ncan reuse a deleted natural key, and a replay using the deleted ID conflicts.\n\nRemote LibSQL coverage currently depends on an SDK fix for its transaction\nand parameter-binding support. A rollback probe against sqld with\n`@happyvertical/sql@0.111.3` persisted changes even when the callback threw.\nThe in-process LibSQL test branch exercises Core’s remote-path selection and\nwrite predicates. Set `SMRT_TEST_LIBSQL_URL` to exercise the real adapter on\na disposable sqld database.\n\n## Credential-bearing tables are never disclosed (#2937)\n\n`src/change-feed-sensitivity.ts` is a leaf module (it imports nothing, so\n`change-feed.ts`, `change-signals.ts` and the registry can all consult it\nwithout a cycle) holding the tables whose **row id or payload is a secret**. A\ntable joins it two ways: by name, via the baseline\n`CHANGE_FEED_CREDENTIAL_TABLES` (`sessions`, `users_cli_auth_requests`,\n`users_magic_link_tokens`, `magic_link_tokens`, `api_keys`,\n`nostr_identities`), or because a class declared `@smrt({ sensitive: true })`\nand registration pushed its resolved table name across\n(`declareChangeFeedSensitiveTable`, called from both the decorator and the\nmanifest-stub registration paths). Both are needed: the declaration is the\npackage's own contract but only binds in a process where that package\nregistered, while the name baseline is all the read path has when serving a\ndatabase another process writes. The set is **monotonic** — `sensitive: false`\nis not an opt-out and nothing removes a name — so a consumer whose domain\ntable is named `sessions` loses feed coverage for it and must rename it via\n`@smrt({ tableName })`.\n\n`isChangeFeedObservableTable()` ANDs the sensitivity check with\n`CHANGE_FEED_EXCLUDED_TABLES`, and the refusal is enforced at four points, not\none: the interceptor write path; `appendChange`/`appendChanges`, the lowest\nwrite API, so `bumpChangeFeed()` and any other escape hatch are covered (a\nrefused append returns `null`, indistinguishable from a staged one);\n`deliverLocally` in `change-signals.ts`, which also catches a signal broadcast\nby a peer replica running an older build; and **`getChangesSince()`**. The\nread-side refusal is what makes upgrading sufficient — rows an earlier version\nalready wrote stay in the log but are never served. A caller-named sensitive\ntable is dropped from the `tables` filter rather than erroring, so nothing\nconfirms the table exists, and a request naming *only* sensitive tables gets\nan empty page rather than an unfiltered one. Filtered rows never hold the\ncursor back: an exhaustive page still advances to the served horizon.\n\nThe PostgreSQL drain also refuses them (#2982). Every drain passes the live\nsensitive set to `_smrt_drain_changes(limit, excluded_tables)`. Under the drain\nlock it deletes staged rows for those tables before allocating any sequence,\nand its batch skips any that commit afterwards. Entries an older replica staged,\nor that were staged before an upgrade, therefore never reach `_smrt_changes`.\nThe single-argument `_smrt_drain_changes(limit)` remains as a compatibility\nentry point for older replicas during a rollout. It delegates with no\nexclusions, which is the old behaviour; its output stays covered by the read,\nsignal and retention refusals above. The bootstrap and raw-handle probes require\nboth overloads, so an upgraded database installs the new one before current code\ncalls it. A newly created two-argument drain inherits the compat drain's\nreconciled EXECUTE grants, so a hardened ACL with no PUBLIC EXECUTE carries\nover. The compat drain has its own exception boundary. The purge is bounded per\npass, like the sequencing batch.\n\nIn a permissions-managed deployment the migration owner installs the helpers\nbefore current replicas boot. Permission plans must come from the current CLI:\nan older planner reports the two-argument overload as an unsupported routine.\n\n`pruneChangeFeed()` additionally deletes sensitive rows below the horizon on\nevery sweep, ahead of either retention bound, so credentials do not sit at rest\nfor the retention window. That deletes from the middle of the retained run,\nwhich the age bound goes to lengths to avoid — permissible only because these\nrows are unservable on every read path, so no page ever contained them and no\ncursor can fall into the gap. It **does** move `floor`, and usually will: a\nsession is created before the first domain write and re-saved on every request,\nso the lowest retained sequences are typically credential rows. `floor` is read\nlive (`MIN(seq)`) on every `getChangesSince` and never cached, so the only\nconsequence is that a cursor below the new floor is answered `resyncRequired`\nand refetches — including a `since=0` client on a never-pruned feed. Extra\nresyncs, never a missed change. The horizon does not move, because the newest\nentry is retained even when it is sensitive; that preserves \"a non-empty feed\nis never emptied\" and means one credential row can linger until the next write\nmoves the horizon past it.\n\nBecause a non-observable table appends nothing, it also has no ETag source:\n`getTableVersion()` would pin at whatever an older build last wrote and then\nfall back to the global horizon, which moves only on unrelated traffic — so a\nconditional GET could answer `304` for a revoked API key or a rotated session.\n`getTableVersion()` therefore returns a deliberately **unrepeatable** value for\nsuch a table — 48 bits of `crypto` randomness per call, not a per-process\ncounter, because two replicas' clock-seeded counters drift through each other\nand the ETag carries no per-process entropy — so no *concrete* `If-None-Match`\ncan match and every such read is a full 200. It is the single point every ETag\npath goes through (the runtime `APIGenerator`, the generated\n`conditionalVersionedRead`, and route files an older generator already\nemitted), so no call site needs a special case. A wildcard `If-None-Match: *`\nstill 304s; the read paths evaluate it only after the payload is built, so it\ndistinguishes nothing an unconditional request would not.\n\nSTI sensitivity is table-wide. Manifest generation and registration refuse a\nhierarchy mixing classes declaring `sensitive: true` with classes omitting it or\ndeclaring false (`CONFIG_STI_MIXED_SENSITIVITY`, #3456). Mark every class sensitive\nor put the sensitive and public models on separate tables. This preserves the\nhistorical-read and live-signal protections without introducing a discriminator\ninto old feed rows. A uniformly sensitive hierarchy declares its shared table;\nthe authoritative write-path check still verifies the instance's actual table.\n\nScope note: the generated `_changes`/`_events` routes — both the SvelteKit\nroutes and the runtime REST generator's — authorize on an authenticated\nprincipal plus tenant scoping (`getTenantScopedChangesSince`, fail-closed) by\ndefault. A consumer-supplied table/row authorization seam beyond that —\n`change-feed-authz.ts` (#3020, below) — is optional and off until registered.\n\n## Consumer table/row authorization seam (#3020)\n\nTenant scoping keeps one tenant from seeing another's rows, but it cannot\nexpress \"table X is readable by some principals of the tenant but not others\"\nor \"principal P only sees their own rows of table X\" (e.g. a bay-tablet\nstation versus the back office). `?tables=` on `_changes` was always a\nclient-chosen filter, never enforcement — a table the client did not ask for\nwas withheld only because it did not ask, not because it could not have.\n\n`src/change-feed-authz.ts` closes that gap with two independent, optional\nhooks, dependency-inverted onto `globalThis` exactly like\n`resolveDispatchTenantScope` (`dispatch/tenant-resolver.ts`), so a consumer\nregisters them once with no change to the generated \"DO NOT EDIT\" route files.\nBoth hooks are evaluated identically by **every** transport — the generated\nSvelteKit `_changes`/`_events` routes AND the runtime REST generator's\n`_changes`/`_events` (`generators/changes-route.ts`, `generators/events-route.ts`)\n— so a consumer serving both cannot register a hook that protects one and\nleaks through the other:\n\n- `setChangeFeedAuthorizer(authorizeChangeFeed)` — table-level.\n `authorizeChangeFeed({ locals, request, tables }) => allowedTables` returns\n the tables the requester may read from the feed at all; the result is\n INTERSECTED with the client's `?tables=` filter (never unioned), so a table\n the hook does not name is never queried, let alone returned.\n- `setChangeFeedEntryVisibility(isChangeFeedEntryVisible)` — row-level, for\n scope narrower than a whole table. Applied per entry, after the table\n filter, before anything is serialized — including a live `_events` signal.\n\n`locals` is SvelteKit's `event.locals`; `request` is SvelteKit's\n`event.request` or, on REST, the `authMiddleware`-processed `Request`. REST\nhas no `locals` concept, so REST routes pass `locals: undefined` and a\nREST-hosting consumer identifies the principal from `request` instead\n(whatever the `authMiddleware` attached — headers, a decoded token, etc.).\nEvery generated route supplies `request`.\n\nBoth hooks are optional and independent; unregistered, every transport\nbehaves exactly as before (tenant-scoped only). A hook that throws or returns\nsomething other than the documented shape fails closed to \"authorizes\nnothing\" for that call — same posture as a throwing `resolveDispatchTenantScope`\nresolver, and the same 200-empty-page shape the sensitivity filter above\nalready gives a request naming only tables it may not see (never a 5xx, which\nwould tell a caller its own hook is broken — indistinguishable from \"denied\"\nfrom the caller's side).\n\nEvery filter narrows the *returned* `changes`; nothing ever touches\n`cursor`/`resyncRequired`/`resyncCursor` — mirrors the sensitivity filter's\n\"filters affect what is returned, never how the cursor advances\" and for the\nsame reason: a client must advance past a denied entry without re-polling it\nforever, and the entry's row id/timing must never be inferable from a stalled\ncursor. Table denial sets `getChangesSince`'s explicit `denyAllTables: true`\noption rather than passing an empty `tables` array, because `getChangesSince`\ntreats an omitted/empty `tables` as \"no filter\" and would otherwise widen the\nread. `denyAllTables` skips the `table_name IN (...)` clause (and the query)\nentirely — an earlier version instead passed a guaranteed-no-match sentinel\ntable name through that clause, which broke on PostgreSQL (it rejects a NUL\nbyte in a text parameter, turning a denied request into a 500 instead of the\nrequired 200 empty page, #3020 P1 follow-up). `denyAllTables` still runs every\nresync/pruned-cursor check unfiltered first, so the real horizon computation\nruns and the cursor still advances — it just matches zero rows.\n`change-feed-authz.ts`'s `isChangeFeedDenyAll()` is the one place that decides\n\"empty allow-list\" (deny all) vs. \"no hook registered\" (no filter); both\n`readAuthorized()` (pull side) and `buildChangeEventStream()`'s catch-up loop\n(push side) call it rather than re-deriving the distinction. With NO hook\nregistered, `resolveAuthorizedChangeFeedTables()` normalizes an explicit empty\nrequested `tables: []` to `undefined` before that decision runs: `?tables=`\nwith nothing in it is documented as equivalent to an omitted filter, and\nwithout a hook there is no authorized answer to narrow anything with — feeding\n`[]` through unchanged would let `isChangeFeedDenyAll()` read it as \"deny\nevery table\" and silently break the promised unchanged default (#3020\nfollow-up). Once a hook IS registered, its own answer is what decides\ndeny-all, exactly as above.\n\nA registered hook's returned table list is also validated for USABLE\nstrings, not just string-typed ones: any entry that is empty or contains a\nNUL byte fails the whole call closed to `[]` (deny all), the same posture as\na non-array or non-string result. This closes the same NUL-byte hazard the\n`denyAllTables` sentinel removal above fixed for a *synthesized* value — here\nthe NUL byte would come from the hook's OWN answer, which otherwise flows\nstraight into the ordinary `table_name IN (...)` clause and 500s on\nPostgreSQL (#3020 Copilot follow-up).\n\n`getAuthorizedChangesSince()` / `getAuthorizedTenantScopedChangesSince()` wrap\n`getChangesSince()` / `getTenantScopedChangesSince()` with both hooks applied;\nBOTH `_changes` routes (SvelteKit's `vite-plugin/changes-route.ts` and REST's\n`generators/changes-route.ts` `handleChangesRoute`) call the tenant-scoped\nvariant, and `buildChangeEventStream()` (`change-signals.md`) — shared by\nBOTH `_events` routes — applies the same hooks to catch-up replay and live\nsignal delivery, resolving the table allow-list ONCE at connection open\n(mirrors captured tenant scope).\n\n## Compatible bulk mutations (#2818)\n\n`appendChanges(db, entries)` validates all inputs before writing and returns one\nsequence (or PostgreSQL staged `null`) per entry in input order. A nonempty batch\nuses one client SQL statement and one set-based insert. The PostgreSQL\n`_smrt_append_changes(jsonb)` helper chooses the staged/direct path once before\nits own writes assign a transaction ID, and retains the same exception isolation\nas the single-row helper. Bootstrap refreshes its body marker and runtime grants\ninclude this exact helper signature.\n\nThe registered feed interceptor explicitly supports grouped lifecycle completion.\n`recordInstanceChanges()` retains observable-table filtering, row/tenant IDs,\nper-row operations, and best-effort failure handling. It publishes each direct\nsequence in order; staged entries publish through the existing committed drain.\nA batch is never replaced with a table-level bump or a single aggregate event.\nThe junction caller bounds its batch; the low-level append API does not split\none logical append into partially committed chunks.\n"
|
|
1193
1201
|
},
|
|
1194
1202
|
{
|
|
1195
1203
|
"path": "agents/change-signals.md",
|
|
@@ -1249,7 +1257,7 @@
|
|
|
1249
1257
|
{
|
|
1250
1258
|
"path": "agents/browser-entry.md",
|
|
1251
1259
|
"module": "browser-entry",
|
|
1252
|
-
"content": "# Browser entry: no Node-only modules (#2838)\n\n`src/browser.ts` is what `package.json#exports[\".\"].browser` resolves to. Its\nmodule graph must build for a browser **and evaluate** in one. Two guards hold\nit:\n\n- `packages/bundle-gate` builds it with Vite browser conditions and fails on\n `node:` built-ins, `pg`, `cosmiconfig`, `jiti` and the rest of\n `FORBIDDEN_NODE_ONLY_MODULES` (core is held to zero even while its ratchet\n entry exists for another reason).\n- `pnpm test:browser` bundles the built `dist/browser.js`, loads it in\n Chromium, registers a decorated class, and fails on any evaluation error or\n any module Vite externalized \"for browser compatibility\". Set\n `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use another Chromium. CI runs it in\n the workbench browser job.\n\n`@noble/hashes`, `import-meta-resolve` and `minimatch` remain external runtime dependencies in the preserve-modules\npackage build. Bundling it under `dist/node_modules` leaves dangling imports\nwhen npm excludes that directory from tarballs. The packed MCP consumer tests\nthe installed relative-import closure and real SHA-256 execution with normal and CI prepack paths (#4008).\n\nCommonJS runtime dependencies are bundled, not external (#4054). Consumers\nthat exclude smrt-core from Vite dependency pre-bundling (#3843) receive\n`dist/*.js` as native browser ESM, where a bare import of a CommonJS package\nfails (`does not provide an export named 'default'`). `pluralize` is\ntherefore not in `vite.config.ts` `external`; its converted module is emitted\nunder `dist/vendor/` (the `entryFileNames` rule maps any bundled\n`node_modules/` module there, since npm never packs `dist/node_modules`), and\nit is a devDependency. `pnpm test:browser` also runs\n`scripts/browser-unbundled-dev.mjs`, which serves `dist/utils/naming.js`\nunbundled from a real Vite dev server (no dependency discovery) and evaluates\nit in Chromium. A new CommonJS runtime dependency on a browser-reachable path\nfollows the same rule.\n\n## How a Node-only dependency stays out\n\nNever import it statically from a module the browser graph reaches. Pick one:\n\n| Need | Use |\n|---|---|\n| `getDatabase`, `buildWhere`, `raw`, `NestedTransactionError`, the AI SDK, installed-package discovery | `src/host.ts`. `package.json#browser` maps `./dist/host.js` to `./dist/host.browser.js`; Node and every test resolve `host.ts`. |\n| JSON parse/stringify | `src/utils/json.ts`; the browser build is `utils/json.browser.ts` (native `JSON`). |\n| `node:fs`/`path`/`module` for manifest discovery | `src/manifest/node-host.ts`, which resolves them with `process.getBuiltinModule()`. No host answers \"absent\". |\n| SHA-256 | `sha256Hex` (`src/utils/sha256.ts`, `@noble/hashes`). Not `node:crypto`. |\n| Random ids | `globalThis.crypto.randomUUID()` / `getRandomValues()`. |\n| Async-local state | `createAsyncContext()` (`src/utils/async-context.ts`). Check `propagatesAcrossAwait` before relying on the store. |\n| A whole Node-only module (registry snapshot) | Keep it out of `system/browser.ts` and the browser entry. |\n\n`browser.ts` and `host.browser.ts` are typed against their Node counterparts, so\nthe surfaces cannot drift. A new browser variant needs its source pair, an\n`entries[...]` line in `vite.config.ts` (nothing imports it, so the build would\nnot emit it), and a `browser` mapping; `browser-field.test.ts` checks all three.\n\n## Known limits\n\n- The browser uses `getDatabase` from `@happyvertical/sql/pglite` and\n `buildWhere`, `raw`, and `NestedTransactionError` from the browser-safe\n `@happyvertical/sql/query` entry. It rejects non-PGlite engines.\n- The AI SDK is unavailable in the browser build.\n- The embedded write queue runs unqueued without async-local state; its only\n browser database, PGlite, serializes statements itself.\n- `smrt-config`'s browser loader resolves to `{}`; use `setConfig()`.\n- The whole browser entry does not yet evaluate unbundled: several modules\n read `process.env` at module scope, and `@happyvertical/utils` imports\n CommonJS `pluralize` itself (#4534).\n"
|
|
1260
|
+
"content": "# Browser entry: no Node-only modules (#2838)\n\n`src/browser.ts` is what `package.json#exports[\".\"].browser` resolves to. Its\nmodule graph must build for a browser **and evaluate** in one. Two guards hold\nit:\n\n- `packages/bundle-gate` builds it with Vite browser conditions and fails on\n `node:` built-ins, `pg`, `cosmiconfig`, `jiti` and the rest of\n `FORBIDDEN_NODE_ONLY_MODULES` (core is held to zero even while its ratchet\n entry exists for another reason).\n- `pnpm test:browser` bundles the built `dist/browser.js`, loads it in\n Chromium, registers a decorated class, and fails on any evaluation error or\n any module Vite externalized \"for browser compatibility\". Set\n `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use another Chromium. CI runs it in\n the workbench browser job.\n\n`@noble/hashes`, `import-meta-resolve` and `minimatch` remain external runtime dependencies in the preserve-modules\npackage build. Bundling it under `dist/node_modules` leaves dangling imports\nwhen npm excludes that directory from tarballs. The packed MCP consumer tests\nthe installed relative-import closure and real SHA-256 execution with normal and CI prepack paths (#4008).\n\nThe browser test also runs a separate Chromium fixture against the SDK's real\nPGlite adapter, checking that a model delete clears both tracked and untracked\n`SET NULL` references, and advances only the tracked revision. It exercises\nboth the `memory://` and `idb://` data directories. Its pinned PGlite peer is\ninstalled from an isolated lockfile so the workspace's browser graph guards\nkeep their original dependency graph. The fixture serves the peer's published\nESM and WASM through an import map, so its Node-only runtime branches are never\nexecuted in Chromium. The regular browser entry bundle check still runs\nseparately.\n\nCommonJS runtime dependencies are bundled, not external (#4054). Consumers\nthat exclude smrt-core from Vite dependency pre-bundling (#3843) receive\n`dist/*.js` as native browser ESM, where a bare import of a CommonJS package\nfails (`does not provide an export named 'default'`). `pluralize` is\ntherefore not in `vite.config.ts` `external`; its converted module is emitted\nunder `dist/vendor/` (the `entryFileNames` rule maps any bundled\n`node_modules/` module there, since npm never packs `dist/node_modules`), and\nit is a devDependency. `pnpm test:browser` also runs\n`scripts/browser-unbundled-dev.mjs`, which serves `dist/utils/naming.js`\nunbundled from a real Vite dev server (no dependency discovery) and evaluates\nit in Chromium. A new CommonJS runtime dependency on a browser-reachable path\nfollows the same rule.\n\n## How a Node-only dependency stays out\n\nNever import it statically from a module the browser graph reaches. Pick one:\n\n| Need | Use |\n|---|---|\n| `getDatabase`, `buildWhere`, `raw`, `NestedTransactionError`, the AI SDK, installed-package discovery | `src/host.ts`. `package.json#browser` maps `./dist/host.js` to `./dist/host.browser.js`; Node and every test resolve `host.ts`. |\n| JSON parse/stringify | `src/utils/json.ts`; the browser build is `utils/json.browser.ts` (native `JSON`). |\n| `node:fs`/`path`/`module` for manifest discovery | `src/manifest/node-host.ts`, which resolves them with `process.getBuiltinModule()`. No host answers \"absent\". |\n| SHA-256 | `sha256Hex` (`src/utils/sha256.ts`, `@noble/hashes`). Not `node:crypto`. |\n| Random ids | `globalThis.crypto.randomUUID()` / `getRandomValues()`. |\n| Async-local state | `createAsyncContext()` (`src/utils/async-context.ts`). Check `propagatesAcrossAwait` before relying on the store. |\n| A whole Node-only module (registry snapshot) | Keep it out of `system/browser.ts` and the browser entry. |\n\n`browser.ts` and `host.browser.ts` are typed against their Node counterparts, so\nthe surfaces cannot drift. A new browser variant needs its source pair, an\n`entries[...]` line in `vite.config.ts` (nothing imports it, so the build would\nnot emit it), and a `browser` mapping; `browser-field.test.ts` checks all three.\n\n## Known limits\n\n- The browser uses `getDatabase` from `@happyvertical/sql/pglite` and\n `buildWhere`, `raw`, and `NestedTransactionError` from the browser-safe\n `@happyvertical/sql/query` entry. It rejects non-PGlite engines.\n- The AI SDK is unavailable in the browser build.\n- The embedded write queue runs unqueued without async-local state; its only\n browser database, PGlite, serializes statements itself.\n- `smrt-config`'s browser loader resolves to `{}`; use `setConfig()`.\n- The whole browser entry does not yet evaluate unbundled: several modules\n read `process.env` at module scope, and `@happyvertical/utils` imports\n CommonJS `pluralize` itself (#4534).\n"
|
|
1253
1261
|
},
|
|
1254
1262
|
{
|
|
1255
1263
|
"path": "agents/test-types.md",
|