@happyvertical/smrt-core 0.57.7 → 0.57.9

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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-core",
5
- "packageVersion": "0.57.7",
5
+ "packageVersion": "0.57.9",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-core:SmrtClass": {
8
8
  "name": "smrtclass",
@@ -3,12 +3,12 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.57.7",
6
+ "packageVersion": "0.57.9",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "9ae05d8b3348ba099a1197bcfe0bb7204c0333d916a48903270479a5b7143ece",
11
- "packageJson": "03172453fcaf761afbcd51fb8d5671dd8543cf286ee95c6d35cc2c0fa5f21ac7",
10
+ "manifest": "65b71a95c9b001eba7e2729141bf2d45635e34346739c7275b563f68d0422e28",
11
+ "packageJson": "4f0a8d064f543e909c0d0321967dd8eb3edbdc2ff7b0df67fe18f6ac567872cf",
12
12
  "agents": "e7153f663754c70fdc7c1a9f014b081f583298eda6387248048d00d852b17685",
13
13
  "moduleDoc:agents/object-runtime.md": "fd2748649e820c2fe5960fa4a44c5f3e2a5afa57da89925e8b4cb3b53d67a07b",
14
14
  "moduleDoc:agents/revision-guard.md": "f6ea32a6860964c98aba14b93587f40b33c8f7d0deccb2c54d21bff45db3da42",
@@ -19,7 +19,7 @@
19
19
  "moduleDoc:agents/change-feed.md": "c3d6206758dd1d2e0475177e1938fb7d7b6cfe8a6c4d3c3b56ef62bc7bc7739d",
20
20
  "moduleDoc:agents/change-signals.md": "a2dbe7077483b5a19bd5ea9589b5a08fe847377c8e05d01d57f813c6d9cbc28b",
21
21
  "moduleDoc:agents/generators.md": "86822b7aa7cb254dcda1a378e1f41881eff48df0d99c5daac50b416a10f81c79",
22
- "moduleDoc:agents/build-knowledge.md": "93ea3d5c708daea35ec7f90de81ed33974ce1610d76a2d1c32a77e149bec7ee8",
22
+ "moduleDoc:agents/build-knowledge.md": "3b277bcef415e2bc627e0cefbdf9e0726b826ed519eabd7e669386fc8ae60080",
23
23
  "moduleDoc:agents/memory.md": "a86bdf370403d08ecad3be86e341eb322dfe6e6b7a4e8806a6f8be9bf3421da5",
24
24
  "moduleDoc:agents/system-diagnostics.md": "b7ccae18ee312bf788d5470f95fa78d3535f1789247d5372e40ca86538290772",
25
25
  "moduleDoc:agents/registry-snapshot.md": "6234aa540427396d1dda1825a4641b1072e247187d5ddf413ae46c691344ee30",
@@ -1197,7 +1197,7 @@
1197
1197
  {
1198
1198
  "path": "agents/build-knowledge.md",
1199
1199
  "module": "build-knowledge",
1200
- "content": "# Decorators, build integration, and knowledge\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes; see [schema-paths.md](schema-paths.md)), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\nAn explicit `@smrt({ collection: 'domain.records' })` names the route/permission\nnamespace independently of `tableName`, including standalone non-STI models.\nScanner output preserves it in both `collection` and `decoratorConfig.collection`.\nGenerated registration reads the merged declaration, so older manifests with a\nderived top-level collection still agree with native decorators. Explicit runtime\nregistration options win; absent declarations retain manifest/STI/default naming.\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n`ui.widget` (#3599) adds a presentation widget hint:\n`'textarea' | 'currency' | 'email' | 'url' | 'phone'`. It rides the same\n`_meta.ui` channel and is also emitted (sanitized) into web-collection\ndefinitions. The manifest generator validates it against the field type and\nfails the build otherwise: every widget needs a `text` field (`currency` is a\ncurrency-CODE picker for an ISO 4217 string such as `currency = 'USD'`, not a\nmoney amount; amounts are integer minor units and take no widget); an unknown\nvalue or a non-text field is an error. `ui.widget` is a hint only — it never changes\nthe column type or validation.\n\n`ui.format` (#3718) says how a value is presented: `money` (an `integer` of\nminor units — the amount hint record pages format and total), `date` (a\nbusiness date on a `datetime`, shown without a time), `datetime`, `percent`\n(a rate on a `decimal`/`integer`). Same channel, same emission, same build-time\ncheck against the field type. `@foreignKey(Target, { role: 'items' })` (or on\n`@crossPackageRef`) marks the declaring model as the target's line items; the\nscanner keeps it at `_meta.role`, the build rejects it on a non-reference or\nan unknown value, and the generated web relationship edge carries\n`role: 'items'` (edges without a role stay byte-stable). Both are hints: no\nschema, persistence or security effect.\n\n## Presentation metadata (#3599)\n\nPure helpers live in `src/ui-metadata.ts`, published browser-safe as\n`@happyvertical/smrt-core/ui-metadata` (also re-exported from the package\nroot). `ManifestGenerator.applyUiMetadata()` runs in `applyGenerationPasses`\nafter inheritance, so every producer (Vite plugin, `ManifestBuilder`,\n`generateManifest`) validates the same way.\n\n- **Display label.** `@smrt({ display: { label: '<field>' } })` names the own\n field generic pickers and assistants use to label a record. Own fields only —\n no paths into other packages; a model whose label lives elsewhere ships a\n selector. Undeclared, it defaults to the first of `name`, `title`, `label`,\n `code` that is a usable own field. Build fails when the declared field is\n missing, `sensitive`, `transient`, or a relationship/json field. The resolved\n field is emitted as `displayLabelField` on the manifest object and in the\n knowledge artifact, and generated MCP/WebMCP `list`/`get`/`update`/`delete`\n descriptions end with ``Records are identified by their `<field>` field.``\n (`describeAction` in `generators/tool-schema.ts`; nothing is added when the\n model has no label field).\n- **Selector slots.** `ModuleUISlot.selects: '@scope/pkg:Model'`\n (`@happyvertical/smrt-types`) marks a package component as THE selector for a\n model. The scanner reads such slots statically from `src/**/ui.ts`\n (`parseUiSelectorsFile`, independent of the class glob) and the manifest\n carries them as `uiSelectors` keyed by slot id. `selects` must be a string\n literal; a duplicate slot id, two selectors for one model, or an own-package\n target that does not exist fails the build. Hosts call\n `findSelectorFor(manifests, qualifiedName)`; generic forms use the selector\n for any `@foreignKey`/`@crossPackageRef` field targeting that model and fall\n back to a generic picker labelled by `displayLabelField`. `display` is read\n per class: an STI subclass that declares none uses the default lookup rather\n than its base's declaration, and a CTI child cannot name a parent's field.\n\n## Worker registration artifact (#3117)\n\nWith `svelteKit.enabled`, a production `vite build` compiles the generated\n`smrt-register.ts` into `.smrt/runtime/register.js` after the server build\n(`src/vite-plugin/worker-registration.ts`, called once from `closeBundle`).\nadapter-node re-bundles the server from its own entries, so the web bundle is\nnever importable by a separate Node process; this artifact is how a deployed\ntask/schedule worker registers the app's local objects (and, through the\n`.smrt/register.js` it imports, consumed packages' objects) with the same\nqualified identities and isolated manifests as the web server. It is a nested\nSSR build with no consumer plugins: only aliases pointing into the project\nsources (e.g. `$lib`) apply, and every other bare import stays external so the\nworker shares the installed `@happyvertical/smrt-core` registry. SvelteKit\nvirtual modules (`$env/*`, `$app/*`) are not available to a worker; an object\nimporting one fails at worker startup. A failure fails the build.\n\n## Lightweight discovery\n\nFilesystem-only discovery, module-doc parsing, and graph freshness are owned by\n`@happyvertical/smrt-scanner/knowledge`. Core's knowledge exports remain compatible\nreexports. Runtime manifest projection and custom-action semantics stay in core.\n\n`src/knowledge-discovery.ts`, exported through `smrt-core/knowledge`, enumerates\ninstalled scope directories and reads canonical AGENTS/legacy CLAUDE docs without\nloading package code, artifacts, or scanning objects. CLI snapshots and MCP share\nthese primitives. Callers retain selection policy: snapshots resolve links and\nfall back to `packages/*` only when no installed SMRT package loads; MCP preserves\nnode_modules paths, deduplicates realpaths, excludes authored workspace links,\nand then enriches the selected packages. Workspace-root/glob discovery remains\nowned by each consumer.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe CLI's schema-command gate reads that same merged file: a pure-consumer\nproject (0 local objects) qualifies on the consumed packages its manifest\nrecords, so a clobbered `objects` map is what made `smrt db:migrate` report\n`missing_local_manifest` (#2925).\n\n`.smrt/manifest.json` has two writers and neither owns all of it: `smrtPlugin()`\ncontributes the project's scanned objects and `smrtConsumer()` the consumed\npackages' entries. Both writes are merge-preserving, keyed on each entry's\nrecorded `packageName` — a plain overwrite in either direction silently drops\nthe other's objects, and the last pass of a multi-environment build is not\nreliably the aggregating one (#1760, #2925). `dist/manifest.json` stays\nlocal-only: a published package must not carry its dependencies' objects.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nTest generation uses that same effective configuration and publishes knowledge\nmatching the manifest it generated. Disabling knowledge removes a previous local\nknowledge artifact, so consumers cannot mistake it for current enabled output.\n`new ManifestBuilder(projectRoot)` keeps discovery, package identity, and output\nat that explicit root, including installed providers and external base classes;\nomitting the argument retains the current-working-directory\nbehavior. Both manifest writers retain declared package dependencies when merging\ntheir local and consumed-object projections.\n\nTest manifests carry optional `artifactPurpose: 'test'`; dependency discovery\nskips those artifacts, including `.smrt` fallbacks. Unmarked runtime manifests,\nempty published providers, and source-only development providers remain eligible.\n`ManifestBuilder` accepts explicit `outputMode: 'dev' | 'build'`; omitted mode\nretains legacy filename inference. Vitest selects dev mode explicitly, so tests\nnever replace a production `dist/manifest.json`. Relative output directories are\nresolved against the builder's project root.\n\nWith `svelteKit.enabled`, `smrtPlugin()`'s transform prepends\n`import './smrt-register.js';` to the configured config module\n(`<configPath>/<configFileName>`, `src/vite-plugin/sveltekit-register-injection.ts`)\nonce the register module exists, on the same first line so line numbers hold.\nApps therefore never hand-write the guarded registration import (#3416); a\nconfig module that still has it imports the same module twice, harmlessly.\n\nTracked `src/lib/server/smrt-register.ts` belongs to SvelteKit config/type\ngeneration. Generic library builds consume it but do not cache or restore it\nas an output; otherwise a concurrent config producer's bytes can be replayed\nover a newer registration after dependency eligibility changes.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n\n## Vite Plugin\n\n`src/vite-preset/` (`@happyvertical/smrt-core/vite`, `smrt()`) composes the Oxc\ndecorator block, `smrtConsumer`, then `smrtPlugin` with the template path\nconventions. Its package list comes only from the `smrt({ packages })` option, or\n`smrt.config` `consumer.packages` (smrt-config schema); it never sniffs\n`package.json`, and a missing or malformed list throws. Keep its output\nbyte-identical to the two-plugin form (`src/vite-preset/index.test.ts`). It\nalso dedupes `@sveltejs/kit` (`smrt:shared-runtime`): SvelteKit matches\n`redirect()`/`fail()` by class, and a linked/workspace SMRT SvelteKit entry\nwould otherwise import its own copy and turn redirects into 500s.\n\n**Package models over REST (#3749).** `consumer.packages` registers a package's\nmodels and gives `@smrt/web` (the consumer's `collectionDefinitions`, one per\nlist-capable model, endpoint `/<collection>`) their definitions, but a package\nmodel gets generated REST routes only when it is on the consumer's hosting\nallowlist (`smrtConsumer({ svelteKit: { objects } })`, #2850: an HTTP exposure\nboundary, each model's own `api` config still applies, so `api: false` and\nempty-include models stay closed, tenancy comes with the generated route). The\npreset fills that allowlist: with `smrt.cookbook.json` present it is the models\nof the cookbook's recipes plus `features`, minus models the cookbook `exposure`\nturns off for `api` or a recipe's `options[model].exposure.api === false`\n(`vite-preset/cookbook-exposure.ts`; recipe `{ exclude }` narrowing is not\napplied by the build yet). `smrt({ expose })` replaces the derived list. No\ncookbook and no `expose` keeps `svelteKit: true` (nothing hosted). The producer's\n`@happyvertical/smrt-virt-web` still covers only the app's own models; read\npackage models from `@smrt/web`. `smrt({ objectsDir })` is passed to the hosting\ncontribution too: the producer and consumer share one `routesDir`, and the\ngenerator refuses it when their settings differ.\n\n**STI siblings (#3749).** Package STI subclasses share their base's table, and\nthe manifest gives them the base's `collection` unless they declare one\n(`consumer-plugin/hosted-sti-collections.ts`). Two hosted siblings would both\nclaim `/<base collection>`, so each hosted subclass that inherits its\ncollection gets its class-derived one (`Order` -> `orders`,\n`defaultCollectionName` in the scanner), in every manifest view the consumer\nderives: routes, `@smrt/web`, the generated client and registration. This is the\nconvention the framework already has for an independent route collection\n(`@smrt({ collection })`), applied by default for hosted subclasses; an explicit\ncollection wins. The route therefore reads through the subclass's own\ncollection (rows scoped to its `_meta_type`) and the definition for that model\nadvertises that route (`objectRef` = the model, `endpoint` = `/orders`). A hosted\nbase keeps the shared name and the base-collection semantics (every row of the\ntable, any subtype). A subclass left off the allowlist keeps the shared\ncollection and folds into the base's definition, as before. A collection class\nthat inherits another's item type (`MaterialCollection extends\nProductCollection`) resolves to the same item and collection, so only one of\nthem is hosted (the class named for the item, else the first). Subclasses that\ndeclare no `api` config get the omitted-config default (full CRUD), not the\nbase's `include`; narrow them on the subclass if the base is meant to restrict\nthem.\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Clean consumer type checks (TypeScript 6)\n\nThe consumer config hook writes `.smrt/register.js` alongside generated types\nafter route preflight succeeds. Generated SvelteKit registration imports that\nmodule, so it must exist during `svelte-kit sync`, before Vite's `buildStart`.\nBoth hosted routes and the legacy `svelteKit: true` mode follow this order.\nThe clean-consumer regression fixture ships real provider declarations and\nchecks the generated imports with `svelte-check`.\nCore's `generate:test` task depends on its own `build`: both publish the local\n`.smrt` manifest/knowledge pair, so Turbo must serialize production before test\ngeneration instead of caching an interleaved pair.\n\n## Model descriptions\n\nEach manifest object and knowledge `objects[]` entry may carry a user-facing\n`description` (for the planner Features tab and similar). The scanner\n(`extractClassJsDocDescription` in `packages/scanner/src/oxc-parser.ts`) reads it\nfrom the parsed source, in priority order: explicit `@smrt({ description })`,\nelse the first paragraph of the class JSDoc (the JSDoc may sit above `export`\nand decorators), minus a leading `ClassName - ` / `ClassName: `, tags\n(`{@link}`, backticks, HTML) and later paragraphs, capped at 200 chars on a\nsentence boundary. `@internal` classes and classes without docs emit no key. It\nis not inherited from a parent class. Generated MCP tool descriptions are\nunchanged (they stay generic).\n"
1200
+ "content": "# Decorators, build integration, and knowledge\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes; see [schema-paths.md](schema-paths.md)), `api`/`mcp`/`cli` (generation config), `ai` (callable methods), `hooks` (beforeSave/afterSave/beforeDelete/afterDelete), `embeddings` (auto-generate), `tenantScoped`, `agent`, `ui` (`{ icon, label, description }` — nav/help hints round-tripped through the manifest as plain data; `description` is the object-level seed for form-level help, #2046).\n\nRegistration sets `SMRT_TABLE_NAME` static property (survives minification).\n\nAn explicit `@smrt({ collection: 'domain.records' })` names the route/permission\nnamespace independently of `tableName`, including standalone non-STI models.\nScanner output preserves it in both `collection` and `decoratorConfig.collection`.\nGenerated registration reads the merged declaration, so older manifests with a\nderived top-level collection still agree with native decorators. Explicit runtime\nregistration options win; absent declarations retain manifest/STI/default naming.\n\n## @field() UI hints (#2046)\n\n`@field({ ui: { basic, group, order, locked } })` — a static, presentation-only\nseed for the field-policy rail (epic #2045). Carried in the manifest under the\nfield's `_meta.ui` (never a top-level `FieldDefinition` key), readable at\nruntime via `getAllFields()` at `field._meta.ui`, and emitted (sanitized) with\n`description` into generated web-collection definitions and browser MCP tool\nschemas. No schema/persistence/security effect — `sensitive`/`readPermission`\nstay the security rail, and `sensitive`/`transient` fields never emit to the\nclient at all.\n\n`ui.widget` (#3599) adds a presentation widget hint:\n`'textarea' | 'currency' | 'email' | 'url' | 'phone'`. It rides the same\n`_meta.ui` channel and is also emitted (sanitized) into web-collection\ndefinitions. The manifest generator validates it against the field type and\nfails the build otherwise: every widget needs a `text` field (`currency` is a\ncurrency-CODE picker for an ISO 4217 string such as `currency = 'USD'`, not a\nmoney amount; amounts are integer minor units and take no widget); an unknown\nvalue or a non-text field is an error. `ui.widget` is a hint only — it never changes\nthe column type or validation.\n\n`ui.format` (#3718) says how a value is presented: `money` (an `integer` of\nminor units — the amount hint record pages format and total), `date` (a\nbusiness date on a `datetime`, shown without a time), `datetime`, `percent`\n(a rate on a `decimal`/`integer`). Same channel, same emission, same build-time\ncheck against the field type. `@foreignKey(Target, { role: 'items' })` (or on\n`@crossPackageRef`) marks the declaring model as the target's line items; the\nscanner keeps it at `_meta.role`, the build rejects it on a non-reference or\nan unknown value, and the generated web relationship edge carries\n`role: 'items'` (edges without a role stay byte-stable). Both are hints: no\nschema, persistence or security effect.\n\n## Presentation metadata (#3599)\n\nPure helpers live in `src/ui-metadata.ts`, published browser-safe as\n`@happyvertical/smrt-core/ui-metadata` (also re-exported from the package\nroot). `ManifestGenerator.applyUiMetadata()` runs in `applyGenerationPasses`\nafter inheritance, so every producer (Vite plugin, `ManifestBuilder`,\n`generateManifest`) validates the same way.\n\n- **Display label.** `@smrt({ display: { label: '<field>' } })` names the own\n field generic pickers and assistants use to label a record. Own fields only —\n no paths into other packages; a model whose label lives elsewhere ships a\n selector. Undeclared, it defaults to the first of `name`, `title`, `label`,\n `code` that is a usable own field. Build fails when the declared field is\n missing, `sensitive`, `transient`, or a relationship/json field. The resolved\n field is emitted as `displayLabelField` on the manifest object and in the\n knowledge artifact, and generated MCP/WebMCP `list`/`get`/`update`/`delete`\n descriptions end with ``Records are identified by their `<field>` field.``\n (`describeAction` in `generators/tool-schema.ts`; nothing is added when the\n model has no label field).\n- **Selector slots.** `ModuleUISlot.selects: '@scope/pkg:Model'`\n (`@happyvertical/smrt-types`) marks a package component as THE selector for a\n model. The scanner reads such slots statically from `src/**/ui.ts`\n (`parseUiSelectorsFile`, independent of the class glob) and the manifest\n carries them as `uiSelectors` keyed by slot id. `selects` must be a string\n literal; a duplicate slot id, two selectors for one model, or an own-package\n target that does not exist fails the build. Hosts call\n `findSelectorFor(manifests, qualifiedName)`; generic forms use the selector\n for any `@foreignKey`/`@crossPackageRef` field targeting that model and fall\n back to a generic picker labelled by `displayLabelField`. `display` is read\n per class: an STI subclass that declares none uses the default lookup rather\n than its base's declaration, and a CTI child cannot name a parent's field.\n\n## Worker registration artifact (#3117)\n\nWith `svelteKit.enabled`, a production `vite build` compiles the generated\n`smrt-register.ts` into `.smrt/runtime/register.js` after the server build\n(`src/vite-plugin/worker-registration.ts`, called once from `closeBundle`).\nadapter-node re-bundles the server from its own entries, so the web bundle is\nnever importable by a separate Node process; this artifact is how a deployed\ntask/schedule worker registers the app's local objects (and, through the\n`.smrt/register.js` it imports, consumed packages' objects) with the same\nqualified identities and isolated manifests as the web server. It is a nested\nSSR build with no consumer plugins: only aliases pointing into the project\nsources (e.g. `$lib`) apply, and every other bare import stays external so the\nworker shares the installed `@happyvertical/smrt-core` registry. SvelteKit\nvirtual modules (`$env/*`, `$app/*`) are not available to a worker; an object\nimporting one fails at worker startup. A failure fails the build.\n\n## Lightweight discovery\n\nFilesystem-only discovery, module-doc parsing, and graph freshness are owned by\n`@happyvertical/smrt-scanner/knowledge`. Core's knowledge exports remain compatible\nreexports. Runtime manifest projection and custom-action semantics stay in core.\n\n`src/knowledge-discovery.ts`, exported through `smrt-core/knowledge`, enumerates\ninstalled scope directories and reads canonical AGENTS/legacy CLAUDE docs without\nloading package code, artifacts, or scanning objects. CLI snapshots and MCP share\nthese primitives. Callers retain selection policy: snapshots resolve links and\nfall back to `packages/*` only when no installed SMRT package loads; MCP preserves\nnode_modules paths, deduplicates realpaths, excludes authored workspace links,\nand then enriches the selected packages. Workspace-root/glob discovery remains\nowned by each consumer.\n\n## Domain Knowledge Artifacts\n\n`smrtPlugin()` writes runtime manifests and agent/developer knowledge artifacts:\n\n- local dev/build: `.smrt/manifest.json` and `.smrt/smrt-knowledge.json`\n- package build: `dist/manifest.json` and `dist/smrt-knowledge.json`\n\nKeep `manifest.json` runtime-focused. `smrt-knowledge.json` is the deterministic\nagent contract for downstream review and architecture tools.\n\nThe CLI's schema-command gate reads that same merged file: a pure-consumer\nproject (0 local objects) qualifies on the consumed packages its manifest\nrecords, so a clobbered `objects` map is what made `smrt db:migrate` report\n`missing_local_manifest` (#2925).\n\n`.smrt/manifest.json` has two writers and neither owns all of it: `smrtPlugin()`\ncontributes the project's scanned objects and `smrtConsumer()` the consumed\npackages' entries. Both writes are merge-preserving, keyed on each entry's\nrecorded `packageName` — a plain overwrite in either direction silently drops\nthe other's objects, and the last pass of a multi-environment build is not\nreliably the aggregating one (#1760, #2925). `dist/manifest.json` stays\nlocal-only: a published package must not carry its dependencies' objects.\n\nThe schema-version-1 object projection is additive and high-signal: it retains\nnormalized tenant mode/field, explicit `cti`/`sti` strategy, conflict columns,\nmethod signatures, and field defaults/constraints/readonly/transient flags.\nSensitive fields are removed before both `fields` and `relationships` are\nderived, including legacy flags stored under `_meta`; matching field and\nsnake-case column names are also removed from projected conflict columns, and a\nsensitive custom tenant field is omitted while retaining scope and mode.\nGenerated artifacts assert this boundary with `sensitiveFieldsExcluded: true`;\nthe optional marker keeps schema version 1 additive while letting readers\nidentify older artifacts that require raw-manifest corroboration.\n\nConfig precedence for knowledge is defaults → top-level `knowledge` in\n`smrt.config.ts` → `packages[packageName].knowledge` → plugin option →\nobject-level `@smrt({ knowledge })`.\n\nTest generation uses that same effective configuration and publishes knowledge\nmatching the manifest it generated. Disabling knowledge removes a previous local\nknowledge artifact, so consumers cannot mistake it for current enabled output.\n`new ManifestBuilder(projectRoot)` keeps discovery, package identity, and output\nat that explicit root, including installed providers and external base classes;\nomitting the argument retains the current-working-directory\nbehavior. Both manifest writers retain declared package dependencies when merging\ntheir local and consumed-object projections.\n\nTest manifests carry optional `artifactPurpose: 'test'`; dependency discovery\nskips those artifacts, including `.smrt` fallbacks. Unmarked runtime manifests,\nempty published providers, and source-only development providers remain eligible.\n`ManifestBuilder` accepts explicit `outputMode: 'dev' | 'build'`; omitted mode\nretains legacy filename inference. Vitest selects dev mode explicitly, so tests\nnever replace a production `dist/manifest.json`. Relative output directories are\nresolved against the builder's project root.\n\nWith `svelteKit.enabled`, `smrtPlugin()`'s transform prepends\n`import './smrt-register.js';` to the configured config module\n(`<configPath>/<configFileName>`, `src/vite-plugin/sveltekit-register-injection.ts`)\nonce the register module exists, on the same first line so line numbers hold.\nApps therefore never hand-write the guarded registration import (#3416); a\nconfig module that still has it imports the same module twice, harmlessly.\n\nTracked `src/lib/server/smrt-register.ts` belongs to SvelteKit config/type\ngeneration. Generic library builds consume it but do not cache or restore it\nas an output; otherwise a concurrent config producer's bytes can be replayed\nover a newer registration after dependency eligibility changes.\n\nObject-level `knowledge: false` excludes an object from authored context only;\nit must not change runtime manifest registration. Use\n`knowledge: { tags, summary, risks }` for review-sensitive domain objects.\n\nHTTP knowledge routes are disabled by default. If `knowledge.api.enabled` is\ntrue, generated SvelteKit routes must stay GET-only and guarded by dev mode or\nadmin auth.\n\n\n## Vite Plugin\n\n`src/vite-preset/` (`@happyvertical/smrt-core/vite`, `smrt()`) composes the Oxc\ndecorator block, `smrtConsumer`, then `smrtPlugin` with the template path\nconventions. Its package list comes only from the `smrt({ packages })` option, or\n`smrt.config` `consumer.packages` (smrt-config schema); it never sniffs\n`package.json`, and a missing or malformed list throws. Keep its output\nbyte-identical to the two-plugin form (`src/vite-preset/index.test.ts`). It\nalso dedupes `@sveltejs/kit` (`smrt:shared-runtime`): SvelteKit matches\n`redirect()`/`fail()` by class, and a linked/workspace SMRT SvelteKit entry\nwould otherwise import its own copy and turn redirects into 500s. The preset\nalso keeps the thin `@happyvertical/smrt-app-runtime/sveltekit` entry inside\nthe SSR bundle: adapter-node bundles Kit itself, and an external runtime\nwould load a separate class through Node even at the same installed version.\nVite matches `ssr.noExternal` by package name, so a pre-resolver keeps the\nexact runtime root external and `ssr.external` keeps `./sveltekit-runtime`\nexternal. That implementation subpath is an internal composition boundary;\napps keep importing `./sveltekit`. This avoids bundling native SQL dependencies.\nThis split applies only to builds; development keeps normal SSR externalization\nand Kit dedupe because Vite's dev module runner ignores resolver external flags.\nOther runtime dependencies retain their normal externalization. Do not explicitly\nexternalize app-runtime in an app config. The production regression in\n`packages/app-runtime/src/sveltekit-production.test.ts` exercises the final\nadapter-node HTTP handler using an installed copy of the published dist entry.\n\n**Package models over REST (#3749).** `consumer.packages` registers a package's\nmodels and gives `@smrt/web` (the consumer's `collectionDefinitions`, one per\nlist-capable model, endpoint `/<collection>`) their definitions, but a package\nmodel gets generated REST routes only when it is on the consumer's hosting\nallowlist (`smrtConsumer({ svelteKit: { objects } })`, #2850: an HTTP exposure\nboundary, each model's own `api` config still applies, so `api: false` and\nempty-include models stay closed, tenancy comes with the generated route). The\npreset fills that allowlist: with `smrt.cookbook.json` present it is the models\nof the cookbook's recipes plus `features`, minus models the cookbook `exposure`\nturns off for `api` or a recipe's `options[model].exposure.api === false`\n(`vite-preset/cookbook-exposure.ts`; recipe `{ exclude }` narrowing is not\napplied by the build yet). `smrt({ expose })` replaces the derived list. No\ncookbook and no `expose` keeps `svelteKit: true` (nothing hosted). The producer's\n`@happyvertical/smrt-virt-web` still covers only the app's own models; read\npackage models from `@smrt/web`. `smrt({ objectsDir })` is passed to the hosting\ncontribution too: the producer and consumer share one `routesDir`, and the\ngenerator refuses it when their settings differ.\n\n**STI siblings (#3749).** Package STI subclasses share their base's table, and\nthe manifest gives them the base's `collection` unless they declare one\n(`consumer-plugin/hosted-sti-collections.ts`). Two hosted siblings would both\nclaim `/<base collection>`, so each hosted subclass that inherits its\ncollection gets its class-derived one (`Order` -> `orders`,\n`defaultCollectionName` in the scanner), in every manifest view the consumer\nderives: routes, `@smrt/web`, the generated client and registration. This is the\nconvention the framework already has for an independent route collection\n(`@smrt({ collection })`), applied by default for hosted subclasses; an explicit\ncollection wins. The route therefore reads through the subclass's own\ncollection (rows scoped to its `_meta_type`) and the definition for that model\nadvertises that route (`objectRef` = the model, `endpoint` = `/orders`). A hosted\nbase keeps the shared name and the base-collection semantics (every row of the\ntable, any subtype). A subclass left off the allowlist keeps the shared\ncollection and folds into the base's definition, as before. A collection class\nthat inherits another's item type (`MaterialCollection extends\nProductCollection`) resolves to the same item and collection, so only one of\nthem is hosted (the class named for the item, else the first). Subclasses that\ndeclare no `api` config get the omitted-config default (full CRUD), not the\nbase's `include`; narrow them on the subclass if the base is meant to restrict\nthem.\n\n```typescript\n// vite.config.ts — required for @smrt() decorators (Vite 8+, oxc transform)\nexport default defineConfig({\n oxc: {\n decorator: {\n legacy: true,\n emitDecoratorMetadata: true,\n },\n },\n});\n```\n\nUnder Vite 8 the oxc transform does not honor the pre-Vite-8 `esbuild.tsconfigRaw`\nrecipe (or tsconfig `experimentalDecorators` reached through SvelteKit's\n`extends \"./.svelte-kit/tsconfig.json\"` chain), so that recipe throws\n`SyntaxError: Invalid or unexpected token` on the first SSR request. Configure\ndecorators through `oxc.decorator` instead. Consumers still pinned on vite<8 need\nthe legacy `esbuild.tsconfigRaw` form with `experimentalDecorators: true,\nemitDecoratorMetadata: true`.\n\nFor independent CI invocations, both `smrtPlugin()` and `smrtConsumer()` accept\nthe same `generationSnapshot: { path, sha256, provenance, sourceRoot }`. The\nschema-v1 snapshot produced by `serializeSmrtGenerationSnapshot()` contains the\nmerged project/dependency manifest, portable source paths, and source-file\ndigests; each plugin selects its own view. Reuse mode fails closed on\nbyte/provenance/path/content drift, skips scans and manifest writes, and still\ngenerates routes, types, registration, and virtual modules. Omit it for normal\nlocal development and watch mode.\n\n## Clean consumer type checks (TypeScript 6)\n\nThe consumer config hook writes `.smrt/register.js` alongside generated types\nafter route preflight succeeds. Generated SvelteKit registration imports that\nmodule, so it must exist during `svelte-kit sync`, before Vite's `buildStart`.\nBoth hosted routes and the legacy `svelteKit: true` mode follow this order.\nThe clean-consumer regression fixture ships real provider declarations and\nchecks the generated imports with `svelte-check`.\nCore's `generate:test` task depends on its own `build`: both publish the local\n`.smrt` manifest/knowledge pair, so Turbo must serialize production before test\ngeneration instead of caching an interleaved pair.\n\n## Model descriptions\n\nEach manifest object and knowledge `objects[]` entry may carry a user-facing\n`description` (for the planner Features tab and similar). The scanner\n(`extractClassJsDocDescription` in `packages/scanner/src/oxc-parser.ts`) reads it\nfrom the parsed source, in priority order: explicit `@smrt({ description })`,\nelse the first paragraph of the class JSDoc (the JSDoc may sit above `export`\nand decorators), minus a leading `ClassName - ` / `ClassName: `, tags\n(`{@link}`, backticks, HTML) and later paragraphs, capped at 200 chars on a\nsentence boundary. `@internal` classes and classes without docs emit no key. It\nis not inherited from a parent class. Generated MCP tool descriptions are\nunchanged (they stay generic).\n"
1201
1201
  },
1202
1202
  {
1203
1203
  "path": "agents/memory.md",
@@ -60,9 +60,10 @@ export declare const SMRT_PRESET_DEFAULTS: {
60
60
  * Packages SMRT's SvelteKit entries share with the app by identity. SvelteKit
61
61
  * recognizes `redirect()`/`fail()` results by class, so a server entry such as
62
62
  * `@happyvertical/smrt-app-runtime/sveltekit` must import the app's own copy.
63
- * A registry install already resolves that peer from the app; a linked or
64
- * workspace package resolves it from its own directory instead, and its
65
- * redirects then surface as 500s. Deduping makes both layouts identical.
63
+ * Deduping selects the app peer for linked/workspace packages. The runtime
64
+ * must also enter the SSR bundle: adapter-node bundles Kit itself, so leaving
65
+ * runtime external would import a second Kit class through Node even when
66
+ * both resolve to the same installed version.
66
67
  */
67
68
  export declare const SMRT_SHARED_RUNTIME_PACKAGES: readonly ["@sveltejs/kit"];
68
69
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite-preset/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,MAAM,CAAC;AAK/C,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,C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CAAC,EAAE,MAAM,CAAC;IACpB,mDAAmD;IACnD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,eAAO,MAAM,oBAAoB;;;;;;;CAOvB,CAAC;AAmEX;;;;;;;;GAQG;AACH,eAAO,MAAM,4BAA4B,4BAA6B,CAAC;AAiCvE;;;;GAIG;AACH,wBAAsB,IAAI,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAgE7E"}
@@ -46,16 +46,32 @@ function decoratorPlugin() {
46
46
  * Packages SMRT's SvelteKit entries share with the app by identity. SvelteKit
47
47
  * recognizes `redirect()`/`fail()` results by class, so a server entry such as
48
48
  * `@happyvertical/smrt-app-runtime/sveltekit` must import the app's own copy.
49
- * A registry install already resolves that peer from the app; a linked or
50
- * workspace package resolves it from its own directory instead, and its
51
- * redirects then surface as 500s. Deduping makes both layouts identical.
49
+ * Deduping selects the app peer for linked/workspace packages. The runtime
50
+ * must also enter the SSR bundle: adapter-node bundles Kit itself, so leaving
51
+ * runtime external would import a second Kit class through Node even when
52
+ * both resolve to the same installed version.
52
53
  */
53
54
  var SMRT_SHARED_RUNTIME_PACKAGES = ["@sveltejs/kit"];
54
55
  function sharedRuntimePlugin() {
56
+ let isBuild = false;
55
57
  return {
56
58
  name: "smrt:shared-runtime",
57
- config() {
58
- return { resolve: { dedupe: [...SMRT_SHARED_RUNTIME_PACKAGES] } };
59
+ enforce: "pre",
60
+ resolveId(id, _importer, options) {
61
+ if (isBuild && options.ssr && id === "@happyvertical/smrt-app-runtime") return {
62
+ id,
63
+ external: true
64
+ };
65
+ },
66
+ config(_user, { command }) {
67
+ isBuild = command === "build";
68
+ return {
69
+ resolve: { dedupe: [...SMRT_SHARED_RUNTIME_PACKAGES] },
70
+ ...isBuild ? { ssr: {
71
+ noExternal: ["@happyvertical/smrt-app-runtime"],
72
+ external: ["@happyvertical/smrt-app-runtime/sveltekit-runtime"]
73
+ } } : {}
74
+ };
59
75
  }
60
76
  };
61
77
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/vite-preset/index.ts"],"sourcesContent":["/**\n * Single-plugin Vite preset for SMRT applications.\n *\n * `plugins: [sveltekit(), smrt()]` replaces the hand-copied glue every app\n * carried: the Oxc legacy-decorator block, `smrtConsumer({...})` with an\n * explicit package list, and `smrtPlugin({...})` with the SvelteKit path\n * options. `smrtConsumer` and `smrtPlugin` stay public and unchanged.\n */\nimport type { Plugin, UserConfig } from 'vite';\nimport { smrtConsumer } from '../consumer-plugin/index.js';\nimport { type SmrtPluginOptions, smrtPlugin } from '../vite-plugin/index.js';\nimport { resolveCookbookHostedObjects } from './cookbook-exposure.js';\n\nexport interface SmrtPresetOptions {\n /**\n * SMRT packages whose object manifests this app consumes. Takes precedence\n * over `consumer.packages` in `smrt.config.ts`. An empty array declares that\n * the app consumes none. Tooling/UI packages must not be listed.\n */\n packages?: readonly string[];\n /**\n * Consumed package models to host over generated REST routes, as\n * provider-qualified refs (`@scope/pkg:Model`). This is an HTTP exposure\n * boundary: each model's own `api` config still applies, so an `api: false`\n * model stays closed. Omit to derive it from `smrt.cookbook.json` (the models\n * of its recipes and `features`, minus those its `exposure` turns off for\n * `api`); without a cookbook nothing is hosted. `[]` hosts nothing.\n */\n expose?: readonly string[];\n /**\n * Project root. Omit to follow the root Vite/SvelteKit resolve (the launch\n * cwd); `smrt.config.ts` is searched from this value or `process.cwd()`.\n */\n projectRoot?: string;\n /** Directory of the app's own `@smrt()` objects. Default `src/lib/objects`. */\n objectsDir?: string;\n /** Generated type declarations. Default `src/lib/types/smrt-generated`. */\n typesDir?: string;\n /** Generated API routes. Default `src/routes/api`. */\n routesDir?: string;\n /** Directory holding the generated runtime config module. Default `src/lib/server`. */\n configPath?: string;\n /** File name of that module. Default `smrt.ts`. */\n configFileName?: string;\n /** Source globs scanned for objects. Default `<objectsDir>/**\\/*.ts`. */\n include?: string[];\n /** Source globs excluded from the scan. Default test and spec files. */\n exclude?: string[];\n /**\n * Apply the Oxc legacy-decorator config. Default `true`. Values the app sets\n * under `oxc.decorator` itself are never overwritten.\n */\n decorators?: boolean;\n}\n\nexport const SMRT_PRESET_DEFAULTS = {\n objectsDir: 'src/lib/objects',\n typesDir: 'src/lib/types/smrt-generated',\n routesDir: 'src/routes/api',\n configPath: 'src/lib/server',\n configFileName: 'smrt.ts',\n exclude: ['**/*.test.ts', '**/*.spec.ts'],\n} as const;\n\nfunction validatePackages(value: unknown, source: string): string[] {\n if (\n !Array.isArray(value) ||\n value.some((p) => typeof p !== 'string' || p.trim() === '')\n ) {\n throw new Error(\n `[smrt] ${source} must be an array of non-empty package names, got ${JSON.stringify(value)}.`,\n );\n }\n return [...new Set(value.map((p: string) => p.trim()))];\n}\n\n/** Resolve the declared consumer package list: option first, then smrt.config. */\nasync function resolvePackages(\n options: SmrtPresetOptions,\n searchFrom: string,\n): Promise<string[]> {\n if (options.packages !== undefined) {\n return validatePackages(options.packages, 'smrt({ packages })');\n }\n\n let declared: unknown;\n try {\n const { loadConfig } = await import('@happyvertical/smrt-config');\n const config = await loadConfig({ cache: false, searchFrom });\n declared = config.consumer?.packages;\n } catch (error) {\n throw new Error(\n `[smrt] Could not read smrt.config to resolve consumer packages: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n if (declared === undefined) {\n throw new Error(\n '[smrt] No consumer package list declared. Set `consumer: { packages: [...] }` in smrt.config.ts ' +\n '(use [] when the app consumes no SMRT packages) or pass `smrt({ packages })`. ' +\n 'The list is explicit so runtime registration is deterministic; it is never inferred from package.json.',\n );\n }\n return validatePackages(declared, 'smrt.config `consumer.packages`');\n}\n\nfunction decoratorPlugin(): Plugin {\n return {\n name: 'smrt:decorators',\n // Vite merges a hook's result over the user config, so fill only the\n // values the app has not set itself.\n config(user: UserConfig) {\n const decorator = (\n user as { oxc?: { decorator?: Record<string, unknown> } }\n ).oxc?.decorator;\n const fill: Record<string, boolean> = {};\n if (decorator?.legacy === undefined) fill.legacy = true;\n if (decorator?.emitDecoratorMetadata === undefined) {\n fill.emitDecoratorMetadata = true;\n }\n return Object.keys(fill).length\n ? ({ oxc: { decorator: fill } } as UserConfig)\n : undefined;\n },\n };\n}\n\n/**\n * Packages SMRT's SvelteKit entries share with the app by identity. SvelteKit\n * recognizes `redirect()`/`fail()` results by class, so a server entry such as\n * `@happyvertical/smrt-app-runtime/sveltekit` must import the app's own copy.\n * A registry install already resolves that peer from the app; a linked or\n * workspace package resolves it from its own directory instead, and its\n * redirects then surface as 500s. Deduping makes both layouts identical.\n */\nexport const SMRT_SHARED_RUNTIME_PACKAGES = ['@sveltejs/kit'] as const;\n\nfunction sharedRuntimePlugin(): Plugin {\n return {\n name: 'smrt:shared-runtime',\n config() {\n return { resolve: { dedupe: [...SMRT_SHARED_RUNTIME_PACKAGES] } };\n },\n };\n}\n\n/**\n * SMRT Vite preset: decorators, dependency manifests, and app object\n * generation in one entry. Returns a promise because the package list is read\n * from `smrt.config.ts`; Vite accepts promised plugins.\n */\nexport async function smrt(options: SmrtPresetOptions = {}): Promise<Plugin[]> {\n const D = SMRT_PRESET_DEFAULTS;\n const objectsDir = options.objectsDir ?? D.objectsDir;\n const typesDir = options.typesDir ?? D.typesDir;\n const routesDir = options.routesDir ?? D.routesDir;\n const configPath = options.configPath ?? D.configPath;\n const configFileName = options.configFileName ?? D.configFileName;\n const rootOption = options.projectRoot\n ? { projectRoot: options.projectRoot }\n : {};\n\n const packages = await resolvePackages(\n options,\n options.projectRoot ?? process.cwd(),\n );\n\n const plugins: Plugin[] = [];\n if (options.decorators !== false) plugins.push(decoratorPlugin());\n plugins.push(sharedRuntimePlugin());\n // smrtConsumer must precede smrtPlugin, as in the template's hand-written form.\n // With no declared packages there is nothing to consume, and an empty list\n // would otherwise trigger dependency discovery.\n if (packages.length > 0) {\n const hosted = options.expose\n ? validatePackages(options.expose, 'smrt({ expose })')\n : resolveCookbookHostedObjects(\n options.projectRoot ?? process.cwd(),\n packages,\n );\n plugins.push(\n smrtConsumer({\n ...rootOption,\n packages,\n generateTypes: true,\n typesDir,\n svelteKit:\n hosted.length > 0\n ? {\n objects: hosted,\n routesDir,\n objectsDir,\n configPath,\n configFileName,\n }\n : true,\n }),\n );\n }\n const pluginOptions: SmrtPluginOptions = {\n ...rootOption,\n include: options.include ?? [`${objectsDir}/**/*.ts`],\n exclude: options.exclude ?? [...D.exclude],\n generateTypes: true,\n typeDeclarationsPath: typesDir,\n svelteKit: {\n enabled: true,\n routesDir,\n objectsDir,\n configPath,\n configFileName,\n },\n };\n plugins.push(smrtPlugin(pluginOptions));\n return plugins;\n}\n"],"mappings":";;;;AAuDA,IAAa,uBAAuB;CAClC,YAAY;CACZ,UAAU;CACV,WAAW;CACX,YAAY;CACZ,gBAAgB;CAChB,SAAS,CAAC,gBAAgB,cAAc;AAC1C;AAEA,SAAS,iBAAiB,OAAgB,QAA0B;CAClE,IACE,CAAC,MAAM,QAAQ,KAAK,KACpB,MAAM,MAAM,MAAM,OAAO,MAAM,YAAY,EAAE,KAAK,MAAM,EAAE,GAE1D,MAAM,IAAI,MACR,UAAU,OAAO,oDAAoD,KAAK,UAAU,KAAK,EAAE,EAC7F;CAEF,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,KAAK,MAAc,EAAE,KAAK,CAAC,CAAC,CAAC;AACxD;;AAGA,eAAe,gBACb,SACA,YACmB;CACnB,IAAI,QAAQ,aAAa,KAAA,GACvB,OAAO,iBAAiB,QAAQ,UAAU,oBAAoB;CAGhE,IAAI;CACJ,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,YAAW,MADU,WAAW;GAAE,OAAO;GAAO;EAAW,CAAC,EAAA,CAC1C,UAAU;CAC9B,SAAS,OAAO;EACd,MAAM,I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AS,QAAQ,SACnB,iBAAiB,QAAQ,QAAQ,kBAAkB,IACnD,6BACE,QAAQ,eAAe,QAAQ,IAAI,GACnC,QACF;EACJ,QAAQ,KACN,aAAa;GACX,GAAG;GACH;GACA,eAAe;GACf;GACA,WACE,OAAO,SAAS,IACZ;IACE,SAAS;IACT;IACA;IACA;IACA;GACF,IACA;EACR,CAAC,CACH;CACF;CACA,MAAM,gBAAmC;EACvC,GAAG;EACH,SAAS,QAAQ,WAAW,CAAC,GAAG,WAAW,SAAS;EACpD,SAAS,QAAQ,WAAW,CAAC,GAAG,EAAE,OAAO;EACzC,eAAe;EACf,sBAAsB;EACtB,WAAW;GACT,SAAS;GACT;GACA;GACA;GACA;EACF;CACF;CACA,QAAQ,KAAK,WAAW,aAAa,CAAC;CACtC,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/vite-preset/index.ts"],"sourcesContent":["/**\n * Single-plugin Vite preset for SMRT applications.\n *\n * `plugins: [sveltekit(), smrt()]` replaces the hand-copied glue every app\n * carried: the Oxc legacy-decorator block, `smrtConsumer({...})` with an\n * explicit package list, and `smrtPlugin({...})` with the SvelteKit path\n * options. `smrtConsumer` and `smrtPlugin` stay public and unchanged.\n */\nimport type { Plugin, UserConfig } from 'vite';\nimport { smrtConsumer } from '../consumer-plugin/index.js';\nimport { type SmrtPluginOptions, smrtPlugin } from '../vite-plugin/index.js';\nimport { resolveCookbookHostedObjects } from './cookbook-exposure.js';\n\nexport interface SmrtPresetOptions {\n /**\n * SMRT packages whose object manifests this app consumes. Takes precedence\n * over `consumer.packages` in `smrt.config.ts`. An empty array declares that\n * the app consumes none. Tooling/UI packages must not be listed.\n */\n packages?: readonly string[];\n /**\n * Consumed package models to host over generated REST routes, as\n * provider-qualified refs (`@scope/pkg:Model`). This is an HTTP exposure\n * boundary: each model's own `api` config still applies, so an `api: false`\n * model stays closed. Omit to derive it from `smrt.cookbook.json` (the models\n * of its recipes and `features`, minus those its `exposure` turns off for\n * `api`); without a cookbook nothing is hosted. `[]` hosts nothing.\n */\n expose?: readonly string[];\n /**\n * Project root. Omit to follow the root Vite/SvelteKit resolve (the launch\n * cwd); `smrt.config.ts` is searched from this value or `process.cwd()`.\n */\n projectRoot?: string;\n /** Directory of the app's own `@smrt()` objects. Default `src/lib/objects`. */\n objectsDir?: string;\n /** Generated type declarations. Default `src/lib/types/smrt-generated`. */\n typesDir?: string;\n /** Generated API routes. Default `src/routes/api`. */\n routesDir?: string;\n /** Directory holding the generated runtime config module. Default `src/lib/server`. */\n configPath?: string;\n /** File name of that module. Default `smrt.ts`. */\n configFileName?: string;\n /** Source globs scanned for objects. Default `<objectsDir>/**\\/*.ts`. */\n include?: string[];\n /** Source globs excluded from the scan. Default test and spec files. */\n exclude?: string[];\n /**\n * Apply the Oxc legacy-decorator config. Default `true`. Values the app sets\n * under `oxc.decorator` itself are never overwritten.\n */\n decorators?: boolean;\n}\n\nexport const SMRT_PRESET_DEFAULTS = {\n objectsDir: 'src/lib/objects',\n typesDir: 'src/lib/types/smrt-generated',\n routesDir: 'src/routes/api',\n configPath: 'src/lib/server',\n configFileName: 'smrt.ts',\n exclude: ['**/*.test.ts', '**/*.spec.ts'],\n} as const;\n\nfunction validatePackages(value: unknown, source: string): string[] {\n if (\n !Array.isArray(value) ||\n value.some((p) => typeof p !== 'string' || p.trim() === '')\n ) {\n throw new Error(\n `[smrt] ${source} must be an array of non-empty package names, got ${JSON.stringify(value)}.`,\n );\n }\n return [...new Set(value.map((p: string) => p.trim()))];\n}\n\n/** Resolve the declared consumer package list: option first, then smrt.config. */\nasync function resolvePackages(\n options: SmrtPresetOptions,\n searchFrom: string,\n): Promise<string[]> {\n if (options.packages !== undefined) {\n return validatePackages(options.packages, 'smrt({ packages })');\n }\n\n let declared: unknown;\n try {\n const { loadConfig } = await import('@happyvertical/smrt-config');\n const config = await loadConfig({ cache: false, searchFrom });\n declared = config.consumer?.packages;\n } catch (error) {\n throw new Error(\n `[smrt] Could not read smrt.config to resolve consumer packages: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n if (declared === undefined) {\n throw new Error(\n '[smrt] No consumer package list declared. Set `consumer: { packages: [...] }` in smrt.config.ts ' +\n '(use [] when the app consumes no SMRT packages) or pass `smrt({ packages })`. ' +\n 'The list is explicit so runtime registration is deterministic; it is never inferred from package.json.',\n );\n }\n return validatePackages(declared, 'smrt.config `consumer.packages`');\n}\n\nfunction decoratorPlugin(): Plugin {\n return {\n name: 'smrt:decorators',\n // Vite merges a hook's result over the user config, so fill only the\n // values the app has not set itself.\n config(user: UserConfig) {\n const decorator = (\n user as { oxc?: { decorator?: Record<string, unknown> } }\n ).oxc?.decorator;\n const fill: Record<string, boolean> = {};\n if (decorator?.legacy === undefined) fill.legacy = true;\n if (decorator?.emitDecoratorMetadata === undefined) {\n fill.emitDecoratorMetadata = true;\n }\n return Object.keys(fill).length\n ? ({ oxc: { decorator: fill } } as UserConfig)\n : undefined;\n },\n };\n}\n\n/**\n * Packages SMRT's SvelteKit entries share with the app by identity. SvelteKit\n * recognizes `redirect()`/`fail()` results by class, so a server entry such as\n * `@happyvertical/smrt-app-runtime/sveltekit` must import the app's own copy.\n * Deduping selects the app peer for linked/workspace packages. The runtime\n * must also enter the SSR bundle: adapter-node bundles Kit itself, so leaving\n * runtime external would import a second Kit class through Node even when\n * both resolve to the same installed version.\n */\nexport const SMRT_SHARED_RUNTIME_PACKAGES = ['@sveltejs/kit'] as const;\n\nfunction sharedRuntimePlugin(): Plugin {\n let isBuild = false;\n return {\n name: 'smrt:shared-runtime',\n enforce: 'pre',\n resolveId(id, _importer, options) {\n // ssr.external on the package root would externalize every subpath.\n // Keep only this exact entry external, preserving native dependencies.\n if (isBuild && options.ssr && id === '@happyvertical/smrt-app-runtime') {\n return { id, external: true };\n }\n },\n config(_user, { command }) {\n // Only adapter builds need this split. Dev import analysis ignores a\n // resolver's external flag, so it must retain normal externalization.\n isBuild = command === 'build';\n return {\n resolve: { dedupe: [...SMRT_SHARED_RUNTIME_PACKAGES] },\n ...(isBuild\n ? {\n ssr: {\n noExternal: ['@happyvertical/smrt-app-runtime'],\n external: ['@happyvertical/smrt-app-runtime/sveltekit-runtime'],\n },\n }\n : {}),\n };\n },\n };\n}\n\n/**\n * SMRT Vite preset: decorators, dependency manifests, and app object\n * generation in one entry. Returns a promise because the package list is read\n * from `smrt.config.ts`; Vite accepts promised plugins.\n */\nexport async function smrt(options: SmrtPresetOptions = {}): Promise<Plugin[]> {\n const D = SMRT_PRESET_DEFAULTS;\n const objectsDir = options.objectsDir ?? D.objectsDir;\n const typesDir = options.typesDir ?? D.typesDir;\n const routesDir = options.routesDir ?? D.routesDir;\n const configPath = options.configPath ?? D.configPath;\n const configFileName = options.configFileName ?? D.configFileName;\n const rootOption = options.projectRoot\n ? { projectRoot: options.projectRoot }\n : {};\n\n const packages = await resolvePackages(\n options,\n options.projectRoot ?? process.cwd(),\n );\n\n const plugins: Plugin[] = [];\n if (options.decorators !== false) plugins.push(decoratorPlugin());\n plugins.push(sharedRuntimePlugin());\n // smrtConsumer must precede smrtPlugin, as in the template's hand-written form.\n // With no declared packages there is nothing to consume, and an empty list\n // would otherwise trigger dependency discovery.\n if (packages.length > 0) {\n const hosted = options.expose\n ? validatePackages(options.expose, 'smrt({ expose })')\n : resolveCookbookHostedObjects(\n options.projectRoot ?? process.cwd(),\n packages,\n );\n plugins.push(\n smrtConsumer({\n ...rootOption,\n packages,\n generateTypes: true,\n typesDir,\n svelteKit:\n hosted.length > 0\n ? {\n objects: hosted,\n routesDir,\n objectsDir,\n configPath,\n configFileName,\n }\n : true,\n }),\n );\n }\n const pluginOptions: SmrtPluginOptions = {\n ...rootOption,\n include: options.include ?? [`${objectsDir}/**/*.ts`],\n exclude: options.exclude ?? [...D.exclude],\n generateTypes: true,\n typeDeclarationsPath: typesDir,\n svelteKit: {\n enabled: true,\n routesDir,\n objectsDir,\n configPath,\n configFileName,\n },\n };\n plugins.push(smrtPlugin(pluginOptions));\n return plugins;\n}\n"],"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gBAAmC;EACvC,GAAG;EACH,SAAS,QAAQ,WAAW,CAAC,GAAG,WAAW,SAAS;EACpD,SAAS,QAAQ,WAAW,CAAC,GAAG,EAAE,OAAO;EACzC,eAAe;EACf,sBAAsB;EACtB,WAAW;GACT,SAAS;GACT;GACA;GACA;GACA;EACF;CACF;CACA,QAAQ,KAAK,WAAW,aAAa,CAAC;CACtC,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-core",
3
- "version": "0.57.7",
3
+ "version": "0.57.9",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -199,9 +199,9 @@
199
199
  "@happyvertical/files": "^0.105.2",
200
200
  "@happyvertical/json": "^0.105.2",
201
201
  "@happyvertical/logger": "^0.105.2",
202
- "@happyvertical/smrt-config": "0.57.7",
203
- "@happyvertical/smrt-scanner": "0.57.7",
204
- "@happyvertical/smrt-types": "0.57.7",
202
+ "@happyvertical/smrt-config": "0.57.9",
203
+ "@happyvertical/smrt-scanner": "0.57.9",
204
+ "@happyvertical/smrt-types": "0.57.9",
205
205
  "@happyvertical/sql": "^0.105.2",
206
206
  "@happyvertical/utils": "^0.105.2",
207
207
  "@noble/hashes": "^2.4.0",