@happyvertical/smrt-core 0.38.18 → 0.38.20
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.
- package/AGENTS.md +28 -0
- package/dist/collection.d.ts +82 -41
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +92 -57
- package/dist/collection.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/interceptors.d.ts +2 -1
- package/dist/interceptors.d.ts.map +1 -1
- package/dist/interceptors.js.map +1 -1
- package/dist/learning/index.d.ts +8 -0
- package/dist/learning/index.d.ts.map +1 -0
- package/dist/learning/memory.d.ts +226 -0
- package/dist/learning/memory.d.ts.map +1 -0
- package/dist/learning/memory.js +340 -0
- package/dist/learning/memory.js.map +1 -0
- package/dist/manifest/static-manifest.js +4 -4
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest/test-manifest-stub.d.ts.map +1 -1
- package/dist/manifest/test-manifest-stub.js +1027 -229
- package/dist/manifest/test-manifest-stub.js.map +1 -1
- package/dist/manifest.json +4 -4
- package/dist/runtime/types.d.ts +1 -0
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +6 -6
- package/dist/testing/database.d.ts +5 -1
- package/dist/testing/database.d.ts.map +1 -1
- package/dist/testing/database.js +4 -1
- package/dist/testing/database.js.map +1 -1
- package/package.json +4 -4
package/dist/index.d.ts
CHANGED
|
@@ -37,6 +37,7 @@ export { type JunctionAttachOptions, type JunctionFilterOptions, SmrtJunction, }
|
|
|
37
37
|
export * from './knowledge';
|
|
38
38
|
export type { ConfigResolver, LazyConfigSentinel, ResolveLazyConfigOptions, } from './lazy-config';
|
|
39
39
|
export { getClassConfigResolvers, getConfigResolver, isLazyConfigSentinel, listConfigResolvers, registerConfigResolver, resetConfigResolvers, resolveLazyConfig, unregisterConfigResolver, } from './lazy-config';
|
|
40
|
+
export { DEFAULT_LEARNING_CONFIG, type LearningEpisode, LearningMemory, type LearningMemoryConfig, type LearningMemoryOptions, type LearningMemoryRecord, type LearningOutcome, type LearningRecallOptions, type LearningSemanticSearch, } from './learning/index';
|
|
40
41
|
export * from './manifest/index';
|
|
41
42
|
export type { DiffOptions } from './migrations/differ';
|
|
42
43
|
export { generateSchemaDiff, getSQLFromDiff, hasActionableChanges, SchemaComparer, } from './migrations/differ';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,cAAc,kBAAkB,CAAC;AAGjC,OAAO,EACL,KAAK,iBAAiB,EACtB,YAAY,EACZ,cAAc,EACd,4BAA4B,EAC5B,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,eAAe,EACf,eAAe,EACf,2BAA2B,EAC3B,iBAAiB,EACjB,eAAe,EACf,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,eAAe,CAAC;AAKvB,OAAO,EACL,qBAAqB,EACrB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAE3B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAE7B,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,KAAK,qBAAqB,EAC1B,+BAA+B,EAC/B,kBAAkB,EAClB,yBAAyB,EACzB,oBAAoB,EACpB,iBAAiB,EACjB,8BAA8B,GAC/B,MAA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CAAC;AAC3B,OAAO,EAAE,IAAI,IAAI,YAAY,EAAE,MAAM,YAAY,CAAC;AAElD,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAElE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,cAAc,iBAAiB,CAAC;AAGhC,cAAc,cAAc,CAAC;AAE7B,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,EACL,eAAe,EACf,KAAK,mBAAmB,GACzB,MAAM,oBAAoB,CAAC;AAE5B,cAAc,eAAe,CAAC;AAE9B,OAAO,EACL,KAAK,EACL,cAAc,EACd,OAAO,EACP,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,EACL,KAAK,MAAM,EACX,KAAK,cAAc,EACnB,SAAS,EACT,aAAa,EACb,SAAS,GACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,2BAA2B,EAC3B,aAAa,EACb,eAAe,EACf,MAAM,EACN,KAAK,mBAAmB,EACxB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -55,6 +55,7 @@ import { SmrtHierarchical } from "./hierarchical.js";
|
|
|
55
55
|
import { SmrtJunction } from "./junction.js";
|
|
56
56
|
import { buildDomainKnowledgeManifest } from "./knowledge.js";
|
|
57
57
|
import { getClassConfigResolvers, getConfigResolver, isLazyConfigSentinel, listConfigResolvers, registerConfigResolver, resetConfigResolvers, resolveLazyConfig, unregisterConfigResolver } from "./lazy-config.js";
|
|
58
|
+
import { DEFAULT_LEARNING_CONFIG, LearningMemory } from "./learning/memory.js";
|
|
58
59
|
import { ManifestBuilder } from "./manifest/generator.js";
|
|
59
60
|
import manifest, { getManifest, staticManifest } from "./manifest/index.js";
|
|
60
61
|
import { SchemaComparer, generateSchemaDiff, getSQLFromDiff, hasActionableChanges } from "./migrations/differ.js";
|
|
@@ -68,4 +69,4 @@ import "./system/index.js";
|
|
|
68
69
|
import { getTestDatabase } from "./testing/database.js";
|
|
69
70
|
import "./tools/index.js";
|
|
70
71
|
import { smrtPlugin } from "./vite-plugin/index.js";
|
|
71
|
-
export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, MAX_CHANGES_LIMIT, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applySyncWritablePolicy, broadcastCacheInvalidation, buildChangeEventStream, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, changeEventSubscribersAtCapacity, childAccessorName, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDispatchBus, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, detectEngine, discoverManifestEntry, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getManifest, getPackageFromQualifiedName, getSQLFromDiff, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, invalidateCollectionCache, isDatabaseInterface, isFromPackage, isLazyConfigSentinel, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isType, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, normalizeEventsMaxSubscribers, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, processSyncApplyBatch, pruneChangeFeed, qualifiedNamesEqual, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveLazyConfig, resolveReadCacheControl, resolveTenantEtagDiscriminator, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized };
|
|
72
|
+
export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_LEARNING_CONFIG, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, MAX_CHANGES_LIMIT, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applySyncWritablePolicy, broadcastCacheInvalidation, buildChangeEventStream, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, changeEventSubscribersAtCapacity, childAccessorName, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDispatchBus, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, detectEngine, discoverManifestEntry, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getManifest, getPackageFromQualifiedName, getSQLFromDiff, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, invalidateCollectionCache, isDatabaseInterface, isFromPackage, isLazyConfigSentinel, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isType, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, normalizeEventsMaxSubscribers, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, processSyncApplyBatch, pruneChangeFeed, qualifiedNamesEqual, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveLazyConfig, resolveReadCacheControl, resolveTenantEtagDiscriminator, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized };
|
package/dist/interceptors.d.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface ListOptions {
|
|
|
22
22
|
orderBy?: string | string[];
|
|
23
23
|
limit?: number;
|
|
24
24
|
offset?: number;
|
|
25
|
+
select?: readonly string[];
|
|
25
26
|
include?: string[];
|
|
26
27
|
[key: string]: unknown;
|
|
27
28
|
}
|
|
@@ -57,7 +58,7 @@ export interface CollectionInterceptor {
|
|
|
57
58
|
/**
|
|
58
59
|
* Called before list() operations
|
|
59
60
|
* @param className - Name of the class being listed
|
|
60
|
-
* @param options - List options (where, orderBy, limit, etc.)
|
|
61
|
+
* @param options - List options (where, orderBy, limit, select, etc.)
|
|
61
62
|
* @param context - Operation context
|
|
62
63
|
* @returns Modified options or void to pass through
|
|
63
64
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptors.d.ts","sourceRoot":"","sources":["../src/interceptors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,+CAA+C;IAC/C,SAAS,EAA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CAQpB"}
|
package/dist/interceptors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptors.js","names":[],"sources":["../src/interceptors.ts"],"sourcesContent":["/**\n * Global Interceptors System for SMRT Collections and Objects\n *\n * Provides a plugin architecture for intercepting collection and object operations.\n * This enables external packages (like @happyvertical/smrt-tenancy) to register\n * interceptors without creating circular dependencies.\n *\n * Pattern: Static methods on GlobalInterceptors class with globalThis state\n * (matches ObjectRegistry pattern for cross-module state sharing)\n *\n * @example Basic interceptor registration\n * ```typescript\n * import { GlobalInterceptors } from '@happyvertical/smrt-core';\n *\n * // Register a beforeList interceptor\n * GlobalInterceptors.register({\n * beforeList(className, options) {\n * console.log(`Listing ${className}`);\n * return options; // Return modified options\n * }\n * });\n * ```\n *\n * @example Tenancy interceptor (from smrt-tenancy)\n * ```typescript\n * GlobalInterceptors.register({\n * beforeList(className, options, context) {\n * const tenantId = getCurrentTenantId();\n * if (tenantId && isTenantScoped(className)) {\n * return {\n * ...options,\n * where: { ...options.where, tenantId }\n * };\n * }\n * return options;\n * },\n * beforeSave(instance, context) {\n * // Validate tenant on save\n * }\n * });\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport type { SmrtObject } from './object.js';\n\n/**\n * Context passed to interceptors with operation metadata\n */\nexport interface InterceptorContext {\n /** Name of the SMRT class being operated on */\n className: string;\n /** Name of the collection (if applicable) */\n collectionName?: string;\n /** Timestamp of the operation */\n timestamp: Date;\n /** Operation type for debugging */\n operation: 'list' | 'get' | 'query' | 'save' | 'delete';\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Options for list operations\n */\nexport interface ListOptions {\n where?: Record<string, unknown>;\n orderBy?: string | string[];\n limit?: number;\n offset?: number;\n include?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Options for query operations (raw SQL)\n */\nexport interface QueryOptions {\n /** The raw SQL query */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** If true, allow raw SQL on tenant-scoped classes (requires explicit opt-in) */\n allowRawOnTenantScoped?: boolean;\n}\n\n/**\n * Result from query interceptor - can modify SQL or throw to block\n */\nexport interface QueryInterceptResult {\n sql: string;\n params: unknown[];\n}\n\n/**\n * Interface for collection/object interceptors\n *\n * All methods are optional. Return void to pass through unchanged,\n * or return modified data to transform the operation.\n */\nexport interface CollectionInterceptor {\n /** Unique identifier for this interceptor (for debugging/unregistration) */\n name?: string;\n\n /** Priority for execution order (higher = earlier). Default: 0 */\n priority?: number;\n\n /**\n * Called before list() operations\n * @param className - Name of the class being listed\n * @param options - List options (where, orderBy, limit, etc.)\n * @param context - Operation context\n * @returns Modified options or void to pass through\n */\n beforeList?(\n className: string,\n options: ListOptions,\n context: InterceptorContext,\n ): ListOptions | Promise<ListOptions> | void | Promise<void>;\n\n /**\n * Called after list() operations with results\n * @param className - Name of the class\n * @param results - Array of hydrated instances\n * @param context - Operation context\n * @returns Modified results or void to pass through\n */\n afterList?<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): T[] | Promise<T[]> | void | Promise<void>;\n\n /**\n * Called before get() operations\n * @param className - Name of the class\n * @param filter - ID, slug, or filter object\n * @param context - Operation context\n * @returns Modified filter or void to pass through\n */\n beforeGet?(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ):\n | string\n | Record<string, unknown>\n | Promise<string | Record<string, unknown>>\n | void\n | Promise<void>;\n\n /**\n * Called after get() operations with result\n * @param className - Name of the class\n * @param instance - Hydrated instance or null if not found\n * @param context - Operation context\n * @returns Modified instance, null, or void to pass through\n */\n afterGet?<T extends SmrtObject>(\n className: string,\n instance: T | null,\n context: InterceptorContext,\n ): T | null | Promise<T | null> | void | Promise<void>;\n\n /**\n * Called before query() operations (raw SQL)\n * @param className - Name of the class\n * @param options - Query options with SQL and params\n * @param context - Operation context\n * @returns Modified query options, or throw to block the query\n */\n beforeQuery?(\n className: string,\n options: QueryOptions,\n context: InterceptorContext,\n ):\n | QueryInterceptResult\n | Promise<QueryInterceptResult>\n | void\n | Promise<void>;\n\n /**\n * Called after query() operations with results\n * @param className - Name of the class\n * @param results - Array of hydrated instances\n * @param context - Operation context\n * @returns Modified results or void to pass through\n */\n afterQuery?<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): T[] | Promise<T[]> | void | Promise<void>;\n\n /**\n * Called before save() operations\n * @param instance - The object being saved\n * @param context - Operation context\n * @returns void (modify instance in place) or throw to block\n */\n beforeSave?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called after save() operations\n * @param instance - The saved object\n * @param context - Operation context\n */\n afterSave?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called before delete() operations\n * @param instance - The object being deleted\n * @param context - Operation context\n * @returns void or throw to block\n */\n beforeDelete?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called after delete() operations\n * @param instance - The deleted object\n * @param context - Operation context\n */\n afterDelete?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n}\n\n/**\n * Extend globalThis to include interceptors state.\n * Using globalThis ensures all module instances share the same interceptors,\n * which is critical in monorepos where the same package can be loaded\n * from different paths.\n *\n * @see ObjectRegistry for similar pattern\n */\ndeclare global {\n // eslint-disable-next-line no-var\n var __smrtInterceptors: unknown[] | undefined;\n}\n\n/**\n * Global Interceptors Registry\n *\n * Manages collection/object interceptors for the SMRT framework.\n * External packages can register interceptors to hook into operations\n * without modifying core code.\n */\nexport class GlobalInterceptors {\n /**\n * Get the global interceptors array (lazy-initialized)\n */\n private static get interceptors(): CollectionInterceptor[] {\n if (!globalThis.__smrtInterceptors) {\n globalThis.__smrtInterceptors = [];\n }\n return globalThis.__smrtInterceptors as CollectionInterceptor[];\n }\n\n /**\n * Register an interceptor\n *\n * @param interceptor - The interceptor to register\n * @example\n * ```typescript\n * GlobalInterceptors.register({\n * name: 'tenancy',\n * priority: 100,\n * beforeList(className, options) {\n * // Add tenant filtering\n * return { ...options, where: { ...options.where, tenantId: 'xxx' } };\n * }\n * });\n * ```\n */\n static register(interceptor: CollectionInterceptor): void {\n // Check for duplicate by name\n if (interceptor.name) {\n const existing = this.interceptors.findIndex(\n (i) => i.name === interceptor.name,\n );\n if (existing >= 0) {\n // Replace existing interceptor with same name\n this.interceptors[existing] = interceptor;\n this.sortByPriority();\n return;\n }\n }\n\n this.interceptors.push(interceptor);\n this.sortByPriority();\n }\n\n /**\n * Unregister an interceptor by reference or name\n *\n * @param interceptorOrName - The interceptor instance or name to remove\n * @returns true if removed, false if not found\n */\n static unregister(\n interceptorOrName: CollectionInterceptor | string,\n ): boolean {\n const idx =\n typeof interceptorOrName === 'string'\n ? this.interceptors.findIndex((i) => i.name === interceptorOrName)\n : this.interceptors.indexOf(interceptorOrName);\n\n if (idx >= 0) {\n this.interceptors.splice(idx, 1);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all interceptors (useful for testing)\n */\n static clear(): void {\n globalThis.__smrtInterceptors = [];\n }\n\n /**\n * Get all registered interceptors (readonly)\n */\n static getAll(): readonly CollectionInterceptor[] {\n return [...this.interceptors];\n }\n\n /**\n * Check if any interceptors are registered\n */\n static hasInterceptors(): boolean {\n return this.interceptors.length > 0;\n }\n\n /**\n * Sort interceptors by priority (higher priority first)\n */\n private static sortByPriority(): void {\n this.interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Execution methods - called by SmrtCollection and SmrtObject\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Execute beforeList interceptors\n * @internal Called by SmrtCollection.list()\n */\n static async executeBeforeList(\n className: string,\n options: ListOptions,\n context: InterceptorContext,\n ): Promise<ListOptions> {\n let result = options;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeList) {\n const modified = await interceptor.beforeList(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterList interceptors\n * @internal Called by SmrtCollection.list()\n */\n static async executeAfterList<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): Promise<T[]> {\n let result = results;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterList) {\n const modified = await interceptor.afterList(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified as T[];\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeGet interceptors\n * @internal Called by SmrtCollection.get()\n */\n static async executeBeforeGet(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ): Promise<string | Record<string, unknown>> {\n let result = filter;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeGet) {\n const modified = await interceptor.beforeGet(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterGet interceptors\n * @internal Called by SmrtCollection.get()\n */\n static async executeAfterGet<T extends SmrtObject>(\n className: string,\n instance: T | null,\n context: InterceptorContext,\n ): Promise<T | null> {\n let result = instance;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterGet) {\n const modified = await interceptor.afterGet(className, result, context);\n if (modified !== undefined) {\n result = modified as T | null;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeQuery interceptors\n * @internal Called by SmrtCollection.query()\n */\n static async executeBeforeQuery(\n className: string,\n options: QueryOptions,\n context: InterceptorContext,\n ): Promise<QueryInterceptResult> {\n let result: QueryInterceptResult = {\n sql: options.sql,\n params: options.params,\n };\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeQuery) {\n const modified = await interceptor.beforeQuery(\n className,\n { ...options, ...result },\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterQuery interceptors\n * @internal Called by SmrtCollection.query()\n */\n static async executeAfterQuery<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): Promise<T[]> {\n let result = results;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterQuery) {\n const modified = await interceptor.afterQuery(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified as T[];\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeSave interceptors\n * @internal Called by SmrtObject.save()\n */\n static async executeBeforeSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeSave) {\n await interceptor.beforeSave(instance, context);\n }\n }\n }\n\n /**\n * Execute afterSave interceptors\n * @internal Called by SmrtObject.save()\n */\n static async executeAfterSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.afterSave) {\n await interceptor.afterSave(instance, context);\n }\n }\n }\n\n /**\n * Execute beforeDelete interceptors\n * @internal Called by SmrtObject.delete()\n */\n static async executeBeforeDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeDelete) {\n await interceptor.beforeDelete(instance, context);\n }\n }\n }\n\n /**\n * Execute afterDelete interceptors\n * @internal Called by SmrtObject.delete()\n */\n static async executeAfterDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.afterDelete) {\n await interceptor.afterDelete(instance, context);\n }\n }\n }\n}\n\n/**\n * Helper function to create an interceptor context\n * @internal\n */\nexport function createInterceptorContext(\n className: string,\n operation: InterceptorContext['operation'],\n collectionName?: string,\n metadata?: Record<string, unknown>,\n): InterceptorContext {\n return {\n className,\n collectionName,\n operation,\n timestamp: new Date(),\n metadata,\n };\n}\n"],"mappings":";;;;;;;;AAkQA,IAAa,qBAAb,MAAgC;;;;CAI9B,WAAmB,eAAwC;EACzD,IAAI,CAAC,WAAW,oBACd,WAAW,qBAAqB,C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M,eAAe,KAAK,cAC7B,IAAI,YAAY,WACd,MAAM,YAAY,UAAU,UAAU,OAAO;CAGnD;;;;;CAMA,aAAa,oBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,cACd,MAAM,YAAY,aAAa,UAAU,OAAO;CAGtD;;;;;CAMA,aAAa,mBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,aACd,MAAM,YAAY,YAAY,UAAU,OAAO;CAGrD;AACF;;;;;AAMA,SAAgB,yBACd,WACA,WACA,gBACA,UACoB;CACpB,OAAO;EACL;EACA;EACA;EACA,2BAAW,IAAI,KAAK;EACpB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"interceptors.js","names":[],"sources":["../src/interceptors.ts"],"sourcesContent":["/**\n * Global Interceptors System for SMRT Collections and Objects\n *\n * Provides a plugin architecture for intercepting collection and object operations.\n * This enables external packages (like @happyvertical/smrt-tenancy) to register\n * interceptors without creating circular dependencies.\n *\n * Pattern: Static methods on GlobalInterceptors class with globalThis state\n * (matches ObjectRegistry pattern for cross-module state sharing)\n *\n * @example Basic interceptor registration\n * ```typescript\n * import { GlobalInterceptors } from '@happyvertical/smrt-core';\n *\n * // Register a beforeList interceptor\n * GlobalInterceptors.register({\n * beforeList(className, options) {\n * console.log(`Listing ${className}`);\n * return options; // Return modified options\n * }\n * });\n * ```\n *\n * @example Tenancy interceptor (from smrt-tenancy)\n * ```typescript\n * GlobalInterceptors.register({\n * beforeList(className, options, context) {\n * const tenantId = getCurrentTenantId();\n * if (tenantId && isTenantScoped(className)) {\n * return {\n * ...options,\n * where: { ...options.where, tenantId }\n * };\n * }\n * return options;\n * },\n * beforeSave(instance, context) {\n * // Validate tenant on save\n * }\n * });\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport type { SmrtObject } from './object.js';\n\n/**\n * Context passed to interceptors with operation metadata\n */\nexport interface InterceptorContext {\n /** Name of the SMRT class being operated on */\n className: string;\n /** Name of the collection (if applicable) */\n collectionName?: string;\n /** Timestamp of the operation */\n timestamp: Date;\n /** Operation type for debugging */\n operation: 'list' | 'get' | 'query' | 'save' | 'delete';\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Options for list operations\n */\nexport interface ListOptions {\n where?: Record<string, unknown>;\n orderBy?: string | string[];\n limit?: number;\n offset?: number;\n select?: readonly string[];\n include?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Options for query operations (raw SQL)\n */\nexport interface QueryOptions {\n /** The raw SQL query */\n sql: string;\n /** Query parameters */\n params: unknown[];\n /** If true, allow raw SQL on tenant-scoped classes (requires explicit opt-in) */\n allowRawOnTenantScoped?: boolean;\n}\n\n/**\n * Result from query interceptor - can modify SQL or throw to block\n */\nexport interface QueryInterceptResult {\n sql: string;\n params: unknown[];\n}\n\n/**\n * Interface for collection/object interceptors\n *\n * All methods are optional. Return void to pass through unchanged,\n * or return modified data to transform the operation.\n */\nexport interface CollectionInterceptor {\n /** Unique identifier for this interceptor (for debugging/unregistration) */\n name?: string;\n\n /** Priority for execution order (higher = earlier). Default: 0 */\n priority?: number;\n\n /**\n * Called before list() operations\n * @param className - Name of the class being listed\n * @param options - List options (where, orderBy, limit, select, etc.)\n * @param context - Operation context\n * @returns Modified options or void to pass through\n */\n beforeList?(\n className: string,\n options: ListOptions,\n context: InterceptorContext,\n ): ListOptions | Promise<ListOptions> | void | Promise<void>;\n\n /**\n * Called after list() operations with results\n * @param className - Name of the class\n * @param results - Array of hydrated instances\n * @param context - Operation context\n * @returns Modified results or void to pass through\n */\n afterList?<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): T[] | Promise<T[]> | void | Promise<void>;\n\n /**\n * Called before get() operations\n * @param className - Name of the class\n * @param filter - ID, slug, or filter object\n * @param context - Operation context\n * @returns Modified filter or void to pass through\n */\n beforeGet?(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ):\n | string\n | Record<string, unknown>\n | Promise<string | Record<string, unknown>>\n | void\n | Promise<void>;\n\n /**\n * Called after get() operations with result\n * @param className - Name of the class\n * @param instance - Hydrated instance or null if not found\n * @param context - Operation context\n * @returns Modified instance, null, or void to pass through\n */\n afterGet?<T extends SmrtObject>(\n className: string,\n instance: T | null,\n context: InterceptorContext,\n ): T | null | Promise<T | null> | void | Promise<void>;\n\n /**\n * Called before query() operations (raw SQL)\n * @param className - Name of the class\n * @param options - Query options with SQL and params\n * @param context - Operation context\n * @returns Modified query options, or throw to block the query\n */\n beforeQuery?(\n className: string,\n options: QueryOptions,\n context: InterceptorContext,\n ):\n | QueryInterceptResult\n | Promise<QueryInterceptResult>\n | void\n | Promise<void>;\n\n /**\n * Called after query() operations with results\n * @param className - Name of the class\n * @param results - Array of hydrated instances\n * @param context - Operation context\n * @returns Modified results or void to pass through\n */\n afterQuery?<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): T[] | Promise<T[]> | void | Promise<void>;\n\n /**\n * Called before save() operations\n * @param instance - The object being saved\n * @param context - Operation context\n * @returns void (modify instance in place) or throw to block\n */\n beforeSave?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called after save() operations\n * @param instance - The saved object\n * @param context - Operation context\n */\n afterSave?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called before delete() operations\n * @param instance - The object being deleted\n * @param context - Operation context\n * @returns void or throw to block\n */\n beforeDelete?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n\n /**\n * Called after delete() operations\n * @param instance - The deleted object\n * @param context - Operation context\n */\n afterDelete?(\n instance: SmrtObject,\n context: InterceptorContext,\n ): void | Promise<void>;\n}\n\n/**\n * Extend globalThis to include interceptors state.\n * Using globalThis ensures all module instances share the same interceptors,\n * which is critical in monorepos where the same package can be loaded\n * from different paths.\n *\n * @see ObjectRegistry for similar pattern\n */\ndeclare global {\n // eslint-disable-next-line no-var\n var __smrtInterceptors: unknown[] | undefined;\n}\n\n/**\n * Global Interceptors Registry\n *\n * Manages collection/object interceptors for the SMRT framework.\n * External packages can register interceptors to hook into operations\n * without modifying core code.\n */\nexport class GlobalInterceptors {\n /**\n * Get the global interceptors array (lazy-initialized)\n */\n private static get interceptors(): CollectionInterceptor[] {\n if (!globalThis.__smrtInterceptors) {\n globalThis.__smrtInterceptors = [];\n }\n return globalThis.__smrtInterceptors as CollectionInterceptor[];\n }\n\n /**\n * Register an interceptor\n *\n * @param interceptor - The interceptor to register\n * @example\n * ```typescript\n * GlobalInterceptors.register({\n * name: 'tenancy',\n * priority: 100,\n * beforeList(className, options) {\n * // Add tenant filtering\n * return { ...options, where: { ...options.where, tenantId: 'xxx' } };\n * }\n * });\n * ```\n */\n static register(interceptor: CollectionInterceptor): void {\n // Check for duplicate by name\n if (interceptor.name) {\n const existing = this.interceptors.findIndex(\n (i) => i.name === interceptor.name,\n );\n if (existing >= 0) {\n // Replace existing interceptor with same name\n this.interceptors[existing] = interceptor;\n this.sortByPriority();\n return;\n }\n }\n\n this.interceptors.push(interceptor);\n this.sortByPriority();\n }\n\n /**\n * Unregister an interceptor by reference or name\n *\n * @param interceptorOrName - The interceptor instance or name to remove\n * @returns true if removed, false if not found\n */\n static unregister(\n interceptorOrName: CollectionInterceptor | string,\n ): boolean {\n const idx =\n typeof interceptorOrName === 'string'\n ? this.interceptors.findIndex((i) => i.name === interceptorOrName)\n : this.interceptors.indexOf(interceptorOrName);\n\n if (idx >= 0) {\n this.interceptors.splice(idx, 1);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all interceptors (useful for testing)\n */\n static clear(): void {\n globalThis.__smrtInterceptors = [];\n }\n\n /**\n * Get all registered interceptors (readonly)\n */\n static getAll(): readonly CollectionInterceptor[] {\n return [...this.interceptors];\n }\n\n /**\n * Check if any interceptors are registered\n */\n static hasInterceptors(): boolean {\n return this.interceptors.length > 0;\n }\n\n /**\n * Sort interceptors by priority (higher priority first)\n */\n private static sortByPriority(): void {\n this.interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Execution methods - called by SmrtCollection and SmrtObject\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Execute beforeList interceptors\n * @internal Called by SmrtCollection.list()\n */\n static async executeBeforeList(\n className: string,\n options: ListOptions,\n context: InterceptorContext,\n ): Promise<ListOptions> {\n let result = options;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeList) {\n const modified = await interceptor.beforeList(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterList interceptors\n * @internal Called by SmrtCollection.list()\n */\n static async executeAfterList<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): Promise<T[]> {\n let result = results;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterList) {\n const modified = await interceptor.afterList(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified as T[];\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeGet interceptors\n * @internal Called by SmrtCollection.get()\n */\n static async executeBeforeGet(\n className: string,\n filter: string | Record<string, unknown>,\n context: InterceptorContext,\n ): Promise<string | Record<string, unknown>> {\n let result = filter;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeGet) {\n const modified = await interceptor.beforeGet(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterGet interceptors\n * @internal Called by SmrtCollection.get()\n */\n static async executeAfterGet<T extends SmrtObject>(\n className: string,\n instance: T | null,\n context: InterceptorContext,\n ): Promise<T | null> {\n let result = instance;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterGet) {\n const modified = await interceptor.afterGet(className, result, context);\n if (modified !== undefined) {\n result = modified as T | null;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeQuery interceptors\n * @internal Called by SmrtCollection.query()\n */\n static async executeBeforeQuery(\n className: string,\n options: QueryOptions,\n context: InterceptorContext,\n ): Promise<QueryInterceptResult> {\n let result: QueryInterceptResult = {\n sql: options.sql,\n params: options.params,\n };\n\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeQuery) {\n const modified = await interceptor.beforeQuery(\n className,\n { ...options, ...result },\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified;\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute afterQuery interceptors\n * @internal Called by SmrtCollection.query()\n */\n static async executeAfterQuery<T extends SmrtObject>(\n className: string,\n results: T[],\n context: InterceptorContext,\n ): Promise<T[]> {\n let result = results;\n\n for (const interceptor of this.interceptors) {\n if (interceptor.afterQuery) {\n const modified = await interceptor.afterQuery(\n className,\n result,\n context,\n );\n if (modified !== undefined && modified !== null) {\n result = modified as T[];\n }\n }\n }\n\n return result;\n }\n\n /**\n * Execute beforeSave interceptors\n * @internal Called by SmrtObject.save()\n */\n static async executeBeforeSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeSave) {\n await interceptor.beforeSave(instance, context);\n }\n }\n }\n\n /**\n * Execute afterSave interceptors\n * @internal Called by SmrtObject.save()\n */\n static async executeAfterSave(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.afterSave) {\n await interceptor.afterSave(instance, context);\n }\n }\n }\n\n /**\n * Execute beforeDelete interceptors\n * @internal Called by SmrtObject.delete()\n */\n static async executeBeforeDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.beforeDelete) {\n await interceptor.beforeDelete(instance, context);\n }\n }\n }\n\n /**\n * Execute afterDelete interceptors\n * @internal Called by SmrtObject.delete()\n */\n static async executeAfterDelete(\n instance: SmrtObject,\n context: InterceptorContext,\n ): Promise<void> {\n for (const interceptor of this.interceptors) {\n if (interceptor.afterDelete) {\n await interceptor.afterDelete(instance, context);\n }\n }\n }\n}\n\n/**\n * Helper function to create an interceptor context\n * @internal\n */\nexport function createInterceptorContext(\n className: string,\n operation: InterceptorContext['operation'],\n collectionName?: string,\n metadata?: Record<string, unknown>,\n): InterceptorContext {\n return {\n className,\n collectionName,\n operation,\n timestamp: new Date(),\n metadata,\n };\n}\n"],"mappings":";;;;;;;;AAmQA,IAAa,qBAAb,MAAgC;;;;CAI9B,WAAmB,eAAwC;EACzD,IAAI,CAAC,WAAW,oBACd,WAAW,qBAAqB,CAAC;EAEnC,OAAO,WAAW;CACpB;;;;;;;;;;;;;;;;;CAkBA,OAAO,SAAS,aAA0C;EAExD,IAAI,YAAY,MAAM;GACpB,MAAM,WAAW,KAAK,aAAa,WAChC,MAAM,EAAE,SAAS,YAAY,IAChC;GACA,IAAI,YAAY,GAAG;IAEjB,KAAK,aAAa,YAAY;IAC9B,KAAK,eAAe;IACpB;GACF;EACF;EAEA,KAAK,aAAa,KAAK,WAAW;EAClC,KAAK,eAAe;CACtB;;;;;;;CAQA,OAAO,WACL,mBACS;EACT,MAAM,MACJ,OAAO,sBAAsB,WACzB,KAAK,aAAa,WAAW,MAAM,EAAE,SAAS,iBAAiB,IAC/D,KAAK,aAAa,QAAQ,iBAAiB;EAEjD,IAAI,OAAO,GAAG;GACZ,KAAK,aAAa,OAAO,KAAK,CAAC;GAC/B,OAAO;EACT;EACA,OAAO;CACT;;;;CAKA,OAAO,QAAc;EACnB,WAAW,qBAAqB,CAAC;CACnC;;;;CAKA,OAAO,SAA2C;EAChD,OAAO,CAAC,GAAG,KAAK,YAAY;CAC9B;;;;CAKA,OAAO,kBAA2B;EAChC,OAAO,KAAK,aAAa,SAAS;CACpC;;;;CAKA,OAAe,iBAAuB;EACpC,KAAK,aAAa,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CACxE;;;;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;;;;CAMA,aAAa,kBACX,WACA,SACA,SACc;EACd,IAAI,SAAS;EAEb,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,YAAY;GAC1B,MAAM,WAAW,MAAM,YAAY,WACjC,WACA,QACA,OACF;GACA,IAAI,aAAa,KAAA,KAAa,aAAa,MACzC,SAAS;EAEb;EAGF,OAAO;CACT;;;;;CAMA,aAAa,kBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,YACd,MAAM,YAAY,WAAW,UAAU,OAAO;CAGpD;;;;;CAMA,aAAa,iBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,WACd,MAAM,YAAY,UAAU,UAAU,OAAO;CAGnD;;;;;CAMA,aAAa,oBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,cACd,MAAM,YAAY,aAAa,UAAU,OAAO;CAGtD;;;;;CAMA,aAAa,mBACX,UACA,SACe;EACf,KAAK,MAAM,eAAe,KAAK,cAC7B,IAAI,YAAY,aACd,MAAM,YAAY,YAAY,UAAU,OAAO;CAGrD;AACF;;;;;AAMA,SAAgB,yBACd,WACA,WACA,gBACA,UACoB;CACpB,OAAO;EACL;EACA;EACA;EACA,2BAAW,IAAI,KAAK;EACpB;CACF;AACF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Learning primitives — confidence-scored, self-correcting memory (L1 of the
|
|
3
|
+
* tenant-learning-agents epic, #1885 / #1886).
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export { DEFAULT_LEARNING_CONFIG, type LearningEpisode, LearningMemory, type LearningMemoryConfig, type LearningMemoryOptions, type LearningMemoryRecord, type LearningOutcome, type LearningRecallOptions, type LearningSemanticSearch, } from './memory.js';
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/learning/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,uBAAuB,EACvB,KAAK,eAAe,EACpB,cAAc,EACd,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC5B,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { DatabaseInterface } from '@happyvertical/sql';
|
|
2
|
+
/**
|
|
3
|
+
* A relevance-scored memory returned by {@link LearningMemory.recall}.
|
|
4
|
+
*
|
|
5
|
+
* Records sourced from keyed `_smrt_contexts` lookups carry reinforcement
|
|
6
|
+
* counters; records sourced from semantic embedding search carry a
|
|
7
|
+
* `similarity` score (mirrored into `confidence` for uniform ranking).
|
|
8
|
+
*/
|
|
9
|
+
export interface LearningMemoryRecord {
|
|
10
|
+
/** Row id in `_smrt_contexts`, or the matched object id for semantic hits. */
|
|
11
|
+
id: string;
|
|
12
|
+
/** Hierarchical scope the memory is filed under. */
|
|
13
|
+
scope: string;
|
|
14
|
+
/** Lookup key within the scope. */
|
|
15
|
+
key: string;
|
|
16
|
+
/** The stored value (JSON-parsed for context rows; the matched object for semantic hits). */
|
|
17
|
+
value: unknown;
|
|
18
|
+
/** Confidence in `[0, 1]`. For semantic hits this equals `similarity`. */
|
|
19
|
+
confidence: number;
|
|
20
|
+
/** Number of captured successes reinforcing this memory. */
|
|
21
|
+
successCount: number;
|
|
22
|
+
/** Number of captured failures decaying this memory. */
|
|
23
|
+
failureCount: number;
|
|
24
|
+
/** Last time this memory was recalled or reinforced. */
|
|
25
|
+
lastUsedAt: Date | null;
|
|
26
|
+
/** Where the record came from. */
|
|
27
|
+
source: 'context' | 'semantic';
|
|
28
|
+
/** Cosine similarity for semantic hits (absent for context rows). */
|
|
29
|
+
similarity?: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The outcome of acting on a recalled (or freshly generated) memory.
|
|
33
|
+
*
|
|
34
|
+
* A boolean `success` signal is the common case; a numeric `metric` delta is
|
|
35
|
+
* supported as a convenience (positive → success, non-positive → failure).
|
|
36
|
+
*/
|
|
37
|
+
export type LearningOutcome = {
|
|
38
|
+
success: boolean;
|
|
39
|
+
error?: string;
|
|
40
|
+
} | {
|
|
41
|
+
metric: number;
|
|
42
|
+
error?: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* The episode being reinforced — the scope/key of the memory the agent acted
|
|
46
|
+
* on, plus (for a first capture) the value to persist.
|
|
47
|
+
*/
|
|
48
|
+
export interface LearningEpisode {
|
|
49
|
+
/** Scope the memory is filed under (e.g. `'sample/parse-invoice'`). */
|
|
50
|
+
scope: string;
|
|
51
|
+
/** Lookup key within the scope. */
|
|
52
|
+
key: string;
|
|
53
|
+
/**
|
|
54
|
+
* The value (strategy) this outcome pertains to. Seeds a new memory when none
|
|
55
|
+
* exists for `(scope, key)`, and refreshes the stored value when one does — so
|
|
56
|
+
* a regenerated strategy supersedes a decayed one. Omit to reinforce an
|
|
57
|
+
* existing memory's confidence without touching its stored value.
|
|
58
|
+
*/
|
|
59
|
+
value?: unknown;
|
|
60
|
+
/** Optional metadata to persist on a first capture. */
|
|
61
|
+
metadata?: Record<string, unknown>;
|
|
62
|
+
/** Optional expiry after which recall ignores the memory. */
|
|
63
|
+
expiresAt?: Date;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Tunable thresholds for the reinforcement loop. Defaults mirror the proven
|
|
67
|
+
* `praeco` behaviour.
|
|
68
|
+
*/
|
|
69
|
+
export interface LearningMemoryConfig {
|
|
70
|
+
/** Reuse floor — recall omits memories below this confidence. Default 0.7. */
|
|
71
|
+
minConfidence: number;
|
|
72
|
+
/** Confidence a brand-new memory is seeded at on a first success. Default 0.9. */
|
|
73
|
+
successConfidence: number;
|
|
74
|
+
/** Target a memory decays toward on failure. Default 0.3. */
|
|
75
|
+
failureConfidence: number;
|
|
76
|
+
/**
|
|
77
|
+
* Blend weight in `[0, 1]` for each reinforcement step. At 0.5 a single
|
|
78
|
+
* failure from any confident value (>= 0.7) always lands below the 0.7 floor
|
|
79
|
+
* (`0.5·c + 0.15 <= 0.65`). Default 0.5.
|
|
80
|
+
*/
|
|
81
|
+
reinforcement: number;
|
|
82
|
+
/**
|
|
83
|
+
* Optional half-life (ms) for time-based confidence decay. When set, recall
|
|
84
|
+
* discounts a memory's stored confidence by `0.5 ^ (age / halfLife)` based on
|
|
85
|
+
* `last_used_at`, so stale memory falls below the floor over time even
|
|
86
|
+
* without an explicit failure. Off (no time decay) when undefined.
|
|
87
|
+
*/
|
|
88
|
+
decayHalfLifeMs?: number;
|
|
89
|
+
}
|
|
90
|
+
/** Default reinforcement thresholds. */
|
|
91
|
+
export declare const DEFAULT_LEARNING_CONFIG: LearningMemoryConfig;
|
|
92
|
+
/**
|
|
93
|
+
* A semantic search over stored embeddings, injected so `LearningMemory` never
|
|
94
|
+
* reaches into a collection's internals. Matches the shape of
|
|
95
|
+
* `SmrtCollection.semanticSearch`.
|
|
96
|
+
*/
|
|
97
|
+
export type LearningSemanticSearch = (query: string, options: {
|
|
98
|
+
limit?: number;
|
|
99
|
+
minSimilarity?: number;
|
|
100
|
+
where?: Record<string, unknown>;
|
|
101
|
+
}) => Promise<Array<{
|
|
102
|
+
id?: string;
|
|
103
|
+
_similarity: number;
|
|
104
|
+
} & Record<string, unknown>>>;
|
|
105
|
+
/** Options for {@link LearningMemory.recall}. */
|
|
106
|
+
export interface LearningRecallOptions {
|
|
107
|
+
/** Exact key to look up within the scope. Omit for a scope-wide recall. */
|
|
108
|
+
key?: string;
|
|
109
|
+
/** Free-text query for semantic recall (only used when a searcher is wired). */
|
|
110
|
+
query?: string;
|
|
111
|
+
/** Override the reuse floor for this call. */
|
|
112
|
+
minConfidence?: number;
|
|
113
|
+
/** Walk up the scope hierarchy when no match is found at `scope`. Default true. */
|
|
114
|
+
includeAncestors?: boolean;
|
|
115
|
+
/** Cap on returned records. */
|
|
116
|
+
limit?: number;
|
|
117
|
+
/** Cap on semantic hits requested from the searcher. Default 10. */
|
|
118
|
+
semanticLimit?: number;
|
|
119
|
+
/** Minimum cosine similarity for semantic hits. Default 0. */
|
|
120
|
+
minSimilarity?: number;
|
|
121
|
+
/** Reference time for decay/expiry evaluation (injectable for tests). */
|
|
122
|
+
now?: Date;
|
|
123
|
+
}
|
|
124
|
+
/** Constructor options for {@link LearningMemory}. */
|
|
125
|
+
export interface LearningMemoryOptions {
|
|
126
|
+
/** System database handle (an owning object's `systemDb`). */
|
|
127
|
+
db: DatabaseInterface;
|
|
128
|
+
/** `owner_class` the memories are filed under. */
|
|
129
|
+
ownerClass: string;
|
|
130
|
+
/** `owner_id` the memories are filed under (isolates memory per owner). */
|
|
131
|
+
ownerId: string;
|
|
132
|
+
/**
|
|
133
|
+
* Optional tenant id. When set it is threaded into the semantic searcher's
|
|
134
|
+
* `where` filter so embedding recall stays tenant-scoped. Keyed-context
|
|
135
|
+
* recall is already isolated by `owner_id`.
|
|
136
|
+
*/
|
|
137
|
+
tenantId?: string | null;
|
|
138
|
+
/** Optional embedding search for the semantic recall arm. */
|
|
139
|
+
semanticSearch?: LearningSemanticSearch;
|
|
140
|
+
/** Threshold overrides; merged over {@link DEFAULT_LEARNING_CONFIG}. */
|
|
141
|
+
config?: Partial<LearningMemoryConfig>;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Confidence-scored, self-correcting memory over `_smrt_contexts` and
|
|
145
|
+
* (optionally) semantic embedding search.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```typescript
|
|
149
|
+
* const memory = new LearningMemory({
|
|
150
|
+
* db: agent.systemDb,
|
|
151
|
+
* ownerClass: 'InvoiceAgent',
|
|
152
|
+
* ownerId: agent.id,
|
|
153
|
+
* tenantId: agent.tenantId,
|
|
154
|
+
* });
|
|
155
|
+
*
|
|
156
|
+
* // Recall a confident strategy for this task.
|
|
157
|
+
* const [hit] = await memory.recall('parser/acme', { key: docUrl });
|
|
158
|
+
* const strategy = hit?.value ?? (await generateStrategy(docUrl));
|
|
159
|
+
*
|
|
160
|
+
* // ...act on `strategy`, then reinforce the outcome.
|
|
161
|
+
* await memory.capture(
|
|
162
|
+
* { scope: 'parser/acme', key: docUrl, value: strategy },
|
|
163
|
+
* { success: extracted.length > 0 },
|
|
164
|
+
* );
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
export declare class LearningMemory {
|
|
168
|
+
private readonly db;
|
|
169
|
+
private readonly ownerClass;
|
|
170
|
+
private readonly ownerId;
|
|
171
|
+
private readonly tenantId;
|
|
172
|
+
private readonly semanticSearch?;
|
|
173
|
+
private readonly config;
|
|
174
|
+
constructor(options: LearningMemoryOptions);
|
|
175
|
+
/** The resolved reinforcement thresholds (defaults merged with overrides). */
|
|
176
|
+
get thresholds(): LearningMemoryConfig;
|
|
177
|
+
/**
|
|
178
|
+
* Recall confidence-filtered, relevant memories for a scope.
|
|
179
|
+
*
|
|
180
|
+
* Unions two arms:
|
|
181
|
+
* 1. **Keyed context recall** over `_smrt_contexts` — owner-scoped (and thus
|
|
182
|
+
* tenant-isolated), filtered by the confidence floor, expiry, and optional
|
|
183
|
+
* time-decay, with hierarchical scope fallback. Surviving rows have their
|
|
184
|
+
* `last_used_at` refreshed.
|
|
185
|
+
* 2. **Semantic recall** over stored embeddings (only when a searcher was
|
|
186
|
+
* wired and a `query` is given) — tenant-scoped via the searcher's `where`.
|
|
187
|
+
*
|
|
188
|
+
* @returns Records sorted by confidence (then similarity) descending.
|
|
189
|
+
*/
|
|
190
|
+
recall(scope: string, options?: LearningRecallOptions): Promise<LearningMemoryRecord[]>;
|
|
191
|
+
/**
|
|
192
|
+
* Reinforce a memory from an observed outcome.
|
|
193
|
+
*
|
|
194
|
+
* - Wires the dormant reinforcement columns: increments `success_count` on
|
|
195
|
+
* success, `failure_count` on failure.
|
|
196
|
+
* - Adjusts `confidence`: success strengthens toward 1.0; failure decays
|
|
197
|
+
* toward `failureConfidence` (default 0.3), dropping a confident memory
|
|
198
|
+
* below the reuse floor in a single step.
|
|
199
|
+
* - Refreshes `last_used_at` and `updated_at`, and (when the episode carries a
|
|
200
|
+
* `value`) the stored value — so a regenerated strategy supersedes a decayed
|
|
201
|
+
* one instead of the old value resurfacing on the next success.
|
|
202
|
+
* - Seeds a new memory when none exists for `(scope, key)` and the episode
|
|
203
|
+
* carries a `value` (a failed first attempt is retained at low confidence
|
|
204
|
+
* for self-correction context).
|
|
205
|
+
*
|
|
206
|
+
* @returns The updated (or seeded) record, or `null` when there was nothing
|
|
207
|
+
* to reinforce (no existing memory and no value to seed).
|
|
208
|
+
*/
|
|
209
|
+
capture(episode: LearningEpisode, outcome: LearningOutcome): Promise<LearningMemoryRecord | null>;
|
|
210
|
+
/**
|
|
211
|
+
* Compute the next confidence from the current value and an outcome.
|
|
212
|
+
*
|
|
213
|
+
* Success strengthens toward 1.0; failure blends toward `failureConfidence`.
|
|
214
|
+
* Exposed as a pure step so callers/tests can reason about the curve.
|
|
215
|
+
*/
|
|
216
|
+
nextConfidence(current: number, success: boolean): number;
|
|
217
|
+
private recallContexts;
|
|
218
|
+
private selectContextRows;
|
|
219
|
+
private filterAndRank;
|
|
220
|
+
private applyTimeDecay;
|
|
221
|
+
private recallSemantic;
|
|
222
|
+
private touch;
|
|
223
|
+
private scopeChain;
|
|
224
|
+
private parseMetadata;
|
|
225
|
+
}
|
|
226
|
+
//# sourceMappingURL=memory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/learning/memory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACnC,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