@happyvertical/smrt-core 0.42.1 → 0.42.3

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.
@@ -79,6 +79,8 @@ export interface FieldMeta {
79
79
  /** Tenancy metadata injected for tenant-scoped models. */
80
80
  __tenancy?: {
81
81
  isTenantIdField?: boolean;
82
+ /** Populated by the tenancy beforeSave interceptor when enabled. */
83
+ autoPopulate?: boolean;
82
84
  [key: string]: unknown;
83
85
  };
84
86
  /** Report-aggregate metadata injected by the report normalizer. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/scanner/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAC;AAEvD;;;;;;;;;GASG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,uEAAuE;IACvE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,SAAS;IACxB,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACzB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,yEAAyE;IACzE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,iDAAiD;IACjD,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,kCAAkC;IAClC,MAAM,CAAC,EAAE,O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,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,qBAAqB,EAAE,CAAC;IACjC,MAAM,EAAE,KAAK,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;CACJ;AAED,MAAM,WAAW,WAAW;IAC1B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/scanner/types.ts"],"sourcesContent":["/**\n * Type definitions for AST scanning and manifest generation\n */\n\nimport type { SmartObjectConfig } from '../registry.js';\n\n/**\n * Qualified class name in format \"@package/name:ClassName\"\n * Example: \"@happyvertical/smrt-core:Product\"\n */\nexport type QualifiedClassName = `${string}:${string}`;\n\n/**\n * Static per-field UI hints authored via `@field({ ui })` (#2046).\n *\n * A pure presentation seed for the field-policy rail (epic #2045): it rides the\n * manifest under the field's `_meta.ui` (never promoted to a top-level\n * `FieldDefinition` key), reaches runtime at `field._meta.ui` via\n * `ObjectRegistry.getAllFields()`, and is emitted to the browser in generated\n * web-collection definitions. It has NO schema, persistence, or security\n * effect — `sensitive`/`readPermission` remain the security rail.\n */\nexport interface FieldUIHints {\n /**\n * Seed the field into the \"basic\" visibility tier (shown before the\n * advanced disclosure). Unmarked fields default per the cold-start rule:\n * an object with no basic markers renders everything basic; once any field\n * is marked, unmarked fields default to advanced.\n */\n basic?: boolean;\n /** Grouping key for form section/grouping (consumer-defined label). */\n group?: string;\n /** Relative sort order within the form/group (ascending). */\n order?: number;\n /**\n * Seed the field's policy as locked: org/user policy tiers may not\n * override it unless an org admin explicitly unlocks it.\n */\n locked?: boolean;\n}\n\n/**\n * Structured metadata attached to a field definition under `_meta`.\n *\n * Captures the field-helper options the scanner and schema/manifest\n * generators read off a field (`sqlType`, `nullable`, `__tenancy`, …). The\n * index signature keeps the bag open for forward-compatible keys without\n * forcing every consumer through `any`.\n */\nexport interface FieldMeta {\n /** Explicit SQL type override (e.g. 'UUID') applied during schema generation. */\n sqlType?: string;\n /** Storage type for cross-package reference ids ('text' forces TEXT). */\n idType?: 'uuid' | 'text';\n /** When true, the column is nullable regardless of `required`. */\n nullable?: boolean;\n /** Mirror of the field's required flag captured at registration. */\n required?: boolean;\n /** Default value carried in metadata for runtime-registry generation. */\n default?: unknown;\n /** Marks the field as the primary key column. */\n primaryKey?: boolean;\n /** Marks the column as unique. */\n unique?: boolean;\n /** Column description carried into generated schema. */\n description?: string;\n /** Static per-field UI hints authored via `@field({ ui })` (#2046). */\n ui?: FieldUIHints;\n /** Opt-in column/JSON-path indexing flag. */\n indexed?: boolean;\n /** Foreign-key delete action carried in metadata. */\n onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT';\n /** Excludes the field from persistence when true. */\n transient?: boolean;\n /** Numeric/length validation bounds and pattern. */\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n /**\n * Validation regex. A string source, a `RegExp`, or — when a manifest was\n * JSON-serialized and a `RegExp` collapsed to `{}` — an opaque object. Read\n * sites must narrow before accessing `.source`.\n */\n pattern?: unknown;\n /** Tenancy metadata injected for tenant-scoped models. */\n __tenancy?: {\n isTenantIdField?: boolean;\n [key: string]: unknown;\n };\n /** Report-aggregate metadata injected by the report normalizer. */\n __report?: {\n kind?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Controls how a class is exposed in manifests and across packages\n */\nexport type SmrtVisibility =\n | 'public' // Included in published manifest, available to all consumers\n | 'internal' // Package-only, excluded from published manifest\n | 'test'; // Test-only, never in any published manifest\n\nexport interface FieldDefinition {\n type:\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef' // Cross-package reference — UUID id column by default, no DDL FK\n | 'oneToMany'\n | 'manyToMany'\n | 'meta'; // STI meta fields (_meta_type, _meta_data)\n required?: boolean;\n default?: unknown;\n min?: number;\n max?: number;\n maxLength?: number;\n minLength?: number;\n related?: string; // For foreignKey, crossPackageRef, oneToMany, manyToMany\n description?: string;\n _meta?: FieldMeta;\n transient?: boolean; // Field not persisted to database\n /**\n * Sensitive value (API secrets, credentials, tax IDs). Still persisted, but\n * excluded from `toPublicJSON()` (generated REST/MCP/SvelteKit responses) and\n * rejected as a `where` filter key.\n */\n sensitive?: boolean;\n /**\n * Read-only over generated write surfaces. Stripped from create/update\n * request bodies so callers cannot mass-assign it.\n */\n readonly?: boolean;\n /**\n * Permission slug required to include this field in public/read responses.\n * Omitted unless the serializer is given a resolved permission set that\n * includes this slug. `sensitive` still wins and hides the field for all\n * callers.\n */\n readPermission?: string;\n /**\n * Controls whether the field is included in JSON exports.\n * - `true`: Always exported (unless site explicitly excludes it)\n * - `false`: Never exported (cannot be overridden by site config)\n * - `undefined`: Uses site's fieldExportDefault setting\n */\n exported?: boolean;\n}\n\nexport interface MethodDefinition {\n name: string;\n async: boolean;\n parameters: Array<{\n name: string;\n type: string;\n optional: boolean;\n default?: unknown;\n }>;\n returnType: string;\n description?: string;\n isStatic: boolean;\n isPublic: boolean;\n}\n\n/**\n * Pre-generated schema column definition for manifest\n */\nexport interface ManifestColumnDefinition {\n type: string; // SQL type: TEXT, INTEGER, DECIMAL, BOOLEAN, DATETIME, JSON\n primaryKey?: boolean;\n /**\n * Non-DDL marker for SMRT-owned identifier/reference columns.\n */\n referenceKind?: 'id' | 'foreignKey' | 'crossPackageRef' | 'tenantId';\n notNull?: boolean;\n unique?: boolean;\n default?: unknown;\n}\n\n/**\n * Pre-generated schema index definition for manifest\n */\nexport interface ManifestIndexDefinition {\n name: string;\n columns: string[];\n unique?: boolean;\n where?: string;\n /**\n * Expression-based index target — when set, the DDL strategy renders the\n * index over a JSON path inside `column` (dialect-specific syntax).\n */\n jsonPath?: {\n column: string;\n path: string;\n };\n}\n\n/**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator, stored in manifest.json\n */\nexport interface ManifestSchema {\n tableName: string;\n /**\n * Engine-neutral CREATE TABLE preview. Not executable as-is: no indexes,\n * abstract SQL types. Consumers render `columns` + `indexes` through the\n * engine DDL strategy (see `schema/manifest-schema.ts`, #2358).\n */\n ddl: string;\n columns: Record<string, ManifestColumnDefinition>;\n indexes: ManifestIndexDefinition[];\n version: string; // Hash of schema definition for migration tracking\n}\n\n/**\n * Validation rule type for pre-computed validators\n * These are serializable rules extracted from field definitions at build time,\n * eliminating the need to compile validator closures at runtime.\n */\nexport type ValidationRuleType =\n | 'required'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * Pre-computed validation rule for a field\n * Generated at build time by ManifestGenerator, stored in manifest.json\n *\n * These rules are evaluated at runtime without creating closure functions,\n * significantly reducing CLI startup time for projects with many SMRT objects.\n */\nexport interface ValidationRule {\n /** Field name to validate */\n field: string;\n /** Type of validation rule */\n rule: ValidationRuleType;\n /** Value for the rule (number for min/max/minLength/maxLength, string for pattern) */\n value?: number | string;\n /** Field type for context (text, integer, decimal, etc.) */\n fieldType?: string;\n}\n\n// ── Agent manifest types ────────────────────────────────────────────────\n\n/**\n * Permission declared by an agent\n * Generated from uiSlots (manage:*) and CLI/MCP methods (execute:*)\n */\nexport interface AgentPermission {\n id: string;\n label: string;\n category: 'slot' | 'method';\n defaultGranted?: boolean;\n}\n\n/**\n * Feature declared by an agent\n */\nexport interface AgentFeature {\n id: string;\n label: string;\n description?: string;\n type: 'slot' | 'method';\n}\n\n/**\n * Menu item derived from agent uiSlots\n */\nexport interface AgentMenuItem {\n id: string;\n label: string;\n icon?: string;\n order: number;\n path: string;\n requiredPermission?: string;\n}\n\n/**\n * Component export declaration derived from package.json exports\n */\nexport interface AgentComponentDeclaration {\n exportPath: string;\n type: string;\n}\n\n/**\n * UI slot definition captured from static uiSlots on Agent subclasses\n */\nexport interface AgentUISlotManifest {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n order?: number;\n disabled?: boolean;\n /** Durable owner for settings written through this slot. */\n scope?: 'agent' | 'persona';\n /** Optional fallback form contract for host applications. */\n settingsSchema?: {\n version: number;\n fields: Array<{\n id: string;\n label: string;\n type: 'string' | 'number' | 'boolean' | 'select' | 'textarea' | 'json';\n description?: string;\n required?: boolean;\n default?: unknown;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n min?: number;\n max?: number;\n }>;\n };\n}\n\n/**\n * Admin route declared by an agent via static adminRoutes\n * Consumed by vitePluginAgentRoutes to register admin routes with SvelteKit\n */\nexport interface AgentAdminRouteManifest {\n /** Route path relative to agent root (e.g., 'sources/[sourceId]') */\n path: string;\n /** Component export name from the agent's admin entry point */\n component: string;\n /** Optional: export name for server load function */\n load?: string;\n}\n\n/**\n * Auto-generated agent manifest section\n * Produced by the manifest build pipeline for any class with `agent` decorator config\n */\nexport interface AgentManifest {\n name: string;\n slug: string;\n icon?: string;\n tier: 'free' | 'standard' | 'premium';\n description?: string;\n uiSlots: Record<string, AgentUISlotManifest>;\n adminRoutes?: AgentAdminRouteManifest[];\n /** Default signal subscriptions declared by this agent */\n signalSubscriptions?: string[];\n permissions: AgentPermission[];\n features: AgentFeature[];\n menuItems: AgentMenuItem[];\n components: AgentComponentDeclaration[];\n}\n\n// ── Core manifest types ─────────────────────────────────────────────────\n\nexport interface SmartObjectDefinition {\n /**\n * Qualified name in format \"@package/name:ClassName\"\n * This is the PRIMARY KEY for manifest lookups.\n * Example: \"@happyvertical/smrt-core:Product\"\n *\n * Optional during transition - will be required in future versions.\n */\n qualifiedName?: QualifiedClassName;\n\n /**\n * Simple class name (PascalCase)\n * Example: \"Product\"\n */\n className: string;\n\n /**\n * Package name where this class is defined.\n * Example: \"@happyvertical/smrt-core\"\n *\n * Optional during transition - will be required in future versions.\n */\n packageName?: string;\n\n /**\n * Visibility control for manifest inclusion\n * - 'public': Included in published manifest (default)\n * - 'internal': Package-only, excluded from published manifest\n * - 'test': Test-only, never in any published manifest\n *\n * Defaults to 'public' if not specified.\n */\n visibility?: SmrtVisibility;\n\n /**\n * @deprecated Use qualifiedName instead. Kept for transition period.\n * Lowercase class name, formerly used as manifest key.\n */\n name: string;\n\n collection: string; // Pluralized name for endpoints\n filePath: string;\n packageVersion?: string; // Package version for external manifest loading\n importPath?: string; // Import path for dynamic loading (e.g., \"@pkg/objects\")\n modulePath?: string; // Relative module path within package\n exportName?: string; // Named export to use (defaults to className)\n collectionExportName?: string; // Collection class export name\n fields: Record<string, FieldDefinition>;\n methods: Record<string, MethodDefinition>;\n decoratorConfig: SmartObjectConfig;\n extends?: string; // Base class name (simple name, not qualified)\n extendsQualified?: string; // Base class qualified name\n extendsTypeArg?: string; // Generic type argument (e.g., \"Meeting\" from \"SmrtCollection<Meeting>\")\n tools?: Array<{\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n };\n }>;\n /**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, consumers can use this pre-computed schema directly\n * without calling generateSchema() at runtime, eliminating latency.\n */\n schema?: ManifestSchema;\n\n /**\n * Pre-computed validation rules for efficient runtime validation\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, the registry uses these rules instead of compiling\n * validator closures at runtime, significantly reducing startup time.\n *\n * @see ValidationRule\n */\n validationRules?: ValidationRule[];\n\n /**\n * Static properties captured from the class definition\n * Currently used for `static uiSlots` on Agent subclasses\n */\n staticProperties?: Record<string, unknown>;\n\n /**\n * Auto-generated agent manifest\n * Only present for classes with `agent` in their decorator config\n * Generated at build time by ManifestGenerator fifth pass\n */\n agent?: AgentManifest;\n}\n\n/**\n * Fixed `timestamp` for every manifest that can reach build output.\n *\n * Manifests are inlined into bundles (`registerPackageManifest(JSON.parse(...))`),\n * so a wall-clock value changes the emitted bytes on every build. That changes\n * Vite's content hash, which changes `dist/`, which invalidates every\n * downstream package through `dependsOn: ['^build']` — one rebuilt package\n * churned 202 of 245 task hashes, and `typecheck` never reused a cache entry\n * across runs (#2223).\n *\n * Nothing reads the field: `getManifestTimestampsHash` invalidates on\n * filesystem mtimes, and `normalizeManifestForHash` deletes it before\n * comparing. A fixed value therefore costs no information.\n *\n * Genuine runtime caches that expire on elapsed time — the discovery cache in\n * `manifest/discover-smrt-packages.ts` — keep using the clock; they never\n * reach build output.\n */\nexport const MANIFEST_TIMESTAMP = 0;\n\n/**\n * Fixed `generatedAt` for knowledge artifacts emitted into `dist/`.\n *\n * Same reasoning as {@link MANIFEST_TIMESTAMP}: build output is compared\n * byte-for-byte, so it cannot carry the clock. The Unix epoch is used rather\n * than `0` because the field is an ISO-8601 string, and a parseable value\n * keeps any consumer that formats it working.\n *\n * The working copy under `.smrt/` keeps a real timestamp — it is useful to a\n * human there, and `preserveKnowledgeGeneratedAt` already stops it churning\n * across incremental rebuilds.\n */\nexport const DETERMINISTIC_GENERATED_AT = '1970-01-01T00:00:00.000Z';\n\nexport interface SmartObjectManifest {\n version: string;\n /** Always {@link MANIFEST_TIMESTAMP} for build-output manifests. */\n timestamp: number;\n packageName?: string; // Root package name (should be set for all new manifests)\n packageVersion?: string; // Root package version\n /**\n * Objects keyed by qualified name (e.g., \"@happyvertical/smrt-core:Product\")\n * Key is string for backward compatibility, but should be QualifiedClassName format.\n */\n objects: Record<string, SmartObjectDefinition>;\n moduleType?: string; // Module type identifier (e.g., \"smrt\") for package discovery\n smrtDependencies?: string[]; // Discovered SMRT packages from dependency tree\n}\n\nexport interface ScanResult {\n filePath: string;\n objects: SmartObjectDefinition[];\n errors: Array<{\n message: string;\n line?: number;\n column?: number;\n }>;\n}\n\nexport interface ScanOptions {\n includePrivateMethods?: boolean;\n includeStaticMethods?: boolean;\n followImports?: boolean;\n baseClasses?: string[]; // Classes to consider as SMRT base classes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAydA,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,6BAA6B"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/scanner/types.ts"],"sourcesContent":["/**\n * Type definitions for AST scanning and manifest generation\n */\n\nimport type { SmartObjectConfig } from '../registry.js';\n\n/**\n * Qualified class name in format \"@package/name:ClassName\"\n * Example: \"@happyvertical/smrt-core:Product\"\n */\nexport type QualifiedClassName = `${string}:${string}`;\n\n/**\n * Static per-field UI hints authored via `@field({ ui })` (#2046).\n *\n * A pure presentation seed for the field-policy rail (epic #2045): it rides the\n * manifest under the field's `_meta.ui` (never promoted to a top-level\n * `FieldDefinition` key), reaches runtime at `field._meta.ui` via\n * `ObjectRegistry.getAllFields()`, and is emitted to the browser in generated\n * web-collection definitions. It has NO schema, persistence, or security\n * effect — `sensitive`/`readPermission` remain the security rail.\n */\nexport interface FieldUIHints {\n /**\n * Seed the field into the \"basic\" visibility tier (shown before the\n * advanced disclosure). Unmarked fields default per the cold-start rule:\n * an object with no basic markers renders everything basic; once any field\n * is marked, unmarked fields default to advanced.\n */\n basic?: boolean;\n /** Grouping key for form section/grouping (consumer-defined label). */\n group?: string;\n /** Relative sort order within the form/group (ascending). */\n order?: number;\n /**\n * Seed the field's policy as locked: org/user policy tiers may not\n * override it unless an org admin explicitly unlocks it.\n */\n locked?: boolean;\n}\n\n/**\n * Structured metadata attached to a field definition under `_meta`.\n *\n * Captures the field-helper options the scanner and schema/manifest\n * generators read off a field (`sqlType`, `nullable`, `__tenancy`, …). The\n * index signature keeps the bag open for forward-compatible keys without\n * forcing every consumer through `any`.\n */\nexport interface FieldMeta {\n /** Explicit SQL type override (e.g. 'UUID') applied during schema generation. */\n sqlType?: string;\n /** Storage type for cross-package reference ids ('text' forces TEXT). */\n idType?: 'uuid' | 'text';\n /** When true, the column is nullable regardless of `required`. */\n nullable?: boolean;\n /** Mirror of the field's required flag captured at registration. */\n required?: boolean;\n /** Default value carried in metadata for runtime-registry generation. */\n default?: unknown;\n /** Marks the field as the primary key column. */\n primaryKey?: boolean;\n /** Marks the column as unique. */\n unique?: boolean;\n /** Column description carried into generated schema. */\n description?: string;\n /** Static per-field UI hints authored via `@field({ ui })` (#2046). */\n ui?: FieldUIHints;\n /** Opt-in column/JSON-path indexing flag. */\n indexed?: boolean;\n /** Foreign-key delete action carried in metadata. */\n onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT';\n /** Excludes the field from persistence when true. */\n transient?: boolean;\n /** Numeric/length validation bounds and pattern. */\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n /**\n * Validation regex. A string source, a `RegExp`, or — when a manifest was\n * JSON-serialized and a `RegExp` collapsed to `{}` — an opaque object. Read\n * sites must narrow before accessing `.source`.\n */\n pattern?: unknown;\n /** Tenancy metadata injected for tenant-scoped models. */\n __tenancy?: {\n isTenantIdField?: boolean;\n /** Populated by the tenancy beforeSave interceptor when enabled. */\n autoPopulate?: boolean;\n [key: string]: unknown;\n };\n /** Report-aggregate metadata injected by the report normalizer. */\n __report?: {\n kind?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Controls how a class is exposed in manifests and across packages\n */\nexport type SmrtVisibility =\n | 'public' // Included in published manifest, available to all consumers\n | 'internal' // Package-only, excluded from published manifest\n | 'test'; // Test-only, never in any published manifest\n\nexport interface FieldDefinition {\n type:\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef' // Cross-package reference — UUID id column by default, no DDL FK\n | 'oneToMany'\n | 'manyToMany'\n | 'meta'; // STI meta fields (_meta_type, _meta_data)\n required?: boolean;\n default?: unknown;\n min?: number;\n max?: number;\n maxLength?: number;\n minLength?: number;\n related?: string; // For foreignKey, crossPackageRef, oneToMany, manyToMany\n description?: string;\n _meta?: FieldMeta;\n transient?: boolean; // Field not persisted to database\n /**\n * Sensitive value (API secrets, credentials, tax IDs). Still persisted, but\n * excluded from `toPublicJSON()` (generated REST/MCP/SvelteKit responses) and\n * rejected as a `where` filter key.\n */\n sensitive?: boolean;\n /**\n * Read-only over generated write surfaces. Stripped from create/update\n * request bodies so callers cannot mass-assign it.\n */\n readonly?: boolean;\n /**\n * Permission slug required to include this field in public/read responses.\n * Omitted unless the serializer is given a resolved permission set that\n * includes this slug. `sensitive` still wins and hides the field for all\n * callers.\n */\n readPermission?: string;\n /**\n * Controls whether the field is included in JSON exports.\n * - `true`: Always exported (unless site explicitly excludes it)\n * - `false`: Never exported (cannot be overridden by site config)\n * - `undefined`: Uses site's fieldExportDefault setting\n */\n exported?: boolean;\n}\n\nexport interface MethodDefinition {\n name: string;\n async: boolean;\n parameters: Array<{\n name: string;\n type: string;\n optional: boolean;\n default?: unknown;\n }>;\n returnType: string;\n description?: string;\n isStatic: boolean;\n isPublic: boolean;\n}\n\n/**\n * Pre-generated schema column definition for manifest\n */\nexport interface ManifestColumnDefinition {\n type: string; // SQL type: TEXT, INTEGER, DECIMAL, BOOLEAN, DATETIME, JSON\n primaryKey?: boolean;\n /**\n * Non-DDL marker for SMRT-owned identifier/reference columns.\n */\n referenceKind?: 'id' | 'foreignKey' | 'crossPackageRef' | 'tenantId';\n notNull?: boolean;\n unique?: boolean;\n default?: unknown;\n}\n\n/**\n * Pre-generated schema index definition for manifest\n */\nexport interface ManifestIndexDefinition {\n name: string;\n columns: string[];\n unique?: boolean;\n where?: string;\n /**\n * Expression-based index target — when set, the DDL strategy renders the\n * index over a JSON path inside `column` (dialect-specific syntax).\n */\n jsonPath?: {\n column: string;\n path: string;\n };\n}\n\n/**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator, stored in manifest.json\n */\nexport interface ManifestSchema {\n tableName: string;\n /**\n * Engine-neutral CREATE TABLE preview. Not executable as-is: no indexes,\n * abstract SQL types. Consumers render `columns` + `indexes` through the\n * engine DDL strategy (see `schema/manifest-schema.ts`, #2358).\n */\n ddl: string;\n columns: Record<string, ManifestColumnDefinition>;\n indexes: ManifestIndexDefinition[];\n version: string; // Hash of schema definition for migration tracking\n}\n\n/**\n * Validation rule type for pre-computed validators\n * These are serializable rules extracted from field definitions at build time,\n * eliminating the need to compile validator closures at runtime.\n */\nexport type ValidationRuleType =\n | 'required'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * Pre-computed validation rule for a field\n * Generated at build time by ManifestGenerator, stored in manifest.json\n *\n * These rules are evaluated at runtime without creating closure functions,\n * significantly reducing CLI startup time for projects with many SMRT objects.\n */\nexport interface ValidationRule {\n /** Field name to validate */\n field: string;\n /** Type of validation rule */\n rule: ValidationRuleType;\n /** Value for the rule (number for min/max/minLength/maxLength, string for pattern) */\n value?: number | string;\n /** Field type for context (text, integer, decimal, etc.) */\n fieldType?: string;\n}\n\n// ── Agent manifest types ────────────────────────────────────────────────\n\n/**\n * Permission declared by an agent\n * Generated from uiSlots (manage:*) and CLI/MCP methods (execute:*)\n */\nexport interface AgentPermission {\n id: string;\n label: string;\n category: 'slot' | 'method';\n defaultGranted?: boolean;\n}\n\n/**\n * Feature declared by an agent\n */\nexport interface AgentFeature {\n id: string;\n label: string;\n description?: string;\n type: 'slot' | 'method';\n}\n\n/**\n * Menu item derived from agent uiSlots\n */\nexport interface AgentMenuItem {\n id: string;\n label: string;\n icon?: string;\n order: number;\n path: string;\n requiredPermission?: string;\n}\n\n/**\n * Component export declaration derived from package.json exports\n */\nexport interface AgentComponentDeclaration {\n exportPath: string;\n type: string;\n}\n\n/**\n * UI slot definition captured from static uiSlots on Agent subclasses\n */\nexport interface AgentUISlotManifest {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n order?: number;\n disabled?: boolean;\n /** Durable owner for settings written through this slot. */\n scope?: 'agent' | 'persona';\n /** Optional fallback form contract for host applications. */\n settingsSchema?: {\n version: number;\n fields: Array<{\n id: string;\n label: string;\n type: 'string' | 'number' | 'boolean' | 'select' | 'textarea' | 'json';\n description?: string;\n required?: boolean;\n default?: unknown;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n min?: number;\n max?: number;\n }>;\n };\n}\n\n/**\n * Admin route declared by an agent via static adminRoutes\n * Consumed by vitePluginAgentRoutes to register admin routes with SvelteKit\n */\nexport interface AgentAdminRouteManifest {\n /** Route path relative to agent root (e.g., 'sources/[sourceId]') */\n path: string;\n /** Component export name from the agent's admin entry point */\n component: string;\n /** Optional: export name for server load function */\n load?: string;\n}\n\n/**\n * Auto-generated agent manifest section\n * Produced by the manifest build pipeline for any class with `agent` decorator config\n */\nexport interface AgentManifest {\n name: string;\n slug: string;\n icon?: string;\n tier: 'free' | 'standard' | 'premium';\n description?: string;\n uiSlots: Record<string, AgentUISlotManifest>;\n adminRoutes?: AgentAdminRouteManifest[];\n /** Default signal subscriptions declared by this agent */\n signalSubscriptions?: string[];\n permissions: AgentPermission[];\n features: AgentFeature[];\n menuItems: AgentMenuItem[];\n components: AgentComponentDeclaration[];\n}\n\n// ── Core manifest types ─────────────────────────────────────────────────\n\nexport interface SmartObjectDefinition {\n /**\n * Qualified name in format \"@package/name:ClassName\"\n * This is the PRIMARY KEY for manifest lookups.\n * Example: \"@happyvertical/smrt-core:Product\"\n *\n * Optional during transition - will be required in future versions.\n */\n qualifiedName?: QualifiedClassName;\n\n /**\n * Simple class name (PascalCase)\n * Example: \"Product\"\n */\n className: string;\n\n /**\n * Package name where this class is defined.\n * Example: \"@happyvertical/smrt-core\"\n *\n * Optional during transition - will be required in future versions.\n */\n packageName?: string;\n\n /**\n * Visibility control for manifest inclusion\n * - 'public': Included in published manifest (default)\n * - 'internal': Package-only, excluded from published manifest\n * - 'test': Test-only, never in any published manifest\n *\n * Defaults to 'public' if not specified.\n */\n visibility?: SmrtVisibility;\n\n /**\n * @deprecated Use qualifiedName instead. Kept for transition period.\n * Lowercase class name, formerly used as manifest key.\n */\n name: string;\n\n collection: string; // Pluralized name for endpoints\n filePath: string;\n packageVersion?: string; // Package version for external manifest loading\n importPath?: string; // Import path for dynamic loading (e.g., \"@pkg/objects\")\n modulePath?: string; // Relative module path within package\n exportName?: string; // Named export to use (defaults to className)\n collectionExportName?: string; // Collection class export name\n fields: Record<string, FieldDefinition>;\n methods: Record<string, MethodDefinition>;\n decoratorConfig: SmartObjectConfig;\n extends?: string; // Base class name (simple name, not qualified)\n extendsQualified?: string; // Base class qualified name\n extendsTypeArg?: string; // Generic type argument (e.g., \"Meeting\" from \"SmrtCollection<Meeting>\")\n tools?: Array<{\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n };\n }>;\n /**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, consumers can use this pre-computed schema directly\n * without calling generateSchema() at runtime, eliminating latency.\n */\n schema?: ManifestSchema;\n\n /**\n * Pre-computed validation rules for efficient runtime validation\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, the registry uses these rules instead of compiling\n * validator closures at runtime, significantly reducing startup time.\n *\n * @see ValidationRule\n */\n validationRules?: ValidationRule[];\n\n /**\n * Static properties captured from the class definition\n * Currently used for `static uiSlots` on Agent subclasses\n */\n staticProperties?: Record<string, unknown>;\n\n /**\n * Auto-generated agent manifest\n * Only present for classes with `agent` in their decorator config\n * Generated at build time by ManifestGenerator fifth pass\n */\n agent?: AgentManifest;\n}\n\n/**\n * Fixed `timestamp` for every manifest that can reach build output.\n *\n * Manifests are inlined into bundles (`registerPackageManifest(JSON.parse(...))`),\n * so a wall-clock value changes the emitted bytes on every build. That changes\n * Vite's content hash, which changes `dist/`, which invalidates every\n * downstream package through `dependsOn: ['^build']` — one rebuilt package\n * churned 202 of 245 task hashes, and `typecheck` never reused a cache entry\n * across runs (#2223).\n *\n * Nothing reads the field: `getManifestTimestampsHash` invalidates on\n * filesystem mtimes, and `normalizeManifestForHash` deletes it before\n * comparing. A fixed value therefore costs no information.\n *\n * Genuine runtime caches that expire on elapsed time — the discovery cache in\n * `manifest/discover-smrt-packages.ts` — keep using the clock; they never\n * reach build output.\n */\nexport const MANIFEST_TIMESTAMP = 0;\n\n/**\n * Fixed `generatedAt` for knowledge artifacts emitted into `dist/`.\n *\n * Same reasoning as {@link MANIFEST_TIMESTAMP}: build output is compared\n * byte-for-byte, so it cannot carry the clock. The Unix epoch is used rather\n * than `0` because the field is an ISO-8601 string, and a parseable value\n * keeps any consumer that formats it working.\n *\n * The working copy under `.smrt/` keeps a real timestamp — it is useful to a\n * human there, and `preserveKnowledgeGeneratedAt` already stops it churning\n * across incremental rebuilds.\n */\nexport const DETERMINISTIC_GENERATED_AT = '1970-01-01T00:00:00.000Z';\n\nexport interface SmartObjectManifest {\n version: string;\n /** Always {@link MANIFEST_TIMESTAMP} for build-output manifests. */\n timestamp: number;\n packageName?: string; // Root package name (should be set for all new manifests)\n packageVersion?: string; // Root package version\n /**\n * Objects keyed by qualified name (e.g., \"@happyvertical/smrt-core:Product\")\n * Key is string for backward compatibility, but should be QualifiedClassName format.\n */\n objects: Record<string, SmartObjectDefinition>;\n moduleType?: string; // Module type identifier (e.g., \"smrt\") for package discovery\n smrtDependencies?: string[]; // Discovered SMRT packages from dependency tree\n}\n\nexport interface ScanResult {\n filePath: string;\n objects: SmartObjectDefinition[];\n errors: Array<{\n message: string;\n line?: number;\n column?: number;\n }>;\n}\n\nexport interface ScanOptions {\n includePrivateMethods?: boolean;\n includeStaticMethods?: boolean;\n followImports?: boolean;\n baseClasses?: string[]; // Classes to consider as SMRT base classes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2dA,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,6BAA6B"}
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-core",
6
- "packageVersion": "0.42.1",
6
+ "packageVersion": "0.42.3",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "70dd43762947f84695992824b02893e1e0f2be402ad5b5753a12411483111d59",
11
- "packageJson": "135d0f4e40c46ab39acaefe15c764be1aad45682096b6e5c394e3359f916f6e1",
12
- "agents": "26f3bcb1b417610ecd69ef7426bb065ca5a9cde3055ff982c04cb6699ac26f72",
10
+ "manifest": "bd256575ec7be8b18c4933b6f4074e3678add66e7da0a54c33fdaddaba278cdf",
11
+ "packageJson": "28f3ce7ad66cb92a92af8bfa3a1f348a490fbac3e24bd8355146d9280f059fec",
12
+ "agents": "97a317c1a988429fac5b4b75650864fcf5dfc2d49228d5ca29e9d19d4cf4971b",
13
13
  "moduleDoc:agents/change-feed.md": "1530ded9ed605aa9b8a772b3ba4dd992a3f797f4d7c9ede3b3389dd7bfb401fa",
14
14
  "moduleDoc:agents/change-signals.md": "d9cb6a5541728ffea46607a6b1d4fa61d4621849f2b4ea86a0645fbb0af892e9",
15
15
  "moduleDoc:agents/generators.md": "2b6ccd5ff557293f2ce84d25cc254ceb518f4c274d93b7e3175985b18f36f564",
@@ -913,7 +913,7 @@
913
913
  "polymorphicAssociations": 1,
914
914
  "uuidColumns": 3
915
915
  },
916
- "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\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- `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`. 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 primitive (#1902): pass `select: ['id', 'title', 'tenantId']` to\n`list()` when an admin/list workflow needs compact rows. `select` uses SMRT\nfield names, maps them to DB columns internally, and returns plain objects keyed\nby the same SMRT field names without hydrating `SmrtObject` instances. It\ncomposes with `where`, `orderBy`, `limit`, and `offset`; `beforeList`\ninterceptors still run. It is for column-backed fields only and cannot combine\nwith `include`/relationship eager loading.\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\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## Bounded Collection Read Plans\n\nUse `executeCollectionReadPlan()` when one operation needs several independent\ncollections. It bounds top-level `collection.list()` concurrency while keeping\nall reads on the normal registry/collection path. Callers must choose an\nexplicit positive `maxConcurrency` and pass their normal shared\n`collectionOptions` when database or tenant context matters.\n\nThe executor deliberately does not compose SQL, cache the plan, or change pool\ndefaults. On failure it stops starting queued entries, drains operations already\nin flight, and rethrows the first error.\n\n## Object Memory & Semantic Search\n\nTwo persistence primitives every `SmrtObject`/`SmrtCollection` inherits — load-bearing for learning agents, usable by any object. Full guide: `docs/content/core.md` → \"Context Memory System\".\n\n- **Context memory** (`remember`/`recall`/`recallAll`/`forget`/`forgetScope`, table `_smrt_contexts`): stores any JSON value keyed by `(owner_class, owner_id, scope, key, version)` with a `confidence` score (0–1) and a stored `expiresAt` (metadata — `recall()` does **not** filter expired rows; expiry is caller-managed). `recall()` returns the highest-confidence match with an optional `minConfidence` floor and **opt-in** hierarchical scope fallback (`includeAncestors: true` → `'a/b/c' → 'a/b' → 'a' → 'global'`; default off); `recallAll()` returns a `Map`. Typical use: cache a learned strategy (e.g. a working selector per host) and reuse it across sessions. `success_count`/`failure_count` columns exist for outcome-weighting: `SmrtObject.remember()` leaves them untouched, `SmrtCollection.remember()` resets them to zero, and neither recall path updates them. `LearningMemory` is the layer that maintains them (and that does filter expired rows).\n- **Semantic search** (on `SmrtCollection`, table `_smrt_embeddings`): `semanticSearch(query)`, `findSimilar(object)`, `findSimilarToEmbedding(vector)` — cosine ranking over embeddings of the fields declared in `@smrt({ embeddings })`. Native pgvector/HNSW when configured, in-memory `CosineSimilarity` fallback otherwise; default local model `Xenova/bge-base-en-v1.5` (768-dim) or AI `text-embedding-3-small`. Hits hydrate via `list({ 'id in': … })`, so `@TenantScoped` isolation applies to results.\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\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()` and emit foreign-key indexes\nproduction never gets: the suite runs on a richer schema than it ships.\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- 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- **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",
916
+ "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\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- `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`. 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 primitive (#1902): pass `select: ['id', 'title', 'tenantId']` to\n`list()` when an admin/list workflow needs compact rows. `select` uses SMRT\nfield names, maps them to DB columns internally, and returns plain objects keyed\nby the same SMRT field names without hydrating `SmrtObject` instances. It\ncomposes with `where`, `orderBy`, `limit`, and `offset`; `beforeList`\ninterceptors still run. It is for column-backed fields only and cannot combine\nwith `include`/relationship eager loading.\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\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## Bounded Collection Read Plans\n\nUse `executeCollectionReadPlan()` when one operation needs several independent\ncollections. It bounds top-level `collection.list()` concurrency while keeping\nall reads on the normal registry/collection path. Callers must choose an\nexplicit positive `maxConcurrency` and pass their normal shared\n`collectionOptions` when database or tenant context matters.\n\nThe executor deliberately does not compose SQL, cache the plan, or change pool\ndefaults. On failure it stops starting queued entries, drains operations already\nin flight, and rethrows the first error.\n\n## Object Memory & Semantic Search\n\nTwo persistence primitives every `SmrtObject`/`SmrtCollection` inherits — load-bearing for learning agents, usable by any object. Full guide: `docs/content/core.md` → \"Context Memory System\".\n\n- **Context memory** (`remember`/`recall`/`recallAll`/`forget`/`forgetScope`, table `_smrt_contexts`): stores any JSON value keyed by `(owner_class, owner_id, scope, key, version)` with a `confidence` score (0–1) and a stored `expiresAt` (metadata — `recall()` does **not** filter expired rows; expiry is caller-managed). `recall()` returns the highest-confidence match with an optional `minConfidence` floor and **opt-in** hierarchical scope fallback (`includeAncestors: true` → `'a/b/c' → 'a/b' → 'a' → 'global'`; default off); `recallAll()` returns a `Map`. Typical use: cache a learned strategy (e.g. a working selector per host) and reuse it across sessions. `success_count`/`failure_count` columns exist for outcome-weighting: `SmrtObject.remember()` leaves them untouched, `SmrtCollection.remember()` resets them to zero, and neither recall path updates them. `LearningMemory` is the layer that maintains them (and that does filter expired rows).\n- **Semantic search** (on `SmrtCollection`, table `_smrt_embeddings`): `semanticSearch(query)`, `findSimilar(object)`, `findSimilarToEmbedding(vector)` — cosine ranking over embeddings of the fields declared in `@smrt({ embeddings })`. Native pgvector/HNSW when configured, in-memory `CosineSimilarity` fallback otherwise; default local model `Xenova/bge-base-en-v1.5` (768-dim) or AI `text-embedding-3-small`. Hits hydrate via `list({ 'id in': … })`, so `@TenantScoped` isolation applies to results.\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()` and emit foreign-key indexes\nproduction never gets: the suite runs on a richer schema than it ships.\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- 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- **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",
917
917
  "moduleDocs": [
918
918
  {
919
919
  "path": "agents/change-feed.md",
@@ -0,0 +1,9 @@
1
+ import { DatabaseInterface } from '@happyvertical/sql';
2
+ /**
3
+ * Ensure every framework-owned SMRT system table exists before use.
4
+ *
5
+ * PostgreSQL provisioning is serialized in a bounded advisory-locked
6
+ * transaction; other engines use the schema's idempotent DDL directly.
7
+ */
8
+ export declare function ensureSystemTables(db: DatabaseInterface, typeHint?: string): Promise<void>;
9
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,107 @@
1
+ import { SMRT_SCHEMA_VERSION, getSystemTableDDL } from "./schema.js";
2
+ import { ensurePostgresChangeFeedAppendFunction } from "../change-feed.js";
3
+ import { assertPostgresSystemTimestampsCurrent, ensureBootstrapSystemTableCompatibility, getDatabaseEngine, tableExists } from "./compatibility.js";
4
+ import { createLogger } from "@happyvertical/logger";
5
+ //#region src/system/bootstrap.ts
6
+ /** Canonical, idempotent SMRT system-table provisioning. */
7
+ var SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL = "SELECT pg_advisory_xact_lock(hashtext('smrt'), hashtext('system-tables'))";
8
+ /**
9
+ * Timeout budget for the PostgreSQL system-table bootstrap transaction.
10
+ *
11
+ * The runtime pool's session `lock_timeout`/`statement_timeout` (#2377) are
12
+ * sized for request work. This transaction is not request work: it holds the
13
+ * advisory lock across up to 29 sequential DDL round-trips — ~18.85 s on a
14
+ * high-latency link at 650 ms per round trip — and a second replica cold-starting
15
+ * against the same fresh database *waits* on that lock. Both GUCs bound that
16
+ * wait, because `pg_advisory_xact_lock` is an ordinary statement in the lock
17
+ * manager, so at the runtime defaults the second replica would abort with
18
+ * "canceling statement due to lock timeout" where it previously waited and
19
+ * succeeded.
20
+ *
21
+ * Five minutes is an order of magnitude above the documented worst case and
22
+ * still bounded — this is a raise, not a disable. `SET LOCAL` scopes it to this
23
+ * transaction, the same lever migrations use for the same reason (#2362).
24
+ */
25
+ var SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL = ["SET LOCAL lock_timeout = '300000ms'", "SET LOCAL statement_timeout = '300000ms'"];
26
+ var logger = createLogger({ level: "info" });
27
+ function getQueryRows(result) {
28
+ if (Array.isArray(result)) return result;
29
+ if (result && typeof result === "object" && "rows" in result) {
30
+ const rows = result.rows;
31
+ if (Array.isArray(rows)) return rows;
32
+ }
33
+ return [];
34
+ }
35
+ async function isSystemSchemaVersionApplied(db, typeHint) {
36
+ const engine = getDatabaseEngine(db, typeHint);
37
+ if (engine === "postgres" && !await tableExists(db, "_smrt_migrations", typeHint)) return false;
38
+ try {
39
+ const versionParam = engine === "postgres" ? "$1" : "?";
40
+ return getQueryRows(await db.query(`SELECT 1 FROM _smrt_migrations WHERE version = ${versionParam} LIMIT 1`, SMRT_SCHEMA_VERSION)).length > 0;
41
+ } catch (error) {
42
+ if (engine === "postgres") throw error;
43
+ return false;
44
+ }
45
+ }
46
+ async function bootstrapSystemTables(db, typeHint) {
47
+ if (await isSystemSchemaVersionApplied(db, typeHint)) return;
48
+ await ensureBootstrapSystemTableCompatibility(db, typeHint);
49
+ const engine = getDatabaseEngine(db, typeHint);
50
+ for (const ddl of getSystemTableDDL(engine)) for (const statement of ddl.split(";").map((value) => value.trim()).filter(Boolean)) await db.query(statement);
51
+ await ensurePostgresChangeFeedAppendFunction(db, { typeHint });
52
+ await assertPostgresSystemTimestampsCurrent(db, typeHint);
53
+ const id = crypto.randomUUID();
54
+ await db.execute`
55
+ INSERT INTO _smrt_migrations (id, version, description)
56
+ VALUES (${id}, ${SMRT_SCHEMA_VERSION}, ${"Initial SMRT system tables"})
57
+ ON CONFLICT(version) DO NOTHING
58
+ `;
59
+ }
60
+ async function rollbackBootstrap(tx) {
61
+ try {
62
+ if (typeof tx.isActive !== "function" || tx.isActive()) await tx.rollback();
63
+ } catch (error) {
64
+ logger.warn(`[smrt] Failed to rollback system table bootstrap transaction: ${error instanceof Error ? error.message : String(error)}`);
65
+ }
66
+ }
67
+ /**
68
+ * Ensure every framework-owned SMRT system table exists before use.
69
+ *
70
+ * PostgreSQL provisioning is serialized in a bounded advisory-locked
71
+ * transaction; other engines use the schema's idempotent DDL directly.
72
+ */
73
+ async function ensureSystemTables(db, typeHint) {
74
+ if (getDatabaseEngine(db, typeHint) !== "postgres") {
75
+ await bootstrapSystemTables(db, typeHint);
76
+ return;
77
+ }
78
+ const beginTransaction = db.beginTransaction;
79
+ const transaction = db.transaction;
80
+ if (typeof beginTransaction === "function") {
81
+ const tx = await beginTransaction.call(db);
82
+ if (!tx) throw new Error("Database transaction could not be started");
83
+ try {
84
+ for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);
85
+ await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);
86
+ await bootstrapSystemTables(tx, typeHint);
87
+ await tx.commit();
88
+ return;
89
+ } catch (error) {
90
+ await rollbackBootstrap(tx);
91
+ throw error;
92
+ }
93
+ }
94
+ if (typeof transaction === "function") {
95
+ await transaction.call(db, async (tx) => {
96
+ for (const sql of SYSTEM_TABLE_BOOTSTRAP_TIMEOUT_SQL) await tx.query(sql);
97
+ await tx.query(SYSTEM_TABLE_BOOTSTRAP_LOCK_SQL);
98
+ await bootstrapSystemTables(tx, typeHint);
99
+ });
100
+ return;
101
+ }
102
+ throw new Error("Postgres system table bootstrap requires a transaction-capable database adapter");
103
+ }
104
+ //#endregion
105
+ export { ensureSystemTables };
106
+
107
+ //# sourceMappingURL=bootstrap.js.map
@@ -0,0 +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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,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"}
@@ -4,6 +4,7 @@
4
4
  * System-level metadata storage for the SMRT framework.
5
5
  * All tables use _smrt_ prefix and share the application's database.
6
6
  */
7
+ export { ensureSystemTables } from './bootstrap.js';
7
8
  export * from './compatibility.js';
8
9
  export * from './retention.js';
9
10
  export * from './types.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/system/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/system/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC"}
@@ -1,3 +1,4 @@
1
1
  import { assertPostgresSystemTimestampsCurrent, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, getDatabaseEngine, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, tableExists } from "./compatibility.js";
2
+ import { ensureSystemTables } from "./bootstrap.js";
2
3
  import { DEFAULT_RETENTION_POLICY, clearRetentionTasks, getRetentionTasks, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, unregisterRetentionTask } from "./retention.js";
3
- export { DEFAULT_RETENTION_POLICY, assertPostgresSystemTimestampsCurrent, clearRetentionTasks, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, getDatabaseEngine, getRetentionTasks, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, tableExists, unregisterRetentionTask };
4
+ export { DEFAULT_RETENTION_POLICY, assertPostgresSystemTimestampsCurrent, clearRetentionTasks, ensureBootstrapSystemTableCompatibility, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, getDatabaseEngine, getRetentionTasks, migratePostgresSystemTimestamps, planPostgresSystemTimestampMigrations, pruneAiUsage, pruneExpiredContexts, registerRetentionTask, runRetentionSweep, tableExists, unregisterRetentionTask };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-core",
3
- "version": "0.42.1",
3
+ "version": "0.42.3",
4
4
  "description": "Core AI agent framework with standardized collections, object-relational mapping, and code generators",
5
5
  "author": "HappyVertical",
6
6
  "type": "module",
@@ -164,9 +164,9 @@
164
164
  "tsx": "^4.23.0",
165
165
  "typescript": "5.9.3",
166
166
  "yaml": "^2.9.0",
167
- "@happyvertical/smrt-config": "0.42.1",
168
- "@happyvertical/smrt-scanner": "0.42.1",
169
- "@happyvertical/smrt-types": "0.42.1"
167
+ "@happyvertical/smrt-scanner": "0.42.3",
168
+ "@happyvertical/smrt-config": "0.42.3",
169
+ "@happyvertical/smrt-types": "0.42.3"
170
170
  },
171
171
  "peerDependencies": {
172
172
  "@huggingface/transformers": ">=3.0.0 <4.0.0",