@happyvertical/smrt-core 0.51.11 → 0.51.14

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.
Files changed (67) hide show
  1. package/agents/schema-paths.md +23 -6
  2. package/dist/class.d.ts +1 -1
  3. package/dist/class.d.ts.map +1 -1
  4. package/dist/class.js +4 -2
  5. package/dist/class.js.map +1 -1
  6. package/dist/decorators/index.d.ts +19 -0
  7. package/dist/decorators/index.d.ts.map +1 -1
  8. package/dist/decorators/index.js.map +1 -1
  9. package/dist/index.js +1 -1
  10. package/dist/manifest/static-manifest.js +1 -1
  11. package/dist/manifest/static-manifest.js.map +1 -1
  12. package/dist/manifest/store.js +1 -1
  13. package/dist/manifest.json +1 -1
  14. package/dist/migrations/differ.d.ts +64 -5
  15. package/dist/migrations/differ.d.ts.map +1 -1
  16. package/dist/migrations/differ.js +274 -37
  17. package/dist/migrations/differ.js.map +1 -1
  18. package/dist/migrations/index.d.ts +1 -1
  19. package/dist/migrations/index.d.ts.map +1 -1
  20. package/dist/migrations/index.js +2 -2
  21. package/dist/migrations/sqlite-rebuild.d.ts +41 -0
  22. package/dist/migrations/sqlite-rebuild.d.ts.map +1 -1
  23. package/dist/migrations/sqlite-rebuild.js +68 -13
  24. package/dist/migrations/sqlite-rebuild.js.map +1 -1
  25. package/dist/migrations.js +2 -2
  26. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/assert-valid-pattern.js +1 -1
  27. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/assert-valid-pattern.js.map +1 -1
  28. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/ast.js +1 -1
  29. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/ast.js.map +1 -1
  30. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/brace-expressions.js +1 -1
  31. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/brace-expressions.js.map +1 -1
  32. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/escape.js +1 -1
  33. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/escape.js.map +1 -1
  34. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/index.js +1 -1
  35. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/index.js.map +1 -1
  36. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/unescape.js +1 -1
  37. package/dist/node_modules/.pnpm/{minimatch@10.2.5 → minimatch@10.2.6}/node_modules/minimatch/dist/esm/unescape.js.map +1 -1
  38. package/dist/registry/db-cache-key.d.ts +47 -0
  39. package/dist/registry/db-cache-key.d.ts.map +1 -0
  40. package/dist/registry/db-cache-key.js +201 -0
  41. package/dist/registry/db-cache-key.js.map +1 -0
  42. package/dist/registry/schema-builder.d.ts.map +1 -1
  43. package/dist/registry/schema-builder.js +6 -1
  44. package/dist/registry/schema-builder.js.map +1 -1
  45. package/dist/registry.d.ts +3 -0
  46. package/dist/registry.d.ts.map +1 -1
  47. package/dist/registry.js +5 -6
  48. package/dist/registry.js.map +1 -1
  49. package/dist/scanner/types.d.ts +2 -0
  50. package/dist/scanner/types.d.ts.map +1 -1
  51. package/dist/scanner/types.js.map +1 -1
  52. package/dist/schema/backfill.d.ts +16 -0
  53. package/dist/schema/backfill.d.ts.map +1 -0
  54. package/dist/schema/backfill.js +26 -0
  55. package/dist/schema/backfill.js.map +1 -0
  56. package/dist/schema/generator.d.ts.map +1 -1
  57. package/dist/schema/generator.js +3 -0
  58. package/dist/schema/generator.js.map +1 -1
  59. package/dist/schema/types.d.ts +12 -0
  60. package/dist/schema/types.d.ts.map +1 -1
  61. package/dist/smrt-knowledge.json +17 -17
  62. package/dist/vite-plugin/index.js +1 -1
  63. package/dist/vite-plugin/sync-apply-route.d.ts +7 -0
  64. package/dist/vite-plugin/sync-apply-route.d.ts.map +1 -1
  65. package/dist/vite-plugin/sync-apply-route.js +50 -3
  66. package/dist/vite-plugin/sync-apply-route.js.map +1 -1
  67. package/package.json +23 -23
@@ -3,19 +3,19 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.51.11",
6
+ "packageVersion": "0.51.14",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "9f334ff64beaac65676a0a79b81cf36c25a033715c452cfd00882054378a8b79",
11
- "packageJson": "64c970a25ff237c41eee105d5a0901899428bfe10eb57c241c78bcdc35472317",
10
+ "manifest": "94a4c427c50c3c3af63811a7b69f82ca92c26a69ed1a43b7e53ad72c87b39a88",
11
+ "packageJson": "73eef22a1ad5e719a351a66891ddb0a826f13e95a217fa64bddd4b86153ae515",
12
12
  "agents": "7e27a7c52729c302d80e9c36bf068fe1811a7ae51eccf66c6a5f9498aaec3318",
13
13
  "moduleDoc:agents/object-runtime.md": "34a4e740c109467cd5486c4af0e3bf4b63915697721ab584df0e5506ea9290ca",
14
14
  "moduleDoc:agents/revision-guard.md": "aa6b1ddb5b6b49fa27ebbe575ec7fcd6d5ceb35ee25acc702f877a226eb9a99a",
15
15
  "moduleDoc:agents/collection-reads.md": "e5bb79b59c17e79a85a71580a019e6b0b641e498ac4d850073fd5ad634b57cb7",
16
16
  "moduleDoc:agents/query-bounds.md": "3a0601ddaf2bea4e90e3f22e16a2eb3508a6fb8c019e3fb2c1f930c90a377cd5",
17
17
  "moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
18
- "moduleDoc:agents/schema-paths.md": "97de3a3a99ba6f44417eee7fc0c91f76963de88d787cf9f3e4278539d3d0454f",
18
+ "moduleDoc:agents/schema-paths.md": "8a8edc9b8d38de15bff09bf5dc20ad7389f83923ad21462253bb88bb4880bce0",
19
19
  "moduleDoc:agents/change-feed.md": "4b71888a93f9dc356196d312149871bf8b6562365cf68cdfd246a52791dffcdc",
20
20
  "moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
21
21
  "moduleDoc:agents/generators.md": "4bc7787947fbcb5c084ce3e7849eff7a240580226e6b64271de7493870683cdf",
@@ -63,26 +63,26 @@
63
63
  "@happyvertical/smrt-types": "workspace:*",
64
64
  "@happyvertical/sql": "catalog:",
65
65
  "@happyvertical/utils": "catalog:",
66
- "@oxc-project/runtime": "^0.138.0",
66
+ "@oxc-project/runtime": "^0.150.0",
67
67
  "cheerio": "^1.2.0",
68
68
  "fast-glob": "3.3.3",
69
- "minimatch": "10.2.5",
70
- "oxc-transform": "0.138.0",
69
+ "minimatch": "10.2.6",
70
+ "oxc-transform": "0.150.0",
71
71
  "pluralize": "^8.0.0",
72
- "tsx": "^4.23.0",
73
- "yaml": "^2.9.0",
74
- "@faker-js/faker": "^10.5.0",
75
- "@huggingface/transformers": ">=3.0.0 <4.0.0",
76
- "@sveltejs/kit": "^2.69.3",
77
- "@sveltejs/vite-plugin-svelte": "^7.1.2",
78
- "@types/node": "24.13.2",
72
+ "tsx": "^4.23.13",
73
+ "yaml": "^2.9.1",
74
+ "@faker-js/faker": "^10.6.0",
75
+ "@huggingface/transformers": ">=3.0.0 <5.0.0",
76
+ "@sveltejs/kit": "2.69.3",
77
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
78
+ "@types/node": "24.13.6",
79
79
  "@types/pluralize": "^0.0.33",
80
80
  "@xenova/transformers": "^2.17.2",
81
- "svelte": "^5.56.4",
81
+ "svelte": "^5.57.1",
82
82
  "svelte-check": "4.7.6",
83
83
  "typescript": "5.9.3",
84
84
  "vite": "8.1.4",
85
- "vite-plugin-dts": "4.5.4",
85
+ "vite-plugin-dts": "5.1.0",
86
86
  "vitest": "4.1.10"
87
87
  },
88
88
  "smrtDependencies": [
@@ -1077,7 +1077,7 @@
1077
1077
  {
1078
1078
  "path": "agents/schema-paths.md",
1079
1079
  "module": "schema-paths",
1080
- "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- **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### 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.\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### A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced only on an empty table;\n on a populated one it is added nullable and the `NOT NULL` is reported as a\n manual follow-up on every engine.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1). The SQLite rebuild consumes\n only `type_upgrade` placeholders today; extending it to rewrite constraints\n would lift this.\n- Defaults compare through `canonicalizeDefault()`, which folds engine\n renderings (`'x'::text`, `CAST('t' AS BOOLEAN)`, `CURRENT_TIMESTAMP` vs\n `now()`) by manifest type; an unclassifiable rendering skips the comparison\n rather than risking a false positive that would churn every run. The\n round-trip test (create from each DDL strategy → compare → zero changes) in\n `src/migrations/__tests__/issue-2369-*.test.ts` guards this.\n\n### `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### 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`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Same-package referential integrity uses two matching rails\n\n`@foreignKey(Target)` emits a physical database constraint when the target is\nin the same package and applies the same action through `SmrtObject.delete()`\nin `src/cascade.ts`. A shared delete-action resolver keeps both paths aligned;\nthe established generated `ON UPDATE CASCADE` default remains unchanged:\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Ordinary same-package reference | `NO ACTION` — deletion is refused while references remain |\n| Every `@tenantId()` field | Excluded from physical constraints and delete cascades |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and therefore defaults to\nimmediate `NO ACTION` unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field.\n\n`@crossPackageRef()` remains runtime-only: it registers relationship loading\nand indexes but deliberately emits no physical constraint, avoiding circular\npackage DDL. Tenant markers follow the same non-constraint rule because a\ntenant is a scope, not an ownership edge.\n\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.\nSQLite 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**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 four built-ins in fixed order, 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`. `smrt.configure({\nretention })` tunes built-ins; contributed 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)`, and dispatch\n`(status, processed_at)` / `(status, updated_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"
1080
+ "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- **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### 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.\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### A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced 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### 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`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Same-package referential integrity uses two matching rails\n\n`@foreignKey(Target)` emits a physical database constraint when the target is\nin the same package and applies the same action through `SmrtObject.delete()`\nin `src/cascade.ts`. A shared delete-action resolver keeps both paths aligned;\nthe established generated `ON UPDATE CASCADE` default remains unchanged:\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Ordinary same-package reference | `NO ACTION` — deletion is refused while references remain |\n| Every `@tenantId()` field | Excluded from physical constraints and delete cascades |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and therefore defaults to\nimmediate `NO ACTION` unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field.\n\n`@crossPackageRef()` remains runtime-only: it registers relationship loading\nand indexes but deliberately emits no physical constraint, avoiding circular\npackage DDL. Tenant markers follow the same non-constraint rule because a\ntenant is a scope, not an ownership edge.\n\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.\nSQLite 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**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 four built-ins in fixed order, 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`. `smrt.configure({\nretention })` tunes built-ins; contributed 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)`, and dispatch\n`(status, processed_at)` / `(status, updated_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"
1081
1081
  },
1082
1082
  {
1083
1083
  "path": "agents/change-feed.md",
@@ -787,7 +787,7 @@ function smrtPlugin(options = {}) {
787
787
  async function shouldRescan(file) {
788
788
  if (pluginMode === "client") return false;
789
789
  try {
790
- const { minimatch } = await import("../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");
790
+ const { minimatch } = await import("../node_modules/.pnpm/minimatch@10.2.6/node_modules/minimatch/dist/esm/index.js");
791
791
  const isIncluded = include.some((pattern) => minimatch(file, pattern));
792
792
  const isExcluded = exclude.some((pattern) => minimatch(file, pattern));
793
793
  return isIncluded && !isExcluded;
@@ -13,6 +13,13 @@ interface SyncTargetSpec {
13
13
  * simple name.
14
14
  */
15
15
  registryKey: string;
16
+ /**
17
+ * `<collection>` prefix of the `<collection>.<action>` operation permission
18
+ * the mirrored generated write routes require (#2977) — the same
19
+ * `decoratorConfig.collection ?? collection` resolution as
20
+ * sveltekit-generator.ts `resolvePermissionCollection`.
21
+ */
22
+ permissionCollection: string;
16
23
  ops: MutatingAction[];
17
24
  readonlyFields: string[];
18
25
  writableAllowlist: string[] | null;
@@ -1 +1 @@
1
- {"version":3,"file":"sync-apply-route.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/sync-apply-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAMH,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAGjE,QAAA,MAAM,gBAAgB,yCAA0C,CAAC;AAEjE,KAAK,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAExD,wDAAwD;AACxD,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;OAMG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,cAAc,EAAE,CAAC;IACtB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACnC,YAAY,EAAE,OAAO,GAAG,MAAM,CAAC;IAC/B,YAAY,EAAE,OAAO,CAAC;CACvB;AAmED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,mBAAmB,GAC5B,cAAc,EAAE,CAgClB;AAgBD;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,OAAO,EAAE,cAAc,EAAE,EACzB,YAAY,EAAE,MAAM,GACnB,MAAM,CA0GR;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,mBAAmB,EAC7B,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAiCT"}
1
+ {"version":3,"file":"sync-apply-route.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/sync-apply-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAMH,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAGjE,QAAA,MAAM,gBAAgB,yCAA0C,CAAC;AAEjE,KAAK,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAExD,wDAAwD;AACxD,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;OAMG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAC7B,GAAG,EAAE,cAAc,EAAE,CAAC;IACtB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,iBAAiB,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IACnC,YAAY,EAAE,OAAO,GAAG,MAAM,CAAC;IAC/B,YAAY,EAAE,OAAO,CAAC;CACvB;AA6ED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,mBAAmB,GAC5B,cAAc,EAAE,CAiClB;AAiBD;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,OAAO,EAAE,cAAc,EAAE,EACzB,YAAY,EAAE,MAAM,GACnB,MAAM,CAkJR;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,mBAAmB,EAC7B,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAiCT"}
@@ -68,6 +68,11 @@ function getApiWritableAllowlist(apiConfig) {
68
68
  const config = getApiConfigObject(apiConfig);
69
69
  return Array.isArray(config?.writable) ? config.writable : null;
70
70
  }
71
+ /** Mirror of sveltekit-generator.ts `resolvePermissionCollection` (#2977). */
72
+ function resolvePermissionCollection(objectDef) {
73
+ const configured = objectDef.decoratorConfig?.collection;
74
+ return typeof configured === "string" && configured.length > 0 ? configured : objectDef.collection;
75
+ }
71
76
  /**
72
77
  * Collect the syncable targets from a manifest: non-collection objects whose
73
78
  * API config is enabled and exposes at least one mutating action.
@@ -85,6 +90,7 @@ function collectSyncApplyTargets(manifest) {
85
90
  targets.push({
86
91
  segment: objectDef.collection,
87
92
  registryKey: className,
93
+ permissionCollection: resolvePermissionCollection(objectDef),
88
94
  ops,
89
95
  readonlyFields: collectReadonlyFieldNames(objectDef),
90
96
  writableAllowlist: getApiWritableAllowlist(apiConfig),
@@ -98,6 +104,7 @@ function serializeTargets(targets) {
98
104
  return `{\n${targets.map((target) => {
99
105
  const fields = [
100
106
  `registryKey: ${JSON.stringify(target.registryKey)}`,
107
+ `permissionCollection: ${JSON.stringify(target.permissionCollection)}`,
101
108
  `ops: ${JSON.stringify(target.ops)}`,
102
109
  `readonlyFields: ${JSON.stringify(target.readonlyFields)}`,
103
110
  `writableAllowlist: ${JSON.stringify(target.writableAllowlist)}`,
@@ -146,6 +153,8 @@ function establishTenantContext(locals: unknown): void {
146
153
  interface SyncTargetConfig {
147
154
  /** Manifest registry key (may be package-qualified), as CRUD routes use. */
148
155
  registryKey: string;
156
+ /** \`<collection>\` prefix of the required \`<collection>.<op>\` permission. */
157
+ permissionCollection: string;
149
158
  ops: SyncApplyOp[];
150
159
  readonlyFields: string[];
151
160
  writableAllowlist: string[] | null;
@@ -170,6 +179,39 @@ function hasAuthenticatedPrincipal(locals: unknown): boolean {
170
179
  );
171
180
  }
172
181
 
182
+ function readRecord(value: unknown): Record<string, unknown> {
183
+ return value && typeof value === 'object'
184
+ ? (value as Record<string, unknown>)
185
+ : {};
186
+ }
187
+
188
+ function hasGrantedPermission(value: unknown, permission: string): boolean {
189
+ if (Array.isArray(value)) return value.includes(permission);
190
+ if (value instanceof Set) return value.has(permission);
191
+ return false;
192
+ }
193
+
194
+ // Fail-closed operation permission (#2977, #3011): each applied op requires
195
+ // the same \`<collection>.<op>\` permission the mirrored generated write route
196
+ // enforces, read from the principal's session permission snapshot. A missing
197
+ // snapshot denies; only an explicit tenancy super-admin bypass skips it.
198
+ function hasOperationPermission(
199
+ locals: unknown,
200
+ permissionCollection: string,
201
+ op: SyncApplyOp,
202
+ ): boolean {
203
+ const l = readRecord(locals);
204
+ const tenantContext = readRecord(l.tenantContext);
205
+ if (tenantContext.superAdminBypass === true) return true;
206
+ const permission = \`\${permissionCollection}.\${op}\`;
207
+ return (
208
+ hasGrantedPermission(l.permissions, permission) ||
209
+ hasGrantedPermission(l.permissionSet, permission) ||
210
+ hasGrantedPermission(l.smrtPermissions, permission) ||
211
+ hasGrantedPermission(tenantContext.permissions, permission)
212
+ );
213
+ }
214
+
173
215
  export const POST: RequestHandler = async ({ locals, request }) => {
174
216
  const authenticated = hasAuthenticatedPrincipal(locals);
175
217
  ${anyTenantScoped ? " establishTenantContext(locals);\n" : ""}
@@ -195,10 +237,15 @@ ${anyTenantScoped ? " establishTenantContext(locals);\n" : ""}
195
237
  objectName: target.registryKey,
196
238
  collection,
197
239
  isOpAllowed: (op: SyncApplyOp) => target.ops.includes(op),
198
- authorize: () =>
199
- authenticated || target.publicAccess === true
240
+ authorize: (op: SyncApplyOp) => {
241
+ // \`public: true\` keeps its unauthenticated write semantics, as on
242
+ // the generated CRUD routes.
243
+ if (target.publicAccess === true) return 'ok' as const;
244
+ if (!authenticated) return 'auth_required' as const;
245
+ return hasOperationPermission(locals, target.permissionCollection, op)
200
246
  ? ('ok' as const)
201
- : ('auth_required' as const),
247
+ : ('forbidden' as const);
248
+ },
202
249
  prepare: (payload: Record<string, unknown>) =>
203
250
  applySyncWritablePolicy(payload, {
204
251
  readonlyFields: target.readonlyFields,
@@ -1 +1 @@
1
- {"version":3,"file":"sync-apply-route.js","names":[],"sources":["../../src/vite-plugin/sync-apply-route.ts"],"sourcesContent":["/**\n * SvelteKit generator for the sync-apply batch write route (#1759).\n *\n * Emits ONE route — `{routesDir}/sync/apply/+server.ts` — implementing the\n * shared web/mobile write contract for every syncable model in the manifest\n * (models whose API config exposes at least one of create/update/delete). The\n * generated file is deliberately thin: it maps `object` segments to\n * collections plus per-model policy data, and delegates all batch processing\n * to `processSyncApplyBatch` from `@happyvertical/smrt-core` — the same\n * engine the runtime REST generator uses, so the two transports cannot drift.\n *\n * This lives in its own module (rather than sveltekit-generator.ts) so the\n * shared generator file only needs a one-line registration hook; sibling\n * work (#1757, #1758) touches the same generator files in parallel.\n *\n * Contract documentation: docs/content/architecture/sync-apply-contract.md\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { isFrameworkBaseClass } from '../registry/framework-base-classes.js';\nimport type { ApiConfig } from '../registry/types.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types';\nimport { AUTO_GENERATED_ROUTE_HEADER } from './route-header.js';\nimport { resolveSvelteKitConfigImport } from './sveltekit-config-import.js';\nimport type { SvelteKitOptions } from './sveltekit-generator.js';\nimport { isCollectionManifestClass } from './web-collections.js';\n\nconst MUTATING_ACTIONS = ['create', 'update', 'delete'] as const;\n\ntype MutatingAction = (typeof MUTATING_ACTIONS)[number];\n\n/** Per-model data embedded into the generated route. */\ninterface SyncTargetSpec {\n segment: string;\n /**\n * The manifest registry key, passed VERBATIM to `getCollection()` exactly\n * as the generated CRUD routes do. May be package-qualified\n * (`@happyvertical/smrt-ledgers:Account`) — collapsing it to a simple class\n * name would resolve ambiguously when two loaded packages declare the same\n * simple name.\n */\n registryKey: string;\n ops: MutatingAction[];\n readonlyFields: string[];\n writableAllowlist: string[] | null;\n publicAccess: boolean | 'read';\n tenantScoped: boolean;\n}\n\nfunction getApiConfigObject(apiConfig: unknown): ApiConfig | null {\n if (!apiConfig || typeof apiConfig !== 'object') {\n return null;\n }\n return apiConfig as ApiConfig;\n}\n\n/**\n * Mirror of sveltekit-generator.ts `resolveStandardCrudActions`, narrowed to\n * the mutating subset the sync contract can carry. Kept local so this module\n * needs no exports added to the (parallel-edited) shared generator file.\n */\nfunction resolveMutatingActions(apiConfig: unknown): MutatingAction[] {\n if (apiConfig === false) return [];\n if (\n apiConfig === true ||\n apiConfig === undefined ||\n typeof apiConfig !== 'object'\n ) {\n return [...MUTATING_ACTIONS];\n }\n\n const config = apiConfig as { include?: string[]; exclude?: string[] };\n let actions: MutatingAction[] = Array.isArray(config.include)\n ? MUTATING_ACTIONS.filter((action) => config.include?.includes(action))\n : [...MUTATING_ACTIONS];\n if (Array.isArray(config.exclude)) {\n const excluded = config.exclude;\n actions = actions.filter((action) => !excluded.includes(action));\n }\n return actions;\n}\n\n/** Mirror of sveltekit-generator.ts `getApiPublicAccess` (fail-closed). */\nfunction getApiPublicAccess(apiConfig: unknown): boolean | 'read' {\n const config = getApiConfigObject(apiConfig);\n const value = config?.public;\n if (value === true || value === 'read') {\n return value;\n }\n return false;\n}\n\n/** Mirror of sveltekit-generator.ts `collectReadonlyFieldNames` (#1540, 2b). */\nfunction collectReadonlyFieldNames(objectDef: SmartObjectDefinition): string[] {\n const fields = objectDef.fields || {};\n const names: string[] = [];\n for (const [name, def] of Object.entries(fields)) {\n const meta = (def as { _meta?: Record<string, unknown> })._meta;\n if (\n (def as { readonly?: boolean }).readonly === true ||\n meta?.readonly === true\n ) {\n names.push(name);\n }\n }\n return names;\n}\n\n/** Mirror of sveltekit-generator.ts `getApiWritableAllowlist`. */\nfunction getApiWritableAllowlist(apiConfig: unknown): string[] | null {\n const config = getApiConfigObject(apiConfig);\n return Array.isArray(config?.writable) ? config.writable : null;\n}\n\n/**\n * Collect the syncable targets from a manifest: non-collection objects whose\n * API config is enabled and exposes at least one mutating action.\n */\nexport function collectSyncApplyTargets(\n manifest: SmartObjectManifest,\n): SyncTargetSpec[] {\n const targets: SyncTargetSpec[] = [];\n\n for (const [className, objectDef] of Object.entries(manifest.objects)) {\n if (isCollectionManifestClass(manifest, objectDef)) continue;\n // The framework's own abstract base classes are scaffolding, not\n // resources — never make them a sync-apply target, regardless of\n // config (#2642).\n if (isFrameworkBaseClass(objectDef.className, objectDef.packageName)) {\n continue;\n }\n\n const apiConfig = objectDef.decoratorConfig?.api;\n if (apiConfig === false) continue;\n\n const ops = resolveMutatingActions(apiConfig);\n if (ops.length === 0) continue;\n\n if (!objectDef.collection) continue;\n\n targets.push({\n segment: objectDef.collection,\n registryKey: className,\n ops,\n readonlyFields: collectReadonlyFieldNames(objectDef),\n writableAllowlist: getApiWritableAllowlist(apiConfig),\n publicAccess: getApiPublicAccess(apiConfig),\n tenantScoped: !!objectDef.decoratorConfig?.tenantScoped,\n });\n }\n\n return targets.sort((a, b) => a.segment.localeCompare(b.segment));\n}\n\nfunction serializeTargets(targets: SyncTargetSpec[]): string {\n const entries = targets.map((target) => {\n const fields = [\n `registryKey: ${JSON.stringify(target.registryKey)}`,\n `ops: ${JSON.stringify(target.ops)}`,\n `readonlyFields: ${JSON.stringify(target.readonlyFields)}`,\n `writableAllowlist: ${JSON.stringify(target.writableAllowlist)}`,\n `publicAccess: ${JSON.stringify(target.publicAccess)}`,\n ];\n return ` ${JSON.stringify(target.segment)}: {\\n ${fields.join(',\\n ')},\\n },`;\n });\n return `{\\n${entries.join('\\n')}\\n}`;\n}\n\n/**\n * Render the generated `+server.ts` content for the sync-apply route.\n * Exported for tests.\n */\nexport function generateSyncApplyRouteTemplate(\n targets: SyncTargetSpec[],\n configImport: string,\n): string {\n const anyTenantScoped = targets.some((target) => target.tenantScoped);\n\n const tenantHelper = anyTenantScoped\n ? `\nimport { enterTenantContext, hasTenantContext } from '@happyvertical/smrt-tenancy';\n\nfunction establishTenantContext(locals: unknown): void {\n if (hasTenantContext()) return;\n if (!locals || typeof locals !== 'object') return;\n const l = locals as Record<string, unknown>;\n const user = l.user as Record<string, unknown> | undefined;\n const session = l.session as Record<string, unknown> | undefined;\n const tenantId = l.tenantId ?? user?.tenantId ?? session?.tenantId;\n if (typeof tenantId === 'string' && tenantId) {\n enterTenantContext({ tenantId });\n }\n}\n`\n : '';\n\n return `${AUTO_GENERATED_ROUTE_HEADER}\n// DO NOT EDIT - changes will be overwritten\n//\n// Idempotent sync-apply batch write contract (#1759) — the shared write path\n// for the web offline outbox (#1762) and the KMP mobile write queue (#1739).\n// Contract: docs/content/architecture/sync-apply-contract.md\n\nimport {\n applySyncWritablePolicy,\n processSyncApplyBatch,\n type SyncApplyOp,\n type SyncApplyTarget,\n} from '@happyvertical/smrt-core';\nimport { json } from '@sveltejs/kit';\nimport { getCollection } from '${configImport}';\nimport type { RequestHandler } from './$types';\n${tenantHelper}\ninterface SyncTargetConfig {\n /** Manifest registry key (may be package-qualified), as CRUD routes use. */\n registryKey: string;\n ops: SyncApplyOp[];\n readonlyFields: string[];\n writableAllowlist: string[] | null;\n publicAccess: boolean | 'read';\n}\n\n// One entry per syncable model, keyed by the collection route segment its\n// generated CRUD routes use.\nconst SYNC_TARGETS: Record<string, SyncTargetConfig> = ${serializeTargets(targets)};\n\n// Fail-closed authorization (#1540): sync mutations require an authenticated\n// principal on \\`locals\\` unless the target model is \\`api: { public: true }\\`.\nfunction hasAuthenticatedPrincipal(locals: unknown): boolean {\n if (!locals || typeof locals !== 'object') return false;\n const l = locals as Record<string, unknown>;\n const isResolvedPrincipal = (v: unknown) =>\n typeof v === 'object' && v !== null;\n return (\n isResolvedPrincipal(l.user) ||\n isResolvedPrincipal(l.session) ||\n l.smrtAuth === true\n );\n}\n\nexport const POST: RequestHandler = async ({ locals, request }) => {\n const authenticated = hasAuthenticatedPrincipal(locals);\n${anyTenantScoped ? ' establishTenantContext(locals);\\n' : ''}\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(\n { error: { code: 'invalid_batch', message: 'Invalid JSON body' } },\n { status: 400 },\n );\n }\n\n const outcome = await processSyncApplyBatch(body, {\n resolveTarget: async (segment: string): Promise<SyncApplyTarget | null> => {\n const target = SYNC_TARGETS[segment];\n if (!target) return null;\n // The verbatim manifest key, exactly as the generated CRUD routes pass\n // it — package-qualified keys stay qualified so same-simple-name\n // classes across packages resolve unambiguously.\n const collection = await getCollection(target.registryKey);\n return {\n objectName: target.registryKey,\n collection,\n isOpAllowed: (op: SyncApplyOp) => target.ops.includes(op),\n authorize: () =>\n authenticated || target.publicAccess === true\n ? ('ok' as const)\n : ('auth_required' as const),\n prepare: (payload: Record<string, unknown>) =>\n applySyncWritablePolicy(payload, {\n readonlyFields: target.readonlyFields,\n writableAllowlist: target.writableAllowlist,\n }),\n };\n },\n });\n\n return json(outcome.body, { status: outcome.status });\n};\n`;\n}\n\n/**\n * Generate `{routesDir}/sync/apply/+server.ts` for the manifest's syncable\n * models. Returns true when a route was written. Skips generation (with a\n * warning) if a non-generated file already occupies the path, and writes\n * nothing when the manifest has no syncable models.\n */\nexport function generateSyncApplyRoute(\n projectRoot: string,\n manifest: SmartObjectManifest,\n options: SvelteKitOptions,\n): boolean {\n const targets = collectSyncApplyTargets(manifest);\n if (targets.length === 0) {\n return false;\n }\n\n const routeDir = join(projectRoot, options.routesDir, 'sync', 'apply');\n const routePath = join(routeDir, '+server.ts');\n\n if (existsSync(routePath)) {\n const existing = readFileSync(routePath, 'utf-8');\n if (!existing.startsWith(AUTO_GENERATED_ROUTE_HEADER)) {\n console.warn(\n `[smrt] Skipping sync-apply route - ${routePath} exists and is not generated`,\n );\n return false;\n }\n }\n\n if (!existsSync(routeDir)) {\n mkdirSync(routeDir, { recursive: true });\n }\n\n writeFileSync(\n routePath,\n generateSyncApplyRouteTemplate(\n targets,\n resolveSvelteKitConfigImport(projectRoot, routeDir, options),\n ),\n 'utf-8',\n );\n console.log(`[smrt] Generated: ${routePath}`);\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,mBAAmB;CAAC;CAAU;CAAU;AAAQ;AAsBtD,SAAS,mBAAmB,WAAsC;CAChE,IAAI,CAAC,aAAa,OAAO,cAAc,UACrC,OAAO;CAET,OAAO;AACT;;;;;;AAOA,SAAS,uBAAuB,WAAsC;CACpE,IAAI,cAAc,OAAO,OAAO,CAAC;CACjC,IACE,cAAc,QACd,cAAc,KAAA,KACd,OAAO,cAAc,UAErB,OAAO,CAAC,GAAG,gBAAgB;CAG7B,MAAM,SAAS;CACf,IAAI,UAA4B,MAAM,QAAQ,OAAO,OAAO,IACxD,iBAAiB,QAAQ,WAAW,OAAO,SAAS,SAAS,MAAM,CAAC,IACpE,CAAC,GAAG,gBAAgB;CACxB,IAAI,MAAM,QAAQ,OAAO,OAAO,GAAG;EACjC,MAAM,WAAW,OAAO;EACxB,UAAU,QAAQ,QAAQ,WAAW,CAAC,SAAS,SAAS,MAAM,CAAC;CACjE;CACA,OAAO;AACT;;AAGA,SAAS,mBAAmB,WAAsC;CAEhE,MAAM,QADS,mBAAmB,SACpB,CAAA,EAAQ;CACtB,IAAI,UAAU,QAAQ,UAAU,QAC9B,OAAO;CAET,OAAO;AACT;;AAGA,SAAS,0BAA0B,WAA4C;CAC7E,MAAM,SAAS,UAAU,UAAU,CAAC;CACpC,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,MAAM,GAAG;EAChD,MAAM,OAAQ,IAA4C;EAC1D,IACG,IAA+B,aAAa,QAC7C,MAAM,aAAa,MAEnB,MAAM,KAAK,IAAI;CAEnB;CACA,OAAO;AACT;;AAGA,SAAS,wBAAwB,WAAqC;CACpE,MAAM,SAAS,mBAAmB,SAAS;CAC3C,OAAO,MAAM,QAAQ,QAAQ,QAAQ,IAAI,OAAO,WAAW;AAC7D;;;;;AAMA,SAAgB,wBACd,UACkB;CAClB,MAAM,UAA4B,CAAC;CAEnC,KAAK,MAAM,CAAC,WAAW,cAAc,OAAO,QAAQ,SAAS,OAAO,GAAG;EACrE,IAAI,0BAA0B,UAAU,SAAS,GAAG;EAIpD,IAAI,qBAAqB,UAAU,WAAW,UAAU,WAAW,GACjE;EAGF,MAAM,YAAY,UAAU,iBAAiB;EAC7C,IAAI,cAAc,OAAO;EAEzB,MAAM,MAAM,uBAAuB,SAAS;EAC5C,IAAI,IAAI,WAAW,GAAG;EAEtB,IAAI,CAAC,UAAU,YAAY;EAE3B,QAAQ,KAAK;GACX,SAAS,UAAU;GACnB,aAAa;GACb;GACA,gBAAgB,0BAA0B,SAAS;GACnD,mBAAmB,wBAAwB,SAAS;GACpD,cAAc,mBAAmB,SAAS;GAC1C,cAAc,CAAC,CAAC,UAAU,iBAAiB;EAC7C,CAAC;CACH;CAEA,OAAO,QAAQ,MAAM,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;AAClE;AAEA,SAAS,iBAAiB,SAAmC;CAW3D,OAAO,MAVS,QAAQ,KAAK,WAAW;EACtC,MAAM,SAAS;GACb,gBAAgB,KAAK,UAAU,OAAO,WAAW;GACjD,QAAQ,KAAK,UAAU,OAAO,GAAG;GACjC,mBAAmB,KAAK,UAAU,OAAO,cAAc;GACvD,sBAAsB,KAAK,UAAU,OAAO,iBAAiB;GAC7D,iBAAiB,KAAK,UAAU,OAAO,YAAY;EACrD;EACA,OAAO,KAAK,KAAK,UAAU,OAAO,OAAO,EAAE,WAAW,OAAO,KAAK,SAAS,EAAE;CAC/E,CACa,CAAA,CAAQ,KAAK,IAAI,EAAE;AAClC;;;;;AAMA,SAAgB,+BACd,SACA,cACQ;CACR,MAAM,kBAAkB,QAAQ,MAAM,WAAW,OAAO,YAAY;CAoBpE,OAAO,GAAG,4BAA4B;;;;;;;;;;;;;;iCAcP,aAAa;;EAhCvB,kBACjB;;;;;;;;;;;;;;IAeA,GAkBS;;;;;;;;;;;;yDAY0C,iBAAiB,OAAO,EAAE;;;;;;;;;;;;;;;;;;EAkBjF,kBAAkB,wCAAwC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuC/D;;;;;;;AAQA,SAAgB,uBACd,aACA,UACA,SACS;CACT,MAAM,UAAU,wBAAwB,QAAQ;CAChD,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,WAAW,KAAK,aAAa,QAAQ,WAAW,QAAQ,OAAO;CACrE,MAAM,YAAY,KAAK,UAAU,YAAY;CAE7C,IAAI,WAAW,SAAS;MAElB,CADa,aAAa,WAAW,OACpC,CAAA,CAAS,WAAA,6CAAsC,GAAG;GACrD,QAAQ,KACN,sCAAsC,UAAU,6BAClD;GACA,OAAO;EACT;;CAGF,IAAI,CAAC,WAAW,QAAQ,GACtB,UAAU,UAAU,EAAE,WAAW,KAAK,CAAC;CAGzC,cACE,WACA,+BACE,SACA,6BAA6B,aAAa,UAAU,OAAO,CAC7D,GACA,OACF;CACA,QAAQ,IAAI,qBAAqB,WAAW;CAC5C,OAAO;AACT"}
1
+ {"version":3,"file":"sync-apply-route.js","names":[],"sources":["../../src/vite-plugin/sync-apply-route.ts"],"sourcesContent":["/**\n * SvelteKit generator for the sync-apply batch write route (#1759).\n *\n * Emits ONE route — `{routesDir}/sync/apply/+server.ts` — implementing the\n * shared web/mobile write contract for every syncable model in the manifest\n * (models whose API config exposes at least one of create/update/delete). The\n * generated file is deliberately thin: it maps `object` segments to\n * collections plus per-model policy data, and delegates all batch processing\n * to `processSyncApplyBatch` from `@happyvertical/smrt-core` — the same\n * engine the runtime REST generator uses, so the two transports cannot drift.\n *\n * This lives in its own module (rather than sveltekit-generator.ts) so the\n * shared generator file only needs a one-line registration hook; sibling\n * work (#1757, #1758) touches the same generator files in parallel.\n *\n * Contract documentation: docs/content/architecture/sync-apply-contract.md\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { isFrameworkBaseClass } from '../registry/framework-base-classes.js';\nimport type { ApiConfig } from '../registry/types.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types';\nimport { AUTO_GENERATED_ROUTE_HEADER } from './route-header.js';\nimport { resolveSvelteKitConfigImport } from './sveltekit-config-import.js';\nimport type { SvelteKitOptions } from './sveltekit-generator.js';\nimport { isCollectionManifestClass } from './web-collections.js';\n\nconst MUTATING_ACTIONS = ['create', 'update', 'delete'] as const;\n\ntype MutatingAction = (typeof MUTATING_ACTIONS)[number];\n\n/** Per-model data embedded into the generated route. */\ninterface SyncTargetSpec {\n segment: string;\n /**\n * The manifest registry key, passed VERBATIM to `getCollection()` exactly\n * as the generated CRUD routes do. May be package-qualified\n * (`@happyvertical/smrt-ledgers:Account`) — collapsing it to a simple class\n * name would resolve ambiguously when two loaded packages declare the same\n * simple name.\n */\n registryKey: string;\n /**\n * `<collection>` prefix of the `<collection>.<action>` operation permission\n * the mirrored generated write routes require (#2977) — the same\n * `decoratorConfig.collection ?? collection` resolution as\n * sveltekit-generator.ts `resolvePermissionCollection`.\n */\n permissionCollection: string;\n ops: MutatingAction[];\n readonlyFields: string[];\n writableAllowlist: string[] | null;\n publicAccess: boolean | 'read';\n tenantScoped: boolean;\n}\n\nfunction getApiConfigObject(apiConfig: unknown): ApiConfig | null {\n if (!apiConfig || typeof apiConfig !== 'object') {\n return null;\n }\n return apiConfig as ApiConfig;\n}\n\n/**\n * Mirror of sveltekit-generator.ts `resolveStandardCrudActions`, narrowed to\n * the mutating subset the sync contract can carry. Kept local so this module\n * needs no exports added to the (parallel-edited) shared generator file.\n */\nfunction resolveMutatingActions(apiConfig: unknown): MutatingAction[] {\n if (apiConfig === false) return [];\n if (\n apiConfig === true ||\n apiConfig === undefined ||\n typeof apiConfig !== 'object'\n ) {\n return [...MUTATING_ACTIONS];\n }\n\n const config = apiConfig as { include?: string[]; exclude?: string[] };\n let actions: MutatingAction[] = Array.isArray(config.include)\n ? MUTATING_ACTIONS.filter((action) => config.include?.includes(action))\n : [...MUTATING_ACTIONS];\n if (Array.isArray(config.exclude)) {\n const excluded = config.exclude;\n actions = actions.filter((action) => !excluded.includes(action));\n }\n return actions;\n}\n\n/** Mirror of sveltekit-generator.ts `getApiPublicAccess` (fail-closed). */\nfunction getApiPublicAccess(apiConfig: unknown): boolean | 'read' {\n const config = getApiConfigObject(apiConfig);\n const value = config?.public;\n if (value === true || value === 'read') {\n return value;\n }\n return false;\n}\n\n/** Mirror of sveltekit-generator.ts `collectReadonlyFieldNames` (#1540, 2b). */\nfunction collectReadonlyFieldNames(objectDef: SmartObjectDefinition): string[] {\n const fields = objectDef.fields || {};\n const names: string[] = [];\n for (const [name, def] of Object.entries(fields)) {\n const meta = (def as { _meta?: Record<string, unknown> })._meta;\n if (\n (def as { readonly?: boolean }).readonly === true ||\n meta?.readonly === true\n ) {\n names.push(name);\n }\n }\n return names;\n}\n\n/** Mirror of sveltekit-generator.ts `getApiWritableAllowlist`. */\nfunction getApiWritableAllowlist(apiConfig: unknown): string[] | null {\n const config = getApiConfigObject(apiConfig);\n return Array.isArray(config?.writable) ? config.writable : null;\n}\n\n/** Mirror of sveltekit-generator.ts `resolvePermissionCollection` (#2977). */\nfunction resolvePermissionCollection(objectDef: SmartObjectDefinition): string {\n const configured = (\n objectDef.decoratorConfig as { collection?: unknown } | undefined\n )?.collection;\n return typeof configured === 'string' && configured.length > 0\n ? configured\n : objectDef.collection;\n}\n\n/**\n * Collect the syncable targets from a manifest: non-collection objects whose\n * API config is enabled and exposes at least one mutating action.\n */\nexport function collectSyncApplyTargets(\n manifest: SmartObjectManifest,\n): SyncTargetSpec[] {\n const targets: SyncTargetSpec[] = [];\n\n for (const [className, objectDef] of Object.entries(manifest.objects)) {\n if (isCollectionManifestClass(manifest, objectDef)) continue;\n // The framework's own abstract base classes are scaffolding, not\n // resources — never make them a sync-apply target, regardless of\n // config (#2642).\n if (isFrameworkBaseClass(objectDef.className, objectDef.packageName)) {\n continue;\n }\n\n const apiConfig = objectDef.decoratorConfig?.api;\n if (apiConfig === false) continue;\n\n const ops = resolveMutatingActions(apiConfig);\n if (ops.length === 0) continue;\n\n if (!objectDef.collection) continue;\n\n targets.push({\n segment: objectDef.collection,\n registryKey: className,\n permissionCollection: resolvePermissionCollection(objectDef),\n ops,\n readonlyFields: collectReadonlyFieldNames(objectDef),\n writableAllowlist: getApiWritableAllowlist(apiConfig),\n publicAccess: getApiPublicAccess(apiConfig),\n tenantScoped: !!objectDef.decoratorConfig?.tenantScoped,\n });\n }\n\n return targets.sort((a, b) => a.segment.localeCompare(b.segment));\n}\n\nfunction serializeTargets(targets: SyncTargetSpec[]): string {\n const entries = targets.map((target) => {\n const fields = [\n `registryKey: ${JSON.stringify(target.registryKey)}`,\n `permissionCollection: ${JSON.stringify(target.permissionCollection)}`,\n `ops: ${JSON.stringify(target.ops)}`,\n `readonlyFields: ${JSON.stringify(target.readonlyFields)}`,\n `writableAllowlist: ${JSON.stringify(target.writableAllowlist)}`,\n `publicAccess: ${JSON.stringify(target.publicAccess)}`,\n ];\n return ` ${JSON.stringify(target.segment)}: {\\n ${fields.join(',\\n ')},\\n },`;\n });\n return `{\\n${entries.join('\\n')}\\n}`;\n}\n\n/**\n * Render the generated `+server.ts` content for the sync-apply route.\n * Exported for tests.\n */\nexport function generateSyncApplyRouteTemplate(\n targets: SyncTargetSpec[],\n configImport: string,\n): string {\n const anyTenantScoped = targets.some((target) => target.tenantScoped);\n\n const tenantHelper = anyTenantScoped\n ? `\nimport { enterTenantContext, hasTenantContext } from '@happyvertical/smrt-tenancy';\n\nfunction establishTenantContext(locals: unknown): void {\n if (hasTenantContext()) return;\n if (!locals || typeof locals !== 'object') return;\n const l = locals as Record<string, unknown>;\n const user = l.user as Record<string, unknown> | undefined;\n const session = l.session as Record<string, unknown> | undefined;\n const tenantId = l.tenantId ?? user?.tenantId ?? session?.tenantId;\n if (typeof tenantId === 'string' && tenantId) {\n enterTenantContext({ tenantId });\n }\n}\n`\n : '';\n\n return `${AUTO_GENERATED_ROUTE_HEADER}\n// DO NOT EDIT - changes will be overwritten\n//\n// Idempotent sync-apply batch write contract (#1759) — the shared write path\n// for the web offline outbox (#1762) and the KMP mobile write queue (#1739).\n// Contract: docs/content/architecture/sync-apply-contract.md\n\nimport {\n applySyncWritablePolicy,\n processSyncApplyBatch,\n type SyncApplyOp,\n type SyncApplyTarget,\n} from '@happyvertical/smrt-core';\nimport { json } from '@sveltejs/kit';\nimport { getCollection } from '${configImport}';\nimport type { RequestHandler } from './$types';\n${tenantHelper}\ninterface SyncTargetConfig {\n /** Manifest registry key (may be package-qualified), as CRUD routes use. */\n registryKey: string;\n /** \\`<collection>\\` prefix of the required \\`<collection>.<op>\\` permission. */\n permissionCollection: string;\n ops: SyncApplyOp[];\n readonlyFields: string[];\n writableAllowlist: string[] | null;\n publicAccess: boolean | 'read';\n}\n\n// One entry per syncable model, keyed by the collection route segment its\n// generated CRUD routes use.\nconst SYNC_TARGETS: Record<string, SyncTargetConfig> = ${serializeTargets(targets)};\n\n// Fail-closed authorization (#1540): sync mutations require an authenticated\n// principal on \\`locals\\` unless the target model is \\`api: { public: true }\\`.\nfunction hasAuthenticatedPrincipal(locals: unknown): boolean {\n if (!locals || typeof locals !== 'object') return false;\n const l = locals as Record<string, unknown>;\n const isResolvedPrincipal = (v: unknown) =>\n typeof v === 'object' && v !== null;\n return (\n isResolvedPrincipal(l.user) ||\n isResolvedPrincipal(l.session) ||\n l.smrtAuth === true\n );\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object'\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction hasGrantedPermission(value: unknown, permission: string): boolean {\n if (Array.isArray(value)) return value.includes(permission);\n if (value instanceof Set) return value.has(permission);\n return false;\n}\n\n// Fail-closed operation permission (#2977, #3011): each applied op requires\n// the same \\`<collection>.<op>\\` permission the mirrored generated write route\n// enforces, read from the principal's session permission snapshot. A missing\n// snapshot denies; only an explicit tenancy super-admin bypass skips it.\nfunction hasOperationPermission(\n locals: unknown,\n permissionCollection: string,\n op: SyncApplyOp,\n): boolean {\n const l = readRecord(locals);\n const tenantContext = readRecord(l.tenantContext);\n if (tenantContext.superAdminBypass === true) return true;\n const permission = \\`\\${permissionCollection}.\\${op}\\`;\n return (\n hasGrantedPermission(l.permissions, permission) ||\n hasGrantedPermission(l.permissionSet, permission) ||\n hasGrantedPermission(l.smrtPermissions, permission) ||\n hasGrantedPermission(tenantContext.permissions, permission)\n );\n}\n\nexport const POST: RequestHandler = async ({ locals, request }) => {\n const authenticated = hasAuthenticatedPrincipal(locals);\n${anyTenantScoped ? ' establishTenantContext(locals);\\n' : ''}\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return json(\n { error: { code: 'invalid_batch', message: 'Invalid JSON body' } },\n { status: 400 },\n );\n }\n\n const outcome = await processSyncApplyBatch(body, {\n resolveTarget: async (segment: string): Promise<SyncApplyTarget | null> => {\n const target = SYNC_TARGETS[segment];\n if (!target) return null;\n // The verbatim manifest key, exactly as the generated CRUD routes pass\n // it — package-qualified keys stay qualified so same-simple-name\n // classes across packages resolve unambiguously.\n const collection = await getCollection(target.registryKey);\n return {\n objectName: target.registryKey,\n collection,\n isOpAllowed: (op: SyncApplyOp) => target.ops.includes(op),\n authorize: (op: SyncApplyOp) => {\n // \\`public: true\\` keeps its unauthenticated write semantics, as on\n // the generated CRUD routes.\n if (target.publicAccess === true) return 'ok' as const;\n if (!authenticated) return 'auth_required' as const;\n return hasOperationPermission(locals, target.permissionCollection, op)\n ? ('ok' as const)\n : ('forbidden' as const);\n },\n prepare: (payload: Record<string, unknown>) =>\n applySyncWritablePolicy(payload, {\n readonlyFields: target.readonlyFields,\n writableAllowlist: target.writableAllowlist,\n }),\n };\n },\n });\n\n return json(outcome.body, { status: outcome.status });\n};\n`;\n}\n\n/**\n * Generate `{routesDir}/sync/apply/+server.ts` for the manifest's syncable\n * models. Returns true when a route was written. Skips generation (with a\n * warning) if a non-generated file already occupies the path, and writes\n * nothing when the manifest has no syncable models.\n */\nexport function generateSyncApplyRoute(\n projectRoot: string,\n manifest: SmartObjectManifest,\n options: SvelteKitOptions,\n): boolean {\n const targets = collectSyncApplyTargets(manifest);\n if (targets.length === 0) {\n return false;\n }\n\n const routeDir = join(projectRoot, options.routesDir, 'sync', 'apply');\n const routePath = join(routeDir, '+server.ts');\n\n if (existsSync(routePath)) {\n const existing = readFileSync(routePath, 'utf-8');\n if (!existing.startsWith(AUTO_GENERATED_ROUTE_HEADER)) {\n console.warn(\n `[smrt] Skipping sync-apply route - ${routePath} exists and is not generated`,\n );\n return false;\n }\n }\n\n if (!existsSync(routeDir)) {\n mkdirSync(routeDir, { recursive: true });\n }\n\n writeFileSync(\n routePath,\n generateSyncApplyRouteTemplate(\n targets,\n resolveSvelteKitConfigImport(projectRoot, routeDir, options),\n ),\n 'utf-8',\n );\n console.log(`[smrt] Generated: ${routePath}`);\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,mBAAmB;CAAC;CAAU;CAAU;AAAQ;AA6BtD,SAAS,mBAAmB,WAAsC;CAChE,IAAI,CAAC,aAAa,OAAO,cAAc,UACrC,OAAO;CAET,OAAO;AACT;;;;;;AAOA,SAAS,uBAAuB,WAAsC;CACpE,IAAI,cAAc,OAAO,OAAO,CAAC;CACjC,IACE,cAAc,QACd,cAAc,KAAA,KACd,OAAO,cAAc,UAErB,OAAO,CAAC,GAAG,gBAAgB;CAG7B,MAAM,SAAS;CACf,IAAI,UAA4B,MAAM,QAAQ,OAAO,OAAO,IACxD,iBAAiB,QAAQ,WAAW,OAAO,SAAS,SAAS,MAAM,CAAC,IACpE,CAAC,GAAG,gBAAgB;CACxB,IAAI,MAAM,QAAQ,OAAO,OAAO,GAAG;EACjC,MAAM,WAAW,OAAO;EACxB,UAAU,QAAQ,QAAQ,WAAW,CAAC,SAAS,SAAS,MAAM,CAAC;CACjE;CACA,OAAO;AACT;;AAGA,SAAS,mBAAmB,WAAsC;CAEhE,MAAM,QADS,mBAAmB,SACpB,CAAA,EAAQ;CACtB,IAAI,UAAU,QAAQ,UAAU,QAC9B,OAAO;CAET,OAAO;AACT;;AAGA,SAAS,0BAA0B,WAA4C;CAC7E,MAAM,SAAS,UAAU,UAAU,CAAC;CACpC,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,MAAM,GAAG;EAChD,MAAM,OAAQ,IAA4C;EAC1D,IACG,IAA+B,aAAa,QAC7C,MAAM,aAAa,MAEnB,MAAM,KAAK,IAAI;CAEnB;CACA,OAAO;AACT;;AAGA,SAAS,wBAAwB,WAAqC;CACpE,MAAM,SAAS,mBAAmB,SAAS;CAC3C,OAAO,MAAM,QAAQ,QAAQ,QAAQ,IAAI,OAAO,WAAW;AAC7D;;AAGA,SAAS,4BAA4B,WAA0C;CAC7E,MAAM,aACJ,UAAU,iBACT;CACH,OAAO,OAAO,eAAe,YAAY,WAAW,SAAS,IACzD,aACA,UAAU;AAChB;;;;;AAMA,SAAgB,wBACd,UACkB;CAClB,MAAM,UAA4B,CAAC;CAEnC,KAAK,MAAM,CAAC,WAAW,cAAc,OAAO,QAAQ,SAAS,OAAO,GAAG;EACrE,IAAI,0BAA0B,UAAU,SAAS,GAAG;EAIpD,IAAI,qBAAqB,UAAU,WAAW,UAAU,WAAW,GACjE;EAGF,MAAM,YAAY,UAAU,iBAAiB;EAC7C,IAAI,cAAc,OAAO;EAEzB,MAAM,MAAM,uBAAuB,SAAS;EAC5C,IAAI,IAAI,WAAW,GAAG;EAEtB,IAAI,CAAC,UAAU,YAAY;EAE3B,QAAQ,KAAK;GACX,SAAS,UAAU;GACnB,aAAa;GACb,sBAAsB,4BAA4B,SAAS;GAC3D;GACA,gBAAgB,0BAA0B,SAAS;GACnD,mBAAmB,wBAAwB,SAAS;GACpD,cAAc,mBAAmB,SAAS;GAC1C,cAAc,CAAC,CAAC,UAAU,iBAAiB;EAC7C,CAAC;CACH;CAEA,OAAO,QAAQ,MAAM,GAAG,MAAM,EAAE,QAAQ,cAAc,EAAE,OAAO,CAAC;AAClE;AAEA,SAAS,iBAAiB,SAAmC;CAY3D,OAAO,MAXS,QAAQ,KAAK,WAAW;EACtC,MAAM,SAAS;GACb,gBAAgB,KAAK,UAAU,OAAO,WAAW;GACjD,yBAAyB,KAAK,UAAU,OAAO,oBAAoB;GACnE,QAAQ,KAAK,UAAU,OAAO,GAAG;GACjC,mBAAmB,KAAK,UAAU,OAAO,cAAc;GACvD,sBAAsB,KAAK,UAAU,OAAO,iBAAiB;GAC7D,iBAAiB,KAAK,UAAU,OAAO,YAAY;EACrD;EACA,OAAO,KAAK,KAAK,UAAU,OAAO,OAAO,EAAE,WAAW,OAAO,KAAK,SAAS,EAAE;CAC/E,CACa,CAAA,CAAQ,KAAK,IAAI,EAAE;AAClC;;;;;AAMA,SAAgB,+BACd,SACA,cACQ;CACR,MAAM,kBAAkB,QAAQ,MAAM,WAAW,OAAO,YAAY;CAoBpE,OAAO,GAAG,4BAA4B;;;;;;;;;;;;;;iCAcP,aAAa;;EAhCvB,kBACjB;;;;;;;;;;;;;;IAeA,GAkBS;;;;;;;;;;;;;;yDAc0C,iBAAiB,OAAO,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmDjF,kBAAkB,wCAAwC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4C/D;;;;;;;AAQA,SAAgB,uBACd,aACA,UACA,SACS;CACT,MAAM,UAAU,wBAAwB,QAAQ;CAChD,IAAI,QAAQ,WAAW,GACrB,OAAO;CAGT,MAAM,WAAW,KAAK,aAAa,QAAQ,WAAW,QAAQ,OAAO;CACrE,MAAM,YAAY,KAAK,UAAU,YAAY;CAE7C,IAAI,WAAW,SAAS;MAElB,CADa,aAAa,WAAW,OACpC,CAAA,CAAS,WAAA,6CAAsC,GAAG;GACrD,QAAQ,KACN,sCAAsC,UAAU,6BAClD;GACA,OAAO;EACT;;CAGF,IAAI,CAAC,WAAW,QAAQ,GACtB,UAAU,UAAU,EAAE,WAAW,KAAK,CAAC;CAGzC,cACE,WACA,+BACE,SACA,6BAA6B,aAAa,UAAU,OAAO,CAC7D,GACA,OACF;CACA,QAAQ,IAAI,qBAAqB,WAAW;CAC5C,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-core",
3
- "version": "0.51.11",
3
+ "version": "0.51.14",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -150,26 +150,26 @@
150
150
  }
151
151
  },
152
152
  "dependencies": {
153
- "@happyvertical/ai": "^0.89.11",
154
- "@happyvertical/files": "^0.89.11",
155
- "@happyvertical/json": "^0.89.11",
156
- "@happyvertical/logger": "^0.89.11",
157
- "@happyvertical/smrt-config": "0.51.11",
158
- "@happyvertical/smrt-scanner": "0.51.11",
159
- "@happyvertical/smrt-types": "0.51.11",
160
- "@happyvertical/sql": "^0.89.11",
161
- "@happyvertical/utils": "^0.89.11",
162
- "@oxc-project/runtime": "^0.138.0",
153
+ "@happyvertical/ai": "^0.89.12",
154
+ "@happyvertical/files": "^0.89.12",
155
+ "@happyvertical/json": "^0.89.12",
156
+ "@happyvertical/logger": "^0.89.12",
157
+ "@happyvertical/smrt-config": "0.51.14",
158
+ "@happyvertical/smrt-scanner": "0.51.14",
159
+ "@happyvertical/smrt-types": "0.51.14",
160
+ "@happyvertical/sql": "^0.89.12",
161
+ "@happyvertical/utils": "^0.89.12",
162
+ "@oxc-project/runtime": "^0.150.0",
163
163
  "cheerio": "^1.2.0",
164
164
  "fast-glob": "3.3.3",
165
- "minimatch": "10.2.5",
166
- "oxc-transform": "0.138.0",
165
+ "minimatch": "10.2.6",
166
+ "oxc-transform": "0.150.0",
167
167
  "pluralize": "^8.0.0",
168
- "tsx": "^4.23.0",
169
- "yaml": "^2.9.0"
168
+ "tsx": "^4.23.13",
169
+ "yaml": "^2.9.1"
170
170
  },
171
171
  "peerDependencies": {
172
- "@huggingface/transformers": ">=3.0.0 <4.0.0",
172
+ "@huggingface/transformers": ">=3.0.0 <5.0.0",
173
173
  "@xenova/transformers": "^2.17.2"
174
174
  },
175
175
  "peerDependenciesMeta": {
@@ -181,18 +181,18 @@
181
181
  }
182
182
  },
183
183
  "devDependencies": {
184
- "@faker-js/faker": "^10.5.0",
185
- "@huggingface/transformers": "^3.8.1",
186
- "@sveltejs/kit": "^2.69.3",
187
- "@sveltejs/vite-plugin-svelte": "^7.1.2",
188
- "@types/node": "24.13.2",
184
+ "@faker-js/faker": "^10.6.0",
185
+ "@huggingface/transformers": "^4.3.0",
186
+ "@sveltejs/kit": "2.69.3",
187
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
188
+ "@types/node": "24.13.6",
189
189
  "@types/pluralize": "^0.0.33",
190
190
  "@xenova/transformers": "^2.17.2",
191
- "svelte": "^5.56.4",
191
+ "svelte": "^5.57.1",
192
192
  "svelte-check": "4.7.6",
193
193
  "typescript": "5.9.3",
194
194
  "vite": "8.1.4",
195
- "vite-plugin-dts": "4.5.4",
195
+ "vite-plugin-dts": "5.1.0",
196
196
  "vitest": "4.1.10"
197
197
  },
198
198
  "publishConfig": {