@happyvertical/smrt-core 0.44.0 → 0.45.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 (104) hide show
  1. package/AGENTS.md +8 -8
  2. package/agents/change-feed.md +3 -2
  3. package/agents/generators.md +34 -0
  4. package/agents/revision-guard.md +66 -0
  5. package/dist/browser.js +2 -1
  6. package/dist/cascade.d.ts +5 -9
  7. package/dist/cascade.d.ts.map +1 -1
  8. package/dist/cascade.js +65 -30
  9. package/dist/cascade.js.map +1 -1
  10. package/dist/change-feed.d.ts +60 -1
  11. package/dist/change-feed.d.ts.map +1 -1
  12. package/dist/change-feed.js +464 -27
  13. package/dist/change-feed.js.map +1 -1
  14. package/dist/change-signals.d.ts.map +1 -1
  15. package/dist/change-signals.js +13 -11
  16. package/dist/change-signals.js.map +1 -1
  17. package/dist/embedded-write-queue.d.ts +8 -0
  18. package/dist/embedded-write-queue.d.ts.map +1 -1
  19. package/dist/embedded-write-queue.js +12 -2
  20. package/dist/embedded-write-queue.js.map +1 -1
  21. package/dist/generators/cli.d.ts.map +1 -1
  22. package/dist/generators/cli.js +10 -18
  23. package/dist/generators/cli.js.map +1 -1
  24. package/dist/generators/custom-action.d.ts +216 -0
  25. package/dist/generators/custom-action.d.ts.map +1 -1
  26. package/dist/generators/custom-action.js +256 -1
  27. package/dist/generators/custom-action.js.map +1 -1
  28. package/dist/generators/index.d.ts +2 -1
  29. package/dist/generators/index.d.ts.map +1 -1
  30. package/dist/generators/index.js +3 -2
  31. package/dist/generators/mcp.d.ts.map +1 -1
  32. package/dist/generators/mcp.js +14 -39
  33. package/dist/generators/mcp.js.map +1 -1
  34. package/dist/generators/preflight-route.d.ts +151 -0
  35. package/dist/generators/preflight-route.d.ts.map +1 -0
  36. package/dist/generators/preflight-route.js +194 -0
  37. package/dist/generators/preflight-route.js.map +1 -0
  38. package/dist/generators/rest.d.ts +12 -0
  39. package/dist/generators/rest.d.ts.map +1 -1
  40. package/dist/generators/rest.js +14 -15
  41. package/dist/generators/rest.js.map +1 -1
  42. package/dist/generators/tool-schema.d.ts.map +1 -1
  43. package/dist/generators/tool-schema.js +2 -8
  44. package/dist/generators/tool-schema.js.map +1 -1
  45. package/dist/generators.js +3 -2
  46. package/dist/index.d.ts +3 -2
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +7 -4
  49. package/dist/knowledge.d.ts.map +1 -1
  50. package/dist/knowledge.js +283 -35
  51. package/dist/knowledge.js.map +1 -1
  52. package/dist/manifest/static-manifest.d.ts.map +1 -1
  53. package/dist/manifest/static-manifest.js +6 -2
  54. package/dist/manifest/static-manifest.js.map +1 -1
  55. package/dist/manifest/store.js +1 -1
  56. package/dist/manifest/store.js.map +1 -1
  57. package/dist/manifest.json +8 -2
  58. package/dist/object.d.ts +31 -1
  59. package/dist/object.d.ts.map +1 -1
  60. package/dist/object.js +57 -9
  61. package/dist/object.js.map +1 -1
  62. package/dist/registry/framework-base-classes.d.ts +10 -0
  63. package/dist/registry/framework-base-classes.d.ts.map +1 -0
  64. package/dist/registry/framework-base-classes.js +92 -0
  65. package/dist/registry/framework-base-classes.js.map +1 -0
  66. package/dist/registry/schema-builder.d.ts.map +1 -1
  67. package/dist/registry/schema-builder.js +2 -0
  68. package/dist/registry/schema-builder.js.map +1 -1
  69. package/dist/registry/types.d.ts +27 -6
  70. package/dist/registry/types.d.ts.map +1 -1
  71. package/dist/registry.d.ts +1 -0
  72. package/dist/registry.d.ts.map +1 -1
  73. package/dist/registry.js +2 -1
  74. package/dist/registry.js.map +1 -1
  75. package/dist/revision-guard.d.ts +84 -0
  76. package/dist/revision-guard.d.ts.map +1 -0
  77. package/dist/revision-guard.js +120 -0
  78. package/dist/revision-guard.js.map +1 -0
  79. package/dist/scanner/manifest-generator.d.ts +46 -16
  80. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  81. package/dist/scanner/manifest-generator.js +198 -45
  82. package/dist/scanner/manifest-generator.js.map +1 -1
  83. package/dist/smrt-knowledge.json +18 -9
  84. package/dist/system/bootstrap.d.ts.map +1 -1
  85. package/dist/system/bootstrap.js +2 -1
  86. package/dist/system/bootstrap.js.map +1 -1
  87. package/dist/system/schema.d.ts +75 -2
  88. package/dist/system/schema.d.ts.map +1 -1
  89. package/dist/system/schema.js +326 -4
  90. package/dist/system/schema.js.map +1 -1
  91. package/dist/vite-plugin/index.d.ts.map +1 -1
  92. package/dist/vite-plugin/index.js +48 -23
  93. package/dist/vite-plugin/index.js.map +1 -1
  94. package/dist/vite-plugin/sveltekit-generator.d.ts +33 -7
  95. package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
  96. package/dist/vite-plugin/sveltekit-generator.js +88 -17
  97. package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
  98. package/dist/vite-plugin/sync-apply-route.d.ts.map +1 -1
  99. package/dist/vite-plugin/sync-apply-route.js +2 -0
  100. package/dist/vite-plugin/sync-apply-route.js.map +1 -1
  101. package/dist/vite-plugin/web-collections.d.ts.map +1 -1
  102. package/dist/vite-plugin/web-collections.js +28 -5
  103. package/dist/vite-plugin/web-collections.js.map +1 -1
  104. package/package.json +4 -4
@@ -3,19 +3,20 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.44.0",
6
+ "packageVersion": "0.45.0",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "a72b490253afe2593b2a72115b48a456c1a0a6a956eea969bd22b85d1f3ac961",
11
- "packageJson": "f4804941176a45578bebc9972b60cca56b62f823940f4d1bc7cb7ba07ab8fdcc",
12
- "agents": "ee09cfd65c615877c7baa31add9a6165a841e1a919c9510b12ab6f541383284b",
13
- "moduleDoc:agents/change-feed.md": "1530ded9ed605aa9b8a772b3ba4dd992a3f797f4d7c9ede3b3389dd7bfb401fa",
10
+ "manifest": "f79031b766cd703e615fcb2dff23863edf70f22921f6519693e70f68e977aca3",
11
+ "packageJson": "c9e3155f3064cd3acde10b265d09cc9833da52df49c568fd8f41ce46cf9b7fe3",
12
+ "agents": "72902bcfc539f0644a0b7f9dec17d3bb72194a753e569a5a6f63f85e52fb1810",
13
+ "moduleDoc:agents/change-feed.md": "c5921f2536c5f092690cc9ce5dcdf906376a34413d3c10613be6287c11f87f86",
14
14
  "moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
15
- "moduleDoc:agents/generators.md": "f45658e75f1887ed4e8354f4e1f23145ef869d87d72ec553cc95733ca1a5d3ac",
15
+ "moduleDoc:agents/generators.md": "1c0243c353204b40ed4d5ad688cf812d8eb7e2bb45ffce7e3ce8dca894917b0a",
16
16
  "moduleDoc:agents/schema-paths.md": "561e01104eda21dd5c2c6f6d290bf722a7478c12800136ce61bff8193c8bbc2f",
17
17
  "moduleDoc:agents/data-query.md": "1b72411d441ce2285bf0c89674e7aa996832a58b552b23a6d43834b907d91355",
18
18
  "moduleDoc:agents/collection-reads.md": "4ce06e8b70b9ce9b77b47b3e2ed266c899bb7962ca015d4714f07a4aca10a865",
19
+ "moduleDoc:agents/revision-guard.md": "aa6b1ddb5b6b49fa27ebbe575ec7fcd6d5ceb35ee25acc702f877a226eb9a99a",
19
20
  "moduleDoc:agents/memory.md": "658cb34f3a499e290c14ba0dd8cf0bf82bcc571da01150b61070abf100894dfc",
20
21
  "moduleDoc:agents/query-bounds.md": "3a0601ddaf2bea4e90e3f22e16a2eb3508a6fb8c019e3fb2c1f930c90a377cd5"
21
22
  },
@@ -678,6 +679,9 @@
678
679
  {
679
680
  "name": "delete",
680
681
  "async": true,
682
+ "params": [
683
+ "options?: SmrtDeleteOptions"
684
+ ],
681
685
  "returns": "Promise<void>"
682
686
  },
683
687
  {
@@ -975,12 +979,12 @@
975
979
  "polymorphicAssociations": 1,
976
980
  "uuidColumns": 3
977
981
  },
978
- "agentDoc": "# @happyvertical/smrt-core\n\nORM, code generation, AI integration, and the DispatchBus. Everything else builds on this.\n\nKey surfaces are `SmrtObject`, `SmrtCollection`, `ObjectRegistry`,\n`DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; this file documents\ntheir invariants and source locations, and the module docs below cover the\nper-subsystem semantics.\n\n## Modules\n\nSubsystem semantics live in sibling module docs — read the one for the\nsubsystem you are editing. This file keeps what holds across all of them.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/change-feed.ts` | the adapter-agnostic change-observation spine — `_smrt_changes`, cursors, table versions, generated `_changes` routes, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` + the generated `_events` SSE route | the push companion to the change feed — the signal bus, cross-replica fan-out, the SSE route, and its documented gaps | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/` + `src/vite-plugin/web-collections.ts` | REST/CLI/MCP/web-collection generation, the `manifestHash` emission sites, and generated conditional-GET / ETag v2 semantics | [agents/generators.md](agents/generators.md) |\n| `src/schema/` | the four `SchemaGenerator` entry points, which two reach production, why schema drift stayed invisible, and the #2382 index/tenancy rules | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/data-query.ts` | canonical bounded data-query normalizer and transport-neutral envelope (#2444) | [agents/data-query.md](agents/data-query.md) |\n| `src/collection.ts` | bounded collection reads, projections, latest-related hydration, facets, counts, and read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n\n## SmrtObject Lifecycle\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- Persisted `save()` calls use the object's loaded `updated_at` revision in the\n database `UPDATE`; zero affected rows throws `RUNTIME_REVISION_CONFLICT`\n without overwriting the newer row. `save({ expectedUpdatedAt })` supplies an\n explicit revision when a caller binds the mutation to an earlier preview or\n selection snapshot. Embedded adapters serialize every same-process model\n save, delete, and complete `SmrtObject.withTransaction()` callback through\n one queue; bound saves re-enter that hold. Custom write paths must use those\n public APIs rather than bypassing the CAS ordering contract.\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\n## LearningMemory (#1886)\n\n`LearningMemory` provides tenant-isolated, confidence-scored recall over\n`_smrt_contexts` plus optional injected semantic search. `capture()` reinforces\nsuccesses and decays failures while updating outcome counters; `recall()`\napplies confidence, expiry, time-decay, and hierarchical-scope filters and\nrefreshes `last_used_at`. Detailed persistence and search semantics are in\n[agents/memory.md](agents/memory.md). Keep semantic search behind the\n`SmrtCollection.semanticSearch`-compatible injection boundary.\n\n## SmrtCollection Query\n\n```typescript\nawait collection.list({\n where: { status: 'active', 'price >': 10 },\n limit: 50, offset: 0, orderBy: 'created_at DESC'\n});\n```\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [agents/collection-reads.md](agents/collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\nThis list is the set `@happyvertical/sql`'s `buildWhere` can execute, and\n`convertWhereKeys` accepts nothing outside it — an operator accepted here but\nunknown there fails inside the query builder, after the API said the query was\nvalid (#2276). Two entries were removed for that reason and now reject at the\nAPI boundary: `contains` (never existed in the SQL layer; use `like` with\nexplicit wildcards) and dot-notation JSON paths such as `metadata.userId` (never\nrewritten into an extraction expression, so they reached SQL as qualified column\nreferences). Re-adding either requires the query builder to support it first;\n`src/__tests__/issue-2276-where-contract.test.ts` executes every accepted\noperator against a database to keep the two in step.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [agents/query-bounds.md](agents/query-bounds.md).\n\n## Canonical Bounded Data Queries (#2444)\n\nThe normalizers and fingerprint are the trust boundary for the\ntransport-neutral query envelope; full bounds, schema, and output rules live in\n[agents/data-query.md](agents/data-query.md). Adapters own tenant/principal\naccess and query execution.\n\n## Object Memory & Semantic Search\n\nContext memory and semantic search are persistence primitives inherited by\n`SmrtObject`/`SmrtCollection`; their storage, scope, expiry, and tenant\ninvariants are in [agents/memory.md](agents/memory.md).\n\n## @smrt() Decorator Options\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes, #2357 — see \"Schema paths\"), `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\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## 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 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\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## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n\n## Vite Plugin\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## Schema paths (#2382)\n\n`ensureSystemTables(db, typeHint?)` is the public, idempotent provisioning\nboundary for framework-owned `_smrt_*` tables. Call it on a base PostgreSQL\nconnection before opening a caller-owned transaction; its advisory-locked\nbootstrap prevents missing-table probes from poisoning that transaction.\n\nProduction DDL comes from the **manifest** paths\n(`generateSTISchemaFromManifest`/`generateCTISchemaFromManifest`, selected in\n`src/scanner/manifest-generator.ts` → registered `schema` → `db:migrate`). The\n**registry** paths feed `getTestDatabase()`. Manifest and registry schemas must\nagree on same-package foreign keys as well as columns and indexes:\n`@foreignKey` emits a named physical constraint, while `@crossPackageRef` and\n`@tenantId` remain indexed runtime relationships without physical constraints.\nNatural-key references default to `CASCADE`; ordinary references default to\nimmediate `NO ACTION`, matching `SmrtObject.delete()`.\n\nSame-package archival/audit identifiers that intentionally outlive their\nparent may use `@foreignKey(Target, { constraint: false })`. This explicit\nexception retains relationship loading, indexing, and application-side delete\nmetadata while omitting the physical constraint, schema dependency, and\napp-side cascade/preflight action so the stored identifier survives deletion;\ndocument the retention reason at the field, and keep ordinary same-package\nrelationships constrained.\n\nWhen a relationship is valid on every engine but a particular database cannot\nfaithfully enforce its physical shape, use the public, explicit allowlist\n`@foreignKey(Target, { constraint: { engines: ['postgres', 'sqlite'] } })`.\nOnly physical DDL and schema dependency planning are engine-scoped; native UUID\nstorage, relationship loading, indexes, and application-side delete enforcement\nremain active on every engine. Empty or unknown allowlists fail closed. Do not\nuse this option to hide an otherwise invalid schema.\n\n- Change column/index emission on every shipping path, proven by the path-parity\n test `src/schema/schema-path-parity.test.ts` (#2359; index rules in the module doc). A \"same as migrations\" comment is a claim to check.\n- Every new query predicate ships with its index, or a reason it doesn't.\n- Creation is dependency-planned on every entry point. PostgreSQL defers mutual\n cycle constraints until both tables exist; SQLite keeps cycles inline;\n DuckDB refuses unsupported cycles/actions unless the field has an explicit\n physical-constraint engine allowlist rather than silently omitting them.\n In particular, generated same-package constraints retain the compatibility\n default `ON UPDATE CASCADE`; DuckDB/JSON cannot enforce that action and must\n return an actionable refusal instead of stripping the clause.\n PostgreSQL deferred adds are idempotent and probe the exact child/parent\n columns for orphans before `NOT VALID` + validation. Rollback drops children\n before parents, removes deferred PostgreSQL cycle constraints first, and\n defers SQLite checks while dropping populated cycles. Schema aggregation that\n deliberately filters a parent also removes the retained child's physical FK.\n- Numeric types, uuid casts, conflict targets, timestamps, migrations: run the\n `test:postgres` lane — SQLite affinity accepts what PostgreSQL rejects.\n- Read `dist/manifest.json`/regenerated schemas for what a decorator produced;\n count across all packages instead of sampling.\n- Tenant scoping is whole-path: every unique constraint and conflict target on a\n tenant-scoped table carries the tenant column, and every read path — not only\n `list()` — is interceptor-aware.\n- Rolling indexes out is part of the change: a bulk `CREATE INDEX` batch needs\n the bounded, concurrent migrate path (#2362, Gotchas), or it takes production\n down on deploy.\n\n## Gotchas\n\n- **Filesystem support is a lazy boundary (#1979)**: `SmrtClass` acquires `options.fs` adapters via `createFilesystemAdapter()` (`src/filesystem-loader.ts`), never a static `@happyvertical/files` import — the files SDK statically pulls @aws-sdk/client-s3 and reaches googleapis, and a static edge here would land it in every downstream SSR bundle. Node/tsx/vite-dev runtimes resolve it on first use; fully-bundled deployments import `@happyvertical/smrt-core/filesystem` at startup. Use `importOptionalDependency()` (`src/lazy-external.ts`) for any similar optional heavyweight dependency.\n- **Transaction-bound instances**: `SmrtClass.withDatabase(db, callback)` temporarily binds an initialized instance (including its public `options.db`) to a caller-owned transaction database and restores only the database binding. Transaction owners persisting one object should use `SmrtObject.withTransaction(callback)`, which restores identity/revision metadata after rollback and serializes its embedded callback with ordinary writes. Bound saves re-enter that hold. Never reach into `_db`, and do not use the same instance concurrently during either callback.\n- **Never override toJSON()** — handles STI discriminator + meta field extraction. Use `transformJSON()`\n- **Property init order**: TypeScript initializers run first, then `initialize()` applies option values (options win)\n- **No runtime schema creation**: application tables must be prepared explicitly via migrations/tooling; runtime verification is `tableExists()` only (`src/schema/table-verifier.ts`) — no column, type, or index check\n- **PostgreSQL migrate batches are always time-bounded (#2362)**: `MigrationTracker.applyAll({ atomic: true })` emits `SET LOCAL lock_timeout`/`statement_timeout` before any DDL, so a batch blocked on one table cannot hold its earlier locks indefinitely. `postgresSafe: true` adds concurrent-index mode — non-index DDL commits atomically, then index DDL runs `CONCURRENTLY` on a session pinned via `db.acquireSession()` (a pooled `db.query` would not keep the `SET` and the DDL on one connection). That mode is deliberately **not atomic**: unfinished index migrations are recorded `failed`, not `running`, and their `error_message` carries a `[smrt: concurrent-index phase 1 committed]` marker so a reconciling re-run resumes at the index build instead of replaying committed DDL. INVALID indexes are found via `pg_index.indisvalid` (`pg_indexes` reports them as present) and dropped before rebuild. Operational detail: `packages/cli/AGENTS.md`.\n- **Retry logic is transient-only (#2366)**: `db.get()`/`db.upsert()` retry 4× total (initial + 3), but `ErrorUtils.withRetry` classifies via the cause chain (`src/db-errors.ts`) and rethrows deterministic failures immediately — constraint violations, bad input syntax, missing tables, aborted PG tx (`25P02`). `@happyvertical/sql` stringifies the driver text into `context.originalError`, so **never match `error.message`**; use `classifyDatabaseError()` / `isUniqueViolationError()` / `isAbortedTransactionError()`.\n- **Field caching**: `_cachedFields` populated during `Collection.create()` — eliminates async `getFields()` per query\n- **Smart cloning**: arrays/objects shallow-cloned in property init to prevent aliasing (Issue #22)\n- **Table verification cache**: `isTableVerified(dbUrl, tableName)` avoids redundant `tableExists()` calls\n- **Manifest required**: build-time AST scanning creates manifest. Without vitest plugin → \"No field metadata\"\n- **ManifestBuilder fails on scanner errors**: every production manifest path\n must abort before adapting partial scan results. A syntax error or unresolved\n `@smrt()` config spread cannot be allowed to emit a default-open manifest.\n- **Vite plugin loads scanner from `dist/` first**: `src/vite-plugin/import-build-aware.ts` prefers `dist/` when it exists on disk; it only falls back to `src/` on fresh clones. So if you edit `src/scanner/*.ts` or `src/schema/generator.ts` and want those edits reflected in consumer manifest generation, you must rebuild (`pnpm build` or have `pnpm dev` / `pnpm build:watch` running in core). This is intentional — sniffing `.ts` vs `.js` via `import.meta.url` was non-deterministic under tsx and broke 12–13 publishes (#1139).\n- **Bundled registry ownership**: flattened production bundles can rewrite constructor names and make decorator-time stack inference attribute provider code to the consumer. Generated registration repairs identity only from the exact imported constructor plus an explicit package and isolated one-object manifest; never infer ownership from output paths, simple names, or table names. Distinct packages may export the same simple name under qualified keys. The production-consumer gate lives in `packages/bundle-gate/src/__tests__/registry-identity.spec.ts` (#2308).\n",
982
+ "agentDoc": "# @happyvertical/smrt-core\n\nORM, code generation, AI integration, and the DispatchBus. Everything else builds on this.\n\nKey surfaces are `SmrtObject`, `SmrtCollection`, `ObjectRegistry`,\n`DispatchBus`, `GlobalInterceptors`, and `LearningMemory`; this file documents\ntheir invariants and source locations, and the module docs below cover the\nper-subsystem semantics.\n\n## Modules\n\nSubsystem semantics live in sibling module docs — read the one for the\nsubsystem you are editing. This file keeps what holds across all of them.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `src/change-feed.ts` | the adapter-agnostic change-observation spine — `_smrt_changes`, cursors, table versions, generated `_changes` routes, retention | [agents/change-feed.md](agents/change-feed.md) |\n| `src/change-signals.ts` + the generated `_events` SSE route | the push companion to the change feed — the signal bus, cross-replica fan-out, the SSE route, and its documented gaps | [agents/change-signals.md](agents/change-signals.md) |\n| `src/generators/` + `src/vite-plugin/web-collections.ts` | REST/CLI/MCP/web-collection generation, the `manifestHash` emission sites, and generated conditional-GET / ETag v2 semantics | [agents/generators.md](agents/generators.md) |\n| `src/schema/` | the four `SchemaGenerator` entry points, which two reach production, why schema drift stayed invisible, and the #2382 index/tenancy rules | [agents/schema-paths.md](agents/schema-paths.md) |\n| `src/data-query.ts` | canonical bounded data-query normalizer and transport-neutral envelope (#2444) | [agents/data-query.md](agents/data-query.md) |\n| `src/collection.ts` | bounded collection reads, projections, latest-related hydration, facets, counts, and read plans | [agents/collection-reads.md](agents/collection-reads.md) |\n\n## SmrtObject Lifecycle\n\n`constructor(options)` → `initialize()` → ready for `save()`/`delete()`/`loadFromId()`\n\n- `initialize()`: loads field initializers, applies option values (options override initializers), loads from DB if id/slug provided\n- `save()`: upsert with STI validation, interceptor execution, auto-embeddings. Persisted objects (`isPersisted` — set by DB hydration and successful saves) upsert on `['id']` so natural-key edits (e.g. slug renames) update in place; new objects upsert on the natural-key conflict columns for ingestion-style dedup (#1472)\n- Persisted `save()` uses loaded `updated_at` in its `UPDATE`; zero rows throws\n `RUNTIME_REVISION_CONFLICT`. Explicit `expectedUpdatedAt` binds a save or\n delete to an earlier snapshot. Remote guarded deletes bind the same predicate\n into the final `DELETE`; embedded adapters compare inside the shared write queue\n before cascading. That queue serializes same-process saves, deletes, and full\n `SmrtObject.withTransaction()` callbacks. Custom writes must preserve this\n public CAS ordering contract. PostgreSQL predicate:\n [agents/revision-guard.md](agents/revision-guard.md).\n- Native DuckDB UUID columns are hydrated as canonical strings before model\n initialization, natural-key lookup, and embedded revision claims. Exact\n natural-key probes retain the interceptor-authorized filter when\n canonicalizing a wrapped identity. Custom embedded-CAS paths that consume\n persisted rows must use `getCanonicalPersistedRow()` so UUID identities are\n cast in the same coherent read before reuse.\n- `is(criteria)` / `do(instructions)` / `describe()`: AI operations via function calling. They inject the object's own `toPublicJSON()` (sensitive fields stripped) as a \"content body\" so the model reasons over the instance. Options: `includeData: false` skips injection (for callers that already curate the relevant fields into the instruction); `maxDataLength` overrides the truncation budget. Neither key is forwarded to `ai.message()`. (#1567)\n- `save()` error contract (#2366): unique/PK violation → `ValidationError` `VALIDATION_UNIQUE_CONSTRAINT`, NOT NULL → `VALIDATION_REQUIRED_FIELD`, both on the first attempt on every adapter; any other database failure → `DatabaseError` with the driver error on `cause`\n- `getSlug()`: auto-generates from name → title → label → id\n- `loadRelated(fieldName)`: lazy-loads relationships (cached in `_loadedRelationships` Map)\n\n## LearningMemory (#1886)\n\n`LearningMemory` provides tenant-isolated, confidence-scored recall over\n`_smrt_contexts` plus optional injected semantic search. `capture()` reinforces\nsuccesses and decays failures while updating outcome counters; `recall()`\napplies confidence, expiry, time-decay, and hierarchical-scope filters and\nrefreshes `last_used_at`. Detailed persistence and search semantics are in\n[agents/memory.md](agents/memory.md). Keep semantic search behind the\n`SmrtCollection.semanticSearch`-compatible injection boundary.\n\n## SmrtCollection Query\n\n```typescript\nawait collection.list({\n where: { status: 'active', 'price >': 10 },\n limit: 50, offset: 0, orderBy: 'created_at DESC'\n});\n```\n\nProjection, latest-related, facets, counts, and bounded read plans are\ndocumented in [agents/collection-reads.md](agents/collection-reads.md).\n\n`list()` and `query()` hydrate model instances serially in result order because\nan `initialize()` hook may query through the same transaction-bound PostgreSQL\nclient. Keep this serialization invariant; use `select` when callers need plain\nrows without model hydration.\n\nNative DuckDB model hydration casts declared UUID columns to `VARCHAR` in the\nread query because its JavaScript binding otherwise returns lossy HUGEINT\nwrapper objects. Explicit projections apply the same cast for selected UUID\nfields so bounded query envelopes preserve canonical row and relationship ids.\nFor STI child columns, raw `query()` SELECTs, and latest-related projections,\nthe read path describes the output types without evaluating the query, then\nperforms one data-bearing SELECT with UUID result columns cast to `VARCHAR`;\nmutation statements are never reinterpreted or replayed.\n\n**WHERE operators**: `=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, `like`.\nArrays auto-detect `IN`. NULL is a value, not an operator: `{ deletedAt: null }`\nrenders `IS NULL` and `{ 'deletedAt !=': null }` renders `IS NOT NULL`.\n\nThis list is the set `@happyvertical/sql`'s `buildWhere` can execute, and\n`convertWhereKeys` accepts nothing outside it — an operator accepted here but\nunknown there fails inside the query builder, after the API said the query was\nvalid (#2276). Two entries were removed for that reason and now reject at the\nAPI boundary: `contains` (never existed in the SQL layer; use `like` with\nexplicit wildcards) and dot-notation JSON paths such as `metadata.userId` (never\nrewritten into an extraction expression, so they reached SQL as qualified column\nreferences). Re-adding either requires the query builder to support it first;\n`src/__tests__/issue-2276-where-contract.test.ts` executes every accepted\noperator against a database to keep the two in step.\n\nSTI child collections auto-filter by `_meta_type`. Query bounds — `LIMIT 1` on `get()`, the `limit`/`offset` parser, the `orderBy` whitelist and sensitive/permission refusals, and the deterministic generated-list ordering (#2367) — are in [agents/query-bounds.md](agents/query-bounds.md).\n\n## Canonical Bounded Data Queries (#2444)\n\nThe normalizers and fingerprint are the trust boundary for the\ntransport-neutral query envelope; full bounds, schema, and output rules live in\n[agents/data-query.md](agents/data-query.md). Adapters own tenant/principal\naccess and query execution.\n\n## Object Memory & Semantic Search\n\nContext memory and semantic search are persistence primitives inherited by\n`SmrtObject`/`SmrtCollection`; their storage, scope, expiry, and tenant\ninvariants are in [agents/memory.md](agents/memory.md).\n\n## @smrt() Decorator Options\n\nKey options: `tableName`, `tableStrategy` ('cti'|'sti'), `conflictColumns`, `indexes` (declared multi-column indexes, #2357 — see \"Schema paths\"), `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\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## 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 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\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## DispatchBus\n\n- `emit(signalType, payload, metadata)` → creates persistent Dispatch record\n- `on(pattern, handler)` → in-memory handler (immediate)\n- `subscribe({ signalType, subscriber })` → persistent subscription (survives restarts)\n- `process(subscriberName, handler)` → process pending dispatches\n- Wildcards: `campaign.*` matches `campaign.completed` (single segment only)\n- Tables: `_smrt_dispatch`, `_smrt_dispatch_subscriptions`\n- Status: `pending → processing → completed` (or `failed`)\n\n## Single Table Inheritance (STI)\n\n- Base: `@smrt({ tableStrategy: 'sti' })` — children inherit, share one table\n- Discriminator: `_meta_type` column with qualified names (`@happyvertical/smrt-content:Article`)\n- Child fields: `@meta()` decorator → stored in `_meta_data` JSONB (not as columns)\n- Polymorphic queries: collection loads `_meta_type`, creates correct subclass dynamically\n- Validation: fail-fast on save if `_meta_type` missing or mismatched\n\n## Child Accessors (R10)\n\n`src/child-accessors.ts` installs a consistent `get<FieldName>()` instance method for every `@oneToMany` field at `@smrt()` registration time (e.g. `@oneToMany('OrderItem') items` → `order.getItems()`), delegating to `loadRelatedMany`. Two invariants:\n\n- **Additive** — never overwrites a hand-rolled method of the same name (checks the whole prototype chain). `Profile.getMetadata()` (key-value) and `ProfileRelationship.getTerms()` are preserved.\n- **Runtime-only** — attached to the prototype, invisible to the build-time manifest, so it never leaks into the REST/CLI/MCP surface.\n\nWhen the target declares multiple FKs back to the parent, annotate `@oneToMany(Target, { foreignKey: '<inverseField>' })`; `loadRelatedMany` and the eager `include:` loader both honor it (else first-match).\n\n## Vite Plugin\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## Schema paths (#2382)\n\n`ensureSystemTables(db, typeHint?)` is the public, idempotent provisioning\nboundary for framework-owned `_smrt_*` tables. Call it on a base PostgreSQL\nconnection before opening a caller-owned transaction; its advisory-locked\nbootstrap prevents missing-table probes from poisoning that transaction.\n\nProduction DDL comes from the **manifest** paths\n(`generateSTISchemaFromManifest`/`generateCTISchemaFromManifest`, selected in\n`src/scanner/manifest-generator.ts` → registered `schema` → `db:migrate`). The\n**registry** paths feed `getTestDatabase()`. Manifest and registry schemas must\nagree on same-package foreign keys as well as columns and indexes:\n`@foreignKey` emits a named physical constraint, while `@crossPackageRef` and\n`@tenantId` remain indexed runtime relationships without physical constraints.\nNatural-key references default to `CASCADE`; ordinary references default to\nimmediate `NO ACTION`, matching `SmrtObject.delete()`.\n\nSame-package archival/audit identifiers that intentionally outlive their\nparent may use `@foreignKey(Target, { constraint: false })`. This explicit\nexception retains relationship loading, indexing, and application-side delete\nmetadata while omitting the physical constraint, schema dependency, and\napp-side cascade/preflight action so the stored identifier survives deletion;\ndocument the retention reason at the field, and keep ordinary same-package\nrelationships constrained.\n\nWhen a relationship is valid on every engine but a particular database cannot\nfaithfully enforce its physical shape, use the public, explicit allowlist\n`@foreignKey(Target, { constraint: { engines: ['postgres', 'sqlite'] } })`.\nOnly physical DDL and schema dependency planning are engine-scoped; native UUID\nstorage, relationship loading, indexes, and application-side delete enforcement\nremain active on every engine. Empty or unknown allowlists fail closed. Do not\nuse this option to hide an otherwise invalid schema.\n\n- Change column/index emission on every shipping path, proven by the path-parity\n test `src/schema/schema-path-parity.test.ts` (#2359; index rules in the module doc). A \"same as migrations\" comment is a claim to check.\n- Every new query predicate ships with its index, or a reason it doesn't.\n- Creation is dependency-planned on every entry point. PostgreSQL defers mutual\n cycle constraints until both tables exist; SQLite keeps cycles inline;\n DuckDB refuses unsupported cycles/actions unless the field has an explicit\n physical-constraint engine allowlist rather than silently omitting them.\n In particular, generated same-package constraints retain the compatibility\n default `ON UPDATE CASCADE`; DuckDB/JSON cannot enforce that action and must\n return an actionable refusal instead of stripping the clause.\n PostgreSQL deferred adds are idempotent and probe the exact child/parent\n columns for orphans before `NOT VALID` + validation. Rollback drops children\n before parents, removes deferred PostgreSQL cycle constraints first, and\n defers SQLite checks while dropping populated cycles. Schema aggregation that\n deliberately filters a parent also removes the retained child's physical FK.\n- Numeric types, uuid casts, conflict targets, timestamps, migrations: run the\n `test:postgres` lane — SQLite affinity accepts what PostgreSQL rejects.\n- Read `dist/manifest.json`/regenerated schemas for what a decorator produced;\n count across all packages instead of sampling.\n- Tenant scoping is whole-path: every unique constraint and conflict target on a\n tenant-scoped table carries the tenant column, and every read path — not only\n `list()` — is interceptor-aware.\n- Rolling indexes out is part of the change: a bulk `CREATE INDEX` batch needs\n the bounded, concurrent migrate path (#2362, Gotchas), or it takes production\n down on deploy.\n\n## Gotchas\n\n- **Filesystem support is a lazy boundary (#1979)**: `SmrtClass` acquires `options.fs` adapters via `createFilesystemAdapter()` (`src/filesystem-loader.ts`), never a static `@happyvertical/files` import — the files SDK statically pulls @aws-sdk/client-s3 and reaches googleapis, and a static edge here would land it in every downstream SSR bundle. Node/tsx/vite-dev runtimes resolve it on first use; fully-bundled deployments import `@happyvertical/smrt-core/filesystem` at startup. Use `importOptionalDependency()` (`src/lazy-external.ts`) for any similar optional heavyweight dependency.\n- **Transaction-bound instances**: `SmrtClass.withDatabase(db, callback)` temporarily binds an initialized instance (including its public `options.db`) to a caller-owned transaction database and restores only the database binding. Transaction owners persisting one object should use `SmrtObject.withTransaction(callback)`, which restores identity/revision metadata after rollback and serializes its embedded callback with ordinary writes. Bound saves re-enter that hold. Never reach into `_db`, and do not use the same instance concurrently during either callback.\n- **Never override toJSON()** — handles STI discriminator + meta field extraction. Use `transformJSON()`\n- **Property init order**: TypeScript initializers run first, then `initialize()` applies option values (options win)\n- **No runtime schema creation**: application tables must be prepared explicitly via migrations/tooling; runtime verification is `tableExists()` only (`src/schema/table-verifier.ts`) — no column, type, or index check\n- **PostgreSQL migrate batches are always time-bounded (#2362)**: `MigrationTracker.applyAll({ atomic: true })` emits `SET LOCAL lock_timeout`/`statement_timeout` before any DDL, so a batch blocked on one table cannot hold its earlier locks indefinitely. `postgresSafe: true` adds concurrent-index mode — non-index DDL commits atomically, then index DDL runs `CONCURRENTLY` on a session pinned via `db.acquireSession()` (a pooled `db.query` would not keep the `SET` and the DDL on one connection). That mode is deliberately **not atomic**: unfinished index migrations are recorded `failed`, not `running`, and their `error_message` carries a `[smrt: concurrent-index phase 1 committed]` marker so a reconciling re-run resumes at the index build instead of replaying committed DDL. INVALID indexes are found via `pg_index.indisvalid` (`pg_indexes` reports them as present) and dropped before rebuild. Operational detail: `packages/cli/AGENTS.md`.\n- **Retry logic is transient-only (#2366)**: `db.get()`/`db.upsert()` retry 4× total (initial + 3), but `ErrorUtils.withRetry` classifies via the cause chain (`src/db-errors.ts`) and rethrows deterministic failures immediately — constraint violations, bad input syntax, missing tables, aborted PG tx (`25P02`). `@happyvertical/sql` stringifies the driver text into `context.originalError`, so **never match `error.message`**; use `classifyDatabaseError()` / `isUniqueViolationError()` / `isAbortedTransactionError()`.\n- **Field caching**: `_cachedFields` populated during `Collection.create()` — eliminates async `getFields()` per query\n- **Smart cloning**: arrays/objects shallow-cloned in property init to prevent aliasing (Issue #22)\n- **Table verification cache**: `isTableVerified(dbUrl, tableName)` avoids redundant `tableExists()` calls\n- **Manifest required**: build-time AST scanning creates manifest. Without vitest plugin → \"No field metadata\"\n- **ManifestBuilder fails on scanner errors**: every production manifest path\n must abort before adapting partial scan results. A syntax error or unresolved\n `@smrt()` config spread cannot be allowed to emit a default-open manifest.\n- **Vite plugin loads scanner from `dist/` first**: `src/vite-plugin/import-build-aware.ts` prefers `dist/` when it exists on disk; it only falls back to `src/` on fresh clones. So if you edit `src/scanner/*.ts` or `src/schema/generator.ts` and want those edits reflected in consumer manifest generation, you must rebuild (`pnpm build` or have `pnpm dev` / `pnpm build:watch` running in core). This is intentional — sniffing `.ts` vs `.js` via `import.meta.url` was non-deterministic under tsx and broke 12–13 publishes (#1139).\n- **Bundled registry ownership**: flattened production bundles can rewrite constructor names and make decorator-time stack inference attribute provider code to the consumer. Generated registration repairs identity only from the exact imported constructor plus an explicit package and isolated one-object manifest; never infer ownership from output paths, simple names, or table names. Distinct packages may export the same simple name under qualified keys. The production-consumer gate lives in `packages/bundle-gate/src/__tests__/registry-identity.spec.ts` (#2308).\n",
979
983
  "moduleDocs": [
980
984
  {
981
985
  "path": "agents/change-feed.md",
982
986
  "module": "change-feed",
983
- "content": "# smrt-core/change feed\n\nModule semantics for `src/change-feed.ts`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Change Feed (#1758)\n\nAdapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):\n\n- `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing); subscribers must tolerate spurious entries — they are convergent.\n- Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).\n- `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).\n- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table, replica-stable — no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.\n- Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.\n- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.\n"
987
+ "content": "# smrt-core/change feed\n\nModule semantics for `src/change-feed.ts`. Package orientation, the cross-module\ninvariants, and the traps that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n## Change Feed (#1758)\n\nAdapter-agnostic change-observation spine (`src/change-feed.ts`) — the server half of the client/mobile sync contract (PRD #1755):\n\n- `_smrt_changes` system table: one append per framework save/delete via a GlobalInterceptors writer registered at framework init. Deletes are tombstones (`operation: 'delete'`). `_smrt_*` tables are skipped. Feed-append failures log and never fail the user's write. On PostgreSQL, `_smrt_append_change` catches the INSERT in an exception subtransaction and returns SQLSTATE as data, so swallowing/retrying a best-effort failure cannot leave a caller-managed transaction aborted with `25P02` (#2026); the feed row still commits or rolls back with the caller transaction. Raw-handle/read initialization checks for both the table and helper before issuing any DDL; a cold schema/helper install acquires the same transaction-scoped `('smrt', 'system-tables')` advisory lock as bootstrap before its first DDL and rechecks inside one server-side statement, while schema migration/bootstrap remains the authoritative replace path. No dirty-check: a field-unchanged `.save()` appends a spurious `update` entry (diff-aware paths like `getOrUpsert`/sync-apply short-circuit before `save()` and append nothing); subscribers must tolerate spurious entries — they are convergent.\n- Sequences: allocated as `MAX(seq)+1` inside the INSERT with conflict retry — committed rows stay contiguous, so commit order == seq order on SQLite/Postgres/DuckDB (deliberately NOT identity/serial: those allocate before commit and break the cursor guarantee under concurrent writers).\n- Staged appends (PostgreSQL, #2649): `MAX+1` costs a *wait* — the loser of a primary-key race waits for the winner's whole transaction — so an append inside a caller transaction that already wrote rows would let a long write transaction and an ordinary concurrent request form a real lock cycle (`40P01`, found downstream in willgriffin/willgriffin.dev#457). `_smrt_append_change` therefore checks `pg_current_xact_id_if_assigned()` (PostgreSQL 13+): when the caller already has a transaction id it stages the entry in `_smrt_changes_pending` (identity key, conflicts with nothing, never waits, still rolled back with the caller) and `appendChange()` returns **`null`** instead of a sequence. `_smrt_drain_changes()` moves *committed* staged rows into `_smrt_changes` with contiguous `MAX(seq)+row_number()` sequences under a **try-only** advisory lock, so the drain never waits either. Draining is driven from JavaScript, never inside the append helper: an entry sequenced invisibly server-side would get no live `_events` signal while the append's own signal carried a higher sequence, and a subscriber resuming from that `Last-Event-ID` would skip it permanently. `drainChangeFeed(db)` is called best-effort by `getChangesSince()`, by `pruneChangeFeed()`, and by the append path itself (throttled to one drain per 250 ms per database, bypassed immediately after this process staged an append). The append path issues ONE drain statement (a single bounded pass) and nothing else — the caller may own the surrounding transaction, and a second statement there could fail and abort it behind the feed's own error-swallowing (#2026); the helper's whole body, preflight included, sits inside its exception boundary for the same reason. It still settles that drain's signals in order without spending a statement: a drain that allocated anything assigns a transaction id, so an append that then takes the DIRECT path proves the drain committed, and its signals publish ahead of the append's own; a deferred append proves nothing and queues them. Signals for drained entries publish only after a follow-up probe proves the drain committed, so an uncommitted drain can never advertise a sequence a rollback releases for reuse. `getChangesSince()` additionally holds back everything the handle's own drains allocated while a transaction id is still assigned at read time (a per-handle watermark, so later reads in the same transaction keep holding back), and `bootstrapSystemTables()` refreshes the helpers before its schema-version fast return so an already-stamped database does not keep the deadlocking function. Consequences: the cursor guarantee is unchanged (one `MAX+1` writer at a time, only over committed work), but a staged entry becomes visible one drain after its transaction commits, its log position is drain order rather than statement order, and it publishes its live `_events` signal at drain time (post-commit — the old pre-commit signal could describe a rolled-back write). SQLite/DuckDB keep the direct insert unchanged. Residual: an append issued as a transaction's *first* statement still allocates inline — it holds no row locks then, so it cannot close a cycle, but it can make other direct appenders wait for that commit; issue explicit `bumpChangeFeed()` calls after the write or outside the transaction. A deployment that writes only through transactions and reads the feed from a connection that cannot write must schedule `drainChangeFeed()` on a writable one.\n- `getChangesSince(db, { since, tables?, tenantId?, limit? }) → { changes, cursor, resyncRequired?, resyncCursor? }`: strictly monotonic cursor; polling with returned cursors misses no committed change and never repeats one. A cursor that cannot be served incrementally — pruned below the retained `[floor..horizon]` run, or foreign/ahead of the horizon — gets `resyncRequired: true` with empty `changes`, an unadvanced `cursor`, and `resyncCursor` set to the current horizon so clients can full-refetch then resume incrementally; detection runs on the UNFILTERED log so `tables`/`tenantId` filters never trigger or mask it. `getTenantScopedChangesSince()` resolves tenant via the DispatchBus resolver hook (fail-closed: tenancy on + no context → global rows only; tenant `T` sees `T` + global rows, never another tenant).\n- `getTableVersion(db, table) → number`: the per-table change version (`MAX(seq)` for the table **plus that table's staged-but-undrained count**, so a staged write still moves the ETag and cannot false-304 a client; the sum is monotonic because draining `n` staged rows raises the table's `MAX(seq)` by at least `n`, and both terms are read in ONE statement — separate reads let a drain be counted twice, minting a version a later write re-mints; replica-stable, with no per-process divergence), the ETag source for zero-query conditional GETs (#1765). Advances on any framework write to the table (CRUD and sync-apply, which all `save()`/`delete()`). A table with no retained entry of its own falls back to the global horizon (never a resettable low value) so an all-pruned table cannot false-304 a stale client; only 0 when the feed is empty.\n- Generated `_changes` routes: REST (`GET {basePath}/_changes`, requires `authMiddleware`, otherwise 401 — per-model `api.public` does NOT apply) and SvelteKit (`{routesDir}/_changes/+server.ts`, requires an authenticated principal on `locals`; opt out via `sveltekit.changesRoute.enabled: false`). Query params: `since`, `tables` (comma-separated), `limit`. Responses stay HTTP 200 in the resync state — `resyncRequired` is protocol state, not an error, and `resyncCursor` is the resume cursor after the client completes a full refetch.\n- Retention: `pruneChangeFeed(db, { maxAgeMs?, maxRows?, dryRun? })` — scheduled since #2375 by `runRetentionSweep()` (30-day default), so nothing needs to call it directly; `dryRun` counts the same predicate instead of deleting. Pruning deletes oldest-first and always retains the newest entry (a non-empty feed is never emptied), which is what makes pruned-cursor detection provable. The age bound is a **prefix** bound — everything below the oldest entry still inside the window — because `created_at` and `seq` are not co-monotonic (writer clocks skew, and a staged entry carries its stage-time stamp into a later-assigned sequence); deleting by timestamp alone could punch a hole in the middle of the retained run, where `since < floor - 1` cannot see it and keeps caught-up consumers polling normally. Raw-SQL writes are invisible to the feed (same documented gap as the #1499 cache); `bumpChangeFeed(db, { table, rowId? })` is the manual escape hatch.\n"
984
988
  },
985
989
  {
986
990
  "path": "agents/change-signals.md",
@@ -990,7 +994,7 @@
990
994
  {
991
995
  "path": "agents/generators.md",
992
996
  "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## 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"
997
+ "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## Browser-plane playbook preflight route (#2590)\n\n`GET {basePath}/_preflight?key=<playbook key>` (`src/generators/preflight-route.ts`)\nis an advisory, read-effect, idempotent report of what a caller's playbook would\nbe allowed to do — capability *selection*, never authorization. Resolution and\nverdict shaping live in `@happyvertical/smrt-playbooks`, which depends on this\npackage, so core takes the evaluator as the `APIConfig.playbookPreflight` seam and\nthe dependency stays one-way. Without a provider the route 404s.\n\n**`authMiddleware` is never invoked by preflight**, and that is enforced\nstructurally rather than by discipline: `PlaybookPreflightRouteOptions` has no\nauth member of any kind, and `rest.ts` passes the boolean `appAuthConfigured`\ninstead — so there is no handle in the module to invoke by mistake. A synthetic-\n`Request` dry run is explicitly not an option: the middleware is request-bound,\nreturns a `Response` rather than a boolean, and may consult session stores,\nrate-limit, or audit. The app-auth layer therefore reports `unknown`, which is the\nhonest answer, and a future `authPredicate` seam can fill it in without changing\nthe contract.\n\nThe static layers preflight predicts against are exported from the same module —\n`isApiActionEnabledForObject`, `isRestActionRoutable`, `isRestRoutePublic`,\n`restFieldReadPermissions`, `restMethodForApiAction`,\n`resolveRegisteredObjectName` — and `APIGenerator`'s own\n`isApiActionEnabled` / `isRoutePublic` now delegate to them, so the route and the\nprediction of the route cannot drift. Exposure and existence are separate\nquestions: `include`/`exclude` gate a route, they do not conjure one, so\n`isRestActionRoutable` additionally requires a custom action to be declared in\n`api.routes` — the only map `dispatchCustomCollectionAction` iterates. A custom\naction is predicted against the verb its own route config declares, so a\n`public: 'read'` opt-out neither silently covers a `POST` action nor falsely\ndenies a declared `GET` one. Every unresolvable key returns the provider's single uniform\n\"unavailable\" body with an unconditional 200: unknown and unauthorized keys are\nindistinguishable at the HTTP layer too.\n\n## Emitted agent surface (#2591)\n\nGenerated model tools have always been build-time artifacts — virtual module,\nmanifest, knowledge graph. View intents (#2588) and playbooks (#2589) existed\nonly once something mounted, so \"what can an agent do in this app\" had no answer\nshort of enumerating every route. This closes that.\n\nThe same OXC scan that builds the manifest also runs the scanner's\nagent-surface matcher (`ScanResults.agentSurface`). `smrtPlugin()` captures it\nin `scanWithOxc`, projects it with `toKnowledgeAgentSurface`, and passes it to\n`buildDomainKnowledgeManifest` as `agentSurface`. Note that declaration\ndiscovery is NOT bound to the plugin's `include` glob — an app that scans\n`src/lib/objects/**` for models still has its `src/lib/agent/*.intents.ts`\nsidecars found (see `packages/scanner/AGENTS.md`). Two more consequences worth\nholding onto:\n\n- **It never touches `manifest.json`.** The runtime manifest stays\n runtime-focused; the agent-addressable surface is an agent/developer contract,\n so it lands in `.smrt/smrt-knowledge.json` and `dist/smrt-knowledge.json`\n only, under `agentSurface: { intents, playbooks, diagnostics }`.\n- **It is passed in, not scanned in `knowledge.ts`.** The scanner carries a\n native parser binary and `smrt-core`'s main entry is browser-reachable, so\n core's sync knowledge builder must not import it. The Vite plugin already\n imports the scanner lazily on the Node side and is the only caller that writes\n this artifact.\n\nThe field is **omitted entirely** when a package declares nothing, which is what\nmakes it additive in practice rather than only on paper: every existing\npackage's checked-in artifact stays byte-identical.\n\nEach declaring module gets a `sourceHashes` entry under the\n`agentSurface:<package-relative path>` prefix (`AGENT_SURFACE_HASH_PREFIX`), so\nEDITING an intent sidecar marks the artifact stale exactly like editing\n`AGENTS.md` does (`stale-domain-knowledge`).\n\nHashes alone cannot see an **added** declaration, though: a brand-new sidecar\nhas no recorded hash to mismatch, the runtime manifest never carries intents,\nand `AGENTS.md` is untouched — so every other signal stays green while the\nartifact omits a real operation. `dev:knowledge-check` therefore also re-derives\nthe declaration SET from source and compares it to the artifact by identity,\nreporting either direction as `stale-agent-surface`. The scan is bounded like\nthe numeric-precision lint: `src` only, behind the scanner's token pre-filter.\n\nThat re-derivation must model what the EMITTER sees, not merely what is on\ndisk, or it reports drift no rebuild can clear. Which files count is decided by\nthe scanner's exported `isAgentSurfaceSourcePath` — the same predicate the\nemitter itself uses, never a list copied into the checker — and the per-file\nresults run through `mergeAgentSurfaces` before comparing, because the merge is\nwhere a duplicate identity and a derived tool-name collision are resolved and\nthe artifact is the merged result.\nDiagnostics are compared alongside identities: a sidecar containing only a\ncomputed declaration adds no identity and has no prior hash, so without that,\n\"a diagnostic, never silence\" would quietly become \"a diagnostic, until the\nartifact goes stale\". The walk covers `<pkg>/src` while the emitter globs the\nwhole project root, so an emitted entry from outside `src` is not reported as\nmissing — this check did not look there, and claiming otherwise would be an\nerror nothing could clear.\n\nBoth `stale-*` codes are warnings by default and errors under `--strict`, which\nis what CI runs. Alongside them: `agent-surface-missing-identity`,\n`agent-surface-duplicate-identity`, and `agent-surface-empty-playbook` are\nerrors, and `agent-surface-not-static` 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
998
  },
995
999
  {
996
1000
  "path": "agents/schema-paths.md",
@@ -1007,6 +1011,11 @@
1007
1011
  "module": "collection-reads",
1008
1012
  "content": "<!-- Module doc for packages/core/AGENTS.md. Linked from the Modules table there. -->\n\n# Collection reads\n\nThis module covers bounded collection reads beyond the basic query contract in\n`packages/core/AGENTS.md`.\n\n## Projections and related rows\n\n`list({ select })` uses SMRT field names, maps them to database columns, and\nreturns plain rows without hydrating objects. It composes with `where`,\n`orderBy`, `limit`, and `offset`, runs normal `beforeList`/tenant interceptors,\nand is limited to column-backed fields; it cannot combine with `include`.\n\n## Bounded STI discriminator scopes\n\nAn STI child collection remains scoped to its own qualified `_meta_type` by\ndefault. A migration that must read registered sibling types may opt into an\nexplicit allowlist:\n\n```typescript\nawait impressionEvents.list({\n stiScope: {\n types: [\n '@anytown/advertising:AdImpression',\n '@anytown/advertising:LegacyAdImpression',\n ],\n },\n orderBy: 'created_at ASC',\n limit: 100,\n});\n```\n\n`stiScope.types` accepts 1–50 unique, qualified, registered types, all sharing\nthe child collection's STI root. Empty, simple-name, unknown, duplicate,\nunrelated, and non-child scopes fail at the collection boundary. The option is\nsupported by `list()`, `count()`, `counts()`, `facets()`, and\n`listWithLatestRelated()`. These methods retain their normal field validation,\nprojection or polymorphic hydration, pagination and cache-key construction;\nnormal read and tenant interceptors still run and are ANDed with the allowlist.\nPoint reads through `get()` remain child-only; use a bounded\n`list({ where, limit: 1, stiScope })` migration read when sibling hydration is\nrequired.\n\nFor one child per parent, use\n[`latest-related.md`](latest-related.md). It uses a portable ranked CTE,\ndeclared primary keys, adapter-specific offset-only syntax, explicit aliases,\nand hydrates only the visible parent page.\n\n## Facets, counts, and read plans\n\n`collection.facets({ fields, where })` runs one bounded `GROUP BY` per requested\nfield and returns `{ field, values: [{ value, count }] }`. It accepts at most 20\nfields, clamps value limits to 1,000 and the collection ceiling, never hydrates\nobjects, and applies the same read/tenant/sensitive-field rails as `select`.\nStored array/string-list values are grouped as stored; they are not unnested.\n`collection.counts({ where })` returns `{ total, filtered }` through two scoped\n`COUNT(*)` queries. Local coverage is SQLite/DuckDB; optional scalar PostgreSQL\ncoverage requires `SMRT_TEST_POSTGRES_URL`.\n\n`executeCollectionReadPlan()` bounds concurrent reads across independent\ncollections while preserving the normal registry and collection options. The\ncaller supplies a positive `maxConcurrency`; the executor does not compose SQL,\ncache, or alter pool defaults, and drains already-started work before returning\nthe first error.\n\n`where` operators must remain aligned with `@happyvertical/sql`'s `buildWhere`:\n`=`, `>`, `<`, `>=`, `<=`, `!=`, `in`, `not in`, and `like`. Arrays imply `IN`,\nand null values render `IS NULL`/`IS NOT NULL`. `contains` and dot-notation JSON\npaths are intentionally rejected until the SQL layer supports them.\n"
1009
1013
  },
1014
+ {
1015
+ "path": "agents/revision-guard.md",
1016
+ "module": "revision-guard",
1017
+ "content": "# Revision compare-and-swap guard (`src/revision-guard.ts`)\n\nEvery persisted `save()` pins its `UPDATE` to the revision the writer loaded;\n`claimRevision()` does the same without running domain hooks, and\n`delete({ expectedUpdatedAt })` binds the same predicate into its final\n`DELETE`. Zero affected rows raises `RUNTIME_REVISION_CONFLICT` rather than\noverwriting or removing a newer row.\n\n## Why the predicate is not an equality (#2620)\n\nThe guard used to compare `updated_at` to `loadedRevision.toISOString()`. On\nPostgreSQL a JavaScript `Date` is two lossy conversions away from the stored\nvalue, so that predicate matched no row at all in two common situations — and\nthe object then conflicted on *every* later save, permanently, rather than\nlosing a race:\n\n- **Precision.** `updated_at` is a microsecond column. Any row last written by\n raw SQL — `updated_at = CURRENT_TIMESTAMP` / `now()`, including SMRT's own\n migration backfills — carries a sub-millisecond tail a `Date` cannot hold.\n- **Process timezone.** Schemas created before the `TIMESTAMPTZ` mapping still\n hold `updated_at` as `timestamp WITHOUT time zone`, and `pg` hydrates that\n type in the process zone, so on a non-UTC host `toISOString()` renders a wall\n clock the row never held. The same columns are written under three different\n conventions — `pg` serializes a bound `Date` in the process zone,\n `claimRevision()` writes a UTC ISO string, and raw `CURRENT_TIMESTAMP` writes\n in the *server* zone — so no single rendering can match every row.\n\n## What the predicate does instead\n\n`postgresRevisionCondition()` builds\n`date_trunc('milliseconds', updated_at) IN (…)` over both wall-clock renderings\nof the revision, the process-zone one and the UTC one, each tagged `+00` so a\n`timestamptz` comparison honours it and a `timestamp` comparison discards it —\nthe predicate therefore does not depend on the *session* TimeZone either. On a\nUTC process the two renderings coincide and the condition is single-valued.\n\nLost-race semantics are preserved: a concurrent writer advances `updated_at` to\nroughly \"now\", so it must land on the loaded revision — or, on a non-UTC\nprocess only, on that revision shifted by the whole UTC offset — to the\nmillisecond before it could slip past. Collapsing that second rendering so the\npredicate is single-valued on every process is tracked as #2623.\n\n## Rules\n\n- Never rebuild this predicate by hand; call `postgresRevisionCondition()`.\n Every guarded write — `save()`, `claimRevision()`, and the guarded `DELETE` —\n goes through `SmrtObject.revisionPredicate()` so no path is left on the exact\n equality.\n- The condition is PostgreSQL-only. Embedded engines take the process-local\n compare/upsert fallback (`usesEmbeddedRevisionFallback`), and remote LibSQL\n stores ISO text whose exact equality round-trips losslessly.\n- Custom write paths must go through `save()`, `save({ expectedUpdatedAt })`,\n or `claimRevision()` rather than bypassing the CAS ordering contract.\n- The driver-layer half — `pg` hydrating and serializing `timestamp` columns in\n the process zone — is tracked as happyvertical/sdk#1223. The guard\n deliberately assumes neither hydration convention, so a UTC-hydration fix\n there cannot break it.\n\n## Coverage\n\n`src/__tests__/issue-2620-revision-guard-precision-postgres.optional.test.ts`\nruns the whole battery — guarded save, `save({ expectedUpdatedAt })`,\n`claimRevision()`, guarded delete, and their still-conflicts counterparts —\nagainst both `updated_at` column shapes in the registered PostgreSQL suite (`pnpm --filter @happyvertical/smrt-core\ntest:postgres`). `src/__tests__/revision-guard.test.ts` covers the rendering\nitself in the default suite.\n"
1018
+ },
1010
1019
  {
1011
1020
  "path": "agents/memory.md",
1012
1021
  "module": "memory",
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../src/system/bootstrap.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAqB,MAAM,oBAAoB,CAAC;AAoH/E;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,iBAAiB,EACrB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAqCf"}
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../src/system/bootstrap.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAqB,MAAM,oBAAoB,CAAC;AA8H/E;;;;;GAKG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,iBAAiB,EACrB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,IAAI,CAAC,CAqCf"}
@@ -1,5 +1,5 @@
1
1
  import { SMRT_SCHEMA_VERSION, getSystemTableDDL } from "./schema.js";
2
- import { ensurePostgresChangeFeedAppendFunction } from "../change-feed.js";
2
+ import { ensurePostgresChangeFeedAppendFunction, ensurePostgresChangeFeedHelpers } from "../change-feed.js";
3
3
  import { assertPostgresSystemTimestampsCurrent, ensureBootstrapSystemTableCompatibility, getDatabaseEngine, tableExists } from "./compatibility.js";
4
4
  import { createLogger } from "@happyvertical/logger";
5
5
  //#region src/system/bootstrap.ts
@@ -44,6 +44,7 @@ async function isSystemSchemaVersionApplied(db, typeHint) {
44
44
  }
45
45
  }
46
46
  async function bootstrapSystemTables(db, typeHint) {
47
+ await ensurePostgresChangeFeedHelpers(db, typeHint);
47
48
  if (await isSystemSchemaVersionApplied(db, typeHint)) return;
48
49
  await ensureBootstrapSystemTableCompatibility(db, typeHint);
49
50
  const engine = getDatabaseEngine(db, typeHint);
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.js","names":[],"sources":["../../src/system/bootstrap.ts"],"sourcesContent":["/** Canonical, idempotent SMRT system-table provisioning. */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface, TransactionHandle } from '@happyvertical/sql';\nimport { ensurePostgresChangeFeedAppendFunction } from '../change-feed.js';\nimport {\n assertPostgresSystemTimestampsCurrent,\n ensureBootstrapSystemTableCompatibility,\n getDatabaseEngine,\n tableExists,\n} from './compatibility.js';\nimport { getSystemTableDDL, SMRT_SCHEMA_VERSION } from './schema.js';\n\nconst SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL =\n \"SELECT pg_advisory_xact_lock(hashtext('smrt'), hashtext('system-tables'))\";\n\n/**\n * Timeout budget for the PostgreSQL system-table bootstrap transaction.\n *\n * The runtime pool's session `lock_timeout`/`statement_timeout` (#2377) are\n * sized for request work. This transaction is not request work: it holds the\n * advisory lock across up to 29 sequential DDL round-trips — ~18.85 s on a\n * high-latency link at 650 ms per round trip — and a second replica cold-starting\n * against the same fresh database *waits* on that lock. Both GUCs bound that\n * wait, because `pg_advisory_xact_lock` is an ordinary statement in the lock\n * manager, so at the runtime defaults the second replica would abort with\n * \"canceling statement due to lock timeout\" where it previously waited and\n * succeeded.\n *\n * Five minutes is an order of magnitude above the documented worst case and\n * still bounded — this is a raise, not a disable. `SET LOCAL` scopes it to this\n * transaction, the same lever migrations use for the same reason (#2362).\n */\nconst SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL = [\n \"SET LOCAL lock_timeout = '300000ms'\",\n \"SET LOCAL statement_timeout = '300000ms'\",\n];\nconst logger = createLogger({ level: 'info' });\n\ntype TransactionCapableDatabase = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\nfunction getQueryRows(result: unknown): Record<string, unknown>[] {\n if (Array.isArray(result)) return result as Record<string, unknown>[];\n if (result && typeof result === 'object' && 'rows' in result) {\n const rows = (result as { rows?: unknown }).rows;\n if (Array.isArray(rows)) return rows as Record<string, unknown>[];\n }\n return [];\n}\n\nasync function isSystemSchemaVersionApplied(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<boolean> {\n const engine = getDatabaseEngine(db, typeHint);\n if (\n engine === 'postgres' &&\n !(await tableExists(db, '_smrt_migrations', typeHint))\n ) {\n return false;\n }\n try {\n const versionParam = engine === 'postgres' ? '$1' : '?';\n const rows = await db.query(\n `SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`,\n SMRT_SCHEMA_VERSION,\n );\n return getQueryRows(rows).length > 0;\n } catch (error) {\n if (engine === 'postgres') throw error;\n return false;\n }\n}\n\nasync function bootstrapSystemTables(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<void> {\n if (await isSystemSchemaVersionApplied(db, typeHint)) return;\n\n await ensureBootstrapSystemTableCompatibility(db, typeHint);\n const engine = getDatabaseEngine(db, typeHint);\n for (const ddl of getSystemTableDDL(engine)) {\n for (const statement of ddl\n .split(';')\n .map((value) => value.trim())\n .filter(Boolean)) {\n await db.query(statement);\n }\n }\n await ensurePostgresChangeFeedAppendFunction(db, { typeHint });\n await assertPostgresSystemTimestampsCurrent(db, typeHint);\n\n const id = crypto.randomUUID();\n const description = 'Initial SMRT system tables';\n await db.execute`\n INSERT INTO _smrt_migrations (id, version, description)\n VALUES (${id}, ${SMRT_SCHEMA_VERSION}, ${description})\n ON CONFLICT(version) DO NOTHING\n `;\n}\n\nasync function rollbackBootstrap(tx: TransactionHandle): Promise<void> {\n try {\n if (typeof tx.isActive !== 'function' || tx.isActive()) await tx.rollback();\n } catch (error) {\n logger.warn(\n `[smrt] Failed to rollback system table bootstrap transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\n/**\n * Ensure every framework-owned SMRT system table exists before use.\n *\n * PostgreSQL provisioning is serialized in a bounded advisory-locked\n * transaction; other engines use the schema's idempotent DDL directly.\n */\nexport async function ensureSystemTables(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<void> {\n if (getDatabaseEngine(db, typeHint) !== 'postgres') {\n await bootstrapSystemTables(db, typeHint);\n return;\n }\n\n const beginTransaction = db.beginTransaction;\n const transaction = (db as TransactionCapableDatabase).transaction;\n if (typeof beginTransaction === 'function') {\n const tx = await beginTransaction.call(db);\n if (!tx) throw new Error('Database transaction could not be started');\n try {\n // Raise the budget before taking the lock — the wait itself is what the\n // runtime session timeouts would otherwise cancel (#2377).\n for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);\n await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);\n await bootstrapSystemTables(tx, typeHint);\n await tx.commit();\n return;\n } catch (error) {\n await rollbackBootstrap(tx);\n throw error;\n }\n }\n\n if (typeof transaction === 'function') {\n await transaction.call(db, async (tx) => {\n for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);\n await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);\n await bootstrapSystemTables(tx, typeHint);\n });\n return;\n }\n\n throw new Error(\n 'Postgres system table bootstrap requires a transaction-capable database adapter',\n );\n}\n"],"mappings":";;;;;;AAaA,IAAM,kCACJ;;;;;;;;;;;;;;;;;;AAmBF,IAAM,qCAAqC,CACzC,uCACA,0CACF;AACA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAS7C,SAAS,aAAa,QAA4C;CAChE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,UAAU,OAAO,WAAW,YAAY,UAAU,QAAQ;EAC5D,MAAM,OAAQ,OAA8B;EAC5C,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO;CAClC;CACA,OAAO,CAAC;AACV;AAEA,eAAe,6BACb,IACA,UACkB;CAClB,MAAM,SAAS,kBAAkB,IAAI,QAAQ;CAC7C,IACE,WAAW,cACX,CAAE,MAAM,YAAY,IAAI,oBAAoB,QAAQ,GAEpD,OAAO;CAET,IAAI;EACF,MAAM,eAAe,WAAW,aAAa,OAAO;EAKpD,OAAO,aAAa,MAJD,GAAG,MACpB,kDAAkD,aAAa,WAC/D,mBACF,CACwB,CAAC,CAAC,SAAS;CACrC,SAAS,OAAO;EACd,IAAI,WAAW,YAAY,MAAM;EACjC,OAAO;CACT;AACF;AAEA,eAAe,sBACb,IACA,UACe;CACf,IAAI,MAAM,6BAA6B,IAAI,QAAQ,GAAG;CAEtD,MAAM,wCAAwC,IAAI,QAAQ;CAC1D,MAAM,SAAS,kBAAkB,IAAI,QAAQ;CAC7C,KAAK,MAAM,OAAO,kBAAkB,MAAM,GACxC,KAAK,MAAM,aAAa,IACrB,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO,GACf,MAAM,GAAG,MAAM,SAAS;CAG5B,MAAM,uCAAuC,IAAI,EAAE,SAAS,CAAC;CAC7D,MAAM,sCAAsC,IAAI,QAAQ;CAExD,MAAM,KAAK,OAAO,WAAW;CAE7B,MAAM,GAAG,OAAO;;cAEJ,GAAG,IAAI,oBAAoB,IAAI,6BAAY;;;AAGzD;AAEA,eAAe,kBAAkB,IAAsC;CACrE,IAAI;EACF,IAAI,OAAO,GAAG,aAAa,cAAc,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS;CAC5E,SAAS,OAAO;EACd,OAAO,KACL,iEACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEzD;CACF;AACF;;;;;;;AAQA,eAAsB,mBACpB,IACA,UACe;CACf,IAAI,kBAAkB,IAAI,QAAQ,MAAM,YAAY;EAClD,MAAM,sBAAsB,IAAI,QAAQ;EACxC;CACF;CAEA,MAAM,mBAAmB,GAAG;CAC5B,MAAM,cAAe,GAAkC;CACvD,IAAI,OAAO,qBAAqB,YAAY;EAC1C,MAAM,KAAK,MAAM,iBAAiB,KAAK,EAAE;EACzC,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,2CAA2C;EACpE,IAAI;GAGF,KAAK,MAAM,OAAO,oCAAoC,MAAM,GAAG,MAAM,GAAG;GACxE,MAAM,GAAG,MAAM,+BAA+B;GAC9C,MAAM,sBAAsB,IAAI,QAAQ;GACxC,MAAM,GAAG,OAAO;GAChB;EACF,SAAS,OAAO;GACd,MAAM,kBAAkB,EAAE;GAC1B,MAAM;EACR;CACF;CAEA,IAAI,OAAO,gBAAgB,YAAY;EACrC,MAAM,YAAY,KAAK,IAAI,OAAO,OAAO;GACvC,KAAK,MAAM,OAAO,oCAAoC,MAAM,GAAG,MAAM,GAAG;GACxE,MAAM,GAAG,MAAM,+BAA+B;GAC9C,MAAM,sBAAsB,IAAI,QAAQ;EAC1C,CAAC;EACD;CACF;CAEA,MAAM,IAAI,MACR,iFACF;AACF"}
1
+ {"version":3,"file":"bootstrap.js","names":[],"sources":["../../src/system/bootstrap.ts"],"sourcesContent":["/** Canonical, idempotent SMRT system-table provisioning. */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface, TransactionHandle } from '@happyvertical/sql';\nimport {\n ensurePostgresChangeFeedAppendFunction,\n ensurePostgresChangeFeedHelpers,\n} from '../change-feed.js';\nimport {\n assertPostgresSystemTimestampsCurrent,\n ensureBootstrapSystemTableCompatibility,\n getDatabaseEngine,\n tableExists,\n} from './compatibility.js';\nimport { getSystemTableDDL, SMRT_SCHEMA_VERSION } from './schema.js';\n\nconst SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL =\n \"SELECT pg_advisory_xact_lock(hashtext('smrt'), hashtext('system-tables'))\";\n\n/**\n * Timeout budget for the PostgreSQL system-table bootstrap transaction.\n *\n * The runtime pool's session `lock_timeout`/`statement_timeout` (#2377) are\n * sized for request work. This transaction is not request work: it holds the\n * advisory lock across up to 29 sequential DDL round-trips — ~18.85 s on a\n * high-latency link at 650 ms per round trip — and a second replica cold-starting\n * against the same fresh database *waits* on that lock. Both GUCs bound that\n * wait, because `pg_advisory_xact_lock` is an ordinary statement in the lock\n * manager, so at the runtime defaults the second replica would abort with\n * \"canceling statement due to lock timeout\" where it previously waited and\n * succeeded.\n *\n * Five minutes is an order of magnitude above the documented worst case and\n * still bounded — this is a raise, not a disable. `SET LOCAL` scopes it to this\n * transaction, the same lever migrations use for the same reason (#2362).\n */\nconst SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL = [\n \"SET LOCAL lock_timeout = '300000ms'\",\n \"SET LOCAL statement_timeout = '300000ms'\",\n];\nconst logger = createLogger({ level: 'info' });\n\ntype TransactionCapableDatabase = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\nfunction getQueryRows(result: unknown): Record<string, unknown>[] {\n if (Array.isArray(result)) return result as Record<string, unknown>[];\n if (result && typeof result === 'object' && 'rows' in result) {\n const rows = (result as { rows?: unknown }).rows;\n if (Array.isArray(rows)) return rows as Record<string, unknown>[];\n }\n return [];\n}\n\nasync function isSystemSchemaVersionApplied(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<boolean> {\n const engine = getDatabaseEngine(db, typeHint);\n if (\n engine === 'postgres' &&\n !(await tableExists(db, '_smrt_migrations', typeHint))\n ) {\n return false;\n }\n try {\n const versionParam = engine === 'postgres' ? '$1' : '?';\n const rows = await db.query(\n `SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`,\n SMRT_SCHEMA_VERSION,\n );\n return getQueryRows(rows).length > 0;\n } catch (error) {\n if (engine === 'postgres') throw error;\n return false;\n }\n}\n\nasync function bootstrapSystemTables(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<void> {\n // #2649: the change-feed helpers changed without a change to the portable\n // system DDL, so a database already stamped with this version would never\n // reach the install below and would keep the deadlocking append function.\n // Ordinary model writes do not call ensureChangeFeedTable(), so nothing else\n // would repair it. One catalog probe when the helpers are already current.\n await ensurePostgresChangeFeedHelpers(db, typeHint);\n\n if (await isSystemSchemaVersionApplied(db, typeHint)) return;\n\n await ensureBootstrapSystemTableCompatibility(db, typeHint);\n const engine = getDatabaseEngine(db, typeHint);\n for (const ddl of getSystemTableDDL(engine)) {\n for (const statement of ddl\n .split(';')\n .map((value) => value.trim())\n .filter(Boolean)) {\n await db.query(statement);\n }\n }\n await ensurePostgresChangeFeedAppendFunction(db, { typeHint });\n await assertPostgresSystemTimestampsCurrent(db, typeHint);\n\n const id = crypto.randomUUID();\n const description = 'Initial SMRT system tables';\n await db.execute`\n INSERT INTO _smrt_migrations (id, version, description)\n VALUES (${id}, ${SMRT_SCHEMA_VERSION}, ${description})\n ON CONFLICT(version) DO NOTHING\n `;\n}\n\nasync function rollbackBootstrap(tx: TransactionHandle): Promise<void> {\n try {\n if (typeof tx.isActive !== 'function' || tx.isActive()) await tx.rollback();\n } catch (error) {\n logger.warn(\n `[smrt] Failed to rollback system table bootstrap transaction: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\n/**\n * Ensure every framework-owned SMRT system table exists before use.\n *\n * PostgreSQL provisioning is serialized in a bounded advisory-locked\n * transaction; other engines use the schema's idempotent DDL directly.\n */\nexport async function ensureSystemTables(\n db: DatabaseInterface,\n typeHint?: string,\n): Promise<void> {\n if (getDatabaseEngine(db, typeHint) !== 'postgres') {\n await bootstrapSystemTables(db, typeHint);\n return;\n }\n\n const beginTransaction = db.beginTransaction;\n const transaction = (db as TransactionCapableDatabase).transaction;\n if (typeof beginTransaction === 'function') {\n const tx = await beginTransaction.call(db);\n if (!tx) throw new Error('Database transaction could not be started');\n try {\n // Raise the budget before taking the lock — the wait itself is what the\n // runtime session timeouts would otherwise cancel (#2377).\n for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);\n await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);\n await bootstrapSystemTables(tx, typeHint);\n await tx.commit();\n return;\n } catch (error) {\n await rollbackBootstrap(tx);\n throw error;\n }\n }\n\n if (typeof transaction === 'function') {\n await transaction.call(db, async (tx) => {\n for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);\n await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);\n await bootstrapSystemTables(tx, typeHint);\n });\n return;\n }\n\n throw new Error(\n 'Postgres system table bootstrap requires a transaction-capable database adapter',\n );\n}\n"],"mappings":";;;;;;AAgBA,IAAM,kCACJ;;;;;;;;;;;;;;;;;;AAmBF,IAAM,qCAAqC,CACzC,uCACA,0CACF;AACA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AAS7C,SAAS,aAAa,QAA4C;CAChE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO;CAClC,IAAI,UAAU,OAAO,WAAW,YAAY,UAAU,QAAQ;EAC5D,MAAM,OAAQ,OAA8B;EAC5C,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO;CAClC;CACA,OAAO,CAAC;AACV;AAEA,eAAe,6BACb,IACA,UACkB;CAClB,MAAM,SAAS,kBAAkB,IAAI,QAAQ;CAC7C,IACE,WAAW,cACX,CAAE,MAAM,YAAY,IAAI,oBAAoB,QAAQ,GAEpD,OAAO;CAET,IAAI;EACF,MAAM,eAAe,WAAW,aAAa,OAAO;EAKpD,OAAO,aAAa,MAJD,GAAG,MACpB,kDAAkD,aAAa,WAC/D,mBACF,CACwB,CAAC,CAAC,SAAS;CACrC,SAAS,OAAO;EACd,IAAI,WAAW,YAAY,MAAM;EACjC,OAAO;CACT;AACF;AAEA,eAAe,sBACb,IACA,UACe;CAMf,MAAM,gCAAgC,IAAI,QAAQ;CAElD,IAAI,MAAM,6BAA6B,IAAI,QAAQ,GAAG;CAEtD,MAAM,wCAAwC,IAAI,QAAQ;CAC1D,MAAM,SAAS,kBAAkB,IAAI,QAAQ;CAC7C,KAAK,MAAM,OAAO,kBAAkB,MAAM,GACxC,KAAK,MAAM,aAAa,IACrB,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO,GACf,MAAM,GAAG,MAAM,SAAS;CAG5B,MAAM,uCAAuC,IAAI,EAAE,SAAS,CAAC;CAC7D,MAAM,sCAAsC,IAAI,QAAQ;CAExD,MAAM,KAAK,OAAO,WAAW;CAE7B,MAAM,GAAG,OAAO;;cAEJ,GAAG,IAAI,oBAAoB,IAAI,6BAAY;;;AAGzD;AAEA,eAAe,kBAAkB,IAAsC;CACrE,IAAI;EACF,IAAI,OAAO,GAAG,aAAa,cAAc,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS;CAC5E,SAAS,OAAO;EACd,OAAO,KACL,iEACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEzD;CACF;AACF;;;;;;;AAQA,eAAsB,mBACpB,IACA,UACe;CACf,IAAI,kBAAkB,IAAI,QAAQ,MAAM,YAAY;EAClD,MAAM,sBAAsB,IAAI,QAAQ;EACxC;CACF;CAEA,MAAM,mBAAmB,GAAG;CAC5B,MAAM,cAAe,GAAkC;CACvD,IAAI,OAAO,qBAAqB,YAAY;EAC1C,MAAM,KAAK,MAAM,iBAAiB,KAAK,EAAE;EACzC,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,2CAA2C;EACpE,IAAI;GAGF,KAAK,MAAM,OAAO,oCAAoC,MAAM,GAAG,MAAM,GAAG;GACxE,MAAM,GAAG,MAAM,+BAA+B;GAC9C,MAAM,sBAAsB,IAAI,QAAQ;GACxC,MAAM,GAAG,OAAO;GAChB;EACF,SAAS,OAAO;GACd,MAAM,kBAAkB,EAAE;GAC1B,MAAM;EACR;CACF;CAEA,IAAI,OAAO,gBAAgB,YAAY;EACrC,MAAM,YAAY,KAAK,IAAI,OAAO,OAAO;GACvC,KAAK,MAAM,OAAO,oCAAoC,MAAM,GAAG,MAAM,GAAG;GACxE,MAAM,GAAG,MAAM,+BAA+B;GAC9C,MAAM,sBAAsB,IAAI,QAAQ;EAC1C,CAAC;EACD;CACF;CAEA,MAAM,IAAI,MACR,iFACF;AACF"}
@@ -57,6 +57,32 @@ export declare const CREATE_SMRT_AI_USAGE_TABLE = "\nCREATE TABLE IF NOT EXISTS
57
57
  * table-level change without a specific row.
58
58
  */
59
59
  export declare const CREATE_SMRT_CHANGES_TABLE = "\nCREATE TABLE IF NOT EXISTS _smrt_changes (\n seq BIGINT PRIMARY KEY,\n table_name TEXT NOT NULL,\n row_id TEXT,\n operation TEXT NOT NULL,\n tenant_id TEXT,\n created_at TIMESTAMP NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_smrt_changes_table_seq\n ON _smrt_changes(table_name, seq);\n\nCREATE INDEX IF NOT EXISTS idx_smrt_changes_tenant_seq\n ON _smrt_changes(tenant_id, seq);\n\nCREATE INDEX IF NOT EXISTS idx_smrt_changes_created_at\n ON _smrt_changes(created_at);\n";
60
+ /**
61
+ * PostgreSQL-only staging table for change-feed appends made inside a
62
+ * caller-managed transaction (issue #2649).
63
+ *
64
+ * `_smrt_changes.seq` is allocated `COALESCE(MAX(seq), 0) + 1`, so two
65
+ * concurrent appends contend on the same primary-key value and the loser
66
+ * *waits for the winner's transaction to end*. When the winner is a long write
67
+ * transaction that goes on to take row locks the loser already holds, that
68
+ * wait closes a genuine lock cycle and PostgreSQL aborts one side with
69
+ * `40P01` — an ordinary concurrent request killing a legitimate long write.
70
+ *
71
+ * The staging table breaks the cycle by removing the wait: an append issued
72
+ * inside a caller transaction inserts here instead, where its identity value
73
+ * conflicts with nothing and it never waits on another transaction. The row is
74
+ * still fate-shared with the caller (a rollback removes it, exactly as
75
+ * before). A later *drain* — {@link CREATE_POSTGRES_CHANGE_FEED_DRAIN_FUNCTION}
76
+ * — moves committed staged rows into `_smrt_changes` with contiguous
77
+ * sequences, so the feed's cursor guarantee is unchanged.
78
+ *
79
+ * PostgreSQL-only on purpose: SQLite and DuckDB do not reach the defect
80
+ * (SQLite serializes writers outright), and keeping the portable DDL untouched
81
+ * keeps the embedded path byte-identical.
82
+ */
83
+ export declare const CREATE_POSTGRES_SMRT_CHANGES_PENDING_TABLE = "\nCREATE TABLE IF NOT EXISTS _smrt_changes_pending (\n pending_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,\n table_name TEXT NOT NULL,\n row_id TEXT,\n operation TEXT NOT NULL,\n tenant_id TEXT,\n created_at TIMESTAMPTZ NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_smrt_changes_pending_table\n ON _smrt_changes_pending(table_name);\n";
84
+ /** Name of the PostgreSQL staging table for deferred change-feed appends. */
85
+ export declare const POSTGRES_CHANGE_FEED_PENDING_TABLE = "_smrt_changes_pending";
60
86
  /** PostgreSQL materialization of the portable change-feed table DDL. */
61
87
  export declare const CREATE_POSTGRES_SMRT_CHANGES_TABLE: string;
62
88
  /** PostgreSQL helper used to isolate best-effort feed appends (#2026). */
@@ -65,6 +91,47 @@ export declare const POSTGRES_CHANGE_FEED_APPEND_FUNCTION_NAME = "_smrt_append_c
65
91
  export declare const LEGACY_POSTGRES_CHANGE_FEED_APPEND_FUNCTION_IDENTITY = "_smrt_append_change(text,text,text,text,timestamp without time zone)";
66
92
  /** Exact PostgreSQL identity used for catalog lookup of the append helper. */
67
93
  export declare const POSTGRES_CHANGE_FEED_APPEND_FUNCTION_IDENTITY = "_smrt_append_change(text,text,text,text,timestamp with time zone)";
94
+ /**
95
+ * Body marker stamped into both PostgreSQL change-feed helpers (#2649).
96
+ *
97
+ * Existence is not currency: an install can hold a helper of the right name
98
+ * and signature whose *body* predates a fix. The probe in `change-feed.ts`
99
+ * matches this token against `pg_proc.prosrc`, so a stale body is detected and
100
+ * replaced. Bump it whenever either helper's body changes in a way an existing
101
+ * database must pick up.
102
+ */
103
+ export declare const POSTGRES_CHANGE_FEED_HELPER_MARKER = "smrt-change-feed-helpers:v3";
104
+ /** PostgreSQL helper that sequences staged change-feed appends (#2649). */
105
+ export declare const POSTGRES_CHANGE_FEED_DRAIN_FUNCTION_NAME = "_smrt_drain_changes";
106
+ /** Exact PostgreSQL identity used for catalog lookup of the drain helper. */
107
+ export declare const POSTGRES_CHANGE_FEED_DRAIN_FUNCTION_IDENTITY = "_smrt_drain_changes(integer)";
108
+ /** How many staged entries one drain call sequences. */
109
+ export declare const POSTGRES_CHANGE_FEED_DRAIN_BATCH = 1000;
110
+ /**
111
+ * PostgreSQL-only drain: move committed staged appends into `_smrt_changes`.
112
+ *
113
+ * This is where the feed's sequence is actually allocated for entries written
114
+ * inside a caller transaction. It runs in its own short transaction (an
115
+ * autocommit append's, or a reader's `drainChangeFeed()` call), holds no user
116
+ * row locks, and never waits on another transaction:
117
+ *
118
+ * - it only ever sees *committed* staged rows — an in-flight transaction's
119
+ * staged row is invisible under MVCC, so the drain neither reads nor locks
120
+ * it, and it is picked up by a later drain once that transaction commits;
121
+ * - concurrent drains are excluded by a `pg_try_advisory_xact_lock`, which
122
+ * *skips* rather than waits, so a drain can never become an edge in a lock
123
+ * cycle either.
124
+ *
125
+ * Because exactly one drain runs at a time and it numbers rows
126
+ * `COALESCE(MAX(seq), 0) + row_number()` in staged order, committed sequences
127
+ * stay contiguous and no reader can observe seq N before seq N-1 — the change
128
+ * feed's cursor guarantee is preserved verbatim (see `change-feed.ts`).
129
+ *
130
+ * Failures are returned as data, like the append helper, so a drain problem
131
+ * never aborts the caller's transaction. A failed drain leaves the staged rows
132
+ * in place for the next attempt.
133
+ */
134
+ export declare const CREATE_POSTGRES_CHANGE_FEED_DRAIN_FUNCTION = "\nCREATE OR REPLACE FUNCTION _smrt_drain_changes(\n p_limit INTEGER DEFAULT 1000\n)\nRETURNS TABLE(\n drained_seq BIGINT,\n drained_table TEXT,\n drained_row_id TEXT,\n drained_operation TEXT,\n drained_tenant_id TEXT,\n error_code TEXT,\n error_message TEXT\n)\nLANGUAGE plpgsql\nSECURITY INVOKER\nAS $smrt_change_feed_drain$\n-- smrt-change-feed-helpers:v3\nDECLARE\n v_base BIGINT;\n v_error_code TEXT;\n v_error_message TEXT;\nBEGIN\n -- EVERY statement below sits inside this exception boundary, preflight\n -- included. The caller may own the surrounding transaction, and an error\n -- escaping this function would abort it \u2014 the #2026 contract. A probe that\n -- blocks on a table lock until statement_timeout is exactly that: it is not\n -- the insert, but it aborts the caller just the same.\n BEGIN\n IF to_regclass('_smrt_changes_pending') IS NULL THEN\n RETURN;\n END IF;\n\n -- Never sequence from inside a transaction that has already written. Doing\n -- so would hold freshly allocated sequences uncommitted for the rest of\n -- that transaction, which is precisely the wait edge #2649 removes \u2014 a\n -- reader calling getChangesSince() inside a long write transaction must\n -- not put it back. The staged rows keep for the next drain.\n IF pg_current_xact_id_if_assigned() IS NOT NULL THEN\n RETURN;\n END IF;\n\n -- Cheap common case: nothing staged, so an autocommit append pays one\n -- index probe rather than a drain.\n IF NOT EXISTS (SELECT 1 FROM _smrt_changes_pending LIMIT 1) THEN\n RETURN;\n END IF;\n\n -- Try, never wait: a drain that waited could become an edge in a cycle.\n IF NOT pg_try_advisory_xact_lock(\n hashtext('smrt'),\n hashtext('change-feed-drain')\n ) THEN\n RETURN;\n END IF;\n\n SELECT COALESCE(MAX(changes.seq), 0) INTO v_base FROM _smrt_changes AS changes;\n\n RETURN QUERY\n WITH removed AS (\n DELETE FROM _smrt_changes_pending AS pending\n WHERE pending.pending_id IN (\n SELECT candidate.pending_id\n FROM _smrt_changes_pending AS candidate\n ORDER BY candidate.pending_id\n LIMIT GREATEST(COALESCE(p_limit, 1000), 1)\n )\n RETURNING\n pending.pending_id,\n pending.table_name,\n pending.row_id,\n pending.operation,\n pending.tenant_id,\n pending.created_at\n ),\n numbered AS (\n SELECT\n removed.*,\n v_base + row_number() OVER (ORDER BY removed.pending_id) AS new_seq\n FROM removed\n ),\n inserted AS (\n INSERT INTO _smrt_changes (\n seq,\n table_name,\n row_id,\n operation,\n tenant_id,\n created_at\n )\n SELECT\n numbered.new_seq,\n numbered.table_name,\n numbered.row_id,\n numbered.operation,\n numbered.tenant_id,\n numbered.created_at\n FROM numbered\n RETURNING\n _smrt_changes.seq,\n _smrt_changes.table_name,\n _smrt_changes.row_id,\n _smrt_changes.operation,\n _smrt_changes.tenant_id\n )\n SELECT\n inserted.seq,\n inserted.table_name,\n inserted.row_id,\n inserted.operation,\n inserted.tenant_id,\n NULL::TEXT,\n NULL::TEXT\n FROM inserted\n ORDER BY inserted.seq;\n EXCEPTION WHEN query_canceled OR assert_failure OR OTHERS THEN\n GET STACKED DIAGNOSTICS\n v_error_code = RETURNED_SQLSTATE,\n v_error_message = MESSAGE_TEXT;\n RETURN QUERY SELECT\n NULL::BIGINT,\n NULL::TEXT,\n NULL::TEXT,\n NULL::TEXT,\n NULL::TEXT,\n v_error_code,\n v_error_message;\n END;\nEND;\n$smrt_change_feed_drain$;\n";
68
135
  /**
69
136
  * PostgreSQL-only change-feed append function.
70
137
  *
@@ -75,7 +142,7 @@ export declare const POSTGRES_CHANGE_FEED_APPEND_FUNCTION_IDENTITY = "_smrt_appe
75
142
  * semicolons, so callers must execute it whole rather than adding it to
76
143
  * {@link ALL_SYSTEM_TABLES}, whose portable DDL entries are semicolon-split.
77
144
  */
78
- export declare const CREATE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION = "\nCREATE OR REPLACE FUNCTION _smrt_append_change(\n p_table_name TEXT,\n p_row_id TEXT,\n p_operation TEXT,\n p_tenant_id TEXT,\n p_created_at TIMESTAMPTZ\n)\nRETURNS TABLE(\n allocated_seq BIGINT,\n error_code TEXT,\n error_message TEXT\n)\nLANGUAGE plpgsql\nSECURITY INVOKER\nAS $smrt_change_feed$\nDECLARE\n v_seq BIGINT;\n v_error_code TEXT;\n v_error_message TEXT;\nBEGIN\n BEGIN\n INSERT INTO _smrt_changes (\n seq,\n table_name,\n row_id,\n operation,\n tenant_id,\n created_at\n )\n SELECT\n COALESCE(MAX(changes.seq), 0) + 1,\n p_table_name,\n p_row_id,\n p_operation,\n p_tenant_id,\n p_created_at\n FROM _smrt_changes AS changes\n RETURNING _smrt_changes.seq INTO v_seq;\n\n RETURN QUERY SELECT v_seq, NULL::TEXT, NULL::TEXT;\n EXCEPTION WHEN query_canceled OR assert_failure OR OTHERS THEN\n GET STACKED DIAGNOSTICS\n v_error_code = RETURNED_SQLSTATE,\n v_error_message = MESSAGE_TEXT;\n RETURN QUERY SELECT NULL::BIGINT, v_error_code, v_error_message;\n END;\nEND;\n$smrt_change_feed$;\n";
145
+ export declare const CREATE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION = "\nCREATE OR REPLACE FUNCTION _smrt_append_change(\n p_table_name TEXT,\n p_row_id TEXT,\n p_operation TEXT,\n p_tenant_id TEXT,\n p_created_at TIMESTAMPTZ\n)\nRETURNS TABLE(\n allocated_seq BIGINT,\n error_code TEXT,\n error_message TEXT\n)\nLANGUAGE plpgsql\nSECURITY INVOKER\nAS $smrt_change_feed$\n-- smrt-change-feed-helpers:v3\nDECLARE\n v_seq BIGINT;\n v_error_code TEXT;\n v_error_message TEXT;\n v_deferred BOOLEAN;\nBEGIN\n -- Has the caller already written in this transaction?\n --\n -- PostgreSQL assigns a transaction id at the first write, so a non-NULL\n -- pg_current_xact_id_if_assigned() means the caller may be holding row\n -- locks. Allocating the feed head here would then make a concurrent appender\n -- wait for this whole transaction to end \u2014 the wait edge that closes the\n -- #2649 cycle. An autocommit append reports NULL: its caller's row write\n -- committed as its own statement, so it holds no row locks and its inline\n -- allocation cannot be part of a cycle. (Requires PostgreSQL 13+.)\n --\n -- This is exactly the condition that makes a cycle possible, not an\n -- approximation of \"inside BEGIN\": a transaction that appends *before* its\n -- first write still allocates inline, but it holds no row locks at that\n -- moment, so nothing that waits on its feed row can also be waited on by it.\n -- Preflight inside its own exception boundary for the same reason the drain\n -- wraps its own: an error here would abort a caller-owned transaction\n -- (#2026), and a catalog probe is still a statement that can fail.\n BEGIN\n v_deferred := pg_current_xact_id_if_assigned() IS NOT NULL\n AND to_regclass('_smrt_changes_pending') IS NOT NULL;\n EXCEPTION WHEN query_canceled OR assert_failure OR OTHERS THEN\n GET STACKED DIAGNOSTICS\n v_error_code = RETURNED_SQLSTATE,\n v_error_message = MESSAGE_TEXT;\n RETURN QUERY SELECT NULL::BIGINT, v_error_code, v_error_message;\n RETURN;\n END;\n\n IF v_deferred THEN\n BEGIN\n -- Staged, not sequenced: an identity value conflicts with nothing, so\n -- this insert never waits on another transaction. It stays fate-shared\n -- with the caller (rollback removes it) and is moved into\n -- _smrt_changes, in order and with a contiguous sequence, by the next\n -- drain after the caller commits.\n INSERT INTO _smrt_changes_pending (\n table_name,\n row_id,\n operation,\n tenant_id,\n created_at\n )\n VALUES (\n p_table_name,\n p_row_id,\n p_operation,\n p_tenant_id,\n p_created_at\n );\n\n -- NULL sequence with NULL error code is the staged marker.\n RETURN QUERY SELECT NULL::BIGINT, NULL::TEXT, NULL::TEXT;\n RETURN;\n EXCEPTION WHEN query_canceled OR assert_failure OR OTHERS THEN\n GET STACKED DIAGNOSTICS\n v_error_code = RETURNED_SQLSTATE,\n v_error_message = MESSAGE_TEXT;\n RETURN QUERY SELECT NULL::BIGINT, v_error_code, v_error_message;\n RETURN;\n END;\n END IF;\n\n -- Autocommit append. The caller's own row write already committed as its own\n -- statement, so this transaction holds no user row locks and allocating the\n -- head here cannot join a lock cycle.\n --\n -- This deliberately does NOT drain: a drain performed here would sequence\n -- staged entries that the JavaScript caller never sees, so no live SSE\n -- signal would be published for them while this append's own signal carries\n -- a HIGHER sequence -- and an EventSource that stores that id as its\n -- Last-Event-ID resumes above them and never receives them. Draining is\n -- driven from JavaScript (drainChangeFeed) so every sequenced entry gets\n -- its signal.\n BEGIN\n INSERT INTO _smrt_changes (\n seq,\n table_name,\n row_id,\n operation,\n tenant_id,\n created_at\n )\n SELECT\n COALESCE(MAX(changes.seq), 0) + 1,\n p_table_name,\n p_row_id,\n p_operation,\n p_tenant_id,\n p_created_at\n FROM _smrt_changes AS changes\n RETURNING _smrt_changes.seq INTO v_seq;\n\n RETURN QUERY SELECT v_seq, NULL::TEXT, NULL::TEXT;\n EXCEPTION WHEN query_canceled OR assert_failure OR OTHERS THEN\n GET STACKED DIAGNOSTICS\n v_error_code = RETURNED_SQLSTATE,\n v_error_message = MESSAGE_TEXT;\n RETURN QUERY SELECT NULL::BIGINT, v_error_code, v_error_message;\n END;\nEND;\n$smrt_change_feed$;\n";
79
146
  /**
80
147
  * Serialize PostgreSQL helper replacement inside one server-side statement.
81
148
  *
@@ -85,11 +152,17 @@ export declare const CREATE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION = "\nCREATE OR
85
152
  */
86
153
  export declare const REPLACE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION: string;
87
154
  /**
88
- * Install the PostgreSQL helper only when missing, serialized server-side.
155
+ * Install the PostgreSQL helpers only when missing, serialized server-side.
89
156
  *
90
157
  * A client-side catalog probe remains the fast path for already-initialized
91
158
  * read handles. This guarded statement is the cold-path race boundary: both
92
159
  * the advisory lock and the post-lock catalog check run before function DDL.
160
+ *
161
+ * The staging table and the drain helper (#2649) are created unconditionally
162
+ * (`IF NOT EXISTS` / `CREATE OR REPLACE`) because an install that already has
163
+ * the append helper from an older SMRT may still be missing them; the append
164
+ * helper itself is replaced when the staging table was absent, which is how an
165
+ * upgraded database picks up the deferring version.
93
166
  */
94
167
  export declare const ENSURE_POSTGRES_CHANGE_FEED_APPEND_FUNCTION: string;
95
168
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/system/schema.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,qpCAoCtC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,4BAA4B,4MAQxC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mCAAmC,o0BA4B/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,4BAA4B,u0BA2BxC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,igDAiDtC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,69CAkCpD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,ilCAkCtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,yBAAyB,weAkBrC,CAAC;AAEF,wEAAwE;AACxE,eAAO,MAAM,kCAAkC,QACqB,CAAC;AAErE,0EAA0E;AAC1E,eAAO,MAAM,yCAAyC,wBAAwB,CAAC;AAE/E,iFAAiF;AACjF,eAAO,MAAM,oDAAoD,yEAAkG,CAAC;AAEpK,8EAA8E;AAC9E,eAAO,MAAM,6CAA6C,sEAA+F,CAAC;AAE1J;;;;;;;;;GASG;AACH,eAAO,MAAM,2CAA2C,ylCAiDvD,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,4CAA4C,QAaxD,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,2CAA2C,QAevD,CAAC;AAaF;;;;;;GAMG;AACH,eAAO,MAAM,kCAAkC,QAgB9C,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,2BAA2B,gLAOvC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,UAU7B,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAMzD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,6BAA6B,EAAE,SAAS,MAAM,EAG1D,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAGlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAIlE;AAED,2EAA2E;AAC3E,wBAAgB,0BAA0B,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,cAAc,GACrB,MAAM,CAQR;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C;;;;;GAKG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CAErD;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,yBAAyB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAInE,CAAC"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../../src/system/schema.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,qpCAoCtC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,4BAA4B,4MAQxC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mCAAmC,o0BA4B/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,4BAA4B,u0BA2BxC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,igDAiDtC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,69CAkCpD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,0BAA0B,ilCAkCtC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,yBAAyB,weAkBrC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,0CAA0C,uWAYtD,CAAC;AAEF,6EAA6E;AAC7E,eAAO,MAAM,kCAAkC,0BAA0B,CAAC;AAE1E,wEAAwE;AACxE,eAAO,MAAM,kCAAkC,QACqB,CAAC;AAErE,0EAA0E;AAC1E,eAAO,MAAM,yCAAyC,wBAAwB,CAAC;AAE/E,iFAAiF;AACjF,eAAO,MAAM,oDAAoD,yEAAkG,CAAC;AAEpK,8EAA8E;AAC9E,eAAO,MAAM,6CAA6C,sEAA+F,CAAC;AAE1J;;;;;;;;GAQG;AACH,eAAO,MAAM,kCAAkC,gCAAgC,CAAC;AAEhF,2EAA2E;AAC3E,eAAO,MAAM,wCAAwC,wBAAwB,CAAC;AAE9E,6EAA6E;AAC7E,eAAO,MAAM,4CAA4C,iCAAyD,CAAC;AAEnH,wDAAwD;AACxD,eAAO,MAAM,gCAAgC,OAAO,CAAC;AAErD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,0CAA0C,grHAiItD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,2CAA2C,u5IA4HvD,CAAC;AAaF;;;;;;GAMG;AACH,eAAO,MAAM,4CAA4C,QAiBxD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,2CAA2C,QA4BvD,CAAC;AAaF;;;;;;GAMG;AACH,eAAO,MAAM,kCAAkC,QA6B9C,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,2BAA2B,gLAOvC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,UAU7B,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAMzD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,6BAA6B,EAAE,SAAS,MAAM,EAG1D,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAGlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,EAAE,CAIlE;AAED,2EAA2E;AAC3E,wBAAgB,0BAA0B,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,cAAc,GACrB,MAAM,CAQR;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C;;;;;GAKG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CAErD;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,yBAAyB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAInE,CAAC"}