@jungjaehoon/mama-core 1.7.0 → 1.9.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.
@@ -18,6 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.PORT_FILE = exports.HOST = exports.DEFAULT_PORT = exports.SHUTDOWN_TOKEN = void 0;
21
+ exports.resolveEmbeddingRole = resolveEmbeddingRole;
21
22
  exports.cleanupPortFile = cleanupPortFile;
22
23
  exports.startEmbeddingServer = startEmbeddingServer;
23
24
  exports.warmModel = warmModel;
@@ -63,6 +64,11 @@ const connections = new Set();
63
64
  // Graph handler (optional, passed from standalone)
64
65
  let graphHandler = null;
65
66
  let _wssInstance = null;
67
+ // Resolve the e5 role from an HTTP body value. Absent/unknown -> passage, so old
68
+ // clients that never send a role keep getting passage vectors (backward compatible).
69
+ function resolveEmbeddingRole(raw) {
70
+ return raw === 'query' ? 'query' : 'passage';
71
+ }
66
72
  /**
67
73
  * Read request body as JSON
68
74
  */
@@ -158,7 +164,8 @@ async function handleRequest(req, res) {
158
164
  res.end(JSON.stringify({ error: 'Missing or invalid "text" field' }));
159
165
  return;
160
166
  }
161
- const embedding = await (0, embeddings_js_1.generateEmbedding)(body.text);
167
+ const role = resolveEmbeddingRole(body.role);
168
+ const embedding = await (0, embeddings_js_1.generateEmbedding)(body.text, role);
162
169
  modelLoaded = true;
163
170
  const latency = Date.now() - startTime;
164
171
  res.writeHead(200);
@@ -186,7 +193,8 @@ async function handleRequest(req, res) {
186
193
  res.end(JSON.stringify({ error: 'Missing or invalid "texts" array' }));
187
194
  return;
188
195
  }
189
- const embeddings = await Promise.all(body.texts.map((text) => (0, embeddings_js_1.generateEmbedding)(text).then((e) => Array.from(e))));
196
+ const role = resolveEmbeddingRole(body.role);
197
+ const embeddings = await Promise.all(body.texts.map((text) => (0, embeddings_js_1.generateEmbedding)(text, role).then((e) => Array.from(e))));
190
198
  modelLoaded = true;
191
199
  const latency = Date.now() - startTime;
192
200
  res.writeHead(200);
@@ -13,6 +13,8 @@ import { embeddingCache } from './embedding-cache.js';
13
13
  import { loadConfig, getModelName, getEmbeddingDim, getQuantized } from './config-loader.js';
14
14
  export declare const EMBEDDING_MODEL_MAX_LENGTH = 512;
15
15
  export declare const EMBEDDING_MAX_TOKENISH_SEGMENTS = 480;
16
+ export type EmbeddingRole = 'passage' | 'query';
17
+ export declare const EMBEDDING_PREFIX_SCHEME = "e5-prefixed-v1";
16
18
  export declare function prepareEmbeddingText(text: string): string;
17
19
  /**
18
20
  * Decision object for enhanced embedding generation
@@ -38,7 +40,7 @@ export interface DecisionForEmbedding {
38
40
  * @returns Embedding vector (dimension from config)
39
41
  * @throws Error if text is empty or embedding fails
40
42
  */
41
- export declare function generateEmbedding(text: string): Promise<Float32Array>;
43
+ export declare function generateEmbedding(text: string, role?: EmbeddingRole): Promise<Float32Array>;
42
44
  /**
43
45
  * Generate enhanced embedding with content + metadata
44
46
  *
@@ -48,7 +50,7 @@ export declare function generateEmbedding(text: string): Promise<Float32Array>;
48
50
  * @param decision - Decision object
49
51
  * @returns 1024-dim enhanced embedding
50
52
  */
51
- export declare function generateEnhancedEmbedding(decision: DecisionForEmbedding): Promise<Float32Array>;
53
+ export declare function generateEnhancedEmbedding(decision: DecisionForEmbedding, role?: EmbeddingRole): Promise<Float32Array>;
52
54
  /**
53
55
  * Batch generate embeddings (optimized)
54
56
  *
@@ -60,7 +62,7 @@ export declare function generateEnhancedEmbedding(decision: DecisionForEmbedding
60
62
  * @param texts - Array of texts to embed (max 10 per batch)
61
63
  * @returns Array of embeddings
62
64
  */
63
- export declare function generateBatchEmbeddings(texts: string[]): Promise<Float32Array[]>;
65
+ export declare function generateBatchEmbeddings(texts: string[], role?: EmbeddingRole): Promise<Float32Array[]>;
64
66
  /**
65
67
  * Calculate cosine similarity between two embeddings
66
68
  *
@@ -14,7 +14,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.getQuantized = exports.getEmbeddingDim = exports.getModelName = exports.loadConfig = exports.MODEL_NAME = exports.EMBEDDING_DIM = exports.embeddingCache = exports.EMBEDDING_MAX_TOKENISH_SEGMENTS = exports.EMBEDDING_MODEL_MAX_LENGTH = void 0;
17
+ exports.getQuantized = exports.getEmbeddingDim = exports.getModelName = exports.loadConfig = exports.MODEL_NAME = exports.EMBEDDING_DIM = exports.embeddingCache = exports.EMBEDDING_PREFIX_SCHEME = exports.EMBEDDING_MAX_TOKENISH_SEGMENTS = exports.EMBEDDING_MODEL_MAX_LENGTH = void 0;
18
18
  exports.prepareEmbeddingText = prepareEmbeddingText;
19
19
  exports.generateEmbedding = generateEmbedding;
20
20
  exports.generateEnhancedEmbedding = generateEnhancedEmbedding;
@@ -36,6 +36,10 @@ const DEFAULT_CACHE_DIR = path_1.default.join(os_1.default.homedir(), '.cache',
36
36
  const TIER3_ENV_VALUES = new Set(['1', 'true', 'yes']);
37
37
  exports.EMBEDDING_MODEL_MAX_LENGTH = 512;
38
38
  exports.EMBEDDING_MAX_TOKENISH_SEGMENTS = 480;
39
+ exports.EMBEDDING_PREFIX_SCHEME = 'e5-prefixed-v1';
40
+ function applyRolePrefix(preparedText, role) {
41
+ return `${role}: ${preparedText}`;
42
+ }
39
43
  const TOKENISH_SEGMENT_PATTERN = /[\p{Script=Hangul}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|\S+/gu;
40
44
  // Singleton pattern for model loading
41
45
  let embeddingPipeline = null;
@@ -128,14 +132,15 @@ async function loadModel() {
128
132
  * @returns Embedding vector (dimension from config)
129
133
  * @throws Error if text is empty or embedding fails
130
134
  */
131
- async function generateEmbedding(text) {
135
+ async function generateEmbedding(text, role = 'passage') {
132
136
  if (typeof text !== 'string' || text.trim().length === 0) {
133
137
  throw new Error('Text cannot be empty');
134
138
  }
135
139
  assertEmbeddingsEnabled();
136
140
  const preparedText = prepareEmbeddingText(text);
137
- // Task 2: Check cache first (AC #3)
138
- const cached = embedding_cache_js_1.embeddingCache.get(preparedText);
141
+ const modelInput = applyRolePrefix(preparedText, role); // e5 instruction prefix
142
+ // Cache key is the PREFIXED input: a passage vector can never be served for a query.
143
+ const cached = embedding_cache_js_1.embeddingCache.get(modelInput);
139
144
  if (cached) {
140
145
  return cached;
141
146
  }
@@ -144,7 +149,7 @@ async function generateEmbedding(text) {
144
149
  const model = await loadModel();
145
150
  const expectedDim = (0, config_loader_js_1.getEmbeddingDim)();
146
151
  // Generate embedding
147
- const output = await model(preparedText, {
152
+ const output = await model(modelInput, {
148
153
  pooling: 'mean', // Mean pooling over tokens
149
154
  normalize: true, // L2 normalization
150
155
  truncation: true,
@@ -159,7 +164,7 @@ async function generateEmbedding(text) {
159
164
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
160
165
  const _latency = Date.now() - startTime;
161
166
  // Task 2: Store in cache (AC #3)
162
- embedding_cache_js_1.embeddingCache.set(preparedText, embedding);
167
+ embedding_cache_js_1.embeddingCache.set(modelInput, embedding);
163
168
  return embedding;
164
169
  }
165
170
  catch (error) {
@@ -176,7 +181,7 @@ async function generateEmbedding(text) {
176
181
  * @param decision - Decision object
177
182
  * @returns 1024-dim enhanced embedding
178
183
  */
179
- async function generateEnhancedEmbedding(decision) {
184
+ async function generateEnhancedEmbedding(decision, role = 'passage') {
180
185
  // Construct enriched text representation with narrative fields (Story 2.2)
181
186
  const parts = [
182
187
  `Topic: ${decision.topic}`,
@@ -207,7 +212,7 @@ async function generateEnhancedEmbedding(decision) {
207
212
  parts.push(`Risks: ${decision.risks}`);
208
213
  }
209
214
  const enrichedText = parts.join('\n').trim();
210
- return generateEmbedding(enrichedText);
215
+ return generateEmbedding(enrichedText, role);
211
216
  }
212
217
  /**
213
218
  * Batch generate embeddings (optimized)
@@ -220,7 +225,7 @@ async function generateEnhancedEmbedding(decision) {
220
225
  * @param texts - Array of texts to embed (max 10 per batch)
221
226
  * @returns Array of embeddings
222
227
  */
223
- async function generateBatchEmbeddings(texts) {
228
+ async function generateBatchEmbeddings(texts, role = 'passage') {
224
229
  if (!Array.isArray(texts) || texts.length === 0) {
225
230
  throw new Error('Texts must be a non-empty array');
226
231
  }
@@ -236,13 +241,14 @@ async function generateBatchEmbeddings(texts) {
236
241
  throw new Error('All texts must be non-empty strings');
237
242
  }
238
243
  }
244
+ const modelInputs = preparedTexts.map((t) => applyRolePrefix(t, role));
239
245
  const startTime = Date.now();
240
246
  try {
241
247
  const model = await loadModel();
242
248
  const expectedDim = (0, config_loader_js_1.getEmbeddingDim)();
243
249
  // Native batch processing - single model forward pass
244
250
  // This is significantly faster than sequential calls
245
- const outputs = await model(preparedTexts, {
251
+ const outputs = await model(modelInputs, {
246
252
  pooling: 'mean',
247
253
  normalize: true,
248
254
  truncation: true,
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * @module mama-core
8
8
  * @version 1.0.0
9
9
  */
10
- export { generateEmbedding, generateEnhancedEmbedding, generateBatchEmbeddings, cosineSimilarity, embeddingCache, EMBEDDING_DIM, MODEL_NAME, } from './embeddings.js';
10
+ export { generateEmbedding, generateEnhancedEmbedding, generateBatchEmbeddings, cosineSimilarity, embeddingCache, EMBEDDING_DIM, MODEL_NAME, EMBEDDING_PREFIX_SCHEME, type EmbeddingRole, } from './embeddings.js';
11
11
  export { EmbeddingCache } from './embedding-cache.js';
12
12
  export { getEmbeddingFromServer, getServerStatus, isServerRunning, getServerPort, DEFAULT_PORT, HOST, TIMEOUT_MS, type ServerStatus, } from './embedding-client.js';
13
13
  export { initDB, getDB, getAdapter, closeDB, insertEmbedding, vectorSearch, queryVectorSearch, insertDecisionWithEmbedding, queryDecisionGraph, querySemanticEdges, updateDecisionOutcome, getPreparedStmt, getDbPath, fts5Search, reindexEmbeddings, type DatabaseAdapter as DBManagerAdapter, type PreparedStatement, type DecisionRecord, type OutcomeData, type VectorSearchParams, type SemanticEdges, type SemanticEdgeItem, type DecisionInput, } from './db-manager.js';
@@ -16,7 +16,7 @@ export { getSessionDecisions, incrementUsageSuccess, incrementUsageFailure, getD
16
16
  import mama from './mama-api.js';
17
17
  export { mama };
18
18
  export { MEMORY_SCOPE_KINDS, MEMORY_KINDS, MEMORY_STATUSES, MEMORY_EDGE_TYPES, createEmptyRecallBundle, type MemoryScopeKind, type MemoryKind, type MemoryStatus, type MemoryEdgeType, type MemoryScopeRef, type MemorySourceRef, type MemoryRecord, type MemoryWriteProvenance, type MemoryProvenanceRecord, type PublicSaveMemoryInput, type PublicIngestMemoryInput, type PublicIngestConversationInput, type MemorySearchResultHit, type MemoryEdge, type ProfileSnapshot, type RecallBundle, type ConversationMessage, type IngestConversationInput, type ExtractedMemoryUnit, type IngestConversationResult, } from './memory/types.js';
19
- export { saveMemory, saveMemoryWithTrustedProvenance, recallMemory, buildProfile, ingestMemory, ingestWithTrustedProvenance, evolveMemory, buildMemoryBootstrap, createAuditAck, recordMemoryAudit, ingestConversation, ingestConversationWithTrustedProvenance, setExtractionFn, upsertChannelSummary, getChannelSummary, } from './memory/api.js';
19
+ export { saveMemory, saveMemoryWithTrustedProvenance, promoteMemoryStatus, recallMemory, buildProfile, ingestMemory, ingestWithTrustedProvenance, evolveMemory, buildMemoryBootstrap, createAuditAck, recordMemoryAudit, ingestConversation, ingestConversationWithTrustedProvenance, setExtractionFn, upsertChannelSummary, getChannelSummary, } from './memory/api.js';
20
20
  export { buildExtractionPrompt, parseExtractionResponse } from './memory/extraction-prompt.js';
21
21
  export { appendMemoryEvent, insertMemoryEventInTransaction, listMemoryEventsForMemory, listRecentMemoryEvents, } from './memory/event-store.js';
22
22
  export { createTrustedProvenanceCapability, assertTrustedProvenanceCapability, type TrustedProvenanceCapability, type TrustedMemoryWriteOptions, } from './memory/provenance.js';
@@ -30,6 +30,7 @@ export { TWIN_EDGE_SOURCES, TWIN_EDGE_TYPES, TWIN_REF_KINDS, type InsertTwinEdge
30
30
  export { getTwinEdge, insertTwinEdge, listTwinEdgesForRefs, mapTwinEdgeRow, } from './edges/store.js';
31
31
  export { assertTwinRefsVisibleToScopes, listVisibleTwinEdgesForRefs, } from './edges/ref-validation.js';
32
32
  export * from './context-compile/index.js';
33
+ export * from './provenance/source-ref.js';
33
34
  export * from './agent-situation/index.js';
34
35
  export * from './agent-graph/index.js';
35
36
  export * from './entities/types.js';
package/dist/index.js CHANGED
@@ -26,10 +26,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.saveMemoryWithTrustedProvenance = exports.saveMemory = exports.createEmptyRecallBundle = exports.MEMORY_EDGE_TYPES = exports.MEMORY_STATUSES = exports.MEMORY_KINDS = exports.MEMORY_SCOPE_KINDS = exports.mama = exports.DEFAULT_DB_PATH = exports.LEGACY_DB_PATH = exports.DB_DIR = exports.DB_PATH = exports.traverseDecisionChain = exports.getDecisionById = exports.incrementUsageFailure = exports.incrementUsageSuccess = exports.getSessionDecisions = exports.SQLiteAdapter = exports.DatabaseAdapter = exports.createAdapter = exports.reindexEmbeddings = exports.fts5Search = exports.getDbPath = exports.getPreparedStmt = exports.updateDecisionOutcome = exports.querySemanticEdges = exports.queryDecisionGraph = exports.insertDecisionWithEmbedding = exports.queryVectorSearch = exports.vectorSearch = exports.insertEmbedding = exports.closeDB = exports.getAdapter = exports.getDB = exports.initDB = exports.TIMEOUT_MS = exports.HOST = exports.DEFAULT_PORT = exports.getServerPort = exports.isServerRunning = exports.getServerStatus = exports.getEmbeddingFromServer = exports.EmbeddingCache = exports.MODEL_NAME = exports.EMBEDDING_DIM = exports.embeddingCache = exports.cosineSimilarity = exports.generateBatchEmbeddings = exports.generateEnhancedEmbedding = exports.generateEmbedding = void 0;
30
- exports.canonicalizeJSON = exports.listVisibleTwinEdgesForRefs = exports.assertTwinRefsVisibleToScopes = exports.mapTwinEdgeRow = exports.listTwinEdgesForRefs = exports.insertTwinEdge = exports.getTwinEdge = exports.TWIN_REF_KINDS = exports.TWIN_EDGE_TYPES = exports.TWIN_EDGE_SOURCES = exports.listToolTracesForRun = exports.appendToolTrace = exports.getModelRunInAdapter = exports.getModelRun = exports.failModelRunInAdapter = exports.failModelRun = exports.commitModelRunInAdapter = exports.commitModelRun = exports.beginModelRunInAdapter = exports.beginModelRun = exports.MODEL_RUN_STATUSES = exports.listMemoryProvenanceAudit = exports.getMemoryProvenanceAudit = exports.backfillConnectorEventScopeMetadata = exports.backfillLegacyMemoryProvenance = exports.listMemoriesByModelRunId = exports.listMemoriesByGatewayCallId = exports.listMemoriesByEnvelopeHash = exports.getMemoryProvenance = exports.assertTrustedProvenanceCapability = exports.createTrustedProvenanceCapability = exports.listRecentMemoryEvents = exports.listMemoryEventsForMemory = exports.insertMemoryEventInTransaction = exports.appendMemoryEvent = exports.parseExtractionResponse = exports.buildExtractionPrompt = exports.getChannelSummary = exports.upsertChannelSummary = exports.setExtractionFn = exports.ingestConversationWithTrustedProvenance = exports.ingestConversation = exports.recordMemoryAudit = exports.createAuditAck = exports.buildMemoryBootstrap = exports.evolveMemory = exports.ingestWithTrustedProvenance = exports.ingestMemory = exports.buildProfile = exports.recallMemory = void 0;
31
- exports.DatabaseError = exports.ValidationError = exports.NotFoundError = exports.MAMAError = exports.formatTimeAgo = exports.DebugLogger = exports.error = exports.warn = exports.info = exports.debug = exports.logSearching = exports.logLoading = exports.logInfo = exports.logError = exports.logFailed = exports.logComplete = exports.logProgress = exports.getTierBanner = exports.getTierDescription = exports.checkDatabase = exports.checkEmbeddings = exports.checkSQLite = exports.checkNodeVersion = exports.validateTier = exports.VALID_EDGE_TYPES = exports.updateConfidence = exports.getSupersededChainDepth = exports.createEdgesFromReasoning = exports.parseReasoningForRelationships = exports.detectRefinement = exports.calculateCombinedConfidence = exports.markSuperseded = exports.createSupersedesEdge = exports.createEdge = exports.getPreviousDecision = exports.generateDecisionId = exports.learnDecision = exports.testRelevanceScoring = exports.formatTopNContext = exports.selectTopDecisions = exports.calculateRelevance = exports.DEFAULT_CONFIG = exports.getConfigPath = exports.updateConfig = exports.getCacheDir = exports.getEmbeddingDim = exports.getModelName = exports.loadConfig = exports.CanonicalizeError = exports.targetRefHash = void 0;
32
- exports.notifyInsight = exports.FALLBACK_MODEL = exports.DEFAULT_MODEL = exports.listModels = exports.isAvailable = exports.analyzeQueryIntent = exports.analyzeDecision = exports.generate = exports.extractTopicKeywords = exports.analyzeIntent = exports.injectDecisionContext = exports.RECENT_WINDOW_MS = exports.PARTIAL_INDICATORS = exports.SUCCESS_INDICATORS = exports.FAILURE_INDICATORS = exports.onUserPromptSubmit = exports.markOutcome = exports.getEvidenceImpact = exports.calculateDurationDays = exports.getRecentDecision = exports.extractFailureReason = exports.matchesPartialIndicators = exports.matchesSuccessIndicators = exports.matchesFailureIndicators = exports.analyzeOutcome = exports.extractCodeExample = exports.extractQuickAnswer = exports.estimateTokens = exports.ensureTokenBudget = exports.formatTrustContext = exports.formatInstantAnswer = exports.formatTeaser = exports.formatList = exports.formatRecall = exports.formatLegacyContext = exports.formatContext = exports.isMAMAError = exports.wrapError = exports.ErrorCodes = exports.TimeoutError = exports.RateLimitError = exports.LinkError = exports.ConfigurationError = exports.EmbeddingError = void 0;
29
+ exports.saveMemory = exports.createEmptyRecallBundle = exports.MEMORY_EDGE_TYPES = exports.MEMORY_STATUSES = exports.MEMORY_KINDS = exports.MEMORY_SCOPE_KINDS = exports.mama = exports.DEFAULT_DB_PATH = exports.LEGACY_DB_PATH = exports.DB_DIR = exports.DB_PATH = exports.traverseDecisionChain = exports.getDecisionById = exports.incrementUsageFailure = exports.incrementUsageSuccess = exports.getSessionDecisions = exports.SQLiteAdapter = exports.DatabaseAdapter = exports.createAdapter = exports.reindexEmbeddings = exports.fts5Search = exports.getDbPath = exports.getPreparedStmt = exports.updateDecisionOutcome = exports.querySemanticEdges = exports.queryDecisionGraph = exports.insertDecisionWithEmbedding = exports.queryVectorSearch = exports.vectorSearch = exports.insertEmbedding = exports.closeDB = exports.getAdapter = exports.getDB = exports.initDB = exports.TIMEOUT_MS = exports.HOST = exports.DEFAULT_PORT = exports.getServerPort = exports.isServerRunning = exports.getServerStatus = exports.getEmbeddingFromServer = exports.EmbeddingCache = exports.EMBEDDING_PREFIX_SCHEME = exports.MODEL_NAME = exports.EMBEDDING_DIM = exports.embeddingCache = exports.cosineSimilarity = exports.generateBatchEmbeddings = exports.generateEnhancedEmbedding = exports.generateEmbedding = void 0;
30
+ exports.assertTwinRefsVisibleToScopes = exports.mapTwinEdgeRow = exports.listTwinEdgesForRefs = exports.insertTwinEdge = exports.getTwinEdge = exports.TWIN_REF_KINDS = exports.TWIN_EDGE_TYPES = exports.TWIN_EDGE_SOURCES = exports.listToolTracesForRun = exports.appendToolTrace = exports.getModelRunInAdapter = exports.getModelRun = exports.failModelRunInAdapter = exports.failModelRun = exports.commitModelRunInAdapter = exports.commitModelRun = exports.beginModelRunInAdapter = exports.beginModelRun = exports.MODEL_RUN_STATUSES = exports.listMemoryProvenanceAudit = exports.getMemoryProvenanceAudit = exports.backfillConnectorEventScopeMetadata = exports.backfillLegacyMemoryProvenance = exports.listMemoriesByModelRunId = exports.listMemoriesByGatewayCallId = exports.listMemoriesByEnvelopeHash = exports.getMemoryProvenance = exports.assertTrustedProvenanceCapability = exports.createTrustedProvenanceCapability = exports.listRecentMemoryEvents = exports.listMemoryEventsForMemory = exports.insertMemoryEventInTransaction = exports.appendMemoryEvent = exports.parseExtractionResponse = exports.buildExtractionPrompt = exports.getChannelSummary = exports.upsertChannelSummary = exports.setExtractionFn = exports.ingestConversationWithTrustedProvenance = exports.ingestConversation = exports.recordMemoryAudit = exports.createAuditAck = exports.buildMemoryBootstrap = exports.evolveMemory = exports.ingestWithTrustedProvenance = exports.ingestMemory = exports.buildProfile = exports.recallMemory = exports.promoteMemoryStatus = exports.saveMemoryWithTrustedProvenance = void 0;
31
+ exports.NotFoundError = exports.MAMAError = exports.formatTimeAgo = exports.DebugLogger = exports.error = exports.warn = exports.info = exports.debug = exports.logSearching = exports.logLoading = exports.logInfo = exports.logError = exports.logFailed = exports.logComplete = exports.logProgress = exports.getTierBanner = exports.getTierDescription = exports.checkDatabase = exports.checkEmbeddings = exports.checkSQLite = exports.checkNodeVersion = exports.validateTier = exports.VALID_EDGE_TYPES = exports.updateConfidence = exports.getSupersededChainDepth = exports.createEdgesFromReasoning = exports.parseReasoningForRelationships = exports.detectRefinement = exports.calculateCombinedConfidence = exports.markSuperseded = exports.createSupersedesEdge = exports.createEdge = exports.getPreviousDecision = exports.generateDecisionId = exports.learnDecision = exports.testRelevanceScoring = exports.formatTopNContext = exports.selectTopDecisions = exports.calculateRelevance = exports.DEFAULT_CONFIG = exports.getConfigPath = exports.updateConfig = exports.getCacheDir = exports.getEmbeddingDim = exports.getModelName = exports.loadConfig = exports.CanonicalizeError = exports.targetRefHash = exports.canonicalizeJSON = exports.listVisibleTwinEdgesForRefs = void 0;
32
+ exports.notifyInsight = exports.FALLBACK_MODEL = exports.DEFAULT_MODEL = exports.listModels = exports.isAvailable = exports.analyzeQueryIntent = exports.analyzeDecision = exports.generate = exports.extractTopicKeywords = exports.analyzeIntent = exports.injectDecisionContext = exports.RECENT_WINDOW_MS = exports.PARTIAL_INDICATORS = exports.SUCCESS_INDICATORS = exports.FAILURE_INDICATORS = exports.onUserPromptSubmit = exports.markOutcome = exports.getEvidenceImpact = exports.calculateDurationDays = exports.getRecentDecision = exports.extractFailureReason = exports.matchesPartialIndicators = exports.matchesSuccessIndicators = exports.matchesFailureIndicators = exports.analyzeOutcome = exports.extractCodeExample = exports.extractQuickAnswer = exports.estimateTokens = exports.ensureTokenBudget = exports.formatTrustContext = exports.formatInstantAnswer = exports.formatTeaser = exports.formatList = exports.formatRecall = exports.formatLegacyContext = exports.formatContext = exports.isMAMAError = exports.wrapError = exports.ErrorCodes = exports.TimeoutError = exports.RateLimitError = exports.LinkError = exports.ConfigurationError = exports.EmbeddingError = exports.DatabaseError = exports.ValidationError = void 0;
33
33
  var embeddings_js_1 = require("./embeddings.js");
34
34
  Object.defineProperty(exports, "generateEmbedding", { enumerable: true, get: function () { return embeddings_js_1.generateEmbedding; } });
35
35
  Object.defineProperty(exports, "generateEnhancedEmbedding", { enumerable: true, get: function () { return embeddings_js_1.generateEnhancedEmbedding; } });
@@ -38,6 +38,7 @@ Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: func
38
38
  Object.defineProperty(exports, "embeddingCache", { enumerable: true, get: function () { return embeddings_js_1.embeddingCache; } });
39
39
  Object.defineProperty(exports, "EMBEDDING_DIM", { enumerable: true, get: function () { return embeddings_js_1.EMBEDDING_DIM; } });
40
40
  Object.defineProperty(exports, "MODEL_NAME", { enumerable: true, get: function () { return embeddings_js_1.MODEL_NAME; } });
41
+ Object.defineProperty(exports, "EMBEDDING_PREFIX_SCHEME", { enumerable: true, get: function () { return embeddings_js_1.EMBEDDING_PREFIX_SCHEME; } });
41
42
  var embedding_cache_js_1 = require("./embedding-cache.js");
42
43
  Object.defineProperty(exports, "EmbeddingCache", { enumerable: true, get: function () { return embedding_cache_js_1.EmbeddingCache; } });
43
44
  var embedding_client_js_1 = require("./embedding-client.js");
@@ -89,6 +90,7 @@ Object.defineProperty(exports, "createEmptyRecallBundle", { enumerable: true, ge
89
90
  var api_js_1 = require("./memory/api.js");
90
91
  Object.defineProperty(exports, "saveMemory", { enumerable: true, get: function () { return api_js_1.saveMemory; } });
91
92
  Object.defineProperty(exports, "saveMemoryWithTrustedProvenance", { enumerable: true, get: function () { return api_js_1.saveMemoryWithTrustedProvenance; } });
93
+ Object.defineProperty(exports, "promoteMemoryStatus", { enumerable: true, get: function () { return api_js_1.promoteMemoryStatus; } });
92
94
  Object.defineProperty(exports, "recallMemory", { enumerable: true, get: function () { return api_js_1.recallMemory; } });
93
95
  Object.defineProperty(exports, "buildProfile", { enumerable: true, get: function () { return api_js_1.buildProfile; } });
94
96
  Object.defineProperty(exports, "ingestMemory", { enumerable: true, get: function () { return api_js_1.ingestMemory; } });
@@ -151,6 +153,7 @@ var ref_validation_js_1 = require("./edges/ref-validation.js");
151
153
  Object.defineProperty(exports, "assertTwinRefsVisibleToScopes", { enumerable: true, get: function () { return ref_validation_js_1.assertTwinRefsVisibleToScopes; } });
152
154
  Object.defineProperty(exports, "listVisibleTwinEdgesForRefs", { enumerable: true, get: function () { return ref_validation_js_1.listVisibleTwinEdgesForRefs; } });
153
155
  __exportStar(require("./context-compile/index.js"), exports);
156
+ __exportStar(require("./provenance/source-ref.js"), exports);
154
157
  __exportStar(require("./agent-situation/index.js"), exports);
155
158
  __exportStar(require("./agent-graph/index.js"), exports);
156
159
  __exportStar(require("./entities/types.js"), exports);
package/dist/mama-api.js CHANGED
@@ -1118,7 +1118,7 @@ async function suggest(userQuestion, options = {}) {
1118
1118
  throw new Error('Vector search not available');
1119
1119
  }
1120
1120
  // Generate query embedding
1121
- const queryEmbedding = await (0, embeddings_js_1.generateEmbedding)(userQuestion);
1121
+ const queryEmbedding = await (0, embeddings_js_1.generateEmbedding)(userQuestion, 'query');
1122
1122
  // Adaptive threshold (shorter queries need higher confidence)
1123
1123
  const wordCount = userQuestion.split(/\s+/).length;
1124
1124
  const adaptiveThreshold = threshold !== undefined ? threshold : wordCount < 3 ? 0.7 : 0.6;
@@ -2,7 +2,7 @@ import { type WikiPageIndexRecord } from '../cases/wiki-page-index.js';
2
2
  import { resolveMemoryEvolution } from './evolution-engine.js';
3
3
  import { getChannelSummary, upsertChannelSummary } from './channel-summary-store.js';
4
4
  import { type SearchHitDiagnostics } from '../search/search-quality.js';
5
- import type { MemoryAgentBootstrap, MemoryAuditAck, MemoryEdge, MemoryRecord, MemoryScopeRef, ProfileSnapshot, PublicIngestMemoryInput, PublicSaveMemoryInput, RecallBundle, IngestConversationInput, ExtractedMemoryUnit, IngestConversationResult, RecallMemoryOptions } from './types.js';
5
+ import type { MemoryAgentBootstrap, MemoryAuditAck, MemoryEdge, MemoryRecord, MemoryScopeRef, MemoryStatus, ProfileSnapshot, PublicIngestMemoryInput, PublicSaveMemoryInput, RecallBundle, IngestConversationInput, ExtractedMemoryUnit, IngestConversationResult, RecallMemoryOptions } from './types.js';
6
6
  import { type TrustedMemoryWriteOptions } from './provenance.js';
7
7
  type SaveMemoryInput = PublicSaveMemoryInput;
8
8
  type IngestMemoryInput = PublicIngestMemoryInput;
@@ -15,6 +15,7 @@ export interface FusedHit {
15
15
  case_id?: string | null;
16
16
  retrieval_diagnostics?: SearchHitDiagnostics;
17
17
  }
18
+ export declare function buildDecisionId(topic: string): string;
18
19
  export declare const LEXICAL_STOPWORDS: Set<string>;
19
20
  export declare function getLexicalQueryTokens(query: string): string[];
20
21
  export declare function loadEdgesForIds(ids: string[]): Promise<MemoryEdge[]>;
@@ -27,6 +28,11 @@ type SaveMemoryResult = {
27
28
  };
28
29
  export declare function saveMemory(input: SaveMemoryInput): Promise<SaveMemoryResult>;
29
30
  export declare function saveMemoryWithTrustedProvenance(input: SaveMemoryInput, options: TrustedMemoryWriteOptions): Promise<SaveMemoryResult>;
31
+ export declare function promoteMemoryStatus(input: {
32
+ memoryId: string;
33
+ status: MemoryStatus;
34
+ nowMs?: number;
35
+ }): Promise<void>;
30
36
  export declare function buildProfile(scopes: MemoryScopeRef[]): Promise<ProfileSnapshot>;
31
37
  export declare function recallMemory(query: string, options?: RecallMemoryOptions): Promise<RecallBundle>;
32
38
  export declare function ingestMemory(input: IngestMemoryInput): Promise<{