@happyvertical/smrt-core 0.43.10 → 0.44.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 (47) hide show
  1. package/agents/generators.md +70 -0
  2. package/agents/schema-paths.md +99 -0
  3. package/dist/generators/custom-action.d.ts.map +1 -1
  4. package/dist/generators/custom-action.js +1 -1
  5. package/dist/generators/custom-action.js.map +1 -1
  6. package/dist/index.js +2 -2
  7. package/dist/knowledge.d.ts +17 -1
  8. package/dist/knowledge.d.ts.map +1 -1
  9. package/dist/knowledge.js +33 -3
  10. package/dist/knowledge.js.map +1 -1
  11. package/dist/manifest/static-manifest.js +1 -1
  12. package/dist/manifest/static-manifest.js.map +1 -1
  13. package/dist/manifest/store.js +1 -1
  14. package/dist/manifest.json +1 -1
  15. package/dist/migrations/differ.d.ts +49 -0
  16. package/dist/migrations/differ.d.ts.map +1 -1
  17. package/dist/migrations/differ.js +220 -4
  18. package/dist/migrations/differ.js.map +1 -1
  19. package/dist/migrations/orchestrate.d.ts +23 -0
  20. package/dist/migrations/orchestrate.d.ts.map +1 -1
  21. package/dist/migrations/orchestrate.js +12 -3
  22. package/dist/migrations/orchestrate.js.map +1 -1
  23. package/dist/registry/types.d.ts +8 -3
  24. package/dist/registry/types.d.ts.map +1 -1
  25. package/dist/schema/foreign-key-ddl.d.ts +7 -0
  26. package/dist/schema/foreign-key-ddl.d.ts.map +1 -1
  27. package/dist/schema/foreign-key-ddl.js +7 -1
  28. package/dist/schema/foreign-key-ddl.js.map +1 -1
  29. package/dist/schema/schema-manager.d.ts +15 -0
  30. package/dist/schema/schema-manager.d.ts.map +1 -1
  31. package/dist/schema/schema-manager.js +52 -9
  32. package/dist/schema/schema-manager.js.map +1 -1
  33. package/dist/schema/types.d.ts +10 -0
  34. package/dist/schema/types.d.ts.map +1 -1
  35. package/dist/schema/uuid-convergence.d.ts +142 -0
  36. package/dist/schema/uuid-convergence.d.ts.map +1 -0
  37. package/dist/schema/uuid-convergence.js +0 -0
  38. package/dist/schema/uuid-convergence.js.map +1 -0
  39. package/dist/smrt-knowledge.json +7 -7
  40. package/dist/utils/scanner-module.d.ts +44 -0
  41. package/dist/utils/scanner-module.d.ts.map +1 -1
  42. package/dist/vite-plugin/index.d.ts +14 -1
  43. package/dist/vite-plugin/index.d.ts.map +1 -1
  44. package/dist/vite-plugin/index.js +54 -2
  45. package/dist/vite-plugin/index.js.map +1 -1
  46. package/dist/vite-plugin.js +3 -2
  47. package/package.json +4 -4
@@ -3,17 +3,17 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.43.10",
6
+ "packageVersion": "0.44.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "854db635a4c26a55bddedcfdad8f61ebc3bbd9b06eb34bfb37c7a2f14219723f",
11
- "packageJson": "3a4b8fee4288482b468136518694856810091374eb206124a415284fa406ab76",
10
+ "manifest": "a72b490253afe2593b2a72115b48a456c1a0a6a956eea969bd22b85d1f3ac961",
11
+ "packageJson": "f4804941176a45578bebc9972b60cca56b62f823940f4d1bc7cb7ba07ab8fdcc",
12
12
  "agents": "ee09cfd65c615877c7baa31add9a6165a841e1a919c9510b12ab6f541383284b",
13
13
  "moduleDoc:agents/change-feed.md": "1530ded9ed605aa9b8a772b3ba4dd992a3f797f4d7c9ede3b3389dd7bfb401fa",
14
14
  "moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
15
- "moduleDoc:agents/generators.md": "e0ccaee143b8a9b9fb69d25ec93502cde686ebcdfbb21e1b022a1352e4d778b4",
16
- "moduleDoc:agents/schema-paths.md": "6293d722d0165e9decf6dce9946a2daaaea77ab0915b85e571df3b3368904ced",
15
+ "moduleDoc:agents/generators.md": "f45658e75f1887ed4e8354f4e1f23145ef869d87d72ec553cc95733ca1a5d3ac",
16
+ "moduleDoc:agents/schema-paths.md": "561e01104eda21dd5c2c6f6d290bf722a7478c12800136ce61bff8193c8bbc2f",
17
17
  "moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
18
18
  "moduleDoc:agents/collection-reads.md": "4ce06e8b70b9ce9b77b47b3e2ed266c899bb7962ca015d4714f07a4aca10a865",
19
19
  "moduleDoc:agents/memory.md": "658cb34f3a499e290c14ba0dd8cf0bf82bcc571da01150b61070abf100894dfc",
@@ -990,12 +990,12 @@
990
990
  {
991
991
  "path": "agents/generators.md",
992
992
  "module": "generators",
993
- "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| CLI | `src/generators/cli.ts` | `objectname:action` admin commands — writable allowlist, exhaustive-include, `--from-file`, fail-closed tenant context |\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## 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"
993
+ "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| CLI | `src/generators/cli.ts` | `objectname:action` admin commands — writable allowlist, exhaustive-include, `--from-file`, fail-closed tenant context |\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## 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` is a warning. A cross-file duplicate\narrives as a *diagnostic* rather than two entries — the scanner's merge already\ndropped the loser — so that diagnostic maps to the duplicate error rather than\nthe not-static warning; otherwise the error would be unreachable for the case it\nexists to catch.\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"
994
994
  },
995
995
  {
996
996
  "path": "agents/schema-paths.md",
997
997
  "module": "schema-paths",
998
- "content": "# smrt-core/schema paths\n\nModule semantics for `src/schema/` — which `SchemaGenerator` entry point reaches\na real database, what each one emits, and the rules that keep them in step.\nPackage orientation, the cross-module invariants, and the traps that apply\nbefore editing anything live in [../AGENTS.md](../AGENTS.md) — read that first;\nits \"Schema paths\" section is the short form of everything below.\n\nWritten from the 2026-08-17 database-layer gap assessment (epic #2382). Symbol\nnames here are stable; the line numbers the assessment quotes are not, so trust\nthis call graph and re-grep before citing a location.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. They do not\nproduce the same schema for the same class.\n\n| Entry point | Selected by | Status |\n|---|---|---|\n| `generateSTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateCTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateSTISchemaFromRegistry` | `src/testing/database.ts` (`getTestDatabase()`), `src/schema/utils.ts` (`generateSchema`; `ensureSchema` only as a fallback) | tests + runtime helpers |\n| `generateSchemaFromRegistry` | the same two callers | tests + runtime helpers |\n\nA fifth entry point, the build-time AST `generateSchema(objectDef)`, existed\nuntil #2380: it fed only the `smrt:schema` virtual module, which had no\nconsumer, had rotted relative to the four paths above (an `idx_`-prefixed\nnaming scheme none of the others use, and no conflict-index emission at all),\nand was deleted rather than wired up. `SchemaOverrideSystem`\n(`schema/override-system.ts`) — unwired, and its two non-generic methods\nhard-coded a schema extension for a project outside this monorepo — was\ndeleted alongside it. See rule 9 and the new rule at the end of this file.\n\nProduction DDL takes the manifest route:\n\n```\n@smrt() class ─▶ scanner ─▶ manifest.json ─▶ generate{STI,CTI}SchemaFromManifest\n ─▶ registered `schema` ─▶ ObjectRegistry.getAllSchemasAsDefinitions()\n ├─▶ smrt db:migrate | db:diff | db:status\n │ (the CLI drives SchemaComparer + MigrationTracker directly)\n └─▶ migrateSmrtSchemas() / getPendingSchemaStatements()\n (src/migrations/orchestrate.ts — exported for programmatic\n use; no in-repo caller outside its own tests)\n```\n\nThe suite takes the registry route. Before #2359 the registry route emitted\nindexes the manifest route did not — per-column foreign-key indexes, and STI\npartial FK indexes filtered by `_meta_type` — so tests ran against a richer\nschema than any deployment received, the manifest STI path populated a\n`fkColumnsByClass` map it never read, and the manifest CTI path had no FK loop\nat all. `src/testing/database.ts`'s \"same as migrations\" comment described an\nintent, not the code.\n\nSince #2359 the two families share one set of index helpers and\n`src/schema/schema-path-parity.test.ts` runs the same fixture manifest through\nthe manifest paths, through `ObjectRegistry.registerFromManifest()` + the\nregistry paths, and through `getAllSchemasAsDefinitions()`, asserting identical\ncolumn and index sets. Extend that fixture with every generator change; a\ndivergence is a bug in the generator, not an exception to add to the test.\n\n### Index rules (#2359)\n\n- **Reference columns are always indexed.** `ensureReferenceColumnIndexes()`\n runs last on every path and gives each `@foreignKey`, `@crossPackageRef` and\n tenant column `<table>_<column>_idx` unless an UNQUALIFIED index (no `WHERE`,\n no JSON path) already leads with it — the `conflictColumns` unique index or an\n `indexed: true` opt-in, or the column's own inline UNIQUE. A partial\n `WHERE _meta_type = …` index does not count: base-class polymorphic queries\n carry no discriminator predicate. `indexed: true` on a reference column is\n redundant. Roll the index wave out to production with\n `smrt db:migrate --postgres-safe` (concurrent-index mode, #2362): a plain\n atomic batch takes SHARE/ACCESS EXCLUSIVE locks for ~230 index builds. STI FK indexes are plain, one per\n column, not per-class partial.\n- **No index on the primary key.** `<table>_id_idx` is gone from every path,\n and `conflictColumns` equal to the PK column set emit no conflict index\n (`ON CONFLICT (id)` binds to the PK constraint). `SchemaComparer` drops the\n legacy non-unique single-column PK index from existing databases without\n `--drop-indexes` when the live table reports that column as its sole primary\n key (never a UNIQUE one — on PostgreSQL that may back a custom-named PRIMARY\n KEY constraint, and `DROP INDEX` on it would fail the atomic batch).\n- **Slug loading keeps its index.** Custom `conflictColumns` replace the\n `(slug, context)` unique index; `loadFromSlug()`/`getId()`/`getSavedId()`\n still filter on slug/context, so a plain `<table>_slug_context_idx` is kept\n (additive; routing those lookups through the conflict key would change which\n row a slug resolves to). The tenant-led default key below counts as serving\n it (`servesSlugLookup()`): a tenant-scoped slug lookup carries the tenant\n predicate (#2365) and is served by the prefix, so no second index.\n- **Tenant-scoped tables key per tenant (#2360).** A tenant-scoped class with\n no explicit `conflictColumns` upserts on, and indexes,\n `(tenant_id, slug, context)` — `(tenant_id, slug, context, _meta_type)` for\n an STI hierarchy — resolved by one rule on both paths:\n `ManifestGenerator.normalizeConflictColumns()` materializes it into\n `decoratorConfig.conflictColumns` for the manifest paths (so the manifest,\n the schema, `smrt-knowledge.json` and the runtime read one value), and\n `ObjectRegistry.getConflictColumns()` derives the same value at runtime from\n the schema owner's `tenantScoped` config (`ObjectRegistry.getTenantColumn()`;\n an STI child resolves through its root; a `@report` class through its\n group/bucket columns; a custom primary key through that key). Explicit\n `conflictColumns` are never rewritten. `src/schema/conflict-target.ts` holds\n the shared helpers. Consequences: the index NAME stays\n `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so the differ\n swaps the columns of an existing global unique in place by name (a superset\n key — creating it cannot fail on existing rows); the tenant-led key also\n serves the tenant column, so `<table>_tenant_id_idx` is no longer emitted\n for those tables (an existing one is an orphan the differ drops only with\n `--drop-indexes`); NULL-tenant rows (`mode: 'optional'` outside a tenant\n context) dedup among themselves through the SDK's null-aware upsert\n (`IS NOT DISTINCT FROM` under a PostgreSQL advisory lock / an in-process\n lock on SQLite) — application-enforced now, where the old global index was\n database-enforced: the tenant-led index treats NULLs as distinct, so raw SQL\n can insert two global rows with one slug, and a raw\n `ON CONFLICT (slug, context…)` against such a table no longer binds (use\n `WHERE NOT EXISTS`, plus an advisory lock on PostgreSQL). Emitting\n `NULLS NOT DISTINCT` on PostgreSQL ≥ 15 (the SDK already detects it) would\n restore the database arbiter — a follow-up. The `save()` path serializes an\n unset tenant field as an explicit `NULL` whatever its registered type,\n because the SDK rejects an upsert whose conflict column is missing from the\n row.\n- **Rolling the tenant-led key out (#2360).** There is no mixed-version state:\n new code against the old index fails every NEW-object create on a\n tenant-scoped default-key table (PostgreSQL 42P10, SQLite \"ON CONFLICT\n clause does not match…\"), and old code against the new index fails the same\n way, because the conflict target must match the unique index's column set\n exactly; only persisted objects (upsert on `id`) keep saving. Deploy the code\n and run `smrt db:migrate` in the same maintenance step. The plan is one\n `DROP INDEX` + `CREATE UNIQUE INDEX` per table under the SAME name (a\n superset key, so the build cannot fail when the old same-name index was a\n valid UNIQUE over the subset key; a #1165-class table whose old index was\n non-unique or missing may hold duplicates that a superset UNIQUE rejects —\n `db:diff` shows which tables' old index is non-unique or missing; dedupe\n those rows before migrating). Atomic mode swaps every table in one\n transaction: `DROP INDEX` takes ACCESS EXCLUSIVE and holds it until commit,\n which blocks ALL access to those tables — reads included — for the batch;\n size `statementTimeout` for the largest tenant-scoped table. That is the\n maintenance window this rollout requires anyway (no mixed-version state), so\n run this wave — the #2359 index wave included — in atomic mode inside it;\n the \"roll out with `--postgres-safe`\" advice above applies to a #2359-only\n wave, because `--postgres-safe` runs the two statements sequentially per\n table, so each table has NO conflict index between them and a failed rebuild\n leaves it without one until the re-run. The recreate has no automatic\n DOWN: reverting the code means re-creating the old index by hand. And\n legacy NULL-tenant rows fork rather than get adopted — a tenant-context save\n whose slug matches a `(NULL, slug, ctx)` row now inserts `(tenant, slug,\n ctx)` beside it, and that tenant no longer sees the legacy row — so backfill\n `tenant_id` (anytown: `SET tenant_id = context::uuid`) BEFORE this release.\n Ingestion that relied on natural-key dedup across tenants now inserts one\n row per tenant (release note).\n- **STI `@field({ unique: true })` is enforced through indexes** (the differ can\n add an index to an existing table, never a column constraint): a full\n `<table>_<col>_unique_idx` when the STI base declares it, one\n `<table>_<col>_<class>_unique_idx WHERE _meta_type = '<qualified>'` per class\n when only descendants do — uniqueness per concrete class, not across the\n subtree. DuckDB/JSON have no partial indexes, so the descendant-scoped shape\n (`isStiSubtypeUniqueIndex`) is not emitted there — degrading it to a full\n UNIQUE would constrain every subtype; the DDL strategy and the differ both\n skip it, while other partial indexes keep degrading to full ones as before. Remember the\n framework serializes an unset text field as `''`, so a unique optional text\n field must be `nullable: true` with a `null` initializer or every unset row\n collides.\n- **Every class in an STI hierarchy carries the schema of the one shared\n table**, generated from the root base (`ManifestGenerator.generateSchemas()`\n resolves the root through `findSTIBaseInfo`), so a child never treats its own\n descendant-only unique field as base-declared.\n\n`src/schema/utils.ts` sits in between, and the two exports differ:\n\n- `generateSchema()` (reached from `SmrtCollection.generateSchema()`) always\n rebuilds from the registry and writes the result back into the registry,\n replacing whatever the manifest registered for that class.\n- `ensureSchema()` (reached from the deprecated `smrt db:setup`) is\n manifest-first: it takes `ObjectRegistry.getSchema()` plus the merged\n `getAllSchemasAsDefinitions()` table definition, and only falls back to\n `generateSchema()` when no schema is registered at all.\n\nSo a normal build keeps the manifest schema through `db:setup`, and a\nregistry-derived schema is a dev/test artifact. `smrt-content` shows what one\nlooks like: `packages/content/src/hooks.server.ts` `bootstrapSchema()` calls\n`generateSchema()` for every registered class and then `ensureSchema()` from the\nSvelteKit `handle` hook on any `/api/*` request, so that process holds\nregistry-derived schemas rather than the manifest ones. It reaches only that\npackage's own `vite dev` app — the library build excludes the file and the\npackage never exports it — but it is the shape to recognize. Check which route a\nprocess actually took before trusting a reproduction.\n\n## Why the drift stayed invisible\n\nEvery drift oracle compares a database with the same artifact that dropped the\nindex:\n\n- `verifyPersistenceTable()` (`src/schema/table-verifier.ts`) calls\n `db.tableExists()` and nothing else. \"Runtime verifies schema\" has always meant\n existence-only — no column, type, constraint, or index comparison.\n- `smrt doctor` never opens a database connection.\n- `db:status` and `db:diff` diff the live database against\n `getAllSchemasAsDefinitions()`, i.e. the manifest projection.\n\nAn index the manifest never emitted is \"in sync\" by construction. That is how a\nproduction database reached 164 unindexed `tenant_id` columns while `db:status`\nreported no drift (#2356 → #2359). The assessment's other counts — 196/231\n`@foreignKey` and 91/92 `@crossPackageRef` columns with no production index,\n238/238 tables carrying a redundant index on the primary key, zero DB-level\nforeign-key constraints on any engine — come from regenerating every package's\nschema against a live database, so re-measure rather than quote them once the\nepic's fixes land.\n\n## Rules\n\n### 1. Verify against the production path, not the test path\n\nAny change to column or index emission goes on **all** paths that ship and is\nproven by the path-parity test (`src/schema/schema-path-parity.test.ts`, #2359)\n— extend its fixture; a green suite otherwise proves the registry paths only.\nRead the call graph before believing a comment: \"same as migrations\" was wrong\nfor years.\n\n### 2. Every new query predicate ships with its index\n\nCollection methods, poll loops, auth lookups, junction right-side filters, and\npolymorphic owner lookups all count — or write down why the predicate does not\nneed one. For list workloads, EXPLAIN on a PostgreSQL snapshot; the measured\nspread on the assessed workload was 21 ms → 0.1 ms.\n\n### 3. Run the PostgreSQL lane\n\nAnything touching numeric types, uuid casts, upsert conflict targets, timestamps,\nor migrations runs the package's `test:postgres` script:\n\n```bash\npnpm --filter @happyvertical/smrt-<pkg> test:postgres\n```\n\ncore, cli, users, sales, marketing, analytics, and vitest carry the lane.\nSQLite's type affinity accepts values PostgreSQL rejects — a money field declared\n`number = 0` compiles to INTEGER and only fails on PG (#2361).\n\n### 4. Read the built artifact, not the source\n\nWhat a decorator produced is in `dist/manifest.json` and in regenerated schemas:\n`integer` vs `decimal`, the actual index list, the actual conflict columns. When\nthe question is \"how many tables/columns/indexes\", regenerate and count across\nevery package; do not sample a few and extrapolate.\n\n### 5. Index intent belongs on both the constraint and the read path\n\nA conflict target is not automatically a unique index, and a unique index is not\nautomatically the index a read path uses. Custom `conflictColumns` used to\nreplace the `(slug, context)` index while `loadFromSlug`/`getId` still queried\nslug+context, and STI dropped `@field({ unique: true })` — both fixed in #2359,\nsee \"Index rules\" above. Check the pair, not the declaration.\n\n### 6. Multi-tenancy is a whole-path property\n\nEvery unique constraint and every conflict target on a tenant-scoped table\nincludes the tenant column — otherwise a second tenant's `save()` of the same\nnatural key updates the first tenant's row through `DO UPDATE SET` (#2360; the\ndefault key now does, see \"Index rules\" — an explicit `conflictColumns` that\nomits the tenant column is the class author's own key and is not rewritten).\nAnd every read path is interceptor-aware: hydration\n(`loadFromId`/`loadFromSlug`), get-by-slug, vector search, and collection\nmemory, not only `list()` (#2365).\n\n### 7. Retry only transient errors\n\nClassify through the cause chain (SQLSTATE), never on a message substring, and\nnever retry inside an aborted PostgreSQL transaction (`25P02`). Test the\ncontract end to end against a real database, not only the classifier (#2366).\n\n### 8. Thread new decorator options through every config-rebuild site\n\nA new `@smrt()` or `@field()` option that affects schema must reach the\n`SchemaGeneratorConfig` type in `src/schema/generator.ts` and every site that\nrebuilds that config — `src/schema/utils.ts` and `src/testing/database.ts` — or\nit is silently dropped on the paths that rebuild it (#2357).\n\n### 9. Delete or wire dead paths, and write docs to what the code does\n\nDead code that looks canonical misleads the next agent: the AST `generateSchema`\npath, `SchemaOverrideSystem`, and the never-emitted `triggers: []` all read as\nsupported surfaces (#2380). Documentation follows the implementation, not the\nintent — say \"verifies the table exists\" when that is what runs.\n\n### 10. Untracked \"known limitation\" comments are bugs nobody will read\n\nFile the issue and link it from the comment. A `products` comment explaining why\na conflict-column change was refrained from sat there for months — and\nmisdescribed the failure mode the whole time.\n\n### 11. Consumer repair scripts are signals\n\nDownstream repair tooling (anytown's `db-repair-plan.ts` carried column-type\nrepairs, missing STI columns and indexes, and `tenant_id` backfills since April)\nis the consumer-side record of framework gaps. Mine it during triage.\n\n### 12. Try to falsify before filing, and treat operations as correctness\n\nRe-verify a finding at source before it becomes an issue — one assessment\ncandidate claimed conflict indexes past two columns were narrowed to two\ncolumns, when only the index *name* is shortened. And an index fix that ships\nwithout a bounded-timeout, `CONCURRENTLY`-capable migrate path can take\nproduction down on rollout (#2362).\n\n### 13. Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), the default list ordering (rule 18\nbelow), and single columns opted in with `@field({ indexed: true })`. A list\nworkload's access path is composite, so declare it:\n\n```ts\n@smrt({\n indexes: [\n { name: 'contents_tenant_id_publish_date_idx',\n columns: ['tenantId', 'publish_date'] },\n ],\n})\n```\n\n`columns` takes field names or column names in access-path order — filter\ncolumns first, sort column last. Declare columns, not a direction: PostgreSQL\nscans a btree either way, so an ascending index also serves the matching\n`ORDER BY ... DESC` as an ordered scan with no Sort node. `unique` and `where`\n(partial index) are honoured.\n\n`appendDeclaredIndexes()` runs first on all four entry points, ahead of\n`ensureDefaultListOrderingIndex()` (rule 18) and `ensureReferenceColumnIndexes()`,\nso a declared composite leading with the tenant column (or any reference column)\nreplaces the automatic standalone index rather than duplicating it.\nUnknown columns, malformed entries, and a name collision with a different index\nall fail generation — a silently dropped index only surfaces later as a\nproduction slowdown. Rule 8 above is why this works at runtime at all.\n\n### 14. Relationship targets resolve to a class name on both paths\n\n`@foreignKey`/`@oneToMany`/`@manyToMany` accept a class, a name string, or a\n`() => Target` thunk. The decorator invokes the thunk and throws when the target\ncannot be resolved (never `related: ''`); the scanner unwraps the same thunk\nfrom raw source (never `related: '() => Target'`). An unresolved target silently\ncosts the relationship edge, `loadRelated()`, and the FK-derived index (#2379).\nA thunk resolves at decoration time, so a target declared later in the same\nmodule is still in its temporal dead zone — use the string form there.\n\n### 15. A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced only on an empty table;\n on a populated one it is added nullable and the `NOT NULL` is reported as a\n manual follow-up on every engine.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1). The #2370 rebuild (rule 15) consumes\n only `type_upgrade` placeholders today; extending it to rewrite constraints\n would lift this.\n- Defaults compare through `canonicalizeDefault()`, which folds engine\n renderings (`'x'::text`, `CAST('t' AS BOOLEAN)`, `CURRENT_TIMESTAMP` vs\n `now()`) by manifest type; an unclassifiable rendering skips the comparison\n rather than risking a false positive that would churn every run. The\n round-trip test (create from each DDL strategy → compare → zero changes) in\n `src/migrations/__tests__/issue-2369-*.test.ts` guards this.\n\n### 16. `schema.ddl` is a preview, not the table\n\n`SchemaDefinition.ddl` / `manifest.json` `schema.ddl` is the engine-neutral\nCREATE TABLE string from `SchemaGenerator.generateSQL()` with no engine: no\nindexes, no triggers, abstract `REAL`/`JSON`/`UUID`/`TIMESTAMP`. It is kept for\nbackward compatibility only. Everything that needs an executable table renders\n`columns` + `indexes` through `getDDLStrategy(engine)` — `db:migrate`\n(`migrations/orchestrate.ts`), `MigrationGenerator` (default\n`materializeStructuredSchema: true`; `false` is a deprecated opt-out),\n`SchemaAggregator`, and `createIsolatedTestDbFromManifest` in smrt-vitest, the\nlast two via `src/schema/manifest-schema.ts` (`collectManifestTables` /\n`renderCollectedManifestTable`). The cached string is merged in only for a\ntable whose contributors expose no structured columns (hand-authored\nmanifests); table constraints that exist only in the string are dropped with a\nwarning, as `db:migrate` drops them. Do not add a new consumer of the\nstring, and do not write a private CREATE INDEX renderer — the retired ones\ndropped `where` and `jsonPath` (#2358). Every DDL strategy also spells out\n`PRIMARY KEY NOT NULL`: SQLite lets a bare non-INTEGER PRIMARY KEY hold NULL.\n\n### 17. The merged table shape is registration-order independent (#2372)\n\n`getAllSchemas()` and `getAllSchemasAsDefinitions()` fold every class that\nshares a physical table — the whole STI hierarchy — into one shape. Both route\nthrough `buildMergedTableSchemas()`, which groups contributors by table and\nthen merges them in a **deterministic** order: the STI base first, then\nancestors before descendants, then by qualified name.\n\nThat order matters because the first contributor seeds the table: it supplies\nthe fallback base columns, the `idType`, the conflict columns and the cached\nDDL, and its columns win every merge conflict. When registration order decided\nit, an STI child that carries no manifest `schema` — the external- and\nconsumer-manifest case — seeded the table from bare fallback columns and the\nbase class's richer ones were skipped when it registered later, yielding\n`context TEXT` instead of `context TEXT NOT NULL DEFAULT ''` and timestamps\nwith no NOT NULL/DEFAULT. The shipped content manifest lists `Article` before\n`Content`, so the losing order was the one that shipped, and the differ\ncompares types only, so the weak fresh-create was never repaired.\n\nTwo invariants keep the two assembly paths agreeing:\n\n- `createBaseColumns()` mirrors what `generateSchemaFromManifest` /\n `generateSTISchemaFromManifest` emit for the same table, so a table built\n from runtime field metadata alone has the same NOT NULL/DEFAULT shape as one\n built from a manifest. Note `_meta_type` is `TEXT NOT NULL` with **no**\n default, matching the generator.\n- `fieldsToColumns()` reads `required`, `default`, and `description` from the\n top level *or* `_meta`. Registry fields normalize them into `_meta`\n (`manifest-field-merge.ts`), so reading only the top level silently dropped\n NOT NULL and DEFAULT for every registry-sourced field.\n\nSTI columns stay nullable regardless of the field's `required` flag\n(`fieldsToColumns(fields, { stiUnionColumns: true })`): the table holds the\nunion of all subtypes' fields, so a column only one subtype declares is never\npopulated on a sibling's row. Declared defaults are still emitted. This matches\n`generateSTISchemaFromManifest`, which sets `notNull: false` on every non-system\nSTI column.\n\nWhen adding a class-level input to the merged shape, take it from the seeding\ncontributor rather than \"whichever class arrives first\", and cover it with a\nchild-first/base-first equality test.\n\n### 18. The generator owns the index for its own default ordering (#2363)\n\nEvery generated list surface — REST, MCP, the SvelteKit list route — pages with\n`ORDER BY created_at DESC, <pk> ASC` (`DEFAULT_LIST_ORDER_BY`, #2367), and\nuntil #2363 no schema path indexed `created_at` (the AST path, deleted in\n#2380, indexed `updated_at`), so the framework's own default page was a\nsequential scan plus a top-N sort. `ensureDefaultListOrderingIndex()` now runs\non all four entry points and emits:\n\n- `(<tenant column>, created_at)` on a tenant-scoped table — the tenancy\n interceptor puts `tenant_id = ?` in front of every list, so the tenant column\n leads and `created_at` orders within it. This composite **replaces** the\n standalone tenant index from #2359: a B-tree serves every prefix of its\n column list, so `ensureDefaultListOrderingIndex()` is called first and\n `ensureReferenceColumnIndexes()` then sees the column as already served. The\n tenant column is found by `referenceKind === 'tenantId'`, never by the\n `tenant_id` spelling — `@smrt({ tenantScoped: { field } })` renames it.\n- `(created_at)` otherwise.\n\nThree deliberate omissions, so nobody \"fixes\" them later:\n\n- **No `DESC`.** `IndexDefinition` carries no per-column direction and\n PostgreSQL scans a B-tree backwards just as cheaply.\n- **No primary-key tiebreak column.** The default order mixes directions\n (`created_at DESC, id ASC`), so no single-direction index satisfies the whole\n key; the leading columns already turn a full sort into an index scan plus an\n incremental sort over rows sharing a timestamp.\n- **Not scoped per STI subtype.** `(_meta_type, created_at)` would serve a\n child collection's list but not the base class's polymorphic one, which\n carries no discriminator predicate — the same reasoning that keeps STI\n reference indexes plain (#2359). One unqualified index per shared table.\n\nAn existing UNQUALIFIED index that already leads with the same columns\nsuppresses it — a partial or JSON-path index never counts. That is how a\ndeclared `@smrt({ indexes: [...] })` composite (#2357) takes over: declaring\n`(tenant_id, created_at, status)` replaces the generated pair, while declaring\na different sort column such as `(tenant_id, publish_date)` sits **beside** it,\nbecause that index cannot order the default page. Declared indexes are appended\nbefore this helper for exactly that reason; anything that appends an index in\nfuture goes in the same slot, ahead of `ensureDefaultListOrderingIndex()` and\n`ensureReferenceColumnIndexes()`.\n\n### 19. One conflict-target rule, applied on every producer\n\n`save()` upserts on `ObjectRegistry.getConflictColumns()`; the schema must\ncarry exactly one unique index over those columns (or they must be the\nprimary key). Keep the derivation in `src/schema/conflict-target.ts` and let\nevery producer call it — the three manifest pipelines share\n`ManifestGenerator.applyGenerationPasses()` since #2360 because\n`ManifestBuilder` had silently skipped the report passes for months. When you\nadd a way for the key to vary (a new decorator option, a new class kind),\nthread it through `getConflictColumns()`, `normalizeConflictColumns()` and the\ngenerator's `resolveConflictTarget()` together, and extend the parity test's\n\"unique index == conflict target\" assertion; a key the runtime uses and the\nschema does not index is a hard PostgreSQL error (42P10) on the first save,\nand a key the schema indexes without the tenant column is the silent\ncross-tenant overwrite this rule exists for.\n\n### 20. Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates any identifier past 63 **bytes** and reports nothing;\nSQLite and DuckDB do not, so the entire test suite was blind to it. The 66-byte\n`content_contribution_revisions_contribution_id_revision_number_idx` shipped\nthat way — only the differ's signature-equivalence check kept it from emitting\n`add_index` on every run. Two names agreeing for 63 bytes is the real hazard:\n`CREATE INDEX IF NOT EXISTS` no-ops against the wrong index, and the second\nindex is never created.\n\n`schema/index-utils.ts` owns the guard, and it splits by who owns the name:\n\n- **Generated index, trigger and PL/pgSQL function names** →\n `shortenIdentifier()`. Deterministic `<head>_<digest><suffix>`, digest taken\n over the **full** original so a shared prefix still yields distinct names, and\n a recognised suffix (`_idx`, `_unique_idx`, `_key`, `_pkey`) preserved.\n- **Hand-declared `@smrt({ indexes: [{ name }] })`** → `assertIdentifierFits()`,\n a hard error in `validateDeclaredIndex()`. Renaming what a developer wrote is\n worse than refusing it, and `SchemaComparer` matches indexes **by name**\n first, so a 70-byte declaration could never match the 63-byte index\n PostgreSQL stored and `db:migrate` would emit `add_index` forever.\n- **Table and column names** → deliberately **not** guarded. PostgreSQL\n truncates identifiers *consistently on every reference*: `CREATE TABLE\n \"<80 bytes>\"` and a later `SELECT ... FROM \"<the same 80 bytes>\"` both resolve\n to the same stored 63-byte name, so one long name round-trips fine end to end.\n `smrt-users` depends on this — it ships an intentional 80-byte\n `@smrt({ tableName })` (`permission_policy_table_name_that_is_far_too_long…`)\n and derives unique Postgres RLS policy names from it. An earlier revision of\n this rule hard-errored here on the theory that the runtime resolves tables by\n name and would break; that theory is wrong for the reason above, and the error\n broke `packages/users`. The residual collision risk is over a name the\n developer chose, not one the generator manufactured.\n\n`enforceIdentifierLimits()` is the single call site per path, placed **after**\n`ensureReferenceColumnIndexes()` — nothing may lengthen a name after it. Doing\nthe shortening at the end rather than at each `indexes.push()` is safe because\nthe digest covers the whole original name, so entries distinct before shortening\nstay distinct after; the helper still throws if two ever collide. The migrate\nleg's `withConflictIndex()` (`registry/schema-builder.ts`) and the PostgreSQL\ntrigger-function name call `shortenIdentifier()` directly, because they compose\na name outside the generator's index list. Note that an over-long *table* name\nstill yields in-limit, distinct *index* names, because the shortening runs over\nthe whole composed name.\n\nThe digest is FNV-1a, not `node:crypto`: `index-utils.ts` is re-exported from\n`schema/utils.ts`, which exists to keep Node built-ins out of browser bundles.\nIt only has to be *stable* — a shortened name that changed between releases\nwould make every deployment drop and recreate the index — so the parity and\nunit tests pin the literal output rather than recomputing it. Unpaired\nsurrogates are folded to U+FFFD before both counting and hashing, so the digest\nis taken over exactly the bytes the driver transmits.\n\nExisting databases migrate **by name swap, without a rebuild**: the live index\nstill carries the name PostgreSQL truncated it to, the manifest now carries the\nshortened one, and the differ claims it by signature (columns + uniqueness +\npredicate), emitting nothing — including under `includeDroppedIndexes`. See\n`migrations/__tests__/index-drift.test.ts` and the PostgreSQL lane test\n`schema/issue-2374-identifier-length-postgres.optional.test.ts`.\n\nOut of scope, deliberately: constraint names PostgreSQL invents for itself. A\nCTI table's inline `UNIQUE` produces an implicit `<table>_<column>_key`, which\ncan exceed 63 bytes even when the table and column each fit. SMRT never names\nit, and PostgreSQL disambiguates its own truncations by appending a counter\nrather than collapsing them, so there is no silent-collision hazard there.\n\n### 21. The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Same-package referential integrity uses two matching rails\n\n`@foreignKey(Target)` emits a physical database constraint when the target is\nin the same package and applies the same action through `SmrtObject.delete()`\nin `src/cascade.ts`. A shared delete-action resolver keeps both paths aligned;\nthe established generated `ON UPDATE CASCADE` default remains unchanged:\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Ordinary same-package reference | `NO ACTION` — deletion is refused while references remain |\n| Every `@tenantId()` field | Excluded from physical constraints and delete cascades |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and therefore defaults to\nimmediate `NO ACTION` unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field.\n\n`@crossPackageRef()` remains runtime-only: it registers relationship loading\nand indexes but deliberately emits no physical constraint, avoiding circular\npackage DDL. Tenant markers follow the same non-constraint rule because a\ntenant is a scope, not an ownership edge.\n\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\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\nProperties to keep if you touch that module:\n\n- **The plan is registry-derived and rebuilt per delete.** Registration is\n incremental — manifests load lazily and tests register classes between cases —\n so a cached plan would silently skip a table that registered later. Cache it\n only behind an invalidation hook that every registration path calls.\n- **A class with nothing pointing at it skips the transaction entirely — but\n `CascadePlan.isEmpty` requires no polymorphic association class anywhere in\n the process, not just no typed references.** `buildCascadePlan()` pushes\n *every* registered `SmrtPolymorphicAssociation` subclass into\n `plan.polymorphic` unconditionally (`cascade.ts` around\n `isPolymorphicAssociationClass`): a `metaType` column can point at any class\n at runtime, so there is no static metadata to scope it by the target being\n deleted. One registered polymorphic class anywhere makes `isEmpty` false for\n every delete in that process — do not read \"the common case skips the\n transaction\" as \"most deletes in a real app skip it\"; in a multi-package app\n that registers even one polymorphic association, almost none do.\n `runCascadeDelete()` builds the plan for `getResolvedQualifiedName()` (not the\n bare constructor name — two packages can register the same simple name).\n- **Cascaded rows are removed set-based.** Their `beforeDelete`/`afterDelete`\n hooks and interceptors do not run and no change-feed tombstone is written for\n them, which is exactly what a DB-level `ON DELETE CASCADE` does. Only the\n object `delete()` was called on runs the lifecycle. Do not \"improve\" this into\n a per-row model delete without deciding what that means for sync consumers.\n- **Everything is one transaction where the adapter has one**, including the\n object's own `DELETE`, whenever there is anything to cascade. The `RESTRICT`\n checks run first, before any mutation, so a refusal costs nothing; the\n transaction is what makes a refusal *deeper* in the graph safe.\n- **`_smrt_embeddings` and `_smrt_contexts` are matched by id *and* a\n class-name candidate set, not id alone.** Their class columns store the\n *runtime* constructor name, which for an STI hierarchy is a concrete\n subclass rather than the class the cascade planned from — id-alone matching\n looked STI-safe, but let two unrelated classes using `idType: 'text'`\n (non-UUID, not guaranteed globally unique) collide on a shared id value and\n delete each other's rows (review fix). `ownerClassCandidates()` expands to\n every STI hierarchy member of the class the ids actually belong to, in both\n qualified and simple form. A failure to clean them is logged, never raised —\n an application database may predate the table, and losing derived rows must\n not fail a valid delete.\n\n`_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals` and the dispatch tables are\ndeliberately **not** cascaded. They are append-only logs; the change feed in\nparticular receives the delete's own tombstone, so cascading it would erase the\nrecord that tells sync clients the row is gone.\n\n### 22. System tables get a retention policy, not just a prune function (#2375)\n\nFour framework-owned tables grow with traffic and nothing used to remove a row:\n`_smrt_changes` (one per save/delete), `_smrt_ai_usage` (one per AI call, and\npersistence is on by default), `_smrt_contexts` (whose `expires_at` nothing\nenforced) and `_smrt_dispatch` (an operator-only `dispatch:cleanup`).\n`src/system/retention.ts` is now the single place that bounds them.\n\n- **`runRetentionSweep(db, policy)` is the entry point.** It runs the four\n built-in tasks in a fixed order, then every task other packages contributed\n via `registerRetentionTask()` — `@happyvertical/smrt-jobs` registers\n `_smrt_jobs`/`_smrt_job_events`, `@happyvertical/smrt-users` registers\n session/magic-link/CLI-auth expiry. A task that throws is recorded on its own\n result and the sweep continues; a missing table reports `unavailable`, so a\n sweep is safe against a partially bootstrapped database.\n- **A contributed task only exists in a process that loaded its package.** Both\n packages register on import from their entry point, and the registry lives on\n `globalThis` (like `ObjectRegistry`) so a duplicated `smrt-core` resolution\n cannot split it. `smrt db:prune` optionally imports both packages for exactly\n this reason — a project that installs neither correctly gets neither task.\n- **Defaults are opt-out, not opt-in.** `DEFAULT_RETENTION_POLICY` covers the\n four built-in tables (changes 30 days, AI usage 90 days, dispatch 30 days\n completed / 90 days failed, contexts strictly by their own `expires_at`), and\n those are the ones `smrt.configure({ retention })` tunes. Contributed tasks\n carry their own defaults and their own window options —\n `DEFAULT_JOB_RETENTION` (7 days terminal / 30 days failed / 30 days events,\n set through `registerJobRetentionTasks()` or the runner's `retention.jobs`),\n and expired credentials, which have no window because an expired credential\n has nothing worth retaining. Every task, built-in or contributed, can be\n turned off: a table set to `false`, a task set to `false` under `tasks`, or\n `enabled: false` for the whole sweep — through `smrt.configure`,\n `smrt db:prune --skip`, or the runner's `retention` config.\n- **Contributed task names are prefixed with the owning package's short name**\n (`jobs-records`, `jobs-events`, `users-sessions`, …) because the registry is\n one process-global namespace.\n- **Scheduling lives outside core.** A running `TaskRunner` sweeps every six\n hours (`retention: false` opts out) and `smrt db:prune` is the cron entry\n point. The first runner sweep is one interval after `start()`, never at\n start: a crash-looping worker must not become a delete loop.\n- **Every prune counts before it deletes.** `rowCount` is not reliably\n populated across the engines SMRT supports, so counting is both what gives a\n usable figure and what lets `dryRun` preview the *same* predicate rather than\n an approximation of it. Count and delete are two statements and deliberately\n not one transaction — a maintenance pass must not hold a write lock over a\n large delete — so the figure is approximate under concurrent writers. Where\n two bounds can select the same row (`pruneChangeFeed`, `pruneAiUsage`), the\n second bound excludes what the first already accounted for, so a dry run does\n not count an entry twice.\n- **Every retention predicate ships with its index** (rule 2 applies to\n maintenance SQL too): `_smrt_contexts(expires_at)`,\n `_smrt_ai_usage(tenant_id, created_at)` — which is also the subscriptions\n billing meter's range scan — `_smrt_dispatch(status, processed_at)` and\n `(status, updated_at)` come from the system DDL, so they reach existing\n databases through the `SMRT_SCHEMA_VERSION` bump that replays it.\n `_smrt_jobs(status, completed_at)` comes from\n `ensureJobsSystemTableCompatibility()` instead, because `_smrt_jobs` is\n generated from a decorated class and does not exist yet when bootstrap runs;\n the jobs collection calls that path on every `initialize()`.\n- **Expiry enforcement is prune-side only.** `recall()`/`recallAll()` keep\n their documented \"expiry is not applied at read time\" contract — changing it\n would change read semantics for existing callers, which is a different issue\n from bounding storage. `LearningMemory` filters expired rows itself.\n\n### 23. Dead generation surfaces were deleted, not wired (#2380)\n\nRule 9 named three surfaces that read as canonical but were not: the AST\n`generateSchema(objectDef)` entry point, `SchemaOverrideSystem`, and the\nnever-emitted `triggers: []`. Resolution, so a future agent does not re-open\nwhat was deliberately decided:\n\n- **The AST path is gone.** `SchemaGenerator.generateSchema(objectDef)` and its\n AST-only private helpers (`generateIndexes`, `generateTriggers`,\n `extractDependencies`, `generateVersion`, `getTableName`,\n `extractPackageName`) were deleted from `schema/generator.ts`, along with\n their sole caller, `generateSchemaModule()` in `vite-plugin/index.ts`, and the\n `smrt:schema` / `@happyvertical/smrt-virt-schema` virtual module registration\n that fed. Nothing else called it — grep the deleted method's exact name\n before assuming a caller was missed; the path-parity fixture and every other\n rule above already speak only of the four surviving entry points.\n- **`SchemaOverrideSystem` is gone**, file and all\n (`schema/override-system.ts` no longer exists). It was never called from\n anywhere in this repository outside its own now-deleted exports, and two of\n its five public methods (`createPraecoContentOverride`,\n `createPraecoMeetingOverride`) hard-coded a schema extension for a\n consuming project outside this monorepo — scaffolding that never belonged in\n the framework, not a generic feature with a missing caller. `SchemaOverride`\n (the type) went with it; `ColumnDefinition`/`IndexDefinition`/\n `TriggerDefinition`, which it merely referenced, did not.\n- **The DDL-strategy trigger machinery was kept, not deleted.**\n `TriggerDefinition`, `SchemaDefinition.triggers`, and every DDL strategy's\n `generateTriggers()` / `generateTriggerStatement()` / `supportsTriggers()`\n (`schema/ddl/*.ts`) are real, engine-uniform, directly-tested rendering code\n that runs on **every** table creation via `strategy.generateTriggers(schema)`\n — unlike the AST path, this is not an orphaned call graph. It is kept for the\n same reason rule 16 keeps the cached `schema.ddl` string: `SchemaDefinition`\n is part of the shape third-party tooling and published manifests may already\n depend on, and `EngineSpecificDDL`/`MultiEngineDDL` (`schema/ddl/types.ts`)\n carry `triggers` as part of that same contract. Deleting a published field is\n a different (and unjustified) risk from deleting a virtual module nothing\n ever imported.\n- **What changed is what is documented, not what runs.** `schema.triggers` is\n now explicitly documented (`schema/types.ts`) as always `[]` on every schema\n a `@smrt()` class can produce, and why: there is no `@smrt()`/`@field()`\n option that populates it (unlike `indexes`, #2357), `updated_at` is\n maintained at the application layer (`SmrtObject.save()`), and\n `migrations/differ.ts` never diffs triggers — so even a hand-populated one\n would only apply to a newly `CREATE TABLE`d table and never retrofit an\n existing one. Wiring live trigger emission was considered and rejected for\n this issue: it is a migration-rollout feature (retrofitting 238+ existing\n production tables needs the same `SMRT_SCHEMA_VERSION`-replay or differ\n support rule 21/rule 22's system-table work required), not a cleanup, and\n nothing in the epic depended on it the way #2359 depended on FK indexes\n actually shipping.\n- **`_smrt_signals` and `ObjectRegistry.persistToDatabase()`/`loadFromDatabase()`**\n — named in the original finding alongside triggers — were already handled by\n #2376 before this issue landed: see rule 21 and `system/schema.ts`'s\n `RETIRED_SYSTEM_TABLES`. Nothing further to do there.\n- **The two config-rebuild-site comments** (`schema/utils.ts`,\n `testing/database.ts`) rule 8 requires were already in place, added by\n #2357/#2360; the `testing/database.ts` \"same as migrations\" overclaim rule 1\n quotes was already corrected by #2359, and doctor's `experimentalDecorators`\n check was already fixed by #2368/#2399 (see `packages/cli/AGENTS.md`\n Gotchas). Re-verify against current source before repeating any of these —\n the epic's PRs landed across one evening and a stale assessment line is not\n proof a fix is still needed.\n"
998
+ "content": "# smrt-core/schema paths\n\nModule semantics for `src/schema/` — which `SchemaGenerator` entry point reaches\na real database, what each one emits, and the rules that keep them in step.\nPackage orientation, the cross-module invariants, and the traps that apply\nbefore editing anything live in [../AGENTS.md](../AGENTS.md) — read that first;\nits \"Schema paths\" section is the short form of everything below.\n\nWritten from the 2026-08-17 database-layer gap assessment (epic #2382). Symbol\nnames here are stable; the line numbers the assessment quotes are not, so trust\nthis call graph and re-grep before citing a location.\n\n## Four entry points, two of which ship\n\n`src/schema/generator.ts` exposes four index-emitting entry points. They do not\nproduce the same schema for the same class.\n\n| Entry point | Selected by | Status |\n|---|---|---|\n| `generateSTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateCTISchemaFromManifest` | `src/scanner/manifest-generator.ts` | **production** |\n| `generateSTISchemaFromRegistry` | `src/testing/database.ts` (`getTestDatabase()`), `src/schema/utils.ts` (`generateSchema`; `ensureSchema` only as a fallback) | tests + runtime helpers |\n| `generateSchemaFromRegistry` | the same two callers | tests + runtime helpers |\n\nA fifth entry point, the build-time AST `generateSchema(objectDef)`, existed\nuntil #2380: it fed only the `smrt:schema` virtual module, which had no\nconsumer, had rotted relative to the four paths above (an `idx_`-prefixed\nnaming scheme none of the others use, and no conflict-index emission at all),\nand was deleted rather than wired up. `SchemaOverrideSystem`\n(`schema/override-system.ts`) — unwired, and its two non-generic methods\nhard-coded a schema extension for a project outside this monorepo — was\ndeleted alongside it. See rule 9 and the new rule at the end of this file.\n\nProduction DDL takes the manifest route:\n\n```\n@smrt() class ─▶ scanner ─▶ manifest.json ─▶ generate{STI,CTI}SchemaFromManifest\n ─▶ registered `schema` ─▶ ObjectRegistry.getAllSchemasAsDefinitions()\n ├─▶ smrt db:migrate | db:diff | db:status\n │ (the CLI drives SchemaComparer + MigrationTracker directly)\n └─▶ migrateSmrtSchemas() / getPendingSchemaStatements()\n (src/migrations/orchestrate.ts — exported for programmatic\n use; no in-repo caller outside its own tests)\n```\n\nThe suite takes the registry route. Before #2359 the registry route emitted\nindexes the manifest route did not — per-column foreign-key indexes, and STI\npartial FK indexes filtered by `_meta_type` — so tests ran against a richer\nschema than any deployment received, the manifest STI path populated a\n`fkColumnsByClass` map it never read, and the manifest CTI path had no FK loop\nat all. `src/testing/database.ts`'s \"same as migrations\" comment described an\nintent, not the code.\n\nSince #2359 the two families share one set of index helpers and\n`src/schema/schema-path-parity.test.ts` runs the same fixture manifest through\nthe manifest paths, through `ObjectRegistry.registerFromManifest()` + the\nregistry paths, and through `getAllSchemasAsDefinitions()`, asserting identical\ncolumn and index sets. Extend that fixture with every generator change; a\ndivergence is a bug in the generator, not an exception to add to the test.\n\n### Index rules (#2359)\n\n- **Reference columns are always indexed.** `ensureReferenceColumnIndexes()`\n runs last on every path and gives each `@foreignKey`, `@crossPackageRef` and\n tenant column `<table>_<column>_idx` unless an UNQUALIFIED index (no `WHERE`,\n no JSON path) already leads with it — the `conflictColumns` unique index or an\n `indexed: true` opt-in, or the column's own inline UNIQUE. A partial\n `WHERE _meta_type = …` index does not count: base-class polymorphic queries\n carry no discriminator predicate. `indexed: true` on a reference column is\n redundant. Roll the index wave out to production with\n `smrt db:migrate --postgres-safe` (concurrent-index mode, #2362): a plain\n atomic batch takes SHARE/ACCESS EXCLUSIVE locks for ~230 index builds. STI FK indexes are plain, one per\n column, not per-class partial.\n- **No index on the primary key.** `<table>_id_idx` is gone from every path,\n and `conflictColumns` equal to the PK column set emit no conflict index\n (`ON CONFLICT (id)` binds to the PK constraint). `SchemaComparer` drops the\n legacy non-unique single-column PK index from existing databases without\n `--drop-indexes` when the live table reports that column as its sole primary\n key (never a UNIQUE one — on PostgreSQL that may back a custom-named PRIMARY\n KEY constraint, and `DROP INDEX` on it would fail the atomic batch).\n- **Slug loading keeps its index.** Custom `conflictColumns` replace the\n `(slug, context)` unique index; `loadFromSlug()`/`getId()`/`getSavedId()`\n still filter on slug/context, so a plain `<table>_slug_context_idx` is kept\n (additive; routing those lookups through the conflict key would change which\n row a slug resolves to). The tenant-led default key below counts as serving\n it (`servesSlugLookup()`): a tenant-scoped slug lookup carries the tenant\n predicate (#2365) and is served by the prefix, so no second index.\n- **Tenant-scoped tables key per tenant (#2360).** A tenant-scoped class with\n no explicit `conflictColumns` upserts on, and indexes,\n `(tenant_id, slug, context)` — `(tenant_id, slug, context, _meta_type)` for\n an STI hierarchy — resolved by one rule on both paths:\n `ManifestGenerator.normalizeConflictColumns()` materializes it into\n `decoratorConfig.conflictColumns` for the manifest paths (so the manifest,\n the schema, `smrt-knowledge.json` and the runtime read one value), and\n `ObjectRegistry.getConflictColumns()` derives the same value at runtime from\n the schema owner's `tenantScoped` config (`ObjectRegistry.getTenantColumn()`;\n an STI child resolves through its root; a `@report` class through its\n group/bucket columns; a custom primary key through that key). Explicit\n `conflictColumns` are never rewritten. `src/schema/conflict-target.ts` holds\n the shared helpers. Consequences: the index NAME stays\n `<table>_slug_context_idx` / `_slug_context_meta_type_idx`, so the differ\n swaps the columns of an existing global unique in place by name (a superset\n key — creating it cannot fail on existing rows); the tenant-led key also\n serves the tenant column, so `<table>_tenant_id_idx` is no longer emitted\n for those tables (an existing one is an orphan the differ drops only with\n `--drop-indexes`); NULL-tenant rows (`mode: 'optional'` outside a tenant\n context) dedup among themselves through the SDK's null-aware upsert\n (`IS NOT DISTINCT FROM` under a PostgreSQL advisory lock / an in-process\n lock on SQLite) — application-enforced now, where the old global index was\n database-enforced: the tenant-led index treats NULLs as distinct, so raw SQL\n can insert two global rows with one slug, and a raw\n `ON CONFLICT (slug, context…)` against such a table no longer binds (use\n `WHERE NOT EXISTS`, plus an advisory lock on PostgreSQL). Emitting\n `NULLS NOT DISTINCT` on PostgreSQL ≥ 15 (the SDK already detects it) would\n restore the database arbiter — a follow-up. The `save()` path serializes an\n unset tenant field as an explicit `NULL` whatever its registered type,\n because the SDK rejects an upsert whose conflict column is missing from the\n row.\n- **Rolling the tenant-led key out (#2360).** There is no mixed-version state:\n new code against the old index fails every NEW-object create on a\n tenant-scoped default-key table (PostgreSQL 42P10, SQLite \"ON CONFLICT\n clause does not match…\"), and old code against the new index fails the same\n way, because the conflict target must match the unique index's column set\n exactly; only persisted objects (upsert on `id`) keep saving. Deploy the code\n and run `smrt db:migrate` in the same maintenance step. The plan is one\n `DROP INDEX` + `CREATE UNIQUE INDEX` per table under the SAME name (a\n superset key, so the build cannot fail when the old same-name index was a\n valid UNIQUE over the subset key; a #1165-class table whose old index was\n non-unique or missing may hold duplicates that a superset UNIQUE rejects —\n `db:diff` shows which tables' old index is non-unique or missing; dedupe\n those rows before migrating). Atomic mode swaps every table in one\n transaction: `DROP INDEX` takes ACCESS EXCLUSIVE and holds it until commit,\n which blocks ALL access to those tables — reads included — for the batch;\n size `statementTimeout` for the largest tenant-scoped table. That is the\n maintenance window this rollout requires anyway (no mixed-version state), so\n run this wave — the #2359 index wave included — in atomic mode inside it;\n the \"roll out with `--postgres-safe`\" advice above applies to a #2359-only\n wave, because `--postgres-safe` runs the two statements sequentially per\n table, so each table has NO conflict index between them and a failed rebuild\n leaves it without one until the re-run. The recreate has no automatic\n DOWN: reverting the code means re-creating the old index by hand. And\n legacy NULL-tenant rows fork rather than get adopted — a tenant-context save\n whose slug matches a `(NULL, slug, ctx)` row now inserts `(tenant, slug,\n ctx)` beside it, and that tenant no longer sees the legacy row — so backfill\n `tenant_id` (anytown: `SET tenant_id = context::uuid`) BEFORE this release.\n Ingestion that relied on natural-key dedup across tenants now inserts one\n row per tenant (release note).\n- **STI `@field({ unique: true })` is enforced through indexes** (the differ can\n add an index to an existing table, never a column constraint): a full\n `<table>_<col>_unique_idx` when the STI base declares it, one\n `<table>_<col>_<class>_unique_idx WHERE _meta_type = '<qualified>'` per class\n when only descendants do — uniqueness per concrete class, not across the\n subtree. DuckDB/JSON have no partial indexes, so the descendant-scoped shape\n (`isStiSubtypeUniqueIndex`) is not emitted there — degrading it to a full\n UNIQUE would constrain every subtype; the DDL strategy and the differ both\n skip it, while other partial indexes keep degrading to full ones as before. Remember the\n framework serializes an unset text field as `''`, so a unique optional text\n field must be `nullable: true` with a `null` initializer or every unset row\n collides.\n- **Every class in an STI hierarchy carries the schema of the one shared\n table**, generated from the root base (`ManifestGenerator.generateSchemas()`\n resolves the root through `findSTIBaseInfo`), so a child never treats its own\n descendant-only unique field as base-declared.\n\n`src/schema/utils.ts` sits in between, and the two exports differ:\n\n- `generateSchema()` (reached from `SmrtCollection.generateSchema()`) always\n rebuilds from the registry and writes the result back into the registry,\n replacing whatever the manifest registered for that class.\n- `ensureSchema()` (reached from the deprecated `smrt db:setup`) is\n manifest-first: it takes `ObjectRegistry.getSchema()` plus the merged\n `getAllSchemasAsDefinitions()` table definition, and only falls back to\n `generateSchema()` when no schema is registered at all.\n\nSo a normal build keeps the manifest schema through `db:setup`, and a\nregistry-derived schema is a dev/test artifact. `smrt-content` shows what one\nlooks like: `packages/content/src/hooks.server.ts` `bootstrapSchema()` calls\n`generateSchema()` for every registered class and then `ensureSchema()` from the\nSvelteKit `handle` hook on any `/api/*` request, so that process holds\nregistry-derived schemas rather than the manifest ones. It reaches only that\npackage's own `vite dev` app — the library build excludes the file and the\npackage never exports it — but it is the shape to recognize. Check which route a\nprocess actually took before trusting a reproduction.\n\n## Why the drift stayed invisible\n\nEvery drift oracle compares a database with the same artifact that dropped the\nindex:\n\n- `verifyPersistenceTable()` (`src/schema/table-verifier.ts`) calls\n `db.tableExists()` and nothing else. \"Runtime verifies schema\" has always meant\n existence-only — no column, type, constraint, or index comparison.\n- `smrt doctor` never opens a database connection.\n- `db:status` and `db:diff` diff the live database against\n `getAllSchemasAsDefinitions()`, i.e. the manifest projection.\n\nAn index the manifest never emitted is \"in sync\" by construction. That is how a\nproduction database reached 164 unindexed `tenant_id` columns while `db:status`\nreported no drift (#2356 → #2359). The assessment's other counts — 196/231\n`@foreignKey` and 91/92 `@crossPackageRef` columns with no production index,\n238/238 tables carrying a redundant index on the primary key, zero DB-level\nforeign-key constraints on any engine — come from regenerating every package's\nschema against a live database, so re-measure rather than quote them once the\nepic's fixes land.\n\n## Rules\n\n### 1. Verify against the production path, not the test path\n\nAny change to column or index emission goes on **all** paths that ship and is\nproven by the path-parity test (`src/schema/schema-path-parity.test.ts`, #2359)\n— extend its fixture; a green suite otherwise proves the registry paths only.\nRead the call graph before believing a comment: \"same as migrations\" was wrong\nfor years.\n\n### 2. Every new query predicate ships with its index\n\nCollection methods, poll loops, auth lookups, junction right-side filters, and\npolymorphic owner lookups all count — or write down why the predicate does not\nneed one. For list workloads, EXPLAIN on a PostgreSQL snapshot; the measured\nspread on the assessed workload was 21 ms → 0.1 ms.\n\n### 3. Run the PostgreSQL lane\n\nAnything touching numeric types, uuid casts, upsert conflict targets, timestamps,\nor migrations runs the package's `test:postgres` script:\n\n```bash\npnpm --filter @happyvertical/smrt-<pkg> test:postgres\n```\n\ncore, cli, users, sales, marketing, analytics, and vitest carry the lane.\nSQLite's type affinity accepts values PostgreSQL rejects — a money field declared\n`number = 0` compiles to INTEGER and only fails on PG (#2361).\n\n### 4. Read the built artifact, not the source\n\nWhat a decorator produced is in `dist/manifest.json` and in regenerated schemas:\n`integer` vs `decimal`, the actual index list, the actual conflict columns. When\nthe question is \"how many tables/columns/indexes\", regenerate and count across\nevery package; do not sample a few and extrapolate.\n\n### 5. Index intent belongs on both the constraint and the read path\n\nA conflict target is not automatically a unique index, and a unique index is not\nautomatically the index a read path uses. Custom `conflictColumns` used to\nreplace the `(slug, context)` index while `loadFromSlug`/`getId` still queried\nslug+context, and STI dropped `@field({ unique: true })` — both fixed in #2359,\nsee \"Index rules\" above. Check the pair, not the declaration.\n\n### 6. Multi-tenancy is a whole-path property\n\nEvery unique constraint and every conflict target on a tenant-scoped table\nincludes the tenant column — otherwise a second tenant's `save()` of the same\nnatural key updates the first tenant's row through `DO UPDATE SET` (#2360; the\ndefault key now does, see \"Index rules\" — an explicit `conflictColumns` that\nomits the tenant column is the class author's own key and is not rewritten).\nAnd every read path is interceptor-aware: hydration\n(`loadFromId`/`loadFromSlug`), get-by-slug, vector search, and collection\nmemory, not only `list()` (#2365).\n\n### 7. Retry only transient errors\n\nClassify through the cause chain (SQLSTATE), never on a message substring, and\nnever retry inside an aborted PostgreSQL transaction (`25P02`). Test the\ncontract end to end against a real database, not only the classifier (#2366).\n\n### 8. Thread new decorator options through every config-rebuild site\n\nA new `@smrt()` or `@field()` option that affects schema must reach the\n`SchemaGeneratorConfig` type in `src/schema/generator.ts` and every site that\nrebuilds that config — `src/schema/utils.ts` and `src/testing/database.ts` — or\nit is silently dropped on the paths that rebuild it (#2357).\n\n### 9. Delete or wire dead paths, and write docs to what the code does\n\nDead code that looks canonical misleads the next agent: the AST `generateSchema`\npath, `SchemaOverrideSystem`, and the never-emitted `triggers: []` all read as\nsupported surfaces (#2380). Documentation follows the implementation, not the\nintent — say \"verifies the table exists\" when that is what runs.\n\n### 10. Untracked \"known limitation\" comments are bugs nobody will read\n\nFile the issue and link it from the comment. A `products` comment explaining why\na conflict-column change was refrained from sat there for months — and\nmisdescribed the failure mode the whole time.\n\n### 11. Consumer repair scripts are signals\n\nDownstream repair tooling (anytown's `db-repair-plan.ts` carried column-type\nrepairs, missing STI columns and indexes, and `tenant_id` backfills since April)\nis the consumer-side record of framework gaps. Mine it during triage.\n\n### 12. Try to falsify before filing, and treat operations as correctness\n\nRe-verify a finding at source before it becomes an issue — one assessment\ncandidate claimed conflict indexes past two columns were narrowed to two\ncolumns, when only the index *name* is shortened. And an index fix that ships\nwithout a bounded-timeout, `CONCURRENTLY`-capable migrate path can take\nproduction down on rollout (#2362).\n\n### 13. Composite indexes are declared, not inferred (#2357)\n\nThe generated set only covers foreign keys, unique/conflict columns, the STI\ndiscriminator, reference columns (#2359), the default list ordering (rule 18\nbelow), and single columns opted in with `@field({ indexed: true })`. A list\nworkload's access path is composite, so declare it:\n\n```ts\n@smrt({\n indexes: [\n { name: 'contents_tenant_id_publish_date_idx',\n columns: ['tenantId', 'publish_date'] },\n ],\n})\n```\n\n`columns` takes field names or column names in access-path order — filter\ncolumns first, sort column last. Declare columns, not a direction: PostgreSQL\nscans a btree either way, so an ascending index also serves the matching\n`ORDER BY ... DESC` as an ordered scan with no Sort node. `unique` and `where`\n(partial index) are honoured.\n\n`appendDeclaredIndexes()` runs first on all four entry points, ahead of\n`ensureDefaultListOrderingIndex()` (rule 18) and `ensureReferenceColumnIndexes()`,\nso a declared composite leading with the tenant column (or any reference column)\nreplaces the automatic standalone index rather than duplicating it.\nUnknown columns, malformed entries, and a name collision with a different index\nall fail generation — a silently dropped index only surfaces later as a\nproduction slowdown. Rule 8 above is why this works at runtime at all.\n\n### 14. Relationship targets resolve to a class name on both paths\n\n`@foreignKey`/`@oneToMany`/`@manyToMany` accept a class, a name string, or a\n`() => Target` thunk. The decorator invokes the thunk and throws when the target\ncannot be resolved (never `related: ''`); the scanner unwraps the same thunk\nfrom raw source (never `related: '() => Target'`). An unresolved target silently\ncosts the relationship edge, `loadRelated()`, and the FK-derived index (#2379).\nA thunk resolves at decoration time, so a target declared later in the same\nmodule is still in its temporal dead zone — use the string form there.\n\n### 15. A SQLite type change is a table rebuild (#2370)\n\nSQLite has no `ALTER TABLE ... ALTER COLUMN ... TYPE`, so\n`src/migrations/sqlite-rebuild.ts` answers a `type_upgrade` on SQLite with the\nstatement list SQLite's own docs prescribe: stage a new table under\n`_smrt_rebuild_<table>`, copy, drop, rename, replay the indexes and triggers.\n`SchemaComparer.compareTable` swaps that plan in for the differ's\n\"requires table recreation\" placeholder, so `db:migrate` applies it inside the\nnormal atomic batch instead of exiting 1 forever.\n\nFour properties of that module are load-bearing; keep them if you touch it:\n\n- **The target shape comes from the live `sqlite_master` DDL**, retyping only\n the drifted columns. It is not regenerated from the manifest, so the rebuild\n never becomes an implicit `DROP COLUMN`, and it preserves table constraints,\n `CHECK`s, and `WITHOUT ROWID`/`STRICT`.\n- **The rebuild is hoisted ahead of the table's other column changes.** Its\n staging DDL and copy list are captured at diff time, and the differ emits\n changes in manifest field order, so a new field declared above the retyped\n one would otherwise run `ALTER TABLE ... ADD COLUMN` first and have the\n rebuild silently drop it — both statements succeed and the batch commits.\n Rebuild first, then add columns to the rebuilt table.\n- **The copy carries no `CAST`.** SQLite applies the destination column's\n affinity on insert — the same conversion a fresh table performs. An explicit\n cast is worse: non-numeric TEXT cast to REAL/INTEGER silently becomes `0`,\n and an ISO timestamp cast to NUMERIC-affinity `DATETIME` becomes its year.\n- **It refuses when any table has a foreign key onto the target and\n `PRAGMA foreign_keys` is ON** (the SMRT adapter's default). `DROP TABLE`\n performs an implicit `DELETE FROM` that fires `ON DELETE CASCADE` on\n children, and `defer_foreign_keys` defers constraint *checks*, not FK\n *actions* — verified: the child rows go. The target's own self-reference\n counts, because the staging table copies that clause and becomes a child of\n the table being dropped (verified: a two-row self-referencing table finishes\n the rebuild holding one row). Such a column stays manual drift.\n- **`PRAGMA legacy_alter_table` brackets the rename**, because SQLite ≥ 3.25\n re-parses the schema on `ALTER TABLE ... RENAME` and a view still pointing at\n the just-dropped table makes it fail outright. It is restored immediately\n after; a rolled-back batch leaves it set on that connection, which is inert\n here only because nothing else in SMRT renames a table.\n\nAll the drifted columns of one table share a single rebuild: the first change\ncarries the plan and the rest become `no change needed` comments that the CLI\nclassifies as no-ops.\n\n## What the differ compares (#2369)\n\n`SchemaComparer` (`src/migrations/differ.ts`) compares each manifest column's\ntype, then — unless the type itself is drifting — its nullability and default,\nand always reports what it will not touch:\n\n- **Strengthening** (`SET NOT NULL`, `SET DEFAULT`) is executable on\n PostgreSQL/DuckDB. `SET NOT NULL` is preceded by an `UPDATE … WHERE c IS NULL`\n backfill of the manifest default; without a default the live data is probed\n and, if NULLs exist, the change is reported (comment SQL + `advisory`) instead\n of emitting an ALTER that would abort the atomic batch.\n- **Relaxing** (`DROP NOT NULL`, `DROP DEFAULT`) is a report-only advisory until\n the caller passes `relaxColumns` (`db:migrate --relax-columns`). The manifest\n can be under-specified (#2372 registration-order weakness), so a live column\n that is stricter than the manifest is never weakened silently.\n- **Orphans** — DB columns absent from the manifest, DB tables no manifest\n declares (`SchemaDiff.orphan_tables`), and unclaimed `*_key` unique constraint\n indexes — are always reported. A NOT NULL orphan without a default is a\n `warning` advisory (every ORM insert fails on it); `includeDroppedColumns`\n (`--drop-columns`) drops it, `relaxColumns` relaxes it. Advisory-only changes\n carry no SQL, never reach the tracker, and do not fail `db:migrate`.\n- **ADD COLUMN** is planned per engine: DuckDB rejects every inline constraint\n (add with `DEFAULT`, then `SET NOT NULL`, `CREATE UNIQUE INDEX`); SQLite\n rejects inline `UNIQUE` (separate `CREATE UNIQUE INDEX <table>_<col>_key`, the\n PostgreSQL constraint-index name, so the orphan sweep leaves it alone) and\n `NOT NULL` without a default on a populated table; PostgreSQL keeps constraints\n inline. DuckDB has no `ADD CONSTRAINT`, so the separate index is the only\n way to add uniqueness there; the bundled DuckDB 1.4.x resolves\n `ON CONFLICT (col)` through that index (the old #12684 limitation the DuckDB\n strategy's `requiresInlineUnique()` note describes no longer reproduces —\n the #2369 DuckDB test pins the upsert), older DuckDB builds may not. A required column with no default is enforced only on an empty table;\n on a populated one it is added nullable and the `NOT NULL` is reported as a\n manual follow-up on every engine.\n- **SQLite** has no `ALTER COLUMN`: nullability/default alterations are manual\n (comment SQL → `db:migrate` exit 1). The #2370 rebuild (rule 15) consumes\n only `type_upgrade` placeholders today; extending it to rewrite constraints\n would lift this.\n- Defaults compare through `canonicalizeDefault()`, which folds engine\n renderings (`'x'::text`, `CAST('t' AS BOOLEAN)`, `CURRENT_TIMESTAMP` vs\n `now()`) by manifest type; an unclassifiable rendering skips the comparison\n rather than risking a false positive that would churn every run. The\n round-trip test (create from each DDL strategy → compare → zero changes) in\n `src/migrations/__tests__/issue-2369-*.test.ts` guards this.\n\n### 16. `schema.ddl` is a preview, not the table\n\n`SchemaDefinition.ddl` / `manifest.json` `schema.ddl` is the engine-neutral\nCREATE TABLE string from `SchemaGenerator.generateSQL()` with no engine: no\nindexes, no triggers, abstract `REAL`/`JSON`/`UUID`/`TIMESTAMP`. It is kept for\nbackward compatibility only. Everything that needs an executable table renders\n`columns` + `indexes` through `getDDLStrategy(engine)` — `db:migrate`\n(`migrations/orchestrate.ts`), `MigrationGenerator` (default\n`materializeStructuredSchema: true`; `false` is a deprecated opt-out),\n`SchemaAggregator`, and `createIsolatedTestDbFromManifest` in smrt-vitest, the\nlast two via `src/schema/manifest-schema.ts` (`collectManifestTables` /\n`renderCollectedManifestTable`). The cached string is merged in only for a\ntable whose contributors expose no structured columns (hand-authored\nmanifests); table constraints that exist only in the string are dropped with a\nwarning, as `db:migrate` drops them. Do not add a new consumer of the\nstring, and do not write a private CREATE INDEX renderer — the retired ones\ndropped `where` and `jsonPath` (#2358). Every DDL strategy also spells out\n`PRIMARY KEY NOT NULL`: SQLite lets a bare non-INTEGER PRIMARY KEY hold NULL.\n\n### 17. The merged table shape is registration-order independent (#2372)\n\n`getAllSchemas()` and `getAllSchemasAsDefinitions()` fold every class that\nshares a physical table — the whole STI hierarchy — into one shape. Both route\nthrough `buildMergedTableSchemas()`, which groups contributors by table and\nthen merges them in a **deterministic** order: the STI base first, then\nancestors before descendants, then by qualified name.\n\nThat order matters because the first contributor seeds the table: it supplies\nthe fallback base columns, the `idType`, the conflict columns and the cached\nDDL, and its columns win every merge conflict. When registration order decided\nit, an STI child that carries no manifest `schema` — the external- and\nconsumer-manifest case — seeded the table from bare fallback columns and the\nbase class's richer ones were skipped when it registered later, yielding\n`context TEXT` instead of `context TEXT NOT NULL DEFAULT ''` and timestamps\nwith no NOT NULL/DEFAULT. The shipped content manifest lists `Article` before\n`Content`, so the losing order was the one that shipped, and the differ\ncompares types only, so the weak fresh-create was never repaired.\n\nTwo invariants keep the two assembly paths agreeing:\n\n- `createBaseColumns()` mirrors what `generateSchemaFromManifest` /\n `generateSTISchemaFromManifest` emit for the same table, so a table built\n from runtime field metadata alone has the same NOT NULL/DEFAULT shape as one\n built from a manifest. Note `_meta_type` is `TEXT NOT NULL` with **no**\n default, matching the generator.\n- `fieldsToColumns()` reads `required`, `default`, and `description` from the\n top level *or* `_meta`. Registry fields normalize them into `_meta`\n (`manifest-field-merge.ts`), so reading only the top level silently dropped\n NOT NULL and DEFAULT for every registry-sourced field.\n\nSTI columns stay nullable regardless of the field's `required` flag\n(`fieldsToColumns(fields, { stiUnionColumns: true })`): the table holds the\nunion of all subtypes' fields, so a column only one subtype declares is never\npopulated on a sibling's row. Declared defaults are still emitted. This matches\n`generateSTISchemaFromManifest`, which sets `notNull: false` on every non-system\nSTI column.\n\nWhen adding a class-level input to the merged shape, take it from the seeding\ncontributor rather than \"whichever class arrives first\", and cover it with a\nchild-first/base-first equality test.\n\n### 18. The generator owns the index for its own default ordering (#2363)\n\nEvery generated list surface — REST, MCP, the SvelteKit list route — pages with\n`ORDER BY created_at DESC, <pk> ASC` (`DEFAULT_LIST_ORDER_BY`, #2367), and\nuntil #2363 no schema path indexed `created_at` (the AST path, deleted in\n#2380, indexed `updated_at`), so the framework's own default page was a\nsequential scan plus a top-N sort. `ensureDefaultListOrderingIndex()` now runs\non all four entry points and emits:\n\n- `(<tenant column>, created_at)` on a tenant-scoped table — the tenancy\n interceptor puts `tenant_id = ?` in front of every list, so the tenant column\n leads and `created_at` orders within it. This composite **replaces** the\n standalone tenant index from #2359: a B-tree serves every prefix of its\n column list, so `ensureDefaultListOrderingIndex()` is called first and\n `ensureReferenceColumnIndexes()` then sees the column as already served. The\n tenant column is found by `referenceKind === 'tenantId'`, never by the\n `tenant_id` spelling — `@smrt({ tenantScoped: { field } })` renames it.\n- `(created_at)` otherwise.\n\nThree deliberate omissions, so nobody \"fixes\" them later:\n\n- **No `DESC`.** `IndexDefinition` carries no per-column direction and\n PostgreSQL scans a B-tree backwards just as cheaply.\n- **No primary-key tiebreak column.** The default order mixes directions\n (`created_at DESC, id ASC`), so no single-direction index satisfies the whole\n key; the leading columns already turn a full sort into an index scan plus an\n incremental sort over rows sharing a timestamp.\n- **Not scoped per STI subtype.** `(_meta_type, created_at)` would serve a\n child collection's list but not the base class's polymorphic one, which\n carries no discriminator predicate — the same reasoning that keeps STI\n reference indexes plain (#2359). One unqualified index per shared table.\n\nAn existing UNQUALIFIED index that already leads with the same columns\nsuppresses it — a partial or JSON-path index never counts. That is how a\ndeclared `@smrt({ indexes: [...] })` composite (#2357) takes over: declaring\n`(tenant_id, created_at, status)` replaces the generated pair, while declaring\na different sort column such as `(tenant_id, publish_date)` sits **beside** it,\nbecause that index cannot order the default page. Declared indexes are appended\nbefore this helper for exactly that reason; anything that appends an index in\nfuture goes in the same slot, ahead of `ensureDefaultListOrderingIndex()` and\n`ensureReferenceColumnIndexes()`.\n\n### 19. One conflict-target rule, applied on every producer\n\n`save()` upserts on `ObjectRegistry.getConflictColumns()`; the schema must\ncarry exactly one unique index over those columns (or they must be the\nprimary key). Keep the derivation in `src/schema/conflict-target.ts` and let\nevery producer call it — the three manifest pipelines share\n`ManifestGenerator.applyGenerationPasses()` since #2360 because\n`ManifestBuilder` had silently skipped the report passes for months. When you\nadd a way for the key to vary (a new decorator option, a new class kind),\nthread it through `getConflictColumns()`, `normalizeConflictColumns()` and the\ngenerator's `resolveConflictTarget()` together, and extend the parity test's\n\"unique index == conflict target\" assertion; a key the runtime uses and the\nschema does not index is a hard PostgreSQL error (42P10) on the first save,\nand a key the schema indexes without the tenant column is the silent\ncross-tenant overwrite this rule exists for.\n\n### 20. Every generated index name is length-guarded before it leaves a path (#2374)\n\nPostgreSQL truncates any identifier past 63 **bytes** and reports nothing;\nSQLite and DuckDB do not, so the entire test suite was blind to it. The 66-byte\n`content_contribution_revisions_contribution_id_revision_number_idx` shipped\nthat way — only the differ's signature-equivalence check kept it from emitting\n`add_index` on every run. Two names agreeing for 63 bytes is the real hazard:\n`CREATE INDEX IF NOT EXISTS` no-ops against the wrong index, and the second\nindex is never created.\n\n`schema/index-utils.ts` owns the guard, and it splits by who owns the name:\n\n- **Generated index, trigger and PL/pgSQL function names** →\n `shortenIdentifier()`. Deterministic `<head>_<digest><suffix>`, digest taken\n over the **full** original so a shared prefix still yields distinct names, and\n a recognised suffix (`_idx`, `_unique_idx`, `_key`, `_pkey`) preserved.\n- **Hand-declared `@smrt({ indexes: [{ name }] })`** → `assertIdentifierFits()`,\n a hard error in `validateDeclaredIndex()`. Renaming what a developer wrote is\n worse than refusing it, and `SchemaComparer` matches indexes **by name**\n first, so a 70-byte declaration could never match the 63-byte index\n PostgreSQL stored and `db:migrate` would emit `add_index` forever.\n- **Table and column names** → deliberately **not** guarded. PostgreSQL\n truncates identifiers *consistently on every reference*: `CREATE TABLE\n \"<80 bytes>\"` and a later `SELECT ... FROM \"<the same 80 bytes>\"` both resolve\n to the same stored 63-byte name, so one long name round-trips fine end to end.\n `smrt-users` depends on this — it ships an intentional 80-byte\n `@smrt({ tableName })` (`permission_policy_table_name_that_is_far_too_long…`)\n and derives unique Postgres RLS policy names from it. An earlier revision of\n this rule hard-errored here on the theory that the runtime resolves tables by\n name and would break; that theory is wrong for the reason above, and the error\n broke `packages/users`. The residual collision risk is over a name the\n developer chose, not one the generator manufactured.\n\n`enforceIdentifierLimits()` is the single call site per path, placed **after**\n`ensureReferenceColumnIndexes()` — nothing may lengthen a name after it. Doing\nthe shortening at the end rather than at each `indexes.push()` is safe because\nthe digest covers the whole original name, so entries distinct before shortening\nstay distinct after; the helper still throws if two ever collide. The migrate\nleg's `withConflictIndex()` (`registry/schema-builder.ts`) and the PostgreSQL\ntrigger-function name call `shortenIdentifier()` directly, because they compose\na name outside the generator's index list. Note that an over-long *table* name\nstill yields in-limit, distinct *index* names, because the shortening runs over\nthe whole composed name.\n\nThe digest is FNV-1a, not `node:crypto`: `index-utils.ts` is re-exported from\n`schema/utils.ts`, which exists to keep Node built-ins out of browser bundles.\nIt only has to be *stable* — a shortened name that changed between releases\nwould make every deployment drop and recreate the index — so the parity and\nunit tests pin the literal output rather than recomputing it. Unpaired\nsurrogates are folded to U+FFFD before both counting and hashing, so the digest\nis taken over exactly the bytes the driver transmits.\n\nExisting databases migrate **by name swap, without a rebuild**: the live index\nstill carries the name PostgreSQL truncated it to, the manifest now carries the\nshortened one, and the differ claims it by signature (columns + uniqueness +\npredicate), emitting nothing — including under `includeDroppedIndexes`. See\n`migrations/__tests__/index-drift.test.ts` and the PostgreSQL lane test\n`schema/issue-2374-identifier-length-postgres.optional.test.ts`.\n\nOut of scope, deliberately: constraint names PostgreSQL invents for itself. A\nCTI table's inline `UNIQUE` produces an implicit `<table>_<column>_key`, which\ncan exceed 63 bytes even when the table and column each fit. SMRT never names\nit, and PostgreSQL disambiguates its own truncations by appending a counter\nrather than collapsing them, so there is no silent-collision hazard there.\n\n### 21. The `_smrt_` prefix does not mean \"system table\" (#2376)\n\n`bootstrapSystemTables()` owns nine hand-written tables; ~25 more `_smrt_*`\ntables belong to `@smrt()` models and are created by `db:migrate` (feature\nflags, prompt overrides, subscription plans, report schedules, field policies,\njobs). Never classify by prefix — use `SYSTEM_TABLE_NAMES`\n(`schema/system-table-shapes.ts`, derived from the DDL parse) plus\n`FRAMEWORK_OPERATIONAL_TABLES` / `RETIRED_SYSTEM_TABLES` in `system/schema.ts`.\nThe change-feed writer skipped by prefix, so clients syncing those domain\ntables through `_changes` never saw an update.\n\nEditing `ALL_SYSTEM_TABLES` requires bumping `SMRT_SCHEMA_VERSION` *and*\nappending to `SMRT_SCHEMA_DDL_CHECKSUMS` — the version gates the DDL replay, so\nwithout a bump no existing database ever applies the change. A new **column**\nadditionally needs an `addColumnIfMissing()` entry in `system/compatibility.ts`\n(`CREATE TABLE IF NOT EXISTS` is a no-op on an existing table).\n`system-schema-evolution.test.ts` enforces both, and asserts a legacy database\nupgrades to exactly the shape a fresh install gets.\n\n`_smrt_jobs` / `_smrt_job_events` are dual-owned: `db:migrate` creates them,\nthe compatibility pass reshapes them. On a fresh install bootstrap runs first,\nso their pass is deferred — `ensureDeferredSystemTableCompatibility()` re-runs\nuntil the tables exist, then stamps a `<version>+deferred-compat` marker. It\nruns OUTSIDE the bootstrap lock and swallows its own failures: those statements\ntarget tables the framework does not own, and inside the PostgreSQL transaction\none failure would roll back system-table creation with it. Only\n`ensureBootstrapSystemTableCompatibility()` (the tables the DDL itself creates)\nbelongs inside the lock.\n\nReconciling `_smrt_jobs.task_id` uniqueness reads the live index catalog, which\nis implemented for PostgreSQL and SQLite only; DuckDB and the JSON adapter keep\nthe redundant compat index rather than risk dropping the one that enforces the\nupsert conflict target. When reading a PostgreSQL catalog array, cast it\n(`attname::text`) and parse both shapes — a driver with no parser registered for\nthe array OID returns the raw `{a,b}` literal, and reading that as \"no columns\"\nsilently inverts an index-existence decision.\n\n## Same-package referential integrity uses two matching rails\n\n`@foreignKey(Target)` emits a physical database constraint when the target is\nin the same package and applies the same action through `SmrtObject.delete()`\nin `src/cascade.ts`. A shared delete-action resolver keeps both paths aligned;\nthe established generated `ON UPDATE CASCADE` default remains unchanged:\n\n| Reference | Default when `onDelete` is absent |\n|---|---|\n| Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n| Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n| Ordinary same-package reference | `NO ACTION` — deletion is refused while references remain |\n| Every `@tenantId()` field | Excluded from physical constraints and delete cascades |\n\nThe natural-key rule is what cleans junction rows up without any per-package\nannotation: a junction declares\n`@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so the\nrow is *identified* by the content and cannot outlive it. An ordinary child\n(`Order.customerId`) is keyed by `(slug, context)` and therefore defaults to\nimmediate `NO ACTION` unless it opts in explicitly.\n\n**`@tenantId()` is excluded even though it lands in `conflictColumns`.**\n#2360 leads every tenant-scoped class's *default* natural key with the\ntenant column, so without this exclusion, deleting one `Tenant` row would\nrecursively CASCADE through every tenant-scoped table in the schema that has\nnot declared its own `conflictColumns` — the overwhelming majority. The\ntenant column scopes ownership; it does not identify the row the way a\njunction's foreign key does. Detected via the `__tenancy.isTenantIdField`\nmarker on `FieldMeta` (`smrt-core` reads it structurally so it never depends\non `smrt-tenancy`). `@tenantId()` exposes no `onDelete` option today, so\nthis cannot currently be overridden per field.\n\n`@crossPackageRef()` remains runtime-only: it registers relationship loading\nand indexes but deliberately emits no physical constraint, avoiding circular\npackage DDL. Tenant markers follow the same non-constraint rule because a\ntenant is a scope, not an ownership edge.\n\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\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### Pre-R11 `text` ids converge to `uuid` before any FK statement (#2608)\n\nR11 made SMRT identifiers and references native `uuid` on PostgreSQL. A\ndatabase created before that change still stores its `id` columns as `text`\nwhile every reference column added afterwards materializes as `uuid`.\nPostgreSQL cannot implement a foreign key across two different physical types —\nFK DDL admits no cast — so `ADD CONSTRAINT … NOT VALID` fails with SQLSTATE\n42804 and aborts every later statement in the same migration batch.\n\nTwo rails handle it, and both are PostgreSQL-only. SQLite stores UUIDs as text\nby design and DuckDB cannot rewrite a column type in place, so neither engine\nemits anything for this drift.\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\nComponents, not individual pairs, are the unit of decision: one legacy `text`\nprimary key can be referenced by several children, and converting it for one\nof them would break every sibling that is still `text`. A self-referential\ntable falls out of the same grouping because both endpoints land in one\ncomponent. Convergence is relationship-driven, so a legacy `text` id that\nnothing references keeps its R11 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\nProperties to keep if you touch that module:\n\n- **The plan is registry-derived and rebuilt per delete.** Registration is\n incremental — manifests load lazily and tests register classes between cases —\n so a cached plan would silently skip a table that registered later. Cache it\n only behind an invalidation hook that every registration path calls.\n- **A class with nothing pointing at it skips the transaction entirely — but\n `CascadePlan.isEmpty` requires no polymorphic association class anywhere in\n the process, not just no typed references.** `buildCascadePlan()` pushes\n *every* registered `SmrtPolymorphicAssociation` subclass into\n `plan.polymorphic` unconditionally (`cascade.ts` around\n `isPolymorphicAssociationClass`): a `metaType` column can point at any class\n at runtime, so there is no static metadata to scope it by the target being\n deleted. One registered polymorphic class anywhere makes `isEmpty` false for\n every delete in that process — do not read \"the common case skips the\n transaction\" as \"most deletes in a real app skip it\"; in a multi-package app\n that registers even one polymorphic association, almost none do.\n `runCascadeDelete()` builds the plan for `getResolvedQualifiedName()` (not the\n bare constructor name — two packages can register the same simple name).\n- **Cascaded rows are removed set-based.** Their `beforeDelete`/`afterDelete`\n hooks and interceptors do not run and no change-feed tombstone is written for\n them, which is exactly what a DB-level `ON DELETE CASCADE` does. Only the\n object `delete()` was called on runs the lifecycle. Do not \"improve\" this into\n a per-row model delete without deciding what that means for sync consumers.\n- **Everything is one transaction where the adapter has one**, including the\n object's own `DELETE`, whenever there is anything to cascade. The `RESTRICT`\n checks run first, before any mutation, so a refusal costs nothing; the\n transaction is what makes a refusal *deeper* in the graph safe.\n- **`_smrt_embeddings` and `_smrt_contexts` are matched by id *and* a\n class-name candidate set, not id alone.** Their class columns store the\n *runtime* constructor name, which for an STI hierarchy is a concrete\n subclass rather than the class the cascade planned from — id-alone matching\n looked STI-safe, but let two unrelated classes using `idType: 'text'`\n (non-UUID, not guaranteed globally unique) collide on a shared id value and\n delete each other's rows (review fix). `ownerClassCandidates()` expands to\n every STI hierarchy member of the class the ids actually belong to, in both\n qualified and simple form. A failure to clean them is logged, never raised —\n an application database may predate the table, and losing derived rows must\n not fail a valid delete.\n\n`_smrt_changes`, `_smrt_ai_usage`, `_smrt_signals` and the dispatch tables are\ndeliberately **not** cascaded. They are append-only logs; the change feed in\nparticular receives the delete's own tombstone, so cascading it would erase the\nrecord that tells sync clients the row is gone.\n\n### 22. System tables get a retention policy, not just a prune function (#2375)\n\nFour framework-owned tables grow with traffic and nothing used to remove a row:\n`_smrt_changes` (one per save/delete), `_smrt_ai_usage` (one per AI call, and\npersistence is on by default), `_smrt_contexts` (whose `expires_at` nothing\nenforced) and `_smrt_dispatch` (an operator-only `dispatch:cleanup`).\n`src/system/retention.ts` is now the single place that bounds them.\n\n- **`runRetentionSweep(db, policy)` is the entry point.** It runs the four\n built-in tasks in a fixed order, then every task other packages contributed\n via `registerRetentionTask()` — `@happyvertical/smrt-jobs` registers\n `_smrt_jobs`/`_smrt_job_events`, `@happyvertical/smrt-users` registers\n session/magic-link/CLI-auth expiry. A task that throws is recorded on its own\n result and the sweep continues; a missing table reports `unavailable`, so a\n sweep is safe against a partially bootstrapped database.\n- **A contributed task only exists in a process that loaded its package.** Both\n packages register on import from their entry point, and the registry lives on\n `globalThis` (like `ObjectRegistry`) so a duplicated `smrt-core` resolution\n cannot split it. `smrt db:prune` optionally imports both packages for exactly\n this reason — a project that installs neither correctly gets neither task.\n- **Defaults are opt-out, not opt-in.** `DEFAULT_RETENTION_POLICY` covers the\n four built-in tables (changes 30 days, AI usage 90 days, dispatch 30 days\n completed / 90 days failed, contexts strictly by their own `expires_at`), and\n those are the ones `smrt.configure({ retention })` tunes. Contributed tasks\n carry their own defaults and their own window options —\n `DEFAULT_JOB_RETENTION` (7 days terminal / 30 days failed / 30 days events,\n set through `registerJobRetentionTasks()` or the runner's `retention.jobs`),\n and expired credentials, which have no window because an expired credential\n has nothing worth retaining. Every task, built-in or contributed, can be\n turned off: a table set to `false`, a task set to `false` under `tasks`, or\n `enabled: false` for the whole sweep — through `smrt.configure`,\n `smrt db:prune --skip`, or the runner's `retention` config.\n- **Contributed task names are prefixed with the owning package's short name**\n (`jobs-records`, `jobs-events`, `users-sessions`, …) because the registry is\n one process-global namespace.\n- **Scheduling lives outside core.** A running `TaskRunner` sweeps every six\n hours (`retention: false` opts out) and `smrt db:prune` is the cron entry\n point. The first runner sweep is one interval after `start()`, never at\n start: a crash-looping worker must not become a delete loop.\n- **Every prune counts before it deletes.** `rowCount` is not reliably\n populated across the engines SMRT supports, so counting is both what gives a\n usable figure and what lets `dryRun` preview the *same* predicate rather than\n an approximation of it. Count and delete are two statements and deliberately\n not one transaction — a maintenance pass must not hold a write lock over a\n large delete — so the figure is approximate under concurrent writers. Where\n two bounds can select the same row (`pruneChangeFeed`, `pruneAiUsage`), the\n second bound excludes what the first already accounted for, so a dry run does\n not count an entry twice.\n- **Every retention predicate ships with its index** (rule 2 applies to\n maintenance SQL too): `_smrt_contexts(expires_at)`,\n `_smrt_ai_usage(tenant_id, created_at)` — which is also the subscriptions\n billing meter's range scan — `_smrt_dispatch(status, processed_at)` and\n `(status, updated_at)` come from the system DDL, so they reach existing\n databases through the `SMRT_SCHEMA_VERSION` bump that replays it.\n `_smrt_jobs(status, completed_at)` comes from\n `ensureJobsSystemTableCompatibility()` instead, because `_smrt_jobs` is\n generated from a decorated class and does not exist yet when bootstrap runs;\n the jobs collection calls that path on every `initialize()`.\n- **Expiry enforcement is prune-side only.** `recall()`/`recallAll()` keep\n their documented \"expiry is not applied at read time\" contract — changing it\n would change read semantics for existing callers, which is a different issue\n from bounding storage. `LearningMemory` filters expired rows itself.\n\n### 23. Dead generation surfaces were deleted, not wired (#2380)\n\nRule 9 named three surfaces that read as canonical but were not: the AST\n`generateSchema(objectDef)` entry point, `SchemaOverrideSystem`, and the\nnever-emitted `triggers: []`. Resolution, so a future agent does not re-open\nwhat was deliberately decided:\n\n- **The AST path is gone.** `SchemaGenerator.generateSchema(objectDef)` and its\n AST-only private helpers (`generateIndexes`, `generateTriggers`,\n `extractDependencies`, `generateVersion`, `getTableName`,\n `extractPackageName`) were deleted from `schema/generator.ts`, along with\n their sole caller, `generateSchemaModule()` in `vite-plugin/index.ts`, and the\n `smrt:schema` / `@happyvertical/smrt-virt-schema` virtual module registration\n that fed. Nothing else called it — grep the deleted method's exact name\n before assuming a caller was missed; the path-parity fixture and every other\n rule above already speak only of the four surviving entry points.\n- **`SchemaOverrideSystem` is gone**, file and all\n (`schema/override-system.ts` no longer exists). It was never called from\n anywhere in this repository outside its own now-deleted exports, and two of\n its five public methods (`createPraecoContentOverride`,\n `createPraecoMeetingOverride`) hard-coded a schema extension for a\n consuming project outside this monorepo — scaffolding that never belonged in\n the framework, not a generic feature with a missing caller. `SchemaOverride`\n (the type) went with it; `ColumnDefinition`/`IndexDefinition`/\n `TriggerDefinition`, which it merely referenced, did not.\n- **The DDL-strategy trigger machinery was kept, not deleted.**\n `TriggerDefinition`, `SchemaDefinition.triggers`, and every DDL strategy's\n `generateTriggers()` / `generateTriggerStatement()` / `supportsTriggers()`\n (`schema/ddl/*.ts`) are real, engine-uniform, directly-tested rendering code\n that runs on **every** table creation via `strategy.generateTriggers(schema)`\n — unlike the AST path, this is not an orphaned call graph. It is kept for the\n same reason rule 16 keeps the cached `schema.ddl` string: `SchemaDefinition`\n is part of the shape third-party tooling and published manifests may already\n depend on, and `EngineSpecificDDL`/`MultiEngineDDL` (`schema/ddl/types.ts`)\n carry `triggers` as part of that same contract. Deleting a published field is\n a different (and unjustified) risk from deleting a virtual module nothing\n ever imported.\n- **What changed is what is documented, not what runs.** `schema.triggers` is\n now explicitly documented (`schema/types.ts`) as always `[]` on every schema\n a `@smrt()` class can produce, and why: there is no `@smrt()`/`@field()`\n option that populates it (unlike `indexes`, #2357), `updated_at` is\n maintained at the application layer (`SmrtObject.save()`), and\n `migrations/differ.ts` never diffs triggers — so even a hand-populated one\n would only apply to a newly `CREATE TABLE`d table and never retrofit an\n existing one. Wiring live trigger emission was considered and rejected for\n this issue: it is a migration-rollout feature (retrofitting 238+ existing\n production tables needs the same `SMRT_SCHEMA_VERSION`-replay or differ\n support rule 21/rule 22's system-table work required), not a cleanup, and\n nothing in the epic depended on it the way #2359 depended on FK indexes\n actually shipping.\n- **`_smrt_signals` and `ObjectRegistry.persistToDatabase()`/`loadFromDatabase()`**\n — named in the original finding alongside triggers — were already handled by\n #2376 before this issue landed: see rule 21 and `system/schema.ts`'s\n `RETIRED_SYSTEM_TABLES`. Nothing further to do there.\n- **The two config-rebuild-site comments** (`schema/utils.ts`,\n `testing/database.ts`) rule 8 requires were already in place, added by\n #2357/#2360; the `testing/database.ts` \"same as migrations\" overclaim rule 1\n quotes was already corrected by #2359, and doctor's `experimentalDecorators`\n check was already fixed by #2368/#2399 (see `packages/cli/AGENTS.md`\n Gotchas). Re-verify against current source before repeating any of these —\n the epic's PRs landed across one evening and a stale assessment line is not\n proof a fix is still needed.\n"
999
999
  },
1000
1000
  {
1001
1001
  "path": "agents/data-query.md",
@@ -1,4 +1,47 @@
1
+ import { CapabilityClassification, DomainKnowledgePlaybookStep } from '@happyvertical/smrt-types';
1
2
  import { SmartObjectManifest } from '../scanner/types.js';
3
+ /**
4
+ * The scanner's declared agent surface (#2591), mirrored structurally like the
5
+ * rest of this module.
6
+ *
7
+ * `@happyvertical/smrt-scanner` cannot import `@happyvertical/smrt-types` —
8
+ * core depends on the scanner, so the reverse edge would close a cycle — which
9
+ * is why the scanner owns its own copy of this vocabulary and core reconciles
10
+ * the two at exactly one place (`toKnowledgeAgentSurface`).
11
+ */
12
+ export interface ScannerAgentSurface {
13
+ intents: Array<{
14
+ kind: 'intent';
15
+ id: string;
16
+ description: string;
17
+ capability: CapabilityClassification;
18
+ target: Record<string, unknown>;
19
+ hasInputSchema: boolean;
20
+ /** Always exactly `['browser']`; see `DomainKnowledgeViewIntent.planes`. */
21
+ planes: ['browser'];
22
+ filePath: string;
23
+ }>;
24
+ playbooks: Array<{
25
+ kind: 'playbook';
26
+ key: string;
27
+ title: string;
28
+ description: string;
29
+ steps: DomainKnowledgePlaybookStep[];
30
+ planes: Array<'browser' | 'server'>;
31
+ planesDeclared: boolean;
32
+ onStepFailure: 'abort' | 'continue';
33
+ enabled: boolean;
34
+ filePath: string;
35
+ }>;
36
+ diagnostics: Array<{
37
+ code: string;
38
+ helper: 'defineIntent' | 'definePlaybook';
39
+ message: string;
40
+ filePath: string;
41
+ line?: number;
42
+ column?: number;
43
+ }>;
44
+ }
2
45
  export interface OxcScannerLike {
3
46
  scanAndResolve(): Promise<{
4
47
  results: {
@@ -9,6 +52,7 @@ export interface OxcScannerLike {
9
52
  line?: number;
10
53
  severity: 'error' | 'warning';
11
54
  }>;
55
+ agentSurface?: ScannerAgentSurface;
12
56
  };
13
57
  resolved: unknown[];
14
58
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"scanner-module.d.ts","sourceRoot":"","sources":["../../src/utils/scanner-module.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,MAAM,WAAW,cAAc;IAC7B,cAAc,IAAI,OAAO,CAAC;QACxB,OAAO,EAAE;YACP,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YACpC,MAAM,EAAE,KAAK,CAAC;gBACZ,QAAQ,EAAE,MAAM,CAAC;gBACjB,OAAO,EAAE,MAAM,CAAC;gBAChB,IAAI,CAAC,EAAE,MAAM,CAAC;gBACd,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;aAC/B,CAAC,CAAC;SACJ,CAAC;QACF,QAAQ,EAAE,OAAO,EAAE,CAAC;KACrB,CAAC,CAAC;CACJ;AAED,MAAM,WAAW,qBAAqB;IACpC,KAAK,OAAO,EAAE;QACZ,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;QACnB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;QACvB,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,oBAAoB,CAAC,EAAE,OAAO,CAAC;QAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC/B,GAAG,cAAc,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IAClC,UAAU,CACR,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,EAAE;QACP,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;KACrC,GACA,mBAAmB,CAAC;CACxB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,qBAAqB,CAAC;IAClC,eAAe,EAAE,UAAU,mBAAmB,CAAC;IAC/C,mBAAmB,CAAC,OAAO,EAAE;QAC3B,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,EAAE,MAAM,EAAE,CAAC;QAClB,OAAO,EAAE,MAAM,EAAE,CAAC;QAClB,mBAAmB,CAAC,EAAE,OAAO,CAAC;KAC/B,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CACvB"}
1
+ {"version":3,"file":"scanner-module.d.ts","sourceRoot":"","sources":["../../src/utils/scanner-module.ts"],"names":[],"mappings":"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"}
@@ -1,10 +1,12 @@
1
- import { DomainKnowledgeConfig } from '@happyvertical/smrt-types';
1
+ import { DomainKnowledgeAgentSurface, DomainKnowledgeConfig } from '@happyvertical/smrt-types';
2
2
  import { Plugin } from 'vite';
3
3
  import { SmrtGenerationSnapshotOptions } from '../generation-snapshot.js';
4
4
  import { SmartObjectManifest } from '../scanner/types.js';
5
+ import { ScannerAgentSurface } from '../utils/scanner-module.js';
5
6
  export { loadVerifiedSmrtGenerationSnapshot, type SerializeSmrtGenerationSnapshotOptions, type SmrtGenerationSnapshotArtifact, type SmrtGenerationSnapshotOptions, type SmrtGenerationSnapshotView, serializeSmrtGenerationSnapshot, sha256SmrtGenerationSnapshot, } from '../generation-snapshot.js';
6
7
  export type { CliApiCoherenceViolation, SvelteKitOptions, } from './sveltekit-generator.js';
7
8
  export { findCliApiCoherenceViolations, generateSvelteKitRoutes, methodNameToKebab, resolveApiActionRouteConfig, resolveApiActionSet, validateCliIncludeAgainstApi, } from './sveltekit-generator.js';
9
+ export { buildWebMcpToolDefinitions } from './web-collections.js';
8
10
  export interface SmrtPluginOptions {
9
11
  /** Root directory that owns generated manifests and SvelteKit routes. */
10
12
  projectRoot?: string;
@@ -89,6 +91,17 @@ export interface SmrtPluginOptions {
89
91
  */
90
92
  validateCliApiCoherence?: boolean;
91
93
  }
94
+ /**
95
+ * Project a scanner agent surface into the knowledge-artifact shape (#2591).
96
+ *
97
+ * The two shapes are deliberately separate: the scanner cannot depend on
98
+ * `@happyvertical/smrt-types` (core depends on the scanner, and importing back
99
+ * would close the cycle), so it mirrors the vocabulary structurally and this
100
+ * function is the one place the mirror is reconciled. `filePath` becomes
101
+ * `sourceFile` here because the artifact records a package-relative path, not a
102
+ * scan path.
103
+ */
104
+ export declare function toKnowledgeAgentSurface(surface: ScannerAgentSurface | undefined): DomainKnowledgeAgentSurface | undefined;
92
105
  export declare function isRegisterShimModuleId(id: string): boolean;
93
106
  /**
94
107
  * Generate the replacement `__smrt-register__` module with the build-time
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/index.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite-plugin/index.ts"],"names":[],"mappings":"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"}
@@ -26,6 +26,49 @@ var VIRTUAL_MODULES = {
26
26
  "@happyvertical/smrt-virt-cli": "smrt:cli",
27
27
  "@happyvertical/smrt-virt-web": "smrt:web"
28
28
  };
29
+ /**
30
+ * Project a scanner agent surface into the knowledge-artifact shape (#2591).
31
+ *
32
+ * The two shapes are deliberately separate: the scanner cannot depend on
33
+ * `@happyvertical/smrt-types` (core depends on the scanner, and importing back
34
+ * would close the cycle), so it mirrors the vocabulary structurally and this
35
+ * function is the one place the mirror is reconciled. `filePath` becomes
36
+ * `sourceFile` here because the artifact records a package-relative path, not a
37
+ * scan path.
38
+ */
39
+ function toKnowledgeAgentSurface(surface) {
40
+ if (!surface) return void 0;
41
+ return {
42
+ intents: surface.intents.map(({ kind: _kind, filePath, ...rest }) => ({
43
+ ...rest,
44
+ sourceFile: filePath
45
+ })),
46
+ playbooks: surface.playbooks.map(({ kind: _kind, filePath, ...rest }) => ({
47
+ ...rest,
48
+ sourceFile: filePath
49
+ })),
50
+ diagnostics: surface.diagnostics.map(({ filePath, ...rest }) => ({
51
+ ...rest,
52
+ sourceFile: filePath
53
+ }))
54
+ };
55
+ }
56
+ /**
57
+ * Print every declaration the matcher recognized but could not emit.
58
+ *
59
+ * A warning rather than a build failure: a computed tool set is a legitimate
60
+ * choice, and `useWebMcpTool` is its supported path. What is NOT acceptable is
61
+ * the declaration disappearing without a word, so the surface records it and
62
+ * the build says so.
63
+ */
64
+ function reportAgentSurfaceDiagnostics(surface) {
65
+ if (!surface || surface.diagnostics.length === 0) return;
66
+ console.warn(`[smrt] ⚠️ ${surface.diagnostics.length} declaration(s) are not statically emittable and were excluded from the agent surface:`);
67
+ for (const diagnostic of surface.diagnostics) {
68
+ const where = diagnostic.line ? `${diagnostic.sourceFile}:${diagnostic.line}` : diagnostic.sourceFile;
69
+ console.warn(` ${where} — ${diagnostic.message}`);
70
+ }
71
+ }
29
72
  async function importScanner() {
30
73
  return importWorkspaceModule({
31
74
  packageName: "@happyvertical/smrt-scanner",
@@ -102,6 +145,12 @@ function smrtPlugin(options = {}) {
102
145
  }
103
146
  let server;
104
147
  let manifest = null;
148
+ /**
149
+ * The declared agent surface from the most recent OXC scan (#2591). Held
150
+ * beside `manifest` rather than on it, because `manifest.json` is the runtime
151
+ * manifest and stays runtime-focused; this belongs to the knowledge artifact.
152
+ */
153
+ let agentSurface;
105
154
  let pluginMode = "server";
106
155
  let projectRoot = process.cwd();
107
156
  let config = null;
@@ -161,7 +210,8 @@ function smrtPlugin(options = {}) {
161
210
  manifest: m,
162
211
  rootDir,
163
212
  manifestPath,
164
- config: resolvedKnowledge
213
+ config: resolvedKnowledge,
214
+ agentSurface
165
215
  });
166
216
  const emitted = deterministic ? {
167
217
  ...artifact,
@@ -522,6 +572,8 @@ function smrtPlugin(options = {}) {
522
572
  exclude: safeExclude,
523
573
  followSymbolicLinks
524
574
  }).scanAndResolve();
575
+ agentSurface = toKnowledgeAgentSurface(results.agentSurface);
576
+ reportAgentSurfaceDiagnostics(agentSurface);
525
577
  if (results.errors.length > 0) {
526
578
  console.error(`\n[smrt] ❌ Build failed: ${results.errors.length} error(s) during scanning:\n`);
527
579
  for (const error of results.errors) console.error(` ${error.filePath}:${error.line || "?"}: ${error.message}\n`);
@@ -1379,6 +1431,6 @@ export default setupCLI;
1379
1431
  }
1380
1432
  }
1381
1433
  //#endregion
1382
- export { findCliApiCoherenceViolations, generateInlineRegisterModule, generateSvelteKitRoutes, generateTypeDeclarationFile, isRegisterShimModuleId, loadVerifiedSmrtGenerationSnapshot, methodNameToKebab, resolveApiActionRouteConfig, resolveApiActionSet, serializeSmrtGenerationSnapshot, sha256SmrtGenerationSnapshot, smrtPlugin, validateCliIncludeAgainstApi };
1434
+ export { buildWebMcpToolDefinitions, findCliApiCoherenceViolations, generateInlineRegisterModule, generateSvelteKitRoutes, generateTypeDeclarationFile, isRegisterShimModuleId, loadVerifiedSmrtGenerationSnapshot, methodNameToKebab, resolveApiActionRouteConfig, resolveApiActionSet, serializeSmrtGenerationSnapshot, sha256SmrtGenerationSnapshot, smrtPlugin, toKnowledgeAgentSurface, validateCliIncludeAgainstApi };
1383
1435
 
1384
1436
  //# sourceMappingURL=index.js.map