@happyvertical/smrt-core 0.47.2 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/agents/generators.md +12 -0
  2. package/agents/object-runtime.md +7 -0
  3. package/agents/schema-paths.md +62 -0
  4. package/agents/system-diagnostics.md +6 -1
  5. package/dist/cascade.d.ts.map +1 -1
  6. package/dist/cascade.js +9 -6
  7. package/dist/cascade.js.map +1 -1
  8. package/dist/collection.d.ts +0 -1
  9. package/dist/collection.d.ts.map +1 -1
  10. package/dist/collection.js +35 -45
  11. package/dist/collection.js.map +1 -1
  12. package/dist/decorators/compatibility.d.ts +1 -1
  13. package/dist/decorators/compatibility.d.ts.map +1 -1
  14. package/dist/decorators/compatibility.js +2 -2
  15. package/dist/decorators/compatibility.js.map +1 -1
  16. package/dist/decorators/index.d.ts.map +1 -1
  17. package/dist/decorators/index.js +33 -24
  18. package/dist/decorators/index.js.map +1 -1
  19. package/dist/interceptors.d.ts +3 -1
  20. package/dist/interceptors.d.ts.map +1 -1
  21. package/dist/interceptors.js +3 -2
  22. package/dist/interceptors.js.map +1 -1
  23. package/dist/manifest/static-manifest.js +1 -1
  24. package/dist/manifest/static-manifest.js.map +1 -1
  25. package/dist/manifest/store.js +1 -1
  26. package/dist/manifest.json +1 -1
  27. package/dist/migrations/differ.d.ts +10 -4
  28. package/dist/migrations/differ.d.ts.map +1 -1
  29. package/dist/migrations/differ.js +173 -5
  30. package/dist/migrations/differ.js.map +1 -1
  31. package/dist/object.d.ts +1 -5
  32. package/dist/object.d.ts.map +1 -1
  33. package/dist/object.js +28 -37
  34. package/dist/object.js.map +1 -1
  35. package/dist/registry/class-registration.d.ts +2 -1
  36. package/dist/registry/class-registration.d.ts.map +1 -1
  37. package/dist/registry/class-registration.js +47 -16
  38. package/dist/registry/class-registration.js.map +1 -1
  39. package/dist/registry/name-resolver.d.ts.map +1 -1
  40. package/dist/registry/name-resolver.js +3 -3
  41. package/dist/registry/name-resolver.js.map +1 -1
  42. package/dist/registry/relationship-graph.d.ts +2 -0
  43. package/dist/registry/relationship-graph.d.ts.map +1 -1
  44. package/dist/registry/relationship-graph.js +60 -5
  45. package/dist/registry/relationship-graph.js.map +1 -1
  46. package/dist/registry/schema-builder.d.ts.map +1 -1
  47. package/dist/registry/schema-builder.js +4 -1
  48. package/dist/registry/schema-builder.js.map +1 -1
  49. package/dist/registry/shared-state.d.ts +18 -0
  50. package/dist/registry/shared-state.d.ts.map +1 -1
  51. package/dist/registry/shared-state.js +25 -1
  52. package/dist/registry/shared-state.js.map +1 -1
  53. package/dist/registry/types.d.ts +8 -0
  54. package/dist/registry/types.d.ts.map +1 -1
  55. package/dist/registry.d.ts +32 -5
  56. package/dist/registry.d.ts.map +1 -1
  57. package/dist/registry.js +120 -12
  58. package/dist/registry.js.map +1 -1
  59. package/dist/relationship-loader.d.ts +6 -0
  60. package/dist/relationship-loader.d.ts.map +1 -0
  61. package/dist/relationship-loader.js +35 -0
  62. package/dist/relationship-loader.js.map +1 -0
  63. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  64. package/dist/scanner/manifest-generator.js +6 -3
  65. package/dist/scanner/manifest-generator.js.map +1 -1
  66. package/dist/schema/foreign-key-ddl.d.ts +8 -0
  67. package/dist/schema/foreign-key-ddl.d.ts.map +1 -1
  68. package/dist/schema/foreign-key-ddl.js +12 -1
  69. package/dist/schema/foreign-key-ddl.js.map +1 -1
  70. package/dist/schema/foreign-key-orphan-report.d.ts.map +1 -1
  71. package/dist/schema/foreign-key-orphan-report.js +18 -1
  72. package/dist/schema/foreign-key-orphan-report.js.map +1 -1
  73. package/dist/schema/generator.d.ts +2 -0
  74. package/dist/schema/generator.d.ts.map +1 -1
  75. package/dist/schema/generator.js +16 -9
  76. package/dist/schema/generator.js.map +1 -1
  77. package/dist/schema/index.d.ts +1 -1
  78. package/dist/schema/index.d.ts.map +1 -1
  79. package/dist/schema/index.js +2 -2
  80. package/dist/schema/live-parity.d.ts.map +1 -1
  81. package/dist/schema/live-parity.js +74 -0
  82. package/dist/schema/live-parity.js.map +1 -1
  83. package/dist/schema/text-cast-probe.d.ts +66 -0
  84. package/dist/schema/text-cast-probe.d.ts.map +1 -0
  85. package/dist/schema/text-cast-probe.js +142 -0
  86. package/dist/schema/text-cast-probe.js.map +1 -0
  87. package/dist/schema/types.d.ts +28 -0
  88. package/dist/schema/types.d.ts.map +1 -1
  89. package/dist/schema/utils.d.ts.map +1 -1
  90. package/dist/schema/utils.js +2 -1
  91. package/dist/schema/utils.js.map +1 -1
  92. package/dist/schema.js +2 -2
  93. package/dist/smrt-knowledge.json +11 -11
  94. package/dist/system/diagnostics.d.ts +22 -0
  95. package/dist/system/diagnostics.d.ts.map +1 -1
  96. package/dist/system/diagnostics.js +88 -31
  97. package/dist/system/diagnostics.js.map +1 -1
  98. package/dist/test-utils.d.ts.map +1 -1
  99. package/dist/utils.d.ts.map +1 -1
  100. package/dist/utils.js +2 -1
  101. package/dist/utils.js.map +1 -1
  102. package/dist/vite-plugin/dev-plane-route.d.ts +5 -0
  103. package/dist/vite-plugin/dev-plane-route.d.ts.map +1 -0
  104. package/dist/vite-plugin/dev-plane-route.js +91 -0
  105. package/dist/vite-plugin/dev-plane-route.js.map +1 -0
  106. package/dist/vite-plugin/sveltekit-generator.d.ts +8 -0
  107. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  108. package/dist/vite-plugin/sveltekit-generator.js +2 -0
  109. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  110. package/package.json +4 -4
@@ -3,25 +3,25 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.47.2",
6
+ "packageVersion": "0.49.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "42b40570c0382a6b246b5137d3fb1c343d24a3671307c6cf4bf8ed3d831c8648",
11
- "packageJson": "272a6a14d8eb238d968214d63acfd64d519cafeb8f7b89809008b8ffe688d984",
10
+ "manifest": "128cec3432bf87a0f0408807841fea0b5810b517144b1bf46ba30340f57e7a72",
11
+ "packageJson": "9568074afc450daff1d40a888e494f2076b1ead06edecfb04cce086e3b03b957",
12
12
  "agents": "6c19f8eab9fbcd9c10d0649279f93c8c36c65c18da3402f2a2b49893432125ec",
13
- "moduleDoc:agents/object-runtime.md": "4b6cc7930b071cf3310732f382fa06492d5eec3720fec24092ae21c207d91bfb",
13
+ "moduleDoc:agents/object-runtime.md": "d05a7143de083f3c2eadf586f915dc8365f5be991295d908fcf01e2926336bcb",
14
14
  "moduleDoc:agents/revision-guard.md": "aa6b1ddb5b6b49fa27ebbe575ec7fcd6d5ceb35ee25acc702f877a226eb9a99a",
15
15
  "moduleDoc:agents/collection-reads.md": "4ce06e8b70b9ce9b77b47b3e2ed266c899bb7962ca015d4714f07a4aca10a865",
16
16
  "moduleDoc:agents/query-bounds.md": "3a0601ddaf2bea4e90e3f22e16a2eb3508a6fb8c019e3fb2c1f930c90a377cd5",
17
17
  "moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
18
- "moduleDoc:agents/schema-paths.md": "1fa13f6bccf6d4c820969caeaa2a76318ac79ac6963555d6d61323d4425774f7",
18
+ "moduleDoc:agents/schema-paths.md": "8f9041378ba6c3f4f75d51179a7103167ff985187c64da61d077a97b08e39dfc",
19
19
  "moduleDoc:agents/change-feed.md": "c5921f2536c5f092690cc9ce5dcdf906376a34413d3c10613be6287c11f87f86",
20
20
  "moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
21
- "moduleDoc:agents/generators.md": "f8eee7c4da45c08939227dc9c14985806bf28b26ae82822b8cab776dd9b5edc0",
21
+ "moduleDoc:agents/generators.md": "280b1889a94eb2b8e0c787e3b98bacbec7901df4bea5ddf363c31ceaa750182a",
22
22
  "moduleDoc:agents/build-knowledge.md": "5e67560801f22ccb1413a512452bcc5d29fafed9b4411561b8c8d9095eba50f3",
23
23
  "moduleDoc:agents/memory.md": "49334471e7a64199bb936756f3a2690ecdd9cff45f677557ea04e7c4b7c78559",
24
- "moduleDoc:agents/system-diagnostics.md": "3685bd381ac31eefe11be221e20125481d637bec70e217f79a9ad092e236b65a",
24
+ "moduleDoc:agents/system-diagnostics.md": "b7ccae18ee312bf788d5470f95fa78d3535f1789247d5372e40ca86538290772",
25
25
  "moduleDoc:agents/registry-snapshot.md": "6234aa540427396d1dda1825a4641b1072e247187d5ddf413ae46c691344ee30"
26
26
  },
27
27
  "exports": [
@@ -988,7 +988,7 @@
988
988
  {
989
989
  "path": "agents/object-runtime.md",
990
990
  "module": "object-runtime",
991
- "content": "# Object and collection runtime\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws\n `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or\n delete to an earlier snapshot. Remote guarded deletes bind the same predicate\n into the final `DELETE`; embedded adapters compare inside the shared write queue\n before cascading. That queue serializes same-process saves, deletes, and full\n `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this\n public CAS ordering contract. PostgreSQL predicate:\n [revision-guard.md](revision-guard.md).\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\n\n## SmrtCollection Query\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [collection-reads.md](collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\n`convertWhereKeys` must accept only operators executable by the SQL builder.\n`contains` and dot-notation JSON paths reject at the boundary; use `like` with\nexplicit wildcards. Adding operators requires SQL support first.\n`src/__tests__/issue-2276-where-contract.test.ts` executes the accepted set.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [query-bounds.md](query-bounds.md).\n\n\n## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n"
991
+ "content": "# Object and collection runtime\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws\n `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or\n delete to an earlier snapshot. Remote guarded deletes bind the same predicate\n into the final `DELETE`; embedded adapters compare inside the shared write queue\n before cascading. That queue serializes same-process saves, deletes, and full\n `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this\n public CAS ordering contract. PostgreSQL predicate:\n [revision-guard.md](revision-guard.md).\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\nRelationship I/O resolves canonical source and target identities, not the public\ndisplay names. `relationship-loader.ts` owns target manifest hydration and inverse\nselection for lazy, eager, junction and latest-related reads. An unresolved exact\nconstructor or ambiguous target fails before querying or caching a foreign peer;\nlegacy external string targets retain manifest discovery. Junction column naming\nconventions still use display names. Cached reads retain their tenant rechecks.\n\n\n## SmrtCollection Query\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [collection-reads.md](collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\n`convertWhereKeys` must accept only operators executable by the SQL builder.\n`contains` and dot-notation JSON paths reject at the boundary; use `like` with\nexplicit wildcards. Adding operators requires SQL support first.\n`src/__tests__/issue-2276-where-contract.test.ts` executes the accepted set.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [query-bounds.md](query-bounds.md).\n\n\n## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n"
992
992
  },
993
993
  {
994
994
  "path": "agents/revision-guard.md",
@@ -1013,7 +1013,7 @@
1013
1013
  {
1014
1014
  "path": "agents/schema-paths.md",
1015
1015
  "module": "schema-paths",
1016
- "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** dedup through SDK null-aware upsert (PostgreSQL\n `IS NOT DISTINCT FROM` plus advisory lock; SQLite process lock), not the\n unique index: raw SQL can duplicate NULL-tenant keys. Raw global inserts need\n `WHERE NOT EXISTS` and a PostgreSQL advisory lock; an old global `ON CONFLICT`\n target no longer binds. Save serializes an unset tenant explicitly as NULL,\n because every conflict column must be present. PostgreSQL `NULLS NOT DISTINCT`\n remains a potential follow-up, not current enforcement.\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.\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### 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"
1016
+ "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** dedup through SDK null-aware upsert (PostgreSQL\n `IS NOT DISTINCT FROM` plus advisory lock; SQLite process lock), not the\n unique index: raw SQL can duplicate NULL-tenant keys. Raw global inserts need\n `WHERE NOT EXISTS` and a PostgreSQL advisory lock; an old global `ON CONFLICT`\n target no longer binds. Save serializes an unset tenant explicitly as NULL,\n because every conflict column must be present. PostgreSQL `NULLS NOT DISTINCT`\n remains a potential follow-up, not current enforcement.\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"
1017
1017
  },
1018
1018
  {
1019
1019
  "path": "agents/change-feed.md",
@@ -1028,7 +1028,7 @@
1028
1028
  {
1029
1029
  "path": "agents/generators.md",
1030
1030
  "module": "generators",
1031
- "content": "# smrt-core/code generators\n\nModule semantics for `src/generators/` + `src/vite-plugin/`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Code Generators\n\n| Generator | Location | Output |\n|-----------|----------|--------|\n| REST API | `src/generators/rest.ts` | OpenAPI-compliant CRUD endpoints |\n| MCP Server | `src/generators/mcp.ts` | Model Context Protocol tools |\n| Web collections | `src/vite-plugin/web-collections.ts` (selectors) + `generateWebModule` | `@happyvertical/smrt-virt-web` — one typed collection definition per API-exposed REST collection (#1761), consumed by `@happyvertical/smrt-web` |\n\nThe same web virtual module exports `webMcpToolDefinitions` (#2518), a\ncanonical per-tool array selected independently of list materialization. Every\nnon-empty canonical API action set contributes tools, so get-only and\ncustom-action-only models are discoverable; custom actions declared on a\n`SmrtCollection` merge into the owning row collection. Each definition carries\ncomplete route and invalidation metadata. `collectionDefinitions` and its\nembedded descriptor copy remain unchanged for existing cache-backed consumers.\n\nGenerated API clients share `selectApiClientEntries()` across the runtime Vite\nmodule, its ambient declaration, and physical prebuild declarations. When a\ncollection class and its populated model share an endpoint, the model owns the\ncanonical collection key and row payload schema; the collection class remains\navailable under a deterministic class-derived secondary key. Selection and\ncollision suffixes must not depend on manifest insertion order (#2027).\nFor aggregated manifests, inheritance and item-type references resolve exact\nqualified names first, then package-local simple names, then a stable identity\nfallback so duplicate class names across packages cannot reintroduce ordering.\n\nThe web module also emits a build-time **`manifestHash`** constant (#1764): `computeWebManifestHash(manifest)` is a deterministic, replica-stable digest of the emitted web-collection SHAPE (name/className/endpoint/idField/actions/fields/relationships), canonicalized (recursive key sort) before `sha256 → base64url`, truncated to 16 chars — so the same schema always hashes the same, and a field add/remove/type-change/edge-change changes it. A change means old persisted client rows may mis-hydrate, so smrt-web keys its durable persistence namespace on it and its `updateAvailable` contract signal compares against it. Four co-managed emission sites must not drift: the runtime value (`generateWebModule`), the `@happyvertical/smrt-virt-web` ambient d.ts (`vite-plugin/index.ts`), the physical `@smrt/web` d.ts (`prebuild/index.ts`), and the hand-written type mirror in `@happyvertical/smrt-web` (`packages/smrt-web/src/index.ts` — dependency-free, so textual sync only).\n\n`webMcpToolDefinitions` is deliberately outside that digest: tool-only route,\nidentifier, or annotation changes cannot alter persisted row hydration.\n\nPer-field web emission (#2046): `buildWebFieldDefinitions` carries `description` (from `@field({ description })`) and sanitized `ui` hints (from `@field({ ui: { basic, group, order, locked } })`, read off the manifest `_meta.ui` bag through per-key type guards) into each emitted field definition, and `buildWebToolDescriptors` threads the same `description` into browser MCP tool schemas. `sensitive`/`transient` fields are excluded from emission entirely, so their descriptions never ship. Both keys are conditional, so hint-less schemas emit byte-identical definitions (and hashes) as before; adding a description/ui hint changes the manifest hash — deliberate over-invalidation, harmless per the #1764 contract.\n\n## Generated MCP server output language\n\n`MCPGenerator` builds every file as TypeScript, so the requested `outputPath`\nextension decides what is written (#2279). `.ts`/`.mts` targets keep the source\nverbatim for `tsx` or Node type stripping — which is why the generated source\nmust stay erasable-syntax-only (no parameter properties, enums, or namespaces).\nEvery other target (`.smrt/mcp-server/index.js` by default) is transpiled to\nJavaScript with lazily loaded `oxc-transform` before writing, because the\nprinted run script and the generated `claude-config.example.json` both invoke\nit with plain `node`. Ordinary core imports and `.ts`/`.mts` output therefore\ndo not load OXC's native bindings.\nThis keeps `typescript` dev-only in `@happyvertical/smrt-core`; generated MCP\nsource must remain erasable-syntax-only. A `.cjs`/`.cts` target is rejected\noutright: generated servers are ES modules. `src/generators/mcp-emit.ts` owns\nthose decisions — do not reintroduce a bare `writeFile` of generated source.\n\nModular output writes `config`, `tools/index`, and `handlers/index` with the\nentry point's own extension, and emits the entry's relative import specifiers\nwith that same extension, so the files it imports both exist and load with the\nsame module semantics — an `.mjs` entry gets `.mjs` siblings, not `.js` ones a\nCommonJS package would then parse as CommonJS. The entry is written at the\nrequested path rather than a hardcoded `index.js`.\nGenerated code also has to be valid in an ES module: `arguments` is not a legal\nbinding name there, however convenient it reads.\n\n## Browser-plane playbook preflight route (#2590)\n\n`GET {basePath}/_preflight?key=<playbook key>` (`src/generators/preflight-route.ts`)\nis an advisory, read-effect, idempotent report of what a caller's playbook would\nbe allowed to do — capability *selection*, never authorization. Resolution and\nverdict shaping live in `@happyvertical/smrt-playbooks`, which depends on this\npackage, so core takes the evaluator as the `APIConfig.playbookPreflight` seam and\nthe dependency stays one-way. Without a provider the route 404s.\n\n**`authMiddleware` is never invoked by preflight**, and that is enforced\nstructurally rather than by discipline: `PlaybookPreflightRouteOptions` has no\nauth member of any kind, and `rest.ts` passes the boolean `appAuthConfigured`\ninstead — so there is no handle in the module to invoke by mistake. A synthetic-\n`Request` dry run is explicitly not an option: the middleware is request-bound,\nreturns a `Response` rather than a boolean, and may consult session stores,\nrate-limit, or audit. The app-auth layer therefore reports `unknown`, which is the\nhonest answer, and a future `authPredicate` seam can fill it in without changing\nthe contract.\n\nThe static layers preflight predicts against are exported from the same module —\n`isApiActionEnabledForObject`, `isRestActionRoutable`, `isRestRoutePublic`,\n`restFieldReadPermissions`, `restMethodForApiAction`,\n`resolveRegisteredObjectName` — and `APIGenerator`'s own\n`isApiActionEnabled` / `isRoutePublic` now delegate to them, so the route and the\nprediction of the route cannot drift. Exposure and existence are separate\nquestions: `include`/`exclude` gate a route, they do not conjure one, so\n`isRestActionRoutable` additionally requires a custom action to be declared in\n`api.routes` — the only map `dispatchCustomCollectionAction` iterates. A custom\naction is predicted against the verb its own route config declares, so a\n`public: 'read'` opt-out neither silently covers a `POST` action nor falsely\ndenies a declared `GET` one. Every unresolvable key returns the provider's single uniform\n\"unavailable\" body with an unconditional 200: unknown and unauthorized keys are\nindistinguishable at the HTTP layer too.\n\n## Emitted agent surface (#2591)\n\nGenerated model tools have always been build-time artifacts — virtual module,\nmanifest, knowledge graph. View intents (#2588) and playbooks (#2589) existed\nonly once something mounted, so \"what can an agent do in this app\" had no answer\nshort of enumerating every route. This closes that.\n\nThe same OXC scan that builds the manifest also runs the scanner's\nagent-surface matcher (`ScanResults.agentSurface`). `smrtPlugin()` captures it\nin `scanWithOxc`, projects it with `toKnowledgeAgentSurface`, and passes it to\n`buildDomainKnowledgeManifest` as `agentSurface`. Note that declaration\ndiscovery is NOT bound to the plugin's `include` glob — an app that scans\n`src/lib/objects/**` for models still has its `src/lib/agent/*.intents.ts`\nsidecars found (see `packages/scanner/AGENTS.md`). Two more consequences worth\nholding onto:\n\n- **It never touches `manifest.json`.** The runtime manifest stays\n runtime-focused; the agent-addressable surface is an agent/developer contract,\n so it lands in `.smrt/smrt-knowledge.json` and `dist/smrt-knowledge.json`\n only, under `agentSurface: { intents, playbooks, diagnostics }`.\n- **It is passed in, not scanned in `knowledge.ts`.** The scanner carries a\n native parser binary and `smrt-core`'s main entry is browser-reachable, so\n core's sync knowledge builder must not import it. The Vite plugin already\n imports the scanner lazily on the Node side and is the only caller that writes\n this artifact.\n\nThe field is **omitted entirely** when a package declares nothing, which is what\nmakes it additive in practice rather than only on paper: every existing\npackage's checked-in artifact stays byte-identical.\n\nEach declaring module gets a `sourceHashes` entry under the\n`agentSurface:<package-relative path>` prefix (`AGENT_SURFACE_HASH_PREFIX`), so\nEDITING an intent sidecar marks the artifact stale exactly like editing\n`AGENTS.md` does (`stale-domain-knowledge`).\n\nHashes alone cannot see an **added** declaration, though: a brand-new sidecar\nhas no recorded hash to mismatch, the runtime manifest never carries intents,\nand `AGENTS.md` is untouched — so every other signal stays green while the\nartifact omits a real operation. `dev:knowledge-check` therefore also re-derives\nthe declaration SET from source and compares it to the artifact by identity,\nreporting either direction as `stale-agent-surface`. The scan is bounded like\nthe numeric-precision lint: `src` only, behind the scanner's token pre-filter.\n\nThat re-derivation must model what the EMITTER sees, not merely what is on\ndisk, or it reports drift no rebuild can clear. Which files count is decided by\nthe scanner's exported `isAgentSurfaceSourcePath` — the same predicate the\nemitter itself uses, never a list copied into the checker — and the per-file\nresults run through `mergeAgentSurfaces` before comparing, because the merge is\nwhere a duplicate identity and a derived tool-name collision are resolved and\nthe artifact is the merged result.\nDiagnostics are compared alongside identities: a sidecar containing only a\ncomputed declaration adds no identity and has no prior hash, so without that,\n\"a diagnostic, never silence\" would quietly become \"a diagnostic, until the\nartifact goes stale\". The walk covers `<pkg>/src` while the emitter globs the\nwhole project root, so an emitted entry from outside `src` is not reported as\nmissing — this check did not look there, and claiming otherwise would be an\nerror nothing could clear.\n\nBoth `stale-*` codes are warnings by default and errors under `--strict`, which\nis what CI runs. Alongside them: `agent-surface-missing-identity`,\n`agent-surface-duplicate-identity`, and `agent-surface-empty-playbook` are\nerrors, and `agent-surface-not-static` and `agent-surface-tool-name-collision`\nare warnings. A cross-file duplicate arrives as a *diagnostic* rather than two\nentries — the scanner's merge already dropped the loser — so that diagnostic\nmaps to the duplicate error rather than the not-static warning; otherwise the\nerror would be unreachable for the case it exists to catch.\n\nA `tool-name-collision` diagnostic (#2725) is derived from the MANIFEST, not\nfrom the declaration: the plugin compares each emitted intent against\n`buildWebMcpToolDefinitions` for the same build, which is already filtered by\nthe exposure policy, and appends the result to the surface. So it is excluded\nfrom the drift comparison above — that pass re-derives declarations from source\nalone and has no manifest, so counting one as \"declared\" would report every\ncollision as drift no rebuild could clear. The check is advisory and drops\nnothing: `defineIntent` accepts the id, so the intent is emitted, and the\ndocument-global tool-name lock (#2613) rejects whichever registers second — the\nbuild-time notice is the earlier, cheaper form of the same answer. A build\ncannot see the provider's WebMCP `namespace` or `effects` policy, either of\nwhich separates the pair outright, so the message states that precondition\nrather than asserting the collision.\n\n`smrt doctor` prints the whole surface — model tools, intents, playbooks — from\nthese artifacts alone, with no application running.\n\n## Custom-action contract\n\n`resolveCustomActionMetadata()` is the common discovery and invocation contract\nfor generated REST routes and API clients, MCP, CLI, WebMCP, and simple\nREST-resource discovery. Receiver scope comes from the executable method, never a\nconfiguration-only `api.routes[name].scope` override: instance model methods\nare item-scoped and require `id`; static model methods and recognized\n`SmrtCollection` methods are collection-scoped and do not accept `id`. Route\nconfiguration may still choose its path and HTTP verb, but it cannot turn an\ninstance call into `ClassRef.action` or vice versa.\n\nWhen scanner method metadata exists, discovery projects each named parameter\nand its JSON-schema type, and invokers pass the values positionally in declared\norder. The legacy single `options` bag remains compatible when metadata is\nabsent (or the declared method takes `options`). Do not infer this from runtime\nfunction arity. An omitted typed `options` parameter remains `undefined`, so a\nmethod's JavaScript default initializer continues to apply; an explicit `null`\nremains `null`. Flat tool and CLI inputs reserve `id` for receiver parsing. If\nan action declares an `id` parameter, its flat MCP/WebMCP field is `actionId`\n(and CLI uses `--action-id`); REST keeps its independent path/body\nnamespaces. Typed CLI actions may use standard flag names such as `limit`,\n`offset`, `where`, and `format` without those values being stripped as CRUD\nflags.\n\nCustom actions may return an explicit, domain-neutral failure object with\n`ok: false`, `code`, and `message` plus optional `status`, `details`,\n`retryable`, and `correlationId`. `normalizeCustomActionFailure()` redacts it;\ngenerated REST returns `{ error: failure }` with the non-2xx status, while MCP\nreturns `isError: true` and `_meta['io.happyvertical/smrt']`. Opaque successful\nobjects (including `{ code, message }`) remain untouched; thrown exceptions are\nnot reclassified as domain failures.\n\nCustom route metadata also classifies browser-tool effects. Set `effect` to\n`read`, `write`, or `destructive`, with truthful `idempotent` and `openWorld`\nflags. CRUD classification is fixed: list/get are read, create/update are write,\nand delete is destructive. An undeclared custom action deliberately defaults to\ndestructive, non-idempotent, and open-world so a browser capability policy never\nfails open.\n\nGenerated reads (`list`/`get`) on the REST and SvelteKit generators support conditional GET (helpers in `src/generators/conditional-get.ts`). ETag v2 (#1765): the validator is the table's change-feed version (`getTableVersion`) keyed by the request representation, so a **concrete** `If-None-Match` short-circuits into a 304 with an empty body **before** the collection query runs — an unchanged table revalidates with zero table scan. A wildcard `If-None-Match: *` is deferred until the payload builds (existence confirmed), so a missing item still returns 404, not a false 304. Tenant-scoped reads fold the active tenant into the representation (`resolveTenantEtagDiscriminator`) so one tenant's cached validator never satisfies another's read of the same URL. Routes whose GET renders via a **custom serializer** (which can load related tables the base-table version can't observe) keep the v1 body-hash ETag (`#1757`, query-first but correct); the default `toPublicJSON` path — all REST reads and non-serializer SvelteKit reads — uses v2. v2 is weakly consistent by design (the cost of not reading the data): a revalidation in the sub-statement window between a committed write and its feed append can return a stale 304 that self-heals on the next revalidation. The other v2 window — a deploy that changes the response shape WITHOUT a table write — is closed by the **#1764 ETag salt**: `computeTableVersionEtag(version, representation, manifestHash?)` folds the build's web-collection shape digest into the digest, so a shape-only redeploy busts every read validator (`undefined` reproduces the pre-#1764 unsalted value byte-for-byte for direct helper callers). The generated SvelteKit route bakes the digest in as a `MANIFEST_HASH` constant (via `generateConditionalGetRouteHelper`'s `manifestHash` option, sourced from `computeWebManifestHash(manifest)`) — automatic for the SvelteKit transport. The runtime `APIGenerator` auto-populates the same salt from the runtime registry with `computeRuntimeWebManifestHash()` when `APIConfig.manifestHash` is omitted; explicit `APIConfig.manifestHash` still wins for custom setups. The digest scope is get-OR-list (`selectWebEtagSaltEntries`), so **get-only** routes are salted too. Strong consistency still requires the v1 body-hash path. Cache-Control policy (unchanged from #1757): `private, no-cache` by default; public models may opt into shared caching via `@smrt({ api: { public: true | 'read', cache: { sMaxage } } })` → `public, max-age=0, s-maxage=<n>`; non-public models never emit shared-cache headers. Tenant-scoped models (any mode) never emit them either — bodies vary with session-cookie tenant context that URL-keyed shared caches cannot see; `sMaxage` is neutralized to `private, no-cache` with a one-time warning.\n"
1031
+ "content": "# smrt-core/code generators\n\nModule semantics for `src/generators/` + `src/vite-plugin/`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Code Generators\n\n| Generator | Location | Output |\n|-----------|----------|--------|\n| REST API | `src/generators/rest.ts` | OpenAPI-compliant CRUD endpoints |\n| MCP Server | `src/generators/mcp.ts` | Model Context Protocol tools |\n| Web collections | `src/vite-plugin/web-collections.ts` (selectors) + `generateWebModule` | `@happyvertical/smrt-virt-web` — one typed collection definition per API-exposed REST collection (#1761), consumed by `@happyvertical/smrt-web` |\n\nThe same web virtual module exports `webMcpToolDefinitions` (#2518), a\ncanonical per-tool array selected independently of list materialization. Every\nnon-empty canonical API action set contributes tools, so get-only and\ncustom-action-only models are discoverable; custom actions declared on a\n`SmrtCollection` merge into the owning row collection. Each definition carries\ncomplete route and invalidation metadata. `collectionDefinitions` and its\nembedded descriptor copy remain unchanged for existing cache-backed consumers.\n\nGenerated API clients share `selectApiClientEntries()` across the runtime Vite\nmodule, its ambient declaration, and physical prebuild declarations. When a\ncollection class and its populated model share an endpoint, the model owns the\ncanonical collection key and row payload schema; the collection class remains\navailable under a deterministic class-derived secondary key. Selection and\ncollision suffixes must not depend on manifest insertion order (#2027).\nFor aggregated manifests, inheritance and item-type references resolve exact\nqualified names first, then package-local simple names, then a stable identity\nfallback so duplicate class names across packages cannot reintroduce ordering.\n\nThe web module also emits a build-time **`manifestHash`** constant (#1764): `computeWebManifestHash(manifest)` is a deterministic, replica-stable digest of the emitted web-collection SHAPE (name/className/endpoint/idField/actions/fields/relationships), canonicalized (recursive key sort) before `sha256 → base64url`, truncated to 16 chars — so the same schema always hashes the same, and a field add/remove/type-change/edge-change changes it. A change means old persisted client rows may mis-hydrate, so smrt-web keys its durable persistence namespace on it and its `updateAvailable` contract signal compares against it. Four co-managed emission sites must not drift: the runtime value (`generateWebModule`), the `@happyvertical/smrt-virt-web` ambient d.ts (`vite-plugin/index.ts`), the physical `@smrt/web` d.ts (`prebuild/index.ts`), and the hand-written type mirror in `@happyvertical/smrt-web` (`packages/smrt-web/src/index.ts` — dependency-free, so textual sync only).\n\n`webMcpToolDefinitions` is deliberately outside that digest: tool-only route,\nidentifier, or annotation changes cannot alter persisted row hydration.\n\nPer-field web emission (#2046): `buildWebFieldDefinitions` carries `description` (from `@field({ description })`) and sanitized `ui` hints (from `@field({ ui: { basic, group, order, locked } })`, read off the manifest `_meta.ui` bag through per-key type guards) into each emitted field definition, and `buildWebToolDescriptors` threads the same `description` into browser MCP tool schemas. `sensitive`/`transient` fields are excluded from emission entirely, so their descriptions never ship. Both keys are conditional, so hint-less schemas emit byte-identical definitions (and hashes) as before; adding a description/ui hint changes the manifest hash — deliberate over-invalidation, harmless per the #1764 contract.\n\n## Generated MCP server output language\n\n`MCPGenerator` builds every file as TypeScript, so the requested `outputPath`\nextension decides what is written (#2279). `.ts`/`.mts` targets keep the source\nverbatim for `tsx` or Node type stripping — which is why the generated source\nmust stay erasable-syntax-only (no parameter properties, enums, or namespaces).\nEvery other target (`.smrt/mcp-server/index.js` by default) is transpiled to\nJavaScript with lazily loaded `oxc-transform` before writing, because the\nprinted run script and the generated `claude-config.example.json` both invoke\nit with plain `node`. Ordinary core imports and `.ts`/`.mts` output therefore\ndo not load OXC's native bindings.\nThis keeps `typescript` dev-only in `@happyvertical/smrt-core`; generated MCP\nsource must remain erasable-syntax-only. A `.cjs`/`.cts` target is rejected\noutright: generated servers are ES modules. `src/generators/mcp-emit.ts` owns\nthose decisions — do not reintroduce a bare `writeFile` of generated source.\n\nModular output writes `config`, `tools/index`, and `handlers/index` with the\nentry point's own extension, and emits the entry's relative import specifiers\nwith that same extension, so the files it imports both exist and load with the\nsame module semantics — an `.mjs` entry gets `.mjs` siblings, not `.js` ones a\nCommonJS package would then parse as CommonJS. The entry is written at the\nrequested path rather than a hardcoded `index.js`.\nGenerated code also has to be valid in an ES module: `arguments` is not a legal\nbinding name there, however convenient it reads.\n\n## Browser-plane playbook preflight route (#2590)\n\n`GET {basePath}/_preflight?key=<playbook key>` (`src/generators/preflight-route.ts`)\nis an advisory, read-effect, idempotent report of what a caller's playbook would\nbe allowed to do — capability *selection*, never authorization. Resolution and\nverdict shaping live in `@happyvertical/smrt-playbooks`, which depends on this\npackage, so core takes the evaluator as the `APIConfig.playbookPreflight` seam and\nthe dependency stays one-way. Without a provider the route 404s.\n\n**`authMiddleware` is never invoked by preflight**, and that is enforced\nstructurally rather than by discipline: `PlaybookPreflightRouteOptions` has no\nauth member of any kind, and `rest.ts` passes the boolean `appAuthConfigured`\ninstead — so there is no handle in the module to invoke by mistake. A synthetic-\n`Request` dry run is explicitly not an option: the middleware is request-bound,\nreturns a `Response` rather than a boolean, and may consult session stores,\nrate-limit, or audit. The app-auth layer therefore reports `unknown`, which is the\nhonest answer, and a future `authPredicate` seam can fill it in without changing\nthe contract.\n\nThe static layers preflight predicts against are exported from the same module —\n`isApiActionEnabledForObject`, `isRestActionRoutable`, `isRestRoutePublic`,\n`restFieldReadPermissions`, `restMethodForApiAction`,\n`resolveRegisteredObjectName` — and `APIGenerator`'s own\n`isApiActionEnabled` / `isRoutePublic` now delegate to them, so the route and the\nprediction of the route cannot drift. Exposure and existence are separate\nquestions: `include`/`exclude` gate a route, they do not conjure one, so\n`isRestActionRoutable` additionally requires a custom action to be declared in\n`api.routes` — the only map `dispatchCustomCollectionAction` iterates. A custom\naction is predicted against the verb its own route config declares, so a\n`public: 'read'` opt-out neither silently covers a `POST` action nor falsely\ndenies a declared `GET` one. Every unresolvable key returns the provider's single uniform\n\"unavailable\" body with an unconditional 200: unknown and unauthorized keys are\nindistinguishable at the HTTP layer too.\n\n## Emitted agent surface (#2591)\n\nGenerated model tools have always been build-time artifacts — virtual module,\nmanifest, knowledge graph. View intents (#2588) and playbooks (#2589) existed\nonly once something mounted, so \"what can an agent do in this app\" had no answer\nshort of enumerating every route. This closes that.\n\nThe same OXC scan that builds the manifest also runs the scanner's\nagent-surface matcher (`ScanResults.agentSurface`). `smrtPlugin()` captures it\nin `scanWithOxc`, projects it with `toKnowledgeAgentSurface`, and passes it to\n`buildDomainKnowledgeManifest` as `agentSurface`. Note that declaration\ndiscovery is NOT bound to the plugin's `include` glob — an app that scans\n`src/lib/objects/**` for models still has its `src/lib/agent/*.intents.ts`\nsidecars found (see `packages/scanner/AGENTS.md`). Two more consequences worth\nholding onto:\n\n- **It never touches `manifest.json`.** The runtime manifest stays\n runtime-focused; the agent-addressable surface is an agent/developer contract,\n so it lands in `.smrt/smrt-knowledge.json` and `dist/smrt-knowledge.json`\n only, under `agentSurface: { intents, playbooks, diagnostics }`.\n- **It is passed in, not scanned in `knowledge.ts`.** The scanner carries a\n native parser binary and `smrt-core`'s main entry is browser-reachable, so\n core's sync knowledge builder must not import it. The Vite plugin already\n imports the scanner lazily on the Node side and is the only caller that writes\n this artifact.\n\nThe field is **omitted entirely** when a package declares nothing, which is what\nmakes it additive in practice rather than only on paper: every existing\npackage's checked-in artifact stays byte-identical.\n\nEach declaring module gets a `sourceHashes` entry under the\n`agentSurface:<package-relative path>` prefix (`AGENT_SURFACE_HASH_PREFIX`), so\nEDITING an intent sidecar marks the artifact stale exactly like editing\n`AGENTS.md` does (`stale-domain-knowledge`).\n\nHashes alone cannot see an **added** declaration, though: a brand-new sidecar\nhas no recorded hash to mismatch, the runtime manifest never carries intents,\nand `AGENTS.md` is untouched — so every other signal stays green while the\nartifact omits a real operation. `dev:knowledge-check` therefore also re-derives\nthe declaration SET from source and compares it to the artifact by identity,\nreporting either direction as `stale-agent-surface`. The scan is bounded like\nthe numeric-precision lint: `src` only, behind the scanner's token pre-filter.\n\nThat re-derivation must model what the EMITTER sees, not merely what is on\ndisk, or it reports drift no rebuild can clear. Which files count is decided by\nthe scanner's exported `isAgentSurfaceSourcePath` — the same predicate the\nemitter itself uses, never a list copied into the checker — and the per-file\nresults run through `mergeAgentSurfaces` before comparing, because the merge is\nwhere a duplicate identity and a derived tool-name collision are resolved and\nthe artifact is the merged result.\nDiagnostics are compared alongside identities: a sidecar containing only a\ncomputed declaration adds no identity and has no prior hash, so without that,\n\"a diagnostic, never silence\" would quietly become \"a diagnostic, until the\nartifact goes stale\". The walk covers `<pkg>/src` while the emitter globs the\nwhole project root, so an emitted entry from outside `src` is not reported as\nmissing — this check did not look there, and claiming otherwise would be an\nerror nothing could clear.\n\nBoth `stale-*` codes are warnings by default and errors under `--strict`, which\nis what CI runs. Alongside them: `agent-surface-missing-identity`,\n`agent-surface-duplicate-identity`, and `agent-surface-empty-playbook` are\nerrors, and `agent-surface-not-static` and `agent-surface-tool-name-collision`\nare warnings. A cross-file duplicate arrives as a *diagnostic* rather than two\nentries — the scanner's merge already dropped the loser — so that diagnostic\nmaps to the duplicate error rather than the not-static warning; otherwise the\nerror would be unreachable for the case it exists to catch.\n\nA `tool-name-collision` diagnostic (#2725) is derived from the MANIFEST, not\nfrom the declaration: the plugin compares each emitted intent against\n`buildWebMcpToolDefinitions` for the same build, which is already filtered by\nthe exposure policy, and appends the result to the surface. So it is excluded\nfrom the drift comparison above — that pass re-derives declarations from source\nalone and has no manifest, so counting one as \"declared\" would report every\ncollision as drift no rebuild could clear. The check is advisory and drops\nnothing: `defineIntent` accepts the id, so the intent is emitted, and the\ndocument-global tool-name lock (#2613) rejects whichever registers second — the\nbuild-time notice is the earlier, cheaper form of the same answer. A build\ncannot see the provider's WebMCP `namespace` or `effects` policy, either of\nwhich separates the pair outright, so the message states that precondition\nrather than asserting the collision.\n\n`smrt doctor` prints the whole surface — model tools, intents, playbooks — from\nthese artifacts alone, with no application running.\n\n## Custom-action contract\n\n`resolveCustomActionMetadata()` is the common discovery and invocation contract\nfor generated REST routes and API clients, MCP, CLI, WebMCP, and simple\nREST-resource discovery. Receiver scope comes from the executable method, never a\nconfiguration-only `api.routes[name].scope` override: instance model methods\nare item-scoped and require `id`; static model methods and recognized\n`SmrtCollection` methods are collection-scoped and do not accept `id`. Route\nconfiguration may still choose its path and HTTP verb, but it cannot turn an\ninstance call into `ClassRef.action` or vice versa.\n\nWhen scanner method metadata exists, discovery projects each named parameter\nand its JSON-schema type, and invokers pass the values positionally in declared\norder. The legacy single `options` bag remains compatible when metadata is\nabsent (or the declared method takes `options`). Do not infer this from runtime\nfunction arity. An omitted typed `options` parameter remains `undefined`, so a\nmethod's JavaScript default initializer continues to apply; an explicit `null`\nremains `null`. Flat tool and CLI inputs reserve `id` for receiver parsing. If\nan action declares an `id` parameter, its flat MCP/WebMCP field is `actionId`\n(and CLI uses `--action-id`); REST keeps its independent path/body\nnamespaces. Typed CLI actions may use standard flag names such as `limit`,\n`offset`, `where`, and `format` without those values being stripped as CRUD\nflags.\n\nCustom actions may return an explicit, domain-neutral failure object with\n`ok: false`, `code`, and `message` plus optional `status`, `details`,\n`retryable`, and `correlationId`. `normalizeCustomActionFailure()` redacts it;\ngenerated REST returns `{ error: failure }` with the non-2xx status, while MCP\nreturns `isError: true` and `_meta['io.happyvertical/smrt']`. Opaque successful\nobjects (including `{ code, message }`) remain untouched; thrown exceptions are\nnot reclassified as domain failures.\n\nCustom route metadata also classifies browser-tool effects. Set `effect` to\n`read`, `write`, or `destructive`, with truthful `idempotent` and `openWorld`\nflags. CRUD classification is fixed: list/get are read, create/update are write,\nand delete is destructive. An undeclared custom action deliberately defaults to\ndestructive, non-idempotent, and open-world so a browser capability policy never\nfails open.\n\nGenerated reads (`list`/`get`) on the REST and SvelteKit generators support conditional GET (helpers in `src/generators/conditional-get.ts`). ETag v2 (#1765): the validator is the table's change-feed version (`getTableVersion`) keyed by the request representation, so a **concrete** `If-None-Match` short-circuits into a 304 with an empty body **before** the collection query runs — an unchanged table revalidates with zero table scan. A wildcard `If-None-Match: *` is deferred until the payload builds (existence confirmed), so a missing item still returns 404, not a false 304. Tenant-scoped reads fold the active tenant into the representation (`resolveTenantEtagDiscriminator`) so one tenant's cached validator never satisfies another's read of the same URL. Routes whose GET renders via a **custom serializer** (which can load related tables the base-table version can't observe) keep the v1 body-hash ETag (`#1757`, query-first but correct); the default `toPublicJSON` path — all REST reads and non-serializer SvelteKit reads — uses v2. v2 is weakly consistent by design (the cost of not reading the data): a revalidation in the sub-statement window between a committed write and its feed append can return a stale 304 that self-heals on the next revalidation. The other v2 window — a deploy that changes the response shape WITHOUT a table write — is closed by the **#1764 ETag salt**: `computeTableVersionEtag(version, representation, manifestHash?)` folds the build's web-collection shape digest into the digest, so a shape-only redeploy busts every read validator (`undefined` reproduces the pre-#1764 unsalted value byte-for-byte for direct helper callers). The generated SvelteKit route bakes the digest in as a `MANIFEST_HASH` constant (via `generateConditionalGetRouteHelper`'s `manifestHash` option, sourced from `computeWebManifestHash(manifest)`) — automatic for the SvelteKit transport. The runtime `APIGenerator` auto-populates the same salt from the runtime registry with `computeRuntimeWebManifestHash()` when `APIConfig.manifestHash` is omitted; explicit `APIConfig.manifestHash` still wins for custom setups. The digest scope is get-OR-list (`selectWebEtagSaltEntries`), so **get-only** routes are salted too. Strong consistency still requires the v1 body-hash path. Cache-Control policy (unchanged from #1757): `private, no-cache` by default; public models may opt into shared caching via `@smrt({ api: { public: true | 'read', cache: { sMaxage } } })` → `public, max-age=0, s-maxage=<n>`; non-public models never emit shared-cache headers. Tenant-scoped models (any mode) never emit them either — bodies vary with session-cookie tenant context that URL-keyed shared caches cannot see; `sMaxage` is neutralized to `private, no-cache` with a one-time warning.\n\n## Generated dev-plane route (#2782)\n\n`src/vite-plugin/dev-plane-route.ts` emits `<routesDir>/_dev/[...tool]/+server.ts`\nonly when `sveltekit.devPlaneRoute.enabled === true` and\n`@happyvertical/smrt-dev-mcp/dev-plane` resolves from the consumer (same\nresolvability guard as `_resources`). The route is dev-only (`$app/environment`\n`dev`, else 404), refuses to start without `SMRT_DEV_MCP_TOKEN` (503), and\ndelegates everything else to `createDevPlane`, passing `getSmrtConfig(...).db`\nfrom the generated `$lib/server/smrt` so the plane shares the app's connection.\nCore never imports smrt-dev-mcp; only the generated file does, at consumer\nruntime. The route carries the auto-generated header so the sweep owns it.\n"
1032
1032
  },
1033
1033
  {
1034
1034
  "path": "agents/build-knowledge.md",
@@ -1043,7 +1043,7 @@
1043
1043
  {
1044
1044
  "path": "agents/system-diagnostics.md",
1045
1045
  "module": "system-diagnostics",
1046
- "content": "<!-- Module doc for packages/core/AGENTS.md. Linked from the Modules table there. -->\n\n# System diagnostics (#1824)\n\n`src/system/diagnostics.ts` is the typed, SELECT-only reader over the\nframework-owned `_smrt_*` tables for development tooling (smrt-dev-mcp runtime\ndiagnostics). It takes a `DatabaseInterface` and never resolves connections,\nnever writes, and never boots the app — connection resolution, redaction, and\nprovenance labeling belong to the caller (`packages/smrt-dev-mcp`\n`tools/runtime/`).\n\nCategories degrade individually: a missing table or failed read returns a\n`CategoryUnavailable` result (`available: false` with `reason`\n`table-missing`/`retired`/`read-error`) instead of throwing, an empty-but-\nhealthy category, or fabricated data. Callers must surface the reason, never\npaper over it. `_smrt_registry` is a retired system table and is reported as\nretired rather than read — only its existence is probed, never its rows.\n\nEvery read is a bounded `SELECT` with an explicit safe-column projection.\nSensitive columns are never selected, not selected-then-stripped: job\n`args`/`result_pointer`/task payloads, schedule `agentConfig`/`methodArgs`, and\ndispatch `payload`/`metadata` stay in the database; short error texts\n(`last_error`, `error_message`) and statuses are surfaced for diagnosis, and\nsmrt-dev-mcp runs every string in a live result through\n`redactConnectionString` before it reaches a client. Migration\ncounts use `MigrationTracker`'s real vocabulary (`completed`, `running`,\n`failed`, `rolled_back`), never an invented `applied`/`pending`. A `running`\njob is stuck only when its `worker_heartbeat` is stale or NULL **and** its\nworker holds no fresh `_smrt_workers.lease_expires_at` — the same rule the\nrunner's recovery uses (#1474), so a handler blocking its event loop under a\nlive off-loop lease is not reported stuck; without the workers table the\nheartbeat is the only signal. Row lists honor `DIAGNOSTICS_DEFAULT_LIMIT` (50)\ncapped at 500; `readRecentChanges()` pages `getChangesSince()` with\n`drain: false` (default 200, same cap) so the PostgreSQL staged-entry drain —\na write — never runs from a diagnostic.\n\nEngine compatibility lives in one place: `placeholders(db)` resolves `$n`\nnumbering (PostgreSQL) versus `?` (SQLite/DuckDB) via the shared\n`getDatabaseEngine` convention — explicit `type`/config hint first, then the\nconnection URL's scheme — and identifiers are never interpolated from caller\ninput, only from the constant `SYSTEM_DIAGNOSTICS_TABLES` map.\n`readSystemDiagnostics()` composes every\ncategory for one-shot snapshots; per-category readers compose it.\n"
1046
+ "content": "<!-- Module doc for packages/core/AGENTS.md. Linked from the Modules table there. -->\n\n# System diagnostics (#1824)\n\n`src/system/diagnostics.ts` is the typed, SELECT-only reader over the\nframework-owned `_smrt_*` tables for development tooling (smrt-dev-mcp runtime\ndiagnostics). It takes a `DatabaseInterface` and never resolves connections,\nnever writes, and never boots the app — connection resolution, redaction, and\nprovenance labeling belong to the caller (`packages/smrt-dev-mcp`\n`tools/runtime/`).\n\nCategories degrade individually: a missing table or failed read returns a\n`CategoryUnavailable` result (`available: false` with `reason`\n`table-missing`/`retired`/`read-error`) instead of throwing, an empty-but-\nhealthy category, or fabricated data. Callers must surface the reason, never\npaper over it. `_smrt_registry` is a retired system table and is reported as\nretired rather than read — only its existence is probed, never its rows.\n\nEvery read is a bounded `SELECT` with an explicit safe-column projection,\nintersected with the live table's columns first (`selectable()`; PRAGMA on\nSQLite/DuckDB, `information_schema.columns` on PostgreSQL): a dev database\nwhose system tables predate a column still answers, reporting the gap in\n`schemaBehind` (#2778). A failed read returns `read-error` with the driver\nmessage in `detail` so the caller can surface a cause after redaction.\nSensitive columns are never selected, not selected-then-stripped: job\n`args`/`result_pointer`/task payloads, schedule `agentConfig`/`methodArgs`, and\ndispatch `payload`/`metadata` stay in the database; short error texts\n(`last_error`, `error_message`) and statuses are surfaced for diagnosis, and\nsmrt-dev-mcp runs every string in a live result through\n`redactConnectionString` before it reaches a client. Migration\ncounts use `MigrationTracker`'s real vocabulary (`completed`, `running`,\n`failed`, `rolled_back`), never an invented `applied`/`pending`. A `running`\njob is stuck only when its `worker_heartbeat` is stale or NULL **and** its\nworker holds no fresh `_smrt_workers.lease_expires_at` — the same rule the\nrunner's recovery uses (#1474), so a handler blocking its event loop under a\nlive off-loop lease is not reported stuck; without the workers table the\nheartbeat is the only signal. Row lists honor `DIAGNOSTICS_DEFAULT_LIMIT` (50)\ncapped at 500; `readRecentChanges()` pages `getChangesSince()` with\n`drain: false` (default 200, same cap) so the PostgreSQL staged-entry drain —\na write — never runs from a diagnostic.\n\nEngine compatibility lives in one place: `placeholders(db)` resolves `$n`\nnumbering (PostgreSQL) versus `?` (SQLite/DuckDB) via the shared\n`getDatabaseEngine` convention — explicit `type`/config hint first, then the\nconnection URL's scheme — and identifiers are never interpolated from caller\ninput, only from the constant `SYSTEM_DIAGNOSTICS_TABLES` map.\n`readSystemDiagnostics()` composes every\ncategory for one-shot snapshots; per-category readers compose it.\n"
1047
1047
  },
1048
1048
  {
1049
1049
  "path": "agents/registry-snapshot.md",
@@ -14,6 +14,15 @@ export declare const SYSTEM_DIAGNOSTICS_TABLES: {
14
14
  };
15
15
  /** Default page size for row-listing categories. */
16
16
  export declare const DIAGNOSTICS_DEFAULT_LIMIT = 50;
17
+ /**
18
+ * Columns the reader wanted but the live table lacks (an older system schema).
19
+ * Readers select only the columns that exist and report the rest here, so a
20
+ * dev database that predates a column still answers instead of failing.
21
+ */
22
+ export interface SchemaBehind {
23
+ tableName: string;
24
+ missingColumns: string[];
25
+ }
17
26
  /**
18
27
  * A category whose table is missing (or whose read failed) on the live
19
28
  * database. Callers must surface this as "category unavailable" — never as an
@@ -24,6 +33,11 @@ export interface CategoryUnavailable {
24
33
  reason: 'table-missing' | 'retired' | 'read-error';
25
34
  message: string;
26
35
  tableName?: string;
36
+ /**
37
+ * Driver error text for `read-error` (never a query with values). Callers
38
+ * that surface it to a client must redact it first.
39
+ */
40
+ detail?: string;
27
41
  }
28
42
  /** Safe projection of one `_smrt_schema_migrations` row. */
29
43
  export interface MigrationStatusRow {
@@ -56,6 +70,8 @@ export interface MigrationStatusSummary {
56
70
  }
57
71
  export type MigrationStatusResult = {
58
72
  available: true;
73
+ /** Wanted columns absent on this database (older system schema). */
74
+ schemaBehind: SchemaBehind[];
59
75
  summary: MigrationStatusSummary;
60
76
  /** Most recently applied migrations, newest first. */
61
77
  latest: MigrationStatusRow[];
@@ -119,6 +135,8 @@ export interface JobHealthSummary {
119
135
  }
120
136
  export type JobHealthResult = {
121
137
  available: true;
138
+ /** Wanted columns absent on this database (older system schema). */
139
+ schemaBehind: SchemaBehind[];
122
140
  summary: JobHealthSummary;
123
141
  jobs: JobHealthRow[];
124
142
  workers: WorkerHealthRow[];
@@ -173,6 +191,8 @@ export interface ScheduleHealthSummary {
173
191
  }
174
192
  export type ScheduleHealthResult = {
175
193
  available: true;
194
+ /** Wanted columns absent on this database (older system schema). */
195
+ schemaBehind: SchemaBehind[];
176
196
  summary: ScheduleHealthSummary;
177
197
  schedules: ScheduleHealthRow[];
178
198
  } | CategoryUnavailable;
@@ -227,6 +247,8 @@ export interface DispatchHealthSummary {
227
247
  }
228
248
  export type DispatchHealthResult = {
229
249
  available: true;
250
+ /** Wanted columns absent on this database (older system schema). */
251
+ schemaBehind: SchemaBehind[];
230
252
  summary: DispatchHealthSummary;
231
253
  dispatches: DispatchHealthRow[];
232
254
  subscriptions: DispatchSubscriptionHealthRow[];
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.d.ts","sourceRoot":"","sources":["../../src/system/diagnostics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,KAAK,eAAe,EAAmB,MAAM,mBAAmB,CAAC;AAG1E,oEAAoE;AACpE,eAAO,MAAM,yBAAyB;;;;;;;;;;CAU5B,CAAC;AAEX,oDAAoD;AACpD,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,KAAK,CAAC;IACjB,MAAM,EAAE,eAAe,GAAG,SAAS,GAAG,YAAY,CAAC;IACnD,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAMD,4DAA4D;AAC5D,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,YAAY,EAAE,OAAO,GAAG,IAAI,CAAC;IAC7B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,EAA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