@anuma/sdk 6.34.0 → 6.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4866,8 +4866,10 @@ declare function isEncrypted(value: string): boolean;
4866
4866
  * budget was in memory and reset on every turn, so one batch that could never
4867
4867
  * extract blocked its conversation's extraction forever. Additive, both
4868
4868
  * nullable, no backfill: NULL reads as "never failed"
4869
+ * - v48: Added kind, kind_value (encrypted) and level to memory_vault; level is
4870
+ * backfilled from scope where SQL steps run
4869
4871
  */
4870
- declare const SDK_SCHEMA_VERSION = 47;
4872
+ declare const SDK_SCHEMA_VERSION = 48;
4871
4873
  /**
4872
4874
  * Combined WatermelonDB schema for all SDK storage modules.
4873
4875
  *
@@ -4956,6 +4958,7 @@ declare const sdkSchema: Readonly<{
4956
4958
  * - v41 → v42: Added `topics` + `topics_updated_at` columns to memory_vault, making a memory's topics the durable synced record and `entity`/`memory_entity` a device-local index over it (null `topics` = pre-v42, backfilled from the row's current links by the sweep)
4957
4959
  * - v42 → v43: Added a composite `(is_deleted, created_at)` index to conversations so the list reads stop temp-sorting (structural only, no data rewritten)
4958
4960
  * - v43 → v44: Added `origin` column to history recording which producer synthesised a row, so the embedding sweep can skip never-rendered tool-result dumps (plaintext by design — the sweep has no wallet context; null = legacy, embedded as before)
4961
+ * - v47 → v48: Added `kind`, `kind_value`, `level` to memory_vault; `level` backfilled from `scope` (`shared`/`public` → matching, else private) where SQL steps run
4959
4962
  */
4960
4963
  declare const sdkMigrations: Readonly<{
4961
4964
  validated: true;
@@ -5126,6 +5129,12 @@ declare class VaultMemory extends Model {
5126
5129
  static table: string;
5127
5130
  content: string;
5128
5131
  scope: string;
5132
+ /** Profile kind, or null for a free-form memory. */
5133
+ kind: string | null;
5134
+ /** Canonical JSON value of a kinded memory, encrypted at rest. */
5135
+ kindValue: string | null;
5136
+ /** private | matching | profile. */
5137
+ level: string | null;
5129
5138
  folderId: string | null;
5130
5139
  userId: string | null;
5131
5140
  embedding: string | null;
@@ -6879,13 +6888,35 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6879
6888
  * the fail-safe direction: it un-publishes rather than exposes.
6880
6889
  */
6881
6890
  type VaultMemoryVisibility = "private" | "public";
6891
+ /** Profile kinds a vault memory can carry. */
6892
+ declare const MEMORY_KINDS: readonly ["display_name", "birth_date", "bio", "occupation", "interest", "gender", "height_cm", "looking_for", "politics", "religion", "ethnicity", "smoking", "drinking", "exercise", "sexuality", "prompt"];
6893
+ /** One of {@link MEMORY_KINDS}. */
6894
+ type VaultMemoryKind = (typeof MEMORY_KINDS)[number];
6895
+ /** Who a memory reaches. */
6896
+ declare const MEMORY_LEVELS: readonly ["private", "matching", "profile"];
6897
+ /** One of {@link MEMORY_LEVELS}. */
6898
+ type MemoryLevel = (typeof MEMORY_LEVELS)[number];
6899
+ /**
6900
+ * Thrown by vault writes that would store an unknown kind or level, or a profile level without a kind.
6901
+ *
6902
+ * @public
6903
+ */
6904
+ declare class MemoryLevelError extends Error {
6905
+ constructor(message: string);
6906
+ }
6882
6907
  interface StoredVaultMemory {
6883
6908
  /** WatermelonDB internal ID */
6884
6909
  uniqueId: string;
6885
6910
  /** Plain text memory content */
6886
6911
  content: string;
6887
- /** Scope for partitioning memories (e.g., "private", "shared") */
6912
+ /** Scope for partitioning memories (e.g., "private", "shared"). */
6888
6913
  scope: string;
6914
+ /** Profile kind ({@link MEMORY_KINDS}) or null for a free-form memory. */
6915
+ kind?: string | null;
6916
+ /** Canonical value of a kinded memory, JSON-encoded (slug, slug[], int, date, text). */
6917
+ kindValue?: string | null;
6918
+ /** Who this memory reaches. */
6919
+ level?: MemoryLevel;
6889
6920
  /** Folder ID for organization, null if unfiled */
6890
6921
  folderId: string | null;
6891
6922
  /** User ID for multi-user server-side scoping, null on client */
@@ -7027,8 +7058,14 @@ interface PhotoMediaRef {
7027
7058
  declare function parseMedia(value: unknown): PhotoMediaRef[] | null;
7028
7059
  interface CreateVaultMemoryOptions {
7029
7060
  content: string;
7030
- /** Scope for the memory. Defaults to "private" if omitted. */
7061
+ /** Scope for the memory. */
7031
7062
  scope?: string;
7063
+ /** Profile kind, or omit/null for a free-form memory. */
7064
+ kind?: VaultMemoryKind | null;
7065
+ /** Canonical JSON value of a kinded memory. */
7066
+ kindValue?: string | null;
7067
+ /** Who this memory reaches. */
7068
+ level?: MemoryLevel;
7032
7069
  /** Folder ID for organization, null or omitted if unfiled */
7033
7070
  folderId?: string | null;
7034
7071
  /** JSON-stringified embedding vector to persist */
@@ -7069,8 +7106,19 @@ interface CreateVaultMemoryOptions {
7069
7106
  }
7070
7107
  interface UpdateVaultMemoryOptions {
7071
7108
  content: string;
7072
- /** If provided, updates the memory's scope. */
7109
+ /** When true, the write is skipped (returns null) if the row carries a profile kind. */
7110
+ freeFormOnly?: boolean;
7111
+ /**
7112
+ * If provided, updates the memory's scope (and the level it implies; a `profile` row keeps
7113
+ * `profile` under `scope: "shared"`).
7114
+ */
7073
7115
  scope?: string;
7116
+ /** If provided, sets the profile kind (null makes the memory free-form). */
7117
+ kind?: VaultMemoryKind | null;
7118
+ /** If provided, sets the canonical JSON value (null clears it). */
7119
+ kindValue?: string | null;
7120
+ /** If provided, sets the level (and dual-writes `scope`). */
7121
+ level?: MemoryLevel;
7074
7122
  /** If provided, moves the memory to this folder. */
7075
7123
  folderId?: string | null;
7076
7124
  /** JSON-stringified embedding vector to persist, or null to clear stale embedding */
@@ -7210,6 +7258,10 @@ declare function getAllVaultMemoriesOp(ctx: VaultMemoryOperationsContext, option
7210
7258
  * published set to diff against the server index.
7211
7259
  */
7212
7260
  visibility?: VaultMemoryVisibility[];
7261
+ /** Filter by level. */
7262
+ levels?: MemoryLevel[];
7263
+ /** Restrict to these profile kinds. */
7264
+ kinds?: string[];
7213
7265
  }): Promise<StoredVaultMemory[]>;
7214
7266
  /**
7215
7267
  * Return content-free {@link RankableVaultMemory} projections for recall
@@ -7491,7 +7543,8 @@ interface DecayCandidateRaw {
7491
7543
  *
7492
7544
  * Includes archived AND quarantined rows (so archived→delete transitions and
7493
7545
  * aged quarantined rows are seen) but excludes hard-deleted rows — the
7494
- * `baseVaultConditions` default keeps `is_deleted = false`.
7546
+ * `baseVaultConditions` default keeps `is_deleted = false`. Excludes kinded
7547
+ * (profile) memories, which never decay.
7495
7548
  *
7496
7549
  * Refuses to run on an unscoped multi-tenant context (see
7497
7550
  * {@link assertVaultScopeForSweep}).
@@ -9495,8 +9548,8 @@ interface SynthesizeProfileOptions extends PortalLlmAuth {
9495
9548
  * on memories the user approved for publication. Empty intersection → empty
9496
9549
  * section (legitimate no-evidence), not a stale fallback.
9497
9550
  *
9498
- * Pass the user's published set (e.g. `getAllVaultMemoriesOp(ctx, { visibility:
9499
- * ["public"] })`) to keep a published profile derivable only from published
9551
+ * Pass the user's published set (e.g. `getAllVaultMemoriesOp(ctx, { levels:
9552
+ * ["matching", "profile"] })`) to keep a published profile derivable only from published
9500
9553
  * memories — People Nearby's two-tier model treats `private` memories as never
9501
9554
  * leaving the device, and a summary derived from them is a derivative that does.
9502
9555
  *
@@ -10953,4 +11006,4 @@ interface UseChatStorageResult extends BaseUseChatStorageResult {
10953
11006
  */
10954
11007
  declare function useChatStorage(options: UseChatStorageOptions): UseChatStorageResult;
10955
11008
 
10956
- export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationAction, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryListOptions, type MemoryMaintenance, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryUpdate, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryPage, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, formatFileProcessingNotes, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
11009
+ export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationAction, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, type DurableAutoExtractorOptions, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type ExtractionFunnel, type ExtractionTimings, type FactType, type FileMetadata, type FileProcessingReason, type FileProcessingStatus, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type LocalMemoryStoreOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, MEMORY_KINDS, MEMORY_LEVELS, type ManualFactType, type MemoriesNeedingTopicExtraction, type MemoryContextItem, type MemoryContextLane, type MemoryContextOptions, type MemoryContextResult, type MemoryCreate, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryLevel, MemoryLevelError, type MemoryListOptions, type MemoryMaintenance, type MemoryQuarantinedEvent, type MemoryRecallOptions, type MemoryRetainOptions, type MemoryStore, type MemorySubscribeOptions, type MemoryToVerify, type MemoryUpdate, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionMcpCaller, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallEmptyReason, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RemoteMemoryCandidateOptions, type RemoteMemoryDecodeFailure, RemoteMemoryError, type RemoteMemoryListOptions, type RemoteMemoryPage, type RemoteMemoryPersistence, type RemoteMemoryPersistenceOptions, type RemoteMemoryPipeline, type RemoteMemoryPipelineOptions, type RemoteMemoryReadFilters, type RemoteMemoryRecord, type RemoteMemoryRow, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type StreamSmoothingConfig, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TopicSkipReason, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultEmbeddingExpectation, type VaultFolderOperationsContext, type VaultMemoryKind, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultMemoryWriter, type VaultSaveOperation, type VaultSearchResult, type VaultWriteAction, type VaultWriteInput, type VaultWriteOutcome, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, assembleMemoryContext, attachFileContextToLastUserMessage, backfillMemoryTopicsOp, buildAttachedFilesText, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createDurableAutoExtractor, createLlmDecayClassifier, createLlmNeighborRefiner, createLocalMemoryStore, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionProxyTools, createNotionTools, createPlatformCursorStore, createRecallTool, createRemoteMemoryPersistence, createRemoteMemoryPipeline, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteMessageOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, deriveKeyFromSignatureBytes, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, formatFileProcessingNotes, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isAttachedFilesText, isDegradedTopicSkip, isEncrypted, isPiiRedactor, isRerankerAvailable, maskScopedEmbeddingCache, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, shouldRecallMemory, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, stripLegacyChunkTextOp, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -9246,6 +9246,15 @@ __decorateClass([
9246
9246
  __decorateClass([
9247
9247
  text6("scope")
9248
9248
  ], VaultMemory.prototype, "scope", 2);
9249
+ __decorateClass([
9250
+ field5("kind")
9251
+ ], VaultMemory.prototype, "kind", 2);
9252
+ __decorateClass([
9253
+ field5("kind_value")
9254
+ ], VaultMemory.prototype, "kindValue", 2);
9255
+ __decorateClass([
9256
+ field5("level")
9257
+ ], VaultMemory.prototype, "level", 2);
9249
9258
  __decorateClass([
9250
9259
  field5("folder_id")
9251
9260
  ], VaultMemory.prototype, "folderId", 2);
@@ -9471,7 +9480,7 @@ __decorateClass([
9471
9480
  ], VaultFolder.prototype, "context", 2);
9472
9481
 
9473
9482
  // src/lib/db/schema.ts
9474
- var SDK_SCHEMA_VERSION = 47;
9483
+ var SDK_SCHEMA_VERSION = 48;
9475
9484
  var sdkSchema = appSchema2({
9476
9485
  version: SDK_SCHEMA_VERSION,
9477
9486
  tables: [
@@ -9566,6 +9575,9 @@ var sdkSchema = appSchema2({
9566
9575
  columns: [
9567
9576
  { name: "content", type: "string" },
9568
9577
  { name: "scope", type: "string", isIndexed: true },
9578
+ { name: "kind", type: "string", isOptional: true, isIndexed: true },
9579
+ { name: "kind_value", type: "string", isOptional: true },
9580
+ { name: "level", type: "string", isOptional: true, isIndexed: true },
9569
9581
  { name: "folder_id", type: "string", isOptional: true, isIndexed: true },
9570
9582
  { name: "created_at", type: "number", isIndexed: true },
9571
9583
  { name: "updated_at", type: "number", isIndexed: true },
@@ -10242,6 +10254,22 @@ var sdkMigrations = schemaMigrations2({
10242
10254
  ]
10243
10255
  })
10244
10256
  ]
10257
+ },
10258
+ {
10259
+ toVersion: 48,
10260
+ steps: [
10261
+ addColumns2({
10262
+ table: "memory_vault",
10263
+ columns: [
10264
+ { name: "kind", type: "string", isOptional: true, isIndexed: true },
10265
+ { name: "kind_value", type: "string", isOptional: true },
10266
+ { name: "level", type: "string", isOptional: true, isIndexed: true }
10267
+ ]
10268
+ }),
10269
+ unsafeExecuteSql(
10270
+ "UPDATE memory_vault SET level = CASE WHEN scope IN ('shared', 'public') THEN 'matching' ELSE 'private' END WHERE level IS NULL;"
10271
+ )
10272
+ ]
10245
10273
  }
10246
10274
  ]
10247
10275
  });
@@ -10807,13 +10835,54 @@ async function decryptVaultMemoryFields(memory, address, signMessage, embeddedWa
10807
10835
  }
10808
10836
  }
10809
10837
  const decryptedContent = await decryptField(memory.content, address);
10838
+ const decryptedKindValue = typeof memory.kindValue === "string" ? await decryptField(memory.kindValue, address) : memory.kindValue;
10810
10839
  return {
10811
10840
  ...memory,
10812
- content: decryptedContent
10841
+ content: decryptedContent,
10842
+ ...decryptedKindValue !== void 0 && { kindValue: decryptedKindValue }
10813
10843
  };
10814
10844
  }
10815
10845
 
10816
10846
  // src/lib/db/memoryVault/types.ts
10847
+ var MEMORY_KINDS = [
10848
+ "display_name",
10849
+ "birth_date",
10850
+ "bio",
10851
+ "occupation",
10852
+ "interest",
10853
+ "gender",
10854
+ "height_cm",
10855
+ "looking_for",
10856
+ "politics",
10857
+ "religion",
10858
+ "ethnicity",
10859
+ "smoking",
10860
+ "drinking",
10861
+ "exercise",
10862
+ "sexuality",
10863
+ "prompt"
10864
+ ];
10865
+ var MEMORY_LEVELS = ["private", "matching", "profile"];
10866
+ var MemoryLevelError = class extends Error {
10867
+ constructor(message) {
10868
+ super(message);
10869
+ this.name = "MemoryLevelError";
10870
+ }
10871
+ };
10872
+ var PUBLISHED_SCOPES = /* @__PURE__ */ new Set(["shared", "public"]);
10873
+ function levelFromScope(scope) {
10874
+ return typeof scope === "string" && PUBLISHED_SCOPES.has(scope) ? "matching" : "private";
10875
+ }
10876
+ function scopeForLevel(level) {
10877
+ return level === "private" ? "private" : "shared";
10878
+ }
10879
+ function resolveMemoryLevel(level, scope) {
10880
+ return typeof level === "string" && MEMORY_LEVELS.includes(level) ? level : levelFromScope(scope);
10881
+ }
10882
+ function levelForScopeChange(current, nextScope) {
10883
+ const implied = levelFromScope(nextScope);
10884
+ return implied === "matching" && resolveMemoryLevel(current.level, current.scope) === "profile" ? "profile" : implied;
10885
+ }
10817
10886
  function parseMedia(value) {
10818
10887
  if (typeof value !== "string" || value === "") return null;
10819
10888
  try {
@@ -10843,6 +10912,56 @@ function visibilityConditions(requested) {
10843
10912
  if (excluded.length === 0) return [];
10844
10913
  return [Q5.or(Q5.where("visibility", null), Q5.where("visibility", Q5.notIn(excluded)))];
10845
10914
  }
10915
+ function isKinded(record2) {
10916
+ return record2.kind !== null && record2.kind !== void 0;
10917
+ }
10918
+ function assertValidKindLevel(kind, level) {
10919
+ const hasKind = kind !== null && kind !== void 0;
10920
+ if (hasKind && !MEMORY_KINDS.includes(kind)) {
10921
+ throw new MemoryLevelError(`Unknown memory kind: ${kind}`);
10922
+ }
10923
+ if (level !== void 0 && !MEMORY_LEVELS.includes(level)) {
10924
+ throw new MemoryLevelError(`Unknown memory level: ${level}`);
10925
+ }
10926
+ if (level === "profile" && !hasKind) {
10927
+ throw new MemoryLevelError("Only a memory with a kind can be at level 'profile'");
10928
+ }
10929
+ }
10930
+ function resolveCreateLevel(opts) {
10931
+ if (opts.level !== void 0) return { level: opts.level, scope: scopeForLevel(opts.level) };
10932
+ if (opts.scope !== void 0) return { level: levelFromScope(opts.scope), scope: opts.scope };
10933
+ return { level: "private", scope: "private" };
10934
+ }
10935
+ async function encryptKindValue(ctx, value) {
10936
+ if (typeof value !== "string" || !ctx.walletAddress || !ctx.signMessage) return value;
10937
+ return encryptVaultMemoryContent(
10938
+ value,
10939
+ ctx.walletAddress,
10940
+ ctx.signMessage,
10941
+ ctx.embeddedWalletSigner
10942
+ );
10943
+ }
10944
+ function levelConditions(requested) {
10945
+ if (!requested?.length) return [];
10946
+ const published = ["shared", "public"];
10947
+ const wantsMatching = requested.includes("matching");
10948
+ const wantsPrivate = requested.includes("private");
10949
+ const unresolved = Q5.or(Q5.where("level", null), Q5.where("level", Q5.notIn([...MEMORY_LEVELS])));
10950
+ const byLevel = Q5.where("level", Q5.oneOf([...requested]));
10951
+ if (wantsMatching && wantsPrivate) return [Q5.or(byLevel, unresolved)];
10952
+ if (wantsMatching) {
10953
+ return [Q5.or(byLevel, Q5.and(unresolved, Q5.where("scope", Q5.oneOf(published))))];
10954
+ }
10955
+ if (wantsPrivate) {
10956
+ return [
10957
+ Q5.or(
10958
+ byLevel,
10959
+ Q5.and(unresolved, Q5.or(Q5.where("scope", null), Q5.where("scope", Q5.notIn(published))))
10960
+ )
10961
+ ];
10962
+ }
10963
+ return [byLevel];
10964
+ }
10846
10965
  function isOwnedByCtxUser(ctx, record2) {
10847
10966
  return ctx.userId === void 0 || record2.userId === ctx.userId;
10848
10967
  }
@@ -10886,6 +11005,9 @@ function vaultMemoryToStoredRaw(memory) {
10886
11005
  uniqueId: memory.id,
10887
11006
  content: memory.content,
10888
11007
  scope: memory.scope,
11008
+ kind: memory.kind ?? null,
11009
+ kindValue: memory.kindValue ?? null,
11010
+ level: resolveMemoryLevel(memory.level, memory.scope),
10889
11011
  folderId: memory.folderId ?? null,
10890
11012
  userId: memory.userId ?? null,
10891
11013
  embedding: memory.embedding ?? null,
@@ -10924,9 +11046,13 @@ async function vaultMemoryToStored(memory, walletAddress, signMessage, embeddedW
10924
11046
  }
10925
11047
  return raw;
10926
11048
  }
10927
- function populateNewVaultMemory(record2, ctx, opts, encryptedContent) {
11049
+ function populateNewVaultMemory(record2, ctx, opts, encryptedContent, encryptedKindValue) {
11050
+ const { level, scope } = resolveCreateLevel(opts);
10928
11051
  record2._setRaw("content", encryptedContent);
10929
- record2._setRaw("scope", opts.scope ?? "private");
11052
+ record2._setRaw("scope", scope);
11053
+ record2._setRaw("level", level);
11054
+ record2._setRaw("kind", opts.kind ?? null);
11055
+ record2._setRaw("kind_value", encryptedKindValue ?? null);
10930
11056
  record2._setRaw("folder_id", opts.folderId ?? null);
10931
11057
  record2._setRaw("user_id", ctx.userId ?? null);
10932
11058
  record2._setRaw("is_deleted", false);
@@ -10960,6 +11086,8 @@ function populateNewVaultMemory(record2, ctx, opts, encryptedContent) {
10960
11086
  }
10961
11087
  }
10962
11088
  async function createVaultMemoryOp(ctx, opts) {
11089
+ assertValidKindLevel(opts.kind, resolveCreateLevel(opts).level);
11090
+ const encryptedKindValue = await encryptKindValue(ctx, opts.kindValue);
10963
11091
  const encryptedContent = ctx.walletAddress && ctx.signMessage ? await encryptVaultMemoryContent(
10964
11092
  opts.content,
10965
11093
  ctx.walletAddress,
@@ -10970,13 +11098,15 @@ async function createVaultMemoryOp(ctx, opts) {
10970
11098
  if (ctx.canWrite && !await ctx.canWrite())
10971
11099
  throw new Error("Memory source is no longer eligible");
10972
11100
  return ctx.vaultMemoryCollection.create(
10973
- (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContent)
11101
+ (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContent, encryptedKindValue)
10974
11102
  );
10975
11103
  });
10976
11104
  return vaultMemoryToStored(created, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner);
10977
11105
  }
10978
11106
  async function createSupersedingMemoryOp(ctx, opts, targetId) {
10979
11107
  if (!targetId) return { created: null, retired: false };
11108
+ assertValidKindLevel(opts.kind, resolveCreateLevel(opts).level);
11109
+ const encryptedKindValue = await encryptKindValue(ctx, opts.kindValue);
10980
11110
  const encryptedContent = ctx.walletAddress && ctx.signMessage ? await encryptVaultMemoryContent(
10981
11111
  opts.content,
10982
11112
  ctx.walletAddress,
@@ -10993,9 +11123,10 @@ async function createSupersedingMemoryOp(ctx, opts, targetId) {
10993
11123
  } catch {
10994
11124
  return;
10995
11125
  }
10996
- if (target.isDeleted || target.supersededBy || !isOwnedByCtxUser(ctx, target)) return;
11126
+ if (target.isDeleted || target.supersededBy || isKinded(target) || !isOwnedByCtxUser(ctx, target))
11127
+ return;
10997
11128
  createdRecord = await ctx.vaultMemoryCollection.create(
10998
- (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContent)
11129
+ (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContent, encryptedKindValue)
10999
11130
  );
11000
11131
  await target.update((r) => {
11001
11132
  r._setRaw("superseded_by", createdRecord.id);
@@ -11059,6 +11190,10 @@ async function getMemoriesByEventTimeOp(ctx, windowStart, windowEnd) {
11059
11190
  }
11060
11191
  async function createVaultMemoriesBatchOp(ctx, optionsArray) {
11061
11192
  if (optionsArray.length === 0) return [];
11193
+ for (const opts of optionsArray) assertValidKindLevel(opts.kind, resolveCreateLevel(opts).level);
11194
+ const encryptedKindValues = await Promise.all(
11195
+ optionsArray.map((opts) => encryptKindValue(ctx, opts.kindValue))
11196
+ );
11062
11197
  const encryptedContents = await Promise.all(
11063
11198
  optionsArray.map(async (opts) => {
11064
11199
  if (ctx.walletAddress && ctx.signMessage) {
@@ -11077,7 +11212,7 @@ async function createVaultMemoriesBatchOp(ctx, optionsArray) {
11077
11212
  throw new Error("Memory source is no longer eligible");
11078
11213
  const prepared = optionsArray.map(
11079
11214
  (opts, i) => ctx.vaultMemoryCollection.prepareCreate(
11080
- (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContents[i])
11215
+ (record2) => populateNewVaultMemory(record2, ctx, opts, encryptedContents[i], encryptedKindValues[i])
11081
11216
  )
11082
11217
  );
11083
11218
  await ctx.database.batch(...prepared);
@@ -11120,6 +11255,9 @@ function vaultMemoryRawToStoredRaw(raw) {
11120
11255
  uniqueId: raw.id,
11121
11256
  content: raw.content ?? "",
11122
11257
  scope: raw.scope ?? "",
11258
+ kind: raw.kind ?? null,
11259
+ kindValue: raw.kind_value ?? null,
11260
+ level: resolveMemoryLevel(raw.level, raw.scope),
11123
11261
  folderId: raw.folder_id ?? null,
11124
11262
  userId: raw.user_id ?? null,
11125
11263
  embedding: raw.embedding ?? null,
@@ -11163,6 +11301,8 @@ async function getAllVaultMemoriesOp(ctx, options) {
11163
11301
  ...baseVaultConditions(ctx, options),
11164
11302
  ...options?.scopes?.length ? [Q5.where("scope", Q5.oneOf(options.scopes))] : [],
11165
11303
  ...visibilityConditions(options?.visibility),
11304
+ ...levelConditions(options?.levels),
11305
+ ...options?.kinds?.length ? [Q5.where("kind", Q5.oneOf(options.kinds))] : [],
11166
11306
  ...options?.folderId !== void 0 ? [Q5.where("folder_id", options.folderId)] : [],
11167
11307
  ...options?.factTypes?.length ? [Q5.where("fact_type", Q5.oneOf(options.factTypes))] : [],
11168
11308
  Q5.sortBy(options?.since ? "updated_at" : "created_at", Q5.desc),
@@ -11329,6 +11469,14 @@ async function updateVaultMemoryOp(ctx, id, opts) {
11329
11469
  try {
11330
11470
  const probe = await ctx.vaultMemoryCollection.find(id);
11331
11471
  if (probe.isDeleted || probe.supersededBy || !isOwnedByCtxUser(ctx, probe)) return null;
11472
+ if (opts.freeFormOnly && isKinded(probe)) return null;
11473
+ const levelAfter = (current) => {
11474
+ if (opts.level !== void 0) return opts.level;
11475
+ if (opts.scope === void 0) return resolveMemoryLevel(current.level, current.scope);
11476
+ return levelForScopeChange(current, opts.scope);
11477
+ };
11478
+ assertValidKindLevel(opts.kind !== void 0 ? opts.kind : probe.kind, levelAfter(probe));
11479
+ const encryptedKindValue = await encryptKindValue(ctx, opts.kindValue);
11332
11480
  const encryptedContent = ctx.walletAddress && ctx.signMessage ? await encryptVaultMemoryContent(
11333
11481
  opts.content,
11334
11482
  ctx.walletAddress,
@@ -11341,10 +11489,13 @@ async function updateVaultMemoryOp(ctx, id, opts) {
11341
11489
  await ctx.database.write(async () => {
11342
11490
  if (ctx.canWrite && !await ctx.canWrite())
11343
11491
  throw new Error("Memory source is no longer eligible");
11344
- if (record2.isDeleted || record2.supersededBy || !isOwnedByCtxUser(ctx, record2)) {
11492
+ if (record2.isDeleted || record2.supersededBy || !isOwnedByCtxUser(ctx, record2) || opts.freeFormOnly && isKinded(record2)) {
11345
11493
  stale = true;
11346
11494
  return;
11347
11495
  }
11496
+ const nextKind = opts.kind !== void 0 ? opts.kind : record2.kind;
11497
+ const nextLevel = levelAfter(record2);
11498
+ assertValidKindLevel(nextKind, nextLevel);
11348
11499
  let observedSources = [];
11349
11500
  let replayedObservation = false;
11350
11501
  if (opts.observationSourceIds?.length) {
@@ -11358,8 +11509,18 @@ async function updateVaultMemoryOp(ctx, id, opts) {
11358
11509
  }
11359
11510
  await record2.update((r) => {
11360
11511
  r._setRaw("content", encryptedContent);
11361
- if (opts.scope !== void 0) {
11512
+ if (opts.level !== void 0) {
11513
+ r._setRaw("level", nextLevel);
11514
+ r._setRaw("scope", scopeForLevel(nextLevel));
11515
+ } else if (opts.scope !== void 0) {
11362
11516
  r._setRaw("scope", opts.scope);
11517
+ r._setRaw("level", nextLevel);
11518
+ }
11519
+ if (opts.kind !== void 0) {
11520
+ r._setRaw("kind", opts.kind);
11521
+ }
11522
+ if (encryptedKindValue !== void 0) {
11523
+ r._setRaw("kind_value", encryptedKindValue);
11363
11524
  }
11364
11525
  if (opts.folderId !== void 0) {
11365
11526
  r._setRaw("folder_id", opts.folderId);
@@ -11418,7 +11579,8 @@ async function updateVaultMemoryOp(ctx, id, opts) {
11418
11579
  ctx.signMessage,
11419
11580
  ctx.embeddedWalletSigner
11420
11581
  );
11421
- } catch {
11582
+ } catch (err) {
11583
+ if (err instanceof MemoryLevelError) throw err;
11422
11584
  return null;
11423
11585
  }
11424
11586
  }
@@ -11554,6 +11716,7 @@ async function supersedeVaultMemoryOp(ctx, id, supersededById) {
11554
11716
  try {
11555
11717
  const record2 = await ctx.vaultMemoryCollection.find(id);
11556
11718
  if (record2.isDeleted || record2.supersededBy || !isOwnedByCtxUser(ctx, record2)) return false;
11719
+ if (isKinded(record2)) return false;
11557
11720
  let successor;
11558
11721
  try {
11559
11722
  successor = await ctx.vaultMemoryCollection.find(supersededById);
@@ -11854,7 +12017,10 @@ function assertVaultScopeForSweep(ctx) {
11854
12017
  }
11855
12018
  async function getDecayCandidatesRawOp(ctx) {
11856
12019
  assertVaultScopeForSweep(ctx);
11857
- const results = await ctx.vaultMemoryCollection.query(...baseVaultConditions(ctx, { includeArchived: true, includeQuarantined: true })).unsafeFetchRaw();
12020
+ const results = await ctx.vaultMemoryCollection.query(
12021
+ ...baseVaultConditions(ctx, { includeArchived: true, includeQuarantined: true }),
12022
+ Q5.where("kind", null)
12023
+ ).unsafeFetchRaw();
11858
12024
  return results.map((raw) => ({
11859
12025
  uniqueId: raw.id,
11860
12026
  factType: raw.fact_type ?? null,
@@ -12114,6 +12280,7 @@ async function ingestPublishedPhotoMemoriesOp(ctx, rows) {
12114
12280
  record2._raw.id = row.memoryId;
12115
12281
  record2._setRaw("content", content);
12116
12282
  record2._setRaw("scope", "shared");
12283
+ record2._setRaw("level", "matching");
12117
12284
  record2._setRaw("folder_id", null);
12118
12285
  record2._setRaw("user_id", ctx.userId ?? null);
12119
12286
  record2._setRaw("is_deleted", false);
@@ -12522,6 +12689,7 @@ async function updateVaultFolderOp(ctx, id, opts) {
12522
12689
  for (const memory of memories) {
12523
12690
  updates.push(
12524
12691
  memory.prepareUpdate((r) => {
12692
+ r._setRaw("level", levelForScopeChange(r, opts.scope));
12525
12693
  r._setRaw("scope", opts.scope);
12526
12694
  })
12527
12695
  );
@@ -12543,6 +12711,7 @@ async function deleteVaultFolderOp(ctx, id) {
12543
12711
  const preparedMemories = memories.map(
12544
12712
  (memory) => memory.prepareUpdate((r) => {
12545
12713
  r._setRaw("folder_id", null);
12714
+ r._setRaw("level", levelForScopeChange(r, "private"));
12546
12715
  r._setRaw("scope", "private");
12547
12716
  })
12548
12717
  );
@@ -12579,6 +12748,7 @@ async function moveMemoriesToFolderOp(ctx, memoryIds, folderId) {
12579
12748
  const prepared = memories.map(
12580
12749
  (memory) => memory.prepareUpdate((r) => {
12581
12750
  r._setRaw("folder_id", folderId);
12751
+ r._setRaw("level", levelForScopeChange(r, targetScope));
12582
12752
  r._setRaw("scope", targetScope);
12583
12753
  })
12584
12754
  );
@@ -14886,6 +15056,7 @@ async function retainWithPersistence(content, ctx, options = {}) {
14886
15056
  includeArchived: true,
14887
15057
  ...options.folderId !== void 0 && { folderId: options.folderId }
14888
15058
  });
15059
+ prepared = withoutKindedRows(prepared);
14889
15060
  if (prepared.embeddingFailure || prepared.embeddingsUnavailable) {
14890
15061
  throw new Error(
14891
15062
  "retain: embeddings unavailable \u2014 refusing to auto-merge against an inert cosine lane, which would create a duplicate instead of merging into the existing memory. Retry when embeddings recover, or pass enableAutoMerge: false to force a create."
@@ -14927,6 +15098,7 @@ async function retainWithPersistence(content, ctx, options = {}) {
14927
15098
  const resurrect = resurrectFields(existing);
14928
15099
  const updated = await ctx.persistence.update(targetId, {
14929
15100
  content: existing.content,
15101
+ freeFormOnly: true,
14930
15102
  proofCountIncrement: 1,
14931
15103
  observationSourceIds: options.sourceChunkIds,
14932
15104
  sourceChunkIds: mergedSourceIds,
@@ -15055,6 +15227,17 @@ async function retainWithPersistence(content, ctx, options = {}) {
15055
15227
  ...consolidationDecidedCreate && { consolidation: "create" }
15056
15228
  };
15057
15229
  }
15230
+ function withoutKindedRows(prepared) {
15231
+ const kinded = new Set(
15232
+ prepared.memories.filter((m) => m.kind !== null && m.kind !== void 0).map((m) => m.uniqueId)
15233
+ );
15234
+ if (kinded.size === 0) return prepared;
15235
+ return {
15236
+ ...prepared,
15237
+ memories: prepared.memories.filter((m) => !kinded.has(m.uniqueId)),
15238
+ embeddedItems: prepared.embeddedItems.filter((item) => !kinded.has(item.id))
15239
+ };
15240
+ }
15058
15241
  function unionStrings(a, b) {
15059
15242
  return [.../* @__PURE__ */ new Set([...a, ...b])];
15060
15243
  }
@@ -15154,6 +15337,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
15154
15337
  const resurrect = resurrectFields(existing);
15155
15338
  const updated = await ctx.persistence.update(decision.targetId, {
15156
15339
  content: existing.content,
15340
+ freeFormOnly: true,
15157
15341
  proofCountIncrement: 1,
15158
15342
  observationSourceIds: options.sourceChunkIds,
15159
15343
  sourceChunkIds: mergedSourceIds,
@@ -15199,6 +15383,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
15199
15383
  const resurrect = resurrectFields(existing);
15200
15384
  const updated = await ctx.persistence.update(decision.targetId, {
15201
15385
  content: decision.content,
15386
+ freeFormOnly: true,
15202
15387
  proofCountIncrement: 1,
15203
15388
  observationSourceIds: options.sourceChunkIds,
15204
15389
  sourceChunkIds: mergedSourceIds,
@@ -15242,7 +15427,7 @@ async function tryConsolidate(trimmed, ctx, options, prepared) {
15242
15427
  }
15243
15428
  async function assertMergeTargetGoneOrThrow(ctx, targetId) {
15244
15429
  const stillExists = await (ctx.persistence.getFresh ? ctx.persistence.getFresh(targetId) : ctx.persistence.get(targetId));
15245
- if (stillExists) {
15430
+ if (stillExists && (stillExists.kind === null || stillExists.kind === void 0)) {
15246
15431
  throw new Error(`retain: merge into memory ${targetId} failed to persist`);
15247
15432
  }
15248
15433
  }
@@ -18294,6 +18479,9 @@ function sourceIds(value) {
18294
18479
  return [];
18295
18480
  }
18296
18481
  }
18482
+ function isMemoryLevel(value) {
18483
+ return MEMORY_LEVELS.includes(value);
18484
+ }
18297
18485
  function stored(row) {
18298
18486
  return {
18299
18487
  uniqueId: row.memory_id,
@@ -18301,6 +18489,9 @@ function stored(row) {
18301
18489
  scope: row.scope,
18302
18490
  folderId: row.folder_id ?? null,
18303
18491
  userId: null,
18492
+ kind: row.kind ?? null,
18493
+ kindValue: row.kind_value ?? null,
18494
+ ...isMemoryLevel(row.level) && { level: row.level },
18304
18495
  embedding: row.embedding ? JSON.stringify(row.embedding) : null,
18305
18496
  embeddingModel: row.embedding_model ?? null,
18306
18497
  sourceChunkIds: row.source_chunk_ids === void 0 ? null : sourceIds(row.source_chunk_ids),
@@ -18522,7 +18713,8 @@ function createRemoteMemoryPipeline(options) {
18522
18713
  create: (input) => write(createRow(input), 0),
18523
18714
  update: async (id, patch) => {
18524
18715
  const existing = await get(id);
18525
- if (!existing) return null;
18716
+ if (!existing || patch.freeFormOnly && existing.kind !== null && existing.kind !== void 0)
18717
+ return null;
18526
18718
  const snapshot = snapshots.get(id);
18527
18719
  const memory = {
18528
18720
  ...snapshot.memory,
@@ -24703,6 +24895,9 @@ export {
24703
24895
  LoggerProvider,
24704
24896
  MAX_HOPS,
24705
24897
  MEDIUM_TTL_MS,
24898
+ MEMORY_KINDS,
24899
+ MEMORY_LEVELS,
24900
+ MemoryLevelError,
24706
24901
  NEVER_TTL_MS,
24707
24902
  NODE_BUDGET,
24708
24903
  NOTION_OAUTH_CONFIG,