@jungjaehoon/mama-core 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/config-loader.d.ts +61 -0
  2. package/dist/config-loader.js +187 -0
  3. package/dist/db-adapter/base-adapter.d.ts +76 -0
  4. package/dist/db-adapter/base-adapter.js +11 -0
  5. package/dist/db-adapter/index.d.ts +24 -0
  6. package/dist/db-adapter/index.js +29 -0
  7. package/dist/db-adapter/sqlite-adapter.d.ts +73 -0
  8. package/dist/db-adapter/sqlite-adapter.js +330 -0
  9. package/dist/db-adapter/statement.d.ts +119 -0
  10. package/dist/db-adapter/statement.js +113 -0
  11. package/dist/db-manager.d.ts +252 -0
  12. package/dist/db-manager.js +622 -0
  13. package/dist/debug-logger.d.ts +32 -0
  14. package/dist/debug-logger.js +83 -0
  15. package/dist/decision-formatter.d.ts +172 -0
  16. package/dist/decision-formatter.js +894 -0
  17. package/dist/decision-tracker.d.ts +218 -0
  18. package/dist/decision-tracker.js +531 -0
  19. package/dist/embedding-cache.d.ts +83 -0
  20. package/dist/embedding-cache.js +182 -0
  21. package/dist/embedding-client.d.ts +43 -0
  22. package/dist/embedding-client.js +132 -0
  23. package/dist/embedding-server/index.d.ts +65 -0
  24. package/dist/embedding-server/index.js +397 -0
  25. package/dist/embedding-server/mobile/auth.d.ts +53 -0
  26. package/dist/embedding-server/mobile/auth.js +140 -0
  27. package/dist/embedding-server/mobile/daemon.d.ts +128 -0
  28. package/dist/embedding-server/mobile/daemon.js +303 -0
  29. package/dist/embedding-server/mobile/output-parser.d.ts +115 -0
  30. package/dist/embedding-server/mobile/output-parser.js +241 -0
  31. package/dist/embedding-server/mobile/session-api.d.ts +57 -0
  32. package/dist/embedding-server/mobile/session-api.js +261 -0
  33. package/dist/embedding-server/mobile/session-manager.d.ts +135 -0
  34. package/dist/embedding-server/mobile/session-manager.js +333 -0
  35. package/dist/embedding-server/mobile/websocket-handler.d.ts +127 -0
  36. package/dist/embedding-server/mobile/websocket-handler.js +435 -0
  37. package/dist/embeddings.d.ts +75 -0
  38. package/dist/embeddings.js +262 -0
  39. package/dist/errors.d.ts +131 -0
  40. package/dist/errors.js +225 -0
  41. package/dist/index.d.ts +32 -0
  42. package/dist/index.js +193 -0
  43. package/dist/mama-api.d.ts +954 -0
  44. package/dist/mama-api.js +2210 -0
  45. package/dist/memory-inject.d.ts +24 -0
  46. package/dist/memory-inject.js +116 -0
  47. package/dist/memory-store.d.ts +103 -0
  48. package/dist/memory-store.js +129 -0
  49. package/dist/notification-manager.d.ts +7 -0
  50. package/dist/notification-manager.js +12 -0
  51. package/dist/ollama-client.d.ts +51 -0
  52. package/dist/ollama-client.js +308 -0
  53. package/dist/outcome-tracker.d.ts +165 -0
  54. package/dist/outcome-tracker.js +315 -0
  55. package/dist/progress-indicator.d.ts +48 -0
  56. package/dist/progress-indicator.js +82 -0
  57. package/dist/query-intent.d.ts +27 -0
  58. package/dist/query-intent.js +144 -0
  59. package/dist/relevance-scorer.d.ts +124 -0
  60. package/dist/relevance-scorer.js +243 -0
  61. package/dist/test-utils.d.ts +66 -0
  62. package/dist/test-utils.js +166 -0
  63. package/dist/tier-validator.d.ts +55 -0
  64. package/dist/tier-validator.js +216 -0
  65. package/dist/time-formatter.d.ts +25 -0
  66. package/dist/time-formatter.js +93 -0
  67. package/package.json +3 -2
@@ -0,0 +1,954 @@
1
+ /**
2
+ * MAMA (Memory-Augmented MCP Architecture) - Simple Public API
3
+ *
4
+ * Clean wrapper around MAMA's internal functions
5
+ * Follows Claude-First Design: Simple, Transparent, Non-Intrusive
6
+ *
7
+ * Core Principle: MAMA = Librarian, Claude = Researcher
8
+ * - MAMA stores (organize books), retrieves (find books), indexes (catalog)
9
+ * - Claude decides what to save and how to use recalled decisions
10
+ *
11
+ * v1.3 Update: Collaborative Reasoning Graph
12
+ * - Auto-search on save: Find similar decisions before saving
13
+ * - Collaborative invitation: Suggest build-on/debate/synthesize
14
+ * - AX-first: Soft warnings, not hard blocks
15
+ *
16
+ * @module mama-api
17
+ * @version 1.3
18
+ * @date 2025-11-26
19
+ */
20
+ import { DecisionRecord } from './db-manager.js';
21
+ import { SemanticEdges } from './decision-formatter.js';
22
+ /**
23
+ * Parameters for mama.save()
24
+ */
25
+ interface SaveParams {
26
+ topic: string;
27
+ decision: string;
28
+ reasoning: string;
29
+ confidence?: number;
30
+ type?: 'user_decision' | 'assistant_insight';
31
+ outcome?: 'pending' | 'success' | 'failure' | 'partial' | 'superseded';
32
+ failure_reason?: string | null;
33
+ limitation?: string | null;
34
+ trust_context?: Record<string, unknown> | null;
35
+ }
36
+ /**
37
+ * Similar decision result from search
38
+ */
39
+ interface SimilarDecision {
40
+ id: string;
41
+ topic: string;
42
+ decision: string;
43
+ reasoning?: string;
44
+ similarity?: number;
45
+ created_at?: number | string;
46
+ }
47
+ /**
48
+ * Search result from mama.search()
49
+ */
50
+ interface SearchResult {
51
+ query: string;
52
+ results: SimilarDecision[];
53
+ meta: {
54
+ count: number;
55
+ search_method: string;
56
+ threshold: number;
57
+ recency_boost: {
58
+ weight: number;
59
+ scale: number;
60
+ decay: number;
61
+ } | null;
62
+ graph_expansion: {
63
+ total_results: number;
64
+ primary_count: number;
65
+ expanded_count: number;
66
+ sources: Record<string, number>;
67
+ } | null;
68
+ };
69
+ }
70
+ /**
71
+ * Suggest options for mama.suggest()
72
+ */
73
+ export interface SuggestOptions {
74
+ limit?: number;
75
+ threshold?: number;
76
+ format?: 'full' | 'teaser' | 'brief' | 'markdown';
77
+ recency_boost?: boolean | {
78
+ weight?: number;
79
+ scale?: number;
80
+ decay?: number;
81
+ };
82
+ graph_expansion?: boolean;
83
+ }
84
+ /**
85
+ * Reasoning graph info
86
+ */
87
+ interface ReasoningGraphInfo {
88
+ topic: string;
89
+ depth: number;
90
+ latest: string;
91
+ }
92
+ /**
93
+ * Save result from mama.save()
94
+ */
95
+ interface SaveResult {
96
+ success: boolean;
97
+ id: string;
98
+ similar_decisions?: SimilarDecision[];
99
+ warning?: string;
100
+ collaboration_hint?: string;
101
+ reasoning_graph?: ReasoningGraphInfo;
102
+ error?: string;
103
+ }
104
+ /**
105
+ * Suggest result from mama.suggest()
106
+ */
107
+ export interface SuggestResult {
108
+ query: string;
109
+ formatted_context: string;
110
+ raw_decisions?: SimilarDecision[];
111
+ meta?: SearchResult['meta'];
112
+ error?: string;
113
+ }
114
+ /**
115
+ * Recall result from mama.recall()
116
+ */
117
+ export interface RecallResult {
118
+ id: string;
119
+ topic: string;
120
+ decision: string;
121
+ reasoning?: string;
122
+ outcome?: string | null;
123
+ failure_reason?: string | null;
124
+ confidence: number;
125
+ supersedes?: string | null;
126
+ superseded_by?: string | null;
127
+ created_at: number | string;
128
+ updated_at?: number | string;
129
+ trust_context?: Record<string, unknown> | null;
130
+ history?: DecisionRecord[];
131
+ semantic_edges?: SemanticEdges;
132
+ error?: string;
133
+ }
134
+ /**
135
+ * Update result from mama.update()
136
+ */
137
+ export interface UpdateResult {
138
+ success: boolean;
139
+ id: string;
140
+ updated_fields: string[];
141
+ error?: string;
142
+ }
143
+ /**
144
+ * Checkpoint params
145
+ */
146
+ export interface CheckpointParams {
147
+ summary: string;
148
+ next_steps?: string;
149
+ open_files?: string[];
150
+ }
151
+ /**
152
+ * Checkpoint result
153
+ */
154
+ export interface CheckpointResult {
155
+ success: boolean;
156
+ id: string;
157
+ timestamp: string;
158
+ error?: string;
159
+ }
160
+ /**
161
+ * Load checkpoint result
162
+ */
163
+ export interface LoadCheckpointResult {
164
+ found: boolean;
165
+ summary?: string;
166
+ next_steps?: string;
167
+ open_files?: string[];
168
+ created_at?: string;
169
+ error?: string;
170
+ }
171
+ /**
172
+ * Outcome badge map type
173
+ */
174
+ export type OutcomeBadgeMap = Record<string, string | null>;
175
+ /**
176
+ * Recall options
177
+ */
178
+ interface RecallOptions {
179
+ format?: 'json' | 'markdown';
180
+ }
181
+ /**
182
+ * DB stats result for decision_edges
183
+ */
184
+ export interface DBStatsResult {
185
+ total_links: number;
186
+ llm_created: number;
187
+ approved: number;
188
+ }
189
+ /**
190
+ * DB link stats result
191
+ */
192
+ export interface DBLinkStatsResult {
193
+ total_links: number;
194
+ llm_created: number;
195
+ approved: number;
196
+ unique_decisions: number;
197
+ relationship_breakdown: string;
198
+ }
199
+ /**
200
+ * Deletion target for auto-generated links
201
+ */
202
+ interface DeletionTarget {
203
+ from_id: string;
204
+ to_id: string;
205
+ relationship: string;
206
+ }
207
+ /**
208
+ * Post cleanup report structure
209
+ */
210
+ export interface PostCleanupReport {
211
+ orphaned_decisions: number;
212
+ duplicate_links: number;
213
+ invalid_references: number;
214
+ }
215
+ /**
216
+ * Quality report options
217
+ */
218
+ interface QualityReportOptions {
219
+ format?: 'json' | 'markdown' | null;
220
+ period?: '24h' | '7d' | '30d' | null;
221
+ thresholds?: QualityThresholds | null;
222
+ }
223
+ /**
224
+ * Quality thresholds
225
+ */
226
+ interface QualityThresholds {
227
+ minSuccessRate?: number;
228
+ maxLatencyMs?: number;
229
+ }
230
+ /**
231
+ * Deprecate auto-links result
232
+ */
233
+ interface DeprecateAutoLinksResult {
234
+ dryRun: boolean;
235
+ deprecated: number;
236
+ protected: number;
237
+ total: number;
238
+ autoLinkRatio: string;
239
+ links: Array<{
240
+ from_id: string;
241
+ to_id: string;
242
+ relationship: string;
243
+ reason?: string;
244
+ created_at?: number | string;
245
+ }>;
246
+ }
247
+ /**
248
+ * Scan auto-links result
249
+ */
250
+ interface ScanAutoLinksResult {
251
+ total_links: number;
252
+ auto_links: number;
253
+ protected_links: number;
254
+ deletion_targets: number;
255
+ deletion_target_list: DeletionTarget[];
256
+ }
257
+ /**
258
+ * Create link backup result
259
+ */
260
+ interface CreateLinkBackupResult {
261
+ backup_file: string;
262
+ manifest_file: string;
263
+ checksum: string;
264
+ link_count: number;
265
+ }
266
+ /**
267
+ * Restore link backup result
268
+ */
269
+ interface RestoreLinkBackupResult {
270
+ total_links: number;
271
+ restored: number;
272
+ failed: number;
273
+ backup_file: string;
274
+ }
275
+ /**
276
+ * Verify backup exists result
277
+ */
278
+ interface VerifyBackupResult {
279
+ backup_file: string;
280
+ age_hours: number;
281
+ link_count: number;
282
+ }
283
+ /**
284
+ * Delete auto-links result (dry run mode)
285
+ */
286
+ interface DeleteAutoLinksDryRunResult {
287
+ dry_run: true;
288
+ would_delete: number;
289
+ deleted: 0;
290
+ backup_file: string;
291
+ large_deletion_warning: boolean;
292
+ warning_message: string | null;
293
+ sample_links: Array<{
294
+ from_id: string;
295
+ to_id: string;
296
+ relationship: string;
297
+ }>;
298
+ message: string;
299
+ }
300
+ /**
301
+ * Delete auto-links error entry
302
+ */
303
+ type DeleteAutoLinksError = {
304
+ link: string;
305
+ error: string;
306
+ } | {
307
+ batch_index: number;
308
+ batch_size: number;
309
+ error: string;
310
+ };
311
+ /**
312
+ * Delete auto-links result (execute mode)
313
+ */
314
+ interface DeleteAutoLinksExecuteResult {
315
+ dry_run: false;
316
+ deleted: number;
317
+ failed: number;
318
+ total_targets: number;
319
+ batches_processed: number;
320
+ backup_file: string;
321
+ errors: DeleteAutoLinksError[];
322
+ success_rate: number;
323
+ }
324
+ /**
325
+ * Delete auto-links result (empty case)
326
+ */
327
+ interface DeleteAutoLinksEmptyResult {
328
+ dry_run: boolean;
329
+ deleted: 0;
330
+ failed: 0;
331
+ total_targets: 0;
332
+ backup_file: string;
333
+ message: string;
334
+ }
335
+ /**
336
+ * Delete auto-links union type
337
+ */
338
+ type DeleteAutoLinksResult = DeleteAutoLinksDryRunResult | DeleteAutoLinksExecuteResult | DeleteAutoLinksEmptyResult;
339
+ /**
340
+ * Quality recommendation
341
+ */
342
+ export interface QualityRecommendation {
343
+ category: string;
344
+ severity: string;
345
+ message: string;
346
+ }
347
+ /**
348
+ * Quality report structure
349
+ */
350
+ export interface QualityReport {
351
+ successRate: {
352
+ period: string;
353
+ total: number;
354
+ success: number;
355
+ failure: number;
356
+ successRate: string;
357
+ meetsTarget: boolean;
358
+ };
359
+ latency?: {
360
+ avgMs: number;
361
+ p50Ms: number;
362
+ p95Ms: number;
363
+ maxMs: number;
364
+ meetsTarget: boolean;
365
+ };
366
+ }
367
+ /**
368
+ * Save a decision or insight to MAMA's memory
369
+ *
370
+ * Simple API for Claude to save insights without complex configuration
371
+ * AC #1: Simple API - no complex configuration required
372
+ *
373
+ * @param {Object} params - Decision parameters
374
+ * @param {string} params.topic - Decision topic (e.g., 'auth_strategy', 'date_format')
375
+ * @param {string} params.decision - The decision made (e.g., 'JWT', 'ISO 8601 + Unix')
376
+ * @param {string} params.reasoning - Why this decision was made
377
+ * @param {number} [params.confidence=0.5] - Confidence score 0.0-1.0 (optional)
378
+ * @param {string} [params.type='user_decision'] - 'user_decision' or 'assistant_insight' (optional)
379
+ * @param {string} [params.outcome='pending'] - 'pending', 'success', 'failure', 'partial', 'superseded' (optional)
380
+ * @param {string} [params.failure_reason] - Why this decision failed (optional, used with outcome='failure')
381
+ * @param {string} [params.limitation] - Known limitations of this decision (optional)
382
+ * @returns {Promise<{success: boolean, id: string, similar_decisions?: Array, warning?: string, collaboration_hint?: string, reasoning_graph?: Object}>} Save result with decision ID and metadata
383
+ *
384
+ * @example
385
+ * const decisionId = await mama.save({
386
+ * topic: 'date_calculation_format',
387
+ * decision: 'Support both ISO 8601 and Unix timestamp formats',
388
+ * reasoning: 'Bootstrap data stored as ISO 8601 causing NaN errors',
389
+ * confidence: 0.95,
390
+ * type: 'assistant_insight',
391
+ * outcome: 'success'
392
+ * });
393
+ */
394
+ declare function save({ topic, decision, reasoning, confidence, type, outcome, failure_reason, limitation, trust_context, }: SaveParams): Promise<SaveResult>;
395
+ /**
396
+ * Recall decisions by topic
397
+ *
398
+ * DEFAULT: Returns JSON object with decisions and edges (LLM-first design)
399
+ * OPTIONAL: Returns Markdown string if format='markdown' (for human display)
400
+ *
401
+ * @param {string} topic - Decision topic to recall
402
+ * @param {Object} [options] - Options
403
+ * @param {string} [options.format='json'] - Output format: 'json' (default) or 'markdown'
404
+ * @returns {Promise<Object|string>} Decision history as JSON or Markdown
405
+ *
406
+ * @example
407
+ * // LLM usage (default)
408
+ * const data = await mama.recall('auth_strategy');
409
+ * // → { topic, decisions: [...], edges: [...], meta: {...} }
410
+ *
411
+ * // Human display
412
+ * const markdown = await mama.recall('auth_strategy', { format: 'markdown' });
413
+ * // → "📋 Decision History: auth_strategy\n━━━━━━━━..."
414
+ */
415
+ declare function recall(topic: string, options?: RecallOptions): Promise<unknown>;
416
+ /**
417
+ * Update outcome of a decision
418
+ *
419
+ * Track whether a decision succeeded, failed, or partially worked
420
+ * AC: Evolutionary Decision Memory - Learn from outcomes
421
+ *
422
+ * @param {string} decisionId - Decision ID to update
423
+ * @param {Object} outcome - Outcome details
424
+ * @param {string} outcome.outcome - 'SUCCESS', 'FAILED', or 'PARTIAL'
425
+ * @param {string} [outcome.failure_reason] - Reason for failure (if FAILED)
426
+ * @param {string} [outcome.limitation] - Limitation description (if PARTIAL)
427
+ * @returns {Promise<void>}
428
+ *
429
+ * @example
430
+ * await mama.updateOutcome('decision_auth_strategy_123456_abc', {
431
+ * outcome: 'FAILED',
432
+ * failure_reason: 'Missing token expiration handling'
433
+ * });
434
+ */
435
+ interface UpdateOutcomeParams {
436
+ outcome: string;
437
+ failure_reason?: string | null;
438
+ limitation?: string | null;
439
+ }
440
+ declare function updateOutcome(decisionId: string, { outcome, failure_reason, limitation }: UpdateOutcomeParams): Promise<void>;
441
+ /**
442
+ * Suggest relevant decisions based on user question
443
+ *
444
+ * DEFAULT: Returns JSON object with search results (LLM-first design)
445
+ * OPTIONAL: Returns Markdown string if format='markdown' (for human display)
446
+ *
447
+ * Simplified: Direct vector search without LLM intent analysis
448
+ * Works with short queries, long questions, Korean/English
449
+ *
450
+ * @param {string} userQuestion - User's question or intent
451
+ * @param {Object} options - Search options
452
+ * @param {string} [options.format='json'] - Output format: 'json' (default) or 'markdown'
453
+ * @param {number} [options.limit=5] - Max results to return
454
+ * @param {number} [options.threshold=0.6] - Minimum similarity (adaptive by query length)
455
+ * @param {boolean} [options.useReranking=false] - Use LLM re-ranking (optional, slower)
456
+ * @returns {Promise<Object|string|null>} Search results as JSON or Markdown, null if no results
457
+ *
458
+ * @example
459
+ * // LLM usage (default)
460
+ * const data = await mama.suggest('Why did we choose JWT?');
461
+ * // → { query, results: [...], meta: {...} }
462
+ *
463
+ * // Human display
464
+ * const markdown = await mama.suggest('mesh optimization', { format: 'markdown' });
465
+ * // → "💡 MAMA found 3 related topics:\n1. ..."
466
+ */
467
+ interface SuggestFunctionOptions {
468
+ format?: 'json' | 'markdown';
469
+ limit?: number;
470
+ threshold?: number;
471
+ useReranking?: boolean;
472
+ recencyWeight?: number;
473
+ recencyScale?: number;
474
+ recencyDecay?: number;
475
+ disableRecency?: boolean;
476
+ }
477
+ declare function suggest(userQuestion: string, options?: SuggestFunctionOptions): Promise<any>;
478
+ /**
479
+ * List recent decisions (all topics, chronological)
480
+ *
481
+ * DEFAULT: Returns JSON array with recent decisions (LLM-first design)
482
+ * OPTIONAL: Returns Markdown string if format='markdown' (for human display)
483
+ *
484
+ * @param {Object} [options] - Options
485
+ * @param {number} [options.limit=10] - Max results
486
+ * @param {string} [options.format='json'] - Output format
487
+ * @returns {Promise<Array|string>} Recent decisions
488
+ */
489
+ interface ListDecisionsOptions {
490
+ limit?: number;
491
+ format?: 'json' | 'markdown';
492
+ }
493
+ declare function listDecisions(options?: ListDecisionsOptions): Promise<DecisionRecord[] | string>;
494
+ /**
495
+ * Save current session checkpoint (New Feature: Session Continuity)
496
+ *
497
+ * @param {string} summary - Summary of current session state
498
+ * @param {Array<string>} openFiles - List of currently open files
499
+ * @param {string} nextSteps - Next steps to be taken
500
+ * @returns {Promise<number>} Checkpoint ID
501
+ */
502
+ declare function saveCheckpoint(summary: string, openFiles?: string[], nextSteps?: string, recentConversation?: any[]): Promise<number | bigint>;
503
+ /**
504
+ * Load latest active checkpoint (New Feature: Session Continuity)
505
+ *
506
+ * @returns {Promise<Object|null>} Latest checkpoint or null
507
+ */
508
+ interface CheckpointRow {
509
+ id?: number;
510
+ timestamp?: number;
511
+ summary?: string;
512
+ open_files?: string | string[];
513
+ next_steps?: string;
514
+ recent_conversation?: string | unknown[];
515
+ status?: string;
516
+ }
517
+ declare function loadCheckpoint(): Promise<CheckpointRow | null>;
518
+ /**
519
+ * List recent checkpoints (New Feature: Session Continuity)
520
+ *
521
+ * @param {number} limit - Max number of checkpoints to return
522
+ * @returns {Promise<Array>} Recent checkpoints
523
+ */
524
+ declare function listCheckpoints(limit?: number): Promise<CheckpointRow[]>;
525
+ /**
526
+ * Propose a new link between decisions (Epic 3 - Story 3.1)
527
+ *
528
+ * LLM proposes a link for user approval. Link is created but marked as pending.
529
+ *
530
+ * @param {Object} params - Link parameters
531
+ * @param {string} params.from_id - Source decision ID
532
+ * @param {string} params.to_id - Target decision ID
533
+ * @param {string} params.relationship - 'refines' or 'contradicts'
534
+ * @param {string} params.reason - Why this link should exist
535
+ * @param {string} [params.decision_id] - Context decision where link was proposed
536
+ * @param {string} [params.evidence] - Supporting evidence
537
+ * @returns {Promise<void>}
538
+ */
539
+ interface ProposeLinkParams {
540
+ from_id: string;
541
+ to_id: string;
542
+ relationship: string;
543
+ reason: string;
544
+ decision_id?: string;
545
+ evidence?: string;
546
+ }
547
+ declare function proposeLink({ from_id, to_id, relationship, reason, decision_id, evidence, }: ProposeLinkParams): Promise<void>;
548
+ /**
549
+ * Approve a proposed link (Epic 3 - Story 3.1)
550
+ *
551
+ * User approves a pending link, making it active.
552
+ *
553
+ * @param {string} from_id - Source decision ID
554
+ * @param {string} to_id - Target decision ID
555
+ * @param {string} relationship - Link relationship type
556
+ * @returns {Promise<void>}
557
+ */
558
+ declare function approveLink(from_id: string, to_id: string, relationship: string): Promise<void>;
559
+ /**
560
+ * Reject a proposed link (Epic 3 - Story 3.1)
561
+ *
562
+ * User rejects a pending link, removing it from the database.
563
+ *
564
+ * @param {string} from_id - Source decision ID
565
+ * @param {string} to_id - Target decision ID
566
+ * @param {string} relationship - Link relationship type
567
+ * @param {string} [reason] - Optional reason for rejection
568
+ * @returns {Promise<void>}
569
+ */
570
+ declare function rejectLink(from_id: string, to_id: string, relationship: string, reason?: string): Promise<void>;
571
+ /**
572
+ * Get pending links awaiting approval (Epic 3 - Story 3.1)
573
+ *
574
+ * Returns all links that need user approval.
575
+ *
576
+ * @param {Object} [options] - Query options
577
+ * @param {string} [options.from_id] - Filter by source decision
578
+ * @param {string} [options.to_id] - Filter by target decision
579
+ * @returns {Promise<Array>} Pending links with decision details
580
+ */
581
+ interface GetPendingLinksOptions {
582
+ from_id?: string;
583
+ to_id?: string;
584
+ }
585
+ declare function getPendingLinks(options?: GetPendingLinksOptions): Promise<any[]>;
586
+ /**
587
+ * Deprecate auto-generated links (Epic 3 - Story 3.3)
588
+ *
589
+ * Identifies and removes v0 auto-generated links that lack explicit approval context.
590
+ * Protected links (with decision_id or created_by='llm') are preserved.
591
+ *
592
+ * @param {Object} [options] - Deprecation options
593
+ * @param {boolean} [options.dryRun=true] - If true, only report without deleting
594
+ * @returns {Promise<Object>} Report with counts and deprecated links
595
+ */
596
+ interface DeprecateAutoLinksOptions {
597
+ dryRun?: boolean;
598
+ }
599
+ interface EdgeLink {
600
+ from_id: string;
601
+ to_id: string;
602
+ relationship: string;
603
+ reason?: string;
604
+ created_at?: number | string;
605
+ }
606
+ declare function deprecateAutoLinks(options?: DeprecateAutoLinksOptions): Promise<DeprecateAutoLinksResult>;
607
+ /**
608
+ * Scan and identify auto-generated links for cleanup (Epic 5 - Story 5.1)
609
+ *
610
+ * Identifies auto-generated links lacking proper approval metadata.
611
+ * Separates deletion targets from protected links.
612
+ *
613
+ * Identification criteria:
614
+ * - approved_by_user = 0 OR (created_by IS NULL AND decision_id IS NULL)
615
+ *
616
+ * Protected (excluded from deletion):
617
+ * - approved_by_user = 1 AND (decision_id IS NOT NULL OR evidence IS NOT NULL)
618
+ *
619
+ * @returns {Object} Scan results with counts and link details
620
+ */
621
+ declare function scanAutoLinks(): ScanAutoLinksResult;
622
+ /**
623
+ * Create backup of links before cleanup (Epic 5 - Story 5.1)
624
+ *
625
+ * Backs up deletion target links with full metadata to JSON file.
626
+ * Generates SHA-256 checksum for data integrity verification.
627
+ * Creates backup manifest with timestamp and metadata.
628
+ *
629
+ * @param {Array} targetLinks - Links to back up
630
+ * @returns {Object} Backup result with file paths and checksum
631
+ */
632
+ declare function createLinkBackup(targetLinks: EdgeLink[]): CreateLinkBackupResult;
633
+ /**
634
+ * Generate pre-cleanup report with risk assessment (Epic 5 - Story 5.1)
635
+ *
636
+ * Creates comprehensive report with statistics, risk level, and samples.
637
+ * Risk assessment based on deletion ratio:
638
+ * - HIGH: > 50% deletion
639
+ * - MEDIUM: 30-50% deletion
640
+ * - LOW: < 30% deletion
641
+ *
642
+ * @returns {Object} Report data with markdown output and file path
643
+ */
644
+ declare function generatePreCleanupReport(): {
645
+ report: {
646
+ generated_at: string;
647
+ statistics: {
648
+ total_links: number;
649
+ auto_links: number;
650
+ protected_links: number;
651
+ deletion_targets: number;
652
+ deletion_ratio: string;
653
+ };
654
+ risk_assessment: {
655
+ level: string;
656
+ message: string;
657
+ };
658
+ deletion_target_samples: {
659
+ from_id: any;
660
+ to_id: any;
661
+ relationship: any;
662
+ reason: any;
663
+ created_by: any;
664
+ approved_by_user: any;
665
+ }[];
666
+ };
667
+ report_file: string;
668
+ markdown: string;
669
+ };
670
+ /**
671
+ * Restore links from backup file (Epic 5 - Story 5.1)
672
+ *
673
+ * Restores previously backed-up links to the database.
674
+ * Verifies checksum before restoration to ensure data integrity.
675
+ * Reports number of restored and failed links.
676
+ *
677
+ * @param {string} backupFile - Path to backup file
678
+ * @returns {Object} Restoration result with counts
679
+ */
680
+ declare function restoreLinkBackup(backupFile: string): RestoreLinkBackupResult;
681
+ /**
682
+ * Verify backup file exists and is recent (Epic 5 - Story 5.2)
683
+ *
684
+ * Checks for backup files in backup directory and verifies they are recent enough.
685
+ * Required as safety check before executing link deletion.
686
+ *
687
+ * @param {number} maxAgeHours - Maximum age of backup in hours (default: 24)
688
+ * @returns {Object} Backup verification result with latest backup info
689
+ */
690
+ declare function verifyBackupExists(maxAgeHours?: number): VerifyBackupResult;
691
+ /**
692
+ * Delete auto-generated links with batch processing (Epic 5 - Story 5.2)
693
+ *
694
+ * Executes batch deletion of auto-generated links with transaction support.
695
+ * Requires recent backup (within 24 hours) before execution.
696
+ * Logs all deletions to audit trail.
697
+ *
698
+ * Safety features:
699
+ * - Backup verification before deletion
700
+ * - Batch processing with transaction support
701
+ * - Dry-run mode for simulation
702
+ * - Large deletion warning (> 1000 links)
703
+ *
704
+ * @param {number} batchSize - Number of links to delete per batch (default: 100)
705
+ * @param {boolean} dryRun - If true, simulate deletion without actual changes (default: true)
706
+ * @returns {Object} Deletion result with counts and backup info
707
+ */
708
+ declare function deleteAutoLinks(batchSize?: number, dryRun?: boolean): DeleteAutoLinksResult;
709
+ /**
710
+ * Validate cleanup result and generate post-cleanup report (Epic 5 - Story 5.2)
711
+ *
712
+ * Re-scans for remaining auto-generated links and evaluates cleanup success.
713
+ * Generates comprehensive report with statistics and recommendations.
714
+ *
715
+ * Success criteria:
716
+ * - SUCCESS: Remaining auto links < 5%
717
+ * - PARTIAL: Remaining auto links 5-10%
718
+ * - FAILED: Remaining auto links > 10%
719
+ *
720
+ * @returns {Object} Validation result with report and file path
721
+ */
722
+ declare function validateCleanupResult(): {
723
+ status: string;
724
+ total_links_before: number;
725
+ auto_links_remaining: number;
726
+ remaining_ratio: number;
727
+ protected_links: number;
728
+ report: {
729
+ validated_at: string;
730
+ status: string;
731
+ message: string;
732
+ statistics: {
733
+ total_links: number;
734
+ remaining_auto_links: number;
735
+ remaining_ratio: string;
736
+ protected_links: number;
737
+ deletion_targets: number;
738
+ };
739
+ recommendation: string;
740
+ };
741
+ report_file: string;
742
+ markdown: string;
743
+ };
744
+ /**
745
+ * Calculate coverage metrics (Epic 4 - Story 4.1)
746
+ *
747
+ * Measures narrative coverage (% of decisions with narrative fields)
748
+ * and link coverage (% of decisions with at least one link).
749
+ *
750
+ * @returns {Object} Coverage metrics
751
+ */
752
+ declare function calculateCoverage(): {
753
+ narrativeCoverage: string;
754
+ linkCoverage: string;
755
+ totalDecisions: number;
756
+ completeNarratives: number;
757
+ decisionsWithLinks: number;
758
+ };
759
+ /**
760
+ * Log restart attempt (Epic 4 - Story 4.2)
761
+ *
762
+ * Records restart attempt with success/failure status, latency, and mode.
763
+ * Replaces in-memory restart-metrics.js with SQLite-backed storage.
764
+ *
765
+ * @param {string} sessionId - Session identifier
766
+ * @param {string} status - 'success' or 'failure'
767
+ * @param {string|null} failureReason - 'NO_CHECKPOINT', 'LOAD_ERROR', 'CONTEXT_INCOMPLETE', or null
768
+ * @param {number} latencyMs - Latency in milliseconds
769
+ * @param {string} mode - 'full' (narrative+links) or 'summary' (summary only)
770
+ * @returns {void}
771
+ */
772
+ declare function logRestartAttempt(sessionId: string, status: string, failureReason: string | null, latencyMs: number, mode?: string): void;
773
+ /**
774
+ * Calculate restart success rate (Epic 4 - Story 4.2)
775
+ *
776
+ * Calculates success rate over a given period (24h, 7d, 30d).
777
+ *
778
+ * @param {string} period - '24h', '7d', or '30d'
779
+ * @returns {Object} Success rate metrics
780
+ */
781
+ declare function calculateRestartSuccessRate(period?: '24h' | '7d' | '30d'): {
782
+ period: "24h" | "7d" | "30d";
783
+ total: number;
784
+ success: number;
785
+ failure: number;
786
+ successRate: string;
787
+ meetsTarget: boolean;
788
+ };
789
+ /**
790
+ * Calculate restart latency percentiles (Epic 4 - Story 4.2)
791
+ *
792
+ * Calculates p50, p95, p99 latencies for successful restarts.
793
+ * Optionally filters by mode (full/summary).
794
+ *
795
+ * @param {string} period - '24h', '7d', or '30d'
796
+ * @param {string|null} mode - 'full', 'summary', or null (all modes)
797
+ * @returns {Object} Latency percentile metrics
798
+ */
799
+ declare function calculateRestartLatency(period?: '24h' | '7d' | '30d', mode?: string | null): {
800
+ p50: number;
801
+ p95: number;
802
+ p99: number;
803
+ count: number;
804
+ mode: string;
805
+ };
806
+ /**
807
+ * Get restart metrics (Epic 4 - Story 4.2)
808
+ *
809
+ * Combines success rate and latency metrics for a given period.
810
+ *
811
+ * @param {string} period - '24h', '7d', or '30d'
812
+ * @param {boolean} includeLatency - Whether to include latency percentiles
813
+ * @returns {Object} Combined restart metrics
814
+ */
815
+ declare function getRestartMetrics(period?: '24h' | '7d' | '30d', includeLatency?: boolean): {
816
+ successRate: ReturnType<typeof calculateRestartSuccessRate>;
817
+ latency?: {
818
+ full: ReturnType<typeof calculateRestartLatency>;
819
+ summary: ReturnType<typeof calculateRestartLatency>;
820
+ };
821
+ };
822
+ /**
823
+ * Calculate quality metrics (Epic 4 - Story 4.1)
824
+ *
825
+ * Measures narrative quality (field completeness per layer)
826
+ * and link quality (rich reason ratio, approved link ratio).
827
+ *
828
+ * @returns {Object} Quality metrics
829
+ */
830
+ declare function calculateQuality(): {
831
+ narrativeQuality: {
832
+ evidence: string;
833
+ alternatives: string;
834
+ risks: string;
835
+ };
836
+ linkQuality: {
837
+ richReasonRatio: string;
838
+ approvedRatio: string;
839
+ totalLinks: number;
840
+ richLinks: number;
841
+ approvedLinks: number;
842
+ };
843
+ };
844
+ /**
845
+ * Generate quality report with recommendations (Epic 4 - Story 4.1 + 4.2)
846
+ *
847
+ * Generates a comprehensive quality report with coverage, quality metrics,
848
+ * restart metrics, and recommendations for improvement.
849
+ *
850
+ * @param {Object} options - Report options
851
+ * @param {string} [options.format='json'] - Output format: 'json' or 'markdown'
852
+ * @param {string} [options.period='7d'] - Period for restart metrics: '24h', '7d', or '30d'
853
+ * @param {Object} [options.thresholds] - Custom thresholds
854
+ * @param {number} [options.thresholds.narrativeCoverage=0.8] - Narrative coverage threshold (0-1)
855
+ * @param {number} [options.thresholds.linkCoverage=0.7] - Link coverage threshold (0-1)
856
+ * @param {number} [options.thresholds.richReasonRatio=0.7] - Rich reason ratio threshold (0-1)
857
+ * @param {number} [options.thresholds.restartSuccessRate=0.95] - Restart success rate threshold (0-1)
858
+ * @param {number} [options.thresholds.restartLatencyP95Full=2500] - Full mode p95 latency threshold (ms)
859
+ * @param {number} [options.thresholds.restartLatencyP95Summary=1000] - Summary mode p95 latency threshold (ms)
860
+ * @returns {Object|string} Quality report as JSON or Markdown
861
+ */
862
+ declare function generateQualityReport(options?: QualityReportOptions): string | {
863
+ generated_at: string;
864
+ period: "24h" | "7d" | "30d" | null;
865
+ coverage: {
866
+ narrativeCoverage: string;
867
+ linkCoverage: string;
868
+ totalDecisions: number;
869
+ completeNarratives: number;
870
+ decisionsWithLinks: number;
871
+ };
872
+ quality: {
873
+ narrativeQuality: {
874
+ evidence: string;
875
+ alternatives: string;
876
+ risks: string;
877
+ };
878
+ linkQuality: {
879
+ richReasonRatio: string;
880
+ approvedRatio: string;
881
+ totalLinks: number;
882
+ richLinks: number;
883
+ approvedLinks: number;
884
+ };
885
+ };
886
+ restart: {
887
+ successRate: ReturnType<typeof calculateRestartSuccessRate>;
888
+ latency?: {
889
+ full: ReturnType<typeof calculateRestartLatency>;
890
+ summary: ReturnType<typeof calculateRestartLatency>;
891
+ };
892
+ };
893
+ thresholds: {
894
+ minSuccessRate?: number;
895
+ maxLatencyMs?: number;
896
+ narrativeCoverage: number;
897
+ linkCoverage: number;
898
+ richReasonRatio: number;
899
+ restartSuccessRate: number;
900
+ restartLatencyP95Full: number;
901
+ restartLatencyP95Summary: number;
902
+ };
903
+ recommendations: {
904
+ type: string;
905
+ message: string;
906
+ target: string;
907
+ current: string;
908
+ }[];
909
+ format: "json" | "markdown" | null;
910
+ };
911
+ /**
912
+ * MAMA Public API
913
+ *
914
+ * Simple, clean interface for Claude to interact with MAMA
915
+ * Hides complex implementation details (embeddings, vector search, graph queries)
916
+ *
917
+ * Key Principles:
918
+ * 1. Simple API First - No complex configuration
919
+ * 2. Transparent Process - Each step is visible
920
+ * 3. Claude-First Design - Claude decides what to save
921
+ * 4. Non-Intrusive - Silent failures for helpers (suggest)
922
+ */
923
+ declare const mama: {
924
+ save: typeof save;
925
+ suggest: typeof suggest;
926
+ list: typeof listDecisions;
927
+ listCheckpoints: typeof listCheckpoints;
928
+ updateOutcome: typeof updateOutcome;
929
+ saveCheckpoint: typeof saveCheckpoint;
930
+ loadCheckpoint: typeof loadCheckpoint;
931
+ recall: typeof recall;
932
+ proposeLink: typeof proposeLink;
933
+ approveLink: typeof approveLink;
934
+ rejectLink: typeof rejectLink;
935
+ getPendingLinks: typeof getPendingLinks;
936
+ deprecateAutoLinks: typeof deprecateAutoLinks;
937
+ calculateCoverage: typeof calculateCoverage;
938
+ calculateQuality: typeof calculateQuality;
939
+ generateQualityReport: typeof generateQualityReport;
940
+ logRestartAttempt: typeof logRestartAttempt;
941
+ calculateRestartSuccessRate: typeof calculateRestartSuccessRate;
942
+ calculateRestartLatency: typeof calculateRestartLatency;
943
+ getRestartMetrics: typeof getRestartMetrics;
944
+ scanAutoLinks: typeof scanAutoLinks;
945
+ createLinkBackup: typeof createLinkBackup;
946
+ generatePreCleanupReport: typeof generatePreCleanupReport;
947
+ restoreLinkBackup: typeof restoreLinkBackup;
948
+ verifyBackupExists: typeof verifyBackupExists;
949
+ deleteAutoLinks: typeof deleteAutoLinks;
950
+ validateCleanupResult: typeof validateCleanupResult;
951
+ };
952
+ export { save, suggest, listDecisions as list, listCheckpoints, updateOutcome, saveCheckpoint, loadCheckpoint, recall, proposeLink, approveLink, rejectLink, getPendingLinks, deprecateAutoLinks, calculateCoverage, calculateQuality, generateQualityReport, logRestartAttempt, calculateRestartSuccessRate, calculateRestartLatency, getRestartMetrics, scanAutoLinks, createLinkBackup, generatePreCleanupReport, restoreLinkBackup, verifyBackupExists, deleteAutoLinks, validateCleanupResult, };
953
+ export default mama;
954
+ //# sourceMappingURL=mama-api.d.ts.map