@linxiraos/pi-mnemopi 1.0.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.
Files changed (135) hide show
  1. package/CHANGELOG.md +248 -0
  2. package/README.md +108 -0
  3. package/dist/types/cli.d.ts +35 -0
  4. package/dist/types/config.d.ts +108 -0
  5. package/dist/types/core/aaak.d.ts +55 -0
  6. package/dist/types/core/annotations.d.ts +75 -0
  7. package/dist/types/core/banks.d.ts +33 -0
  8. package/dist/types/core/beam/consolidate.d.ts +38 -0
  9. package/dist/types/core/beam/helpers.d.ts +69 -0
  10. package/dist/types/core/beam/index.d.ts +59 -0
  11. package/dist/types/core/beam/recall.d.ts +52 -0
  12. package/dist/types/core/beam/schema.d.ts +2 -0
  13. package/dist/types/core/beam/store.d.ts +57 -0
  14. package/dist/types/core/beam/types.d.ts +268 -0
  15. package/dist/types/core/binary-vectors.d.ts +54 -0
  16. package/dist/types/core/chat-normalize.d.ts +13 -0
  17. package/dist/types/core/content-sanitizer.d.ts +18 -0
  18. package/dist/types/core/cost-log.d.ts +13 -0
  19. package/dist/types/core/embeddings.d.ts +93 -0
  20. package/dist/types/core/entities.d.ts +9 -0
  21. package/dist/types/core/episodic-graph.d.ts +89 -0
  22. package/dist/types/core/extraction/client.d.ts +35 -0
  23. package/dist/types/core/extraction/diagnostics.d.ts +51 -0
  24. package/dist/types/core/extraction/prompts.d.ts +2 -0
  25. package/dist/types/core/extraction.d.ts +34 -0
  26. package/dist/types/core/fastembed-model-cache.d.ts +2 -0
  27. package/dist/types/core/fastembed-runtime.d.ts +41 -0
  28. package/dist/types/core/index.d.ts +6 -0
  29. package/dist/types/core/llm-backends.d.ts +23 -0
  30. package/dist/types/core/local-llm.d.ts +20 -0
  31. package/dist/types/core/memory.d.ts +186 -0
  32. package/dist/types/core/migrations/e6-triplestore-split.d.ts +17 -0
  33. package/dist/types/core/migrations/index.d.ts +1 -0
  34. package/dist/types/core/mmr.d.ts +8 -0
  35. package/dist/types/core/orchestrator.d.ts +20 -0
  36. package/dist/types/core/patterns.d.ts +61 -0
  37. package/dist/types/core/plugins.d.ts +109 -0
  38. package/dist/types/core/polyphonic-recall.d.ts +66 -0
  39. package/dist/types/core/query-cache.d.ts +45 -0
  40. package/dist/types/core/query-intent.d.ts +20 -0
  41. package/dist/types/core/recall-diagnostics.d.ts +48 -0
  42. package/dist/types/core/runtime-options.d.ts +76 -0
  43. package/dist/types/core/shmr.d.ts +62 -0
  44. package/dist/types/core/streaming.d.ts +136 -0
  45. package/dist/types/core/synonyms.d.ts +46 -0
  46. package/dist/types/core/temporal-parser.d.ts +16 -0
  47. package/dist/types/core/token-counter.d.ts +8 -0
  48. package/dist/types/core/triples.d.ts +63 -0
  49. package/dist/types/core/typed-memory.d.ts +39 -0
  50. package/dist/types/core/vector-index.d.ts +16 -0
  51. package/dist/types/core/vector-math.d.ts +1 -0
  52. package/dist/types/core/veracity-consolidation.d.ts +60 -0
  53. package/dist/types/core/weibull.d.ts +96 -0
  54. package/dist/types/db.d.ts +18 -0
  55. package/dist/types/diagnose.d.ts +24 -0
  56. package/dist/types/dr/index.d.ts +1 -0
  57. package/dist/types/dr/recovery.d.ts +68 -0
  58. package/dist/types/index.d.ts +6 -0
  59. package/dist/types/mcp-server.d.ts +40 -0
  60. package/dist/types/mcp-tools.d.ts +484 -0
  61. package/dist/types/migrations/e6-triplestore-split.d.ts +1 -0
  62. package/dist/types/migrations/index.d.ts +1 -0
  63. package/dist/types/types.d.ts +145 -0
  64. package/dist/types/util/datetime.d.ts +8 -0
  65. package/dist/types/util/env.d.ts +10 -0
  66. package/dist/types/util/ids.d.ts +3 -0
  67. package/dist/types/util/lru.d.ts +12 -0
  68. package/dist/types/util/regex.d.ts +11 -0
  69. package/package.json +108 -0
  70. package/src/cli.ts +398 -0
  71. package/src/config.ts +373 -0
  72. package/src/core/aaak.ts +142 -0
  73. package/src/core/annotations.ts +456 -0
  74. package/src/core/banks.ts +133 -0
  75. package/src/core/beam/consolidate.ts +1132 -0
  76. package/src/core/beam/helpers.ts +831 -0
  77. package/src/core/beam/index.ts +358 -0
  78. package/src/core/beam/recall.ts +1225 -0
  79. package/src/core/beam/schema.ts +426 -0
  80. package/src/core/beam/store.ts +1083 -0
  81. package/src/core/beam/types.ts +303 -0
  82. package/src/core/binary-vectors.ts +317 -0
  83. package/src/core/chat-normalize.ts +160 -0
  84. package/src/core/content-sanitizer.ts +136 -0
  85. package/src/core/cost-log.ts +101 -0
  86. package/src/core/embeddings.ts +624 -0
  87. package/src/core/entities.ts +263 -0
  88. package/src/core/episodic-graph.ts +708 -0
  89. package/src/core/extraction/client.ts +187 -0
  90. package/src/core/extraction/diagnostics.ts +193 -0
  91. package/src/core/extraction/prompts.ts +31 -0
  92. package/src/core/extraction.ts +491 -0
  93. package/src/core/fastembed-model-cache.ts +39 -0
  94. package/src/core/fastembed-runtime.ts +172 -0
  95. package/src/core/index.ts +39 -0
  96. package/src/core/llm-backends.ts +54 -0
  97. package/src/core/local-llm.ts +475 -0
  98. package/src/core/memory.ts +680 -0
  99. package/src/core/migrations/e6-triplestore-split.ts +211 -0
  100. package/src/core/migrations/index.ts +1 -0
  101. package/src/core/mmr.ts +101 -0
  102. package/src/core/orchestrator.ts +62 -0
  103. package/src/core/patterns.ts +484 -0
  104. package/src/core/plugins.ts +375 -0
  105. package/src/core/polyphonic-recall.ts +563 -0
  106. package/src/core/query-cache.ts +351 -0
  107. package/src/core/query-intent.ts +139 -0
  108. package/src/core/recall-diagnostics.ts +157 -0
  109. package/src/core/runtime-options.ts +130 -0
  110. package/src/core/shmr.ts +567 -0
  111. package/src/core/streaming.ts +419 -0
  112. package/src/core/synonyms.ts +197 -0
  113. package/src/core/temporal-parser.ts +363 -0
  114. package/src/core/token-counter.ts +30 -0
  115. package/src/core/triples.ts +452 -0
  116. package/src/core/typed-memory.ts +407 -0
  117. package/src/core/vector-index.ts +83 -0
  118. package/src/core/vector-math.ts +23 -0
  119. package/src/core/veracity-consolidation.ts +477 -0
  120. package/src/core/weibull.ts +124 -0
  121. package/src/db.ts +186 -0
  122. package/src/diagnose.ts +174 -0
  123. package/src/dr/index.ts +1 -0
  124. package/src/dr/recovery.ts +405 -0
  125. package/src/index.ts +33 -0
  126. package/src/mcp-server.ts +155 -0
  127. package/src/mcp-tools.ts +970 -0
  128. package/src/migrations/e6-triplestore-split.ts +1 -0
  129. package/src/migrations/index.ts +1 -0
  130. package/src/types.ts +157 -0
  131. package/src/util/datetime.ts +69 -0
  132. package/src/util/env.ts +65 -0
  133. package/src/util/ids.ts +19 -0
  134. package/src/util/lru.ts +48 -0
  135. package/src/util/regex.ts +165 -0
@@ -0,0 +1,20 @@
1
+ import type { BeamMemoryState, RecallOptions, RecallResult } from "./beam/types.js";
2
+ import { type PolyphonicMemoryResult, type PolyphonicRecallOptions } from "./polyphonic-recall.js";
3
+ export interface OrchestratorBeam extends BeamMemoryState {
4
+ recall?: (query: string, topK?: number, options?: RecallOptions) => Promise<RecallResult[]>;
5
+ recallEnhanced?: (query: string, topK?: number, options?: RecallOptions) => Promise<RecallResult[]>;
6
+ }
7
+ export interface OrchestrateRecallOptions extends Omit<RecallOptions, "queryEmbedding">, Omit<PolyphonicRecallOptions, "queryEmbedding"> {
8
+ readonly queryEmbedding?: readonly number[] | Float32Array | null;
9
+ readonly enhanced?: boolean;
10
+ readonly forcePolyphonic?: boolean;
11
+ readonly forceLinear?: boolean;
12
+ }
13
+ export interface OrchestratedRecallResult extends Omit<RecallResult, "metadata" | "score" | "tier"> {
14
+ score?: number;
15
+ metadata?: RecallResult["metadata"];
16
+ tier?: RecallResult["tier"] | PolyphonicMemoryResult["tier"];
17
+ combined_score?: PolyphonicMemoryResult["combined_score"];
18
+ voice_scores?: PolyphonicMemoryResult["voice_scores"];
19
+ }
20
+ export declare function orchestrateRecall(beam: OrchestratorBeam, query: string, topK?: number, options?: OrchestrateRecallOptions): Promise<OrchestratedRecallResult[]>;
@@ -0,0 +1,61 @@
1
+ export interface CompressionStatsInit {
2
+ readonly originalSize?: number;
3
+ readonly compressedSize?: number;
4
+ readonly ratio?: number;
5
+ readonly method?: string;
6
+ readonly patternsFound?: number;
7
+ readonly memoriesCompressed?: number;
8
+ }
9
+ export declare class CompressionStats {
10
+ originalSize: number;
11
+ compressedSize: number;
12
+ ratio: number;
13
+ method: string;
14
+ patternsFound: number;
15
+ memoriesCompressed: number;
16
+ constructor(init?: CompressionStatsInit);
17
+ get savingsPercent(): number;
18
+ }
19
+ export type MemoryRecord = Record<string, unknown> & {
20
+ content?: string;
21
+ timestamp?: string;
22
+ created_at?: string;
23
+ source?: string;
24
+ };
25
+ export declare class MemoryCompressor {
26
+ readonly dictionary: Readonly<Record<string, string>>;
27
+ constructor(dictionary?: Readonly<Record<string, string>>);
28
+ static buildDefaultDict(): Record<string, string>;
29
+ compress(content: string, method?: string): readonly [string, CompressionStats];
30
+ private dictCompress;
31
+ private rleCompress;
32
+ private semanticCompressSingle;
33
+ compressBatch(memories: readonly MemoryRecord[], method?: string): readonly [MemoryRecord[], CompressionStats];
34
+ decompress(content: string, method?: string): string;
35
+ }
36
+ export interface DetectedPatternInit {
37
+ readonly patternType?: string;
38
+ readonly pattern_type?: string;
39
+ readonly description: string;
40
+ readonly confidence: number;
41
+ readonly samples?: readonly string[];
42
+ readonly metadata?: Record<string, unknown>;
43
+ }
44
+ export declare class DetectedPattern {
45
+ patternType: string;
46
+ description: string;
47
+ confidence: number;
48
+ samples: string[];
49
+ metadata: Record<string, unknown>;
50
+ constructor(init: DetectedPatternInit);
51
+ toDict(): Record<string, unknown>;
52
+ }
53
+ export declare class PatternDetector {
54
+ readonly minConfidence: number;
55
+ constructor(minConfidence?: number);
56
+ detectTemporal(memories: readonly MemoryRecord[]): DetectedPattern[];
57
+ detectContent(memories: readonly MemoryRecord[]): DetectedPattern[];
58
+ detectSequence(memories: readonly MemoryRecord[]): DetectedPattern[];
59
+ detectAll(memories: readonly MemoryRecord[]): DetectedPattern[];
60
+ summarizePatterns(memories: readonly MemoryRecord[]): Record<string, unknown>;
61
+ }
@@ -0,0 +1,109 @@
1
+ export declare const DEFAULT_PLUGIN_DIR: string;
2
+ export type PluginConfig = Record<string, unknown>;
3
+ export type MemoryDict = Record<string, unknown>;
4
+ export declare class MnemopiPlugin {
5
+ static readonly abstractBase = true;
6
+ name: string;
7
+ version: string;
8
+ enabled: boolean;
9
+ protected initialized: boolean;
10
+ readonly config: PluginConfig;
11
+ constructor(config?: PluginConfig);
12
+ initialize(): void;
13
+ shutdown(): void;
14
+ onRemember(_memory: MemoryDict): void;
15
+ onRecall(_memory: MemoryDict): void;
16
+ onConsolidate(_summary: MemoryDict): void;
17
+ onInvalidate(_memoryId: string): void;
18
+ toDict(): Record<string, unknown>;
19
+ }
20
+ export declare class LoggingPlugin extends MnemopiPlugin {
21
+ name: string;
22
+ version: string;
23
+ private readonly memoryLog;
24
+ private readonly maxEntries;
25
+ constructor(config?: PluginConfig);
26
+ private append;
27
+ onRemember(memory: MemoryDict): void;
28
+ onRecall(memory: MemoryDict): void;
29
+ onConsolidate(summary: MemoryDict): void;
30
+ onInvalidate(memoryId: string): void;
31
+ getLog(): MemoryDict[];
32
+ clearLog(): void;
33
+ }
34
+ export declare class MetricsPlugin extends MnemopiPlugin {
35
+ name: string;
36
+ version: string;
37
+ private readonly counters;
38
+ private readonly timings;
39
+ private readonly maxTimingSamples;
40
+ constructor(config?: PluginConfig);
41
+ onRemember(_memory: MemoryDict): void;
42
+ onRecall(_memory: MemoryDict): void;
43
+ onConsolidate(_summary: MemoryDict): void;
44
+ onInvalidate(_memoryId: string): void;
45
+ recordTiming(event: string, durationMs: number): void;
46
+ getCounters(): Record<string, number>;
47
+ getTimings(event: string): number[];
48
+ getAverageTiming(event: string): number | null;
49
+ reset(): void;
50
+ getSummary(): Record<string, unknown>;
51
+ }
52
+ export type FilterRule = (item: MemoryDict) => boolean;
53
+ export declare class FilterPlugin extends MnemopiPlugin {
54
+ name: string;
55
+ version: string;
56
+ private readonly rules;
57
+ private readonly blocked;
58
+ private readonly maxBlocked;
59
+ constructor(config?: PluginConfig);
60
+ addRule(rule: FilterRule): void;
61
+ removeRule(rule: FilterRule): void;
62
+ clearRules(): void;
63
+ onRemember(memory: MemoryDict): void;
64
+ onRecall(memory: MemoryDict): void;
65
+ onConsolidate(summary: MemoryDict): void;
66
+ onInvalidate(_memoryId: string): void;
67
+ private passes;
68
+ private block;
69
+ getBlocked(): MemoryDict[];
70
+ isBlocked(memoryId: string): boolean;
71
+ }
72
+ export declare class CompressionPlugin extends MnemopiPlugin {
73
+ name: string;
74
+ version: string;
75
+ enabled: boolean;
76
+ private readonly threshold;
77
+ constructor(config?: PluginConfig);
78
+ compressLines(lines: string[]): string[];
79
+ onRemember(_memory: MemoryDict): void;
80
+ onRecall(_memory: MemoryDict): void;
81
+ onConsolidate(_summary: MemoryDict): void;
82
+ onInvalidate(_memoryId: string): void;
83
+ }
84
+ export type PluginConstructor<T extends MnemopiPlugin = MnemopiPlugin> = new (config?: PluginConfig) => T;
85
+ export declare class PluginManager {
86
+ private readonly pluginDir;
87
+ private readonly registry;
88
+ private readonly instances;
89
+ constructor(pluginDir?: string);
90
+ registerPlugin(name: string, pluginClass: PluginConstructor): void;
91
+ loadPlugin(name: string, config?: PluginConfig): MnemopiPlugin;
92
+ unloadPlugin(name: string): void;
93
+ listPlugins(): Array<Record<string, unknown>>;
94
+ getPlugin(name: string): MnemopiPlugin | null;
95
+ isLoaded(name: string): boolean;
96
+ isRegistered(name: string): boolean;
97
+ loadAll(configs?: Record<string, PluginConfig>): MnemopiPlugin[];
98
+ unloadAll(): void;
99
+ discoverPlugins(): string[];
100
+ notifyRemember(memory: MemoryDict): void;
101
+ notifyRecall(memory: MemoryDict): void;
102
+ notifyConsolidate(summary: MemoryDict): void;
103
+ notifyInvalidate(memoryId: string): void;
104
+ }
105
+ export declare class ValueError extends Error {
106
+ name: string;
107
+ }
108
+ export declare function getManager(): PluginManager;
109
+ export declare function resetManager(): void;
@@ -0,0 +1,66 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { type Env } from "../config.js";
3
+ import { type DatabasePath } from "../db.js";
4
+ import type { BeamMemoryState, JsonValue, Metadata, RecallResult } from "./beam/types.js";
5
+ import { EpisodicGraph } from "./episodic-graph.js";
6
+ import { VeracityConsolidator } from "./veracity-consolidation.js";
7
+ export type PolyphonicVoice = "vector" | "graph" | "fact" | "temporal";
8
+ export interface VoiceRecallResult {
9
+ readonly memoryId: string;
10
+ readonly score: number;
11
+ readonly voice: PolyphonicVoice;
12
+ readonly metadata: Metadata;
13
+ }
14
+ export interface PolyphonicResult {
15
+ readonly memoryId: string;
16
+ combinedScore: number;
17
+ readonly voiceScores: Partial<Record<PolyphonicVoice, number>>;
18
+ readonly metadata: Metadata;
19
+ }
20
+ export interface PolyphonicMemoryResult extends Omit<RecallResult, "metadata" | "score" | "tier"> {
21
+ score: number;
22
+ combined_score: number;
23
+ voice_scores: Partial<Record<PolyphonicVoice, number>>;
24
+ metadata: Metadata;
25
+ tier: "working" | "episodic";
26
+ }
27
+ export interface PolyphonicRecallOptions {
28
+ readonly queryEmbedding?: readonly number[] | Float32Array | null;
29
+ readonly contextBudget?: number;
30
+ }
31
+ interface PolyphonicEngineOptions {
32
+ readonly dbPath?: DatabasePath;
33
+ readonly db?: Database;
34
+ readonly graph?: EpisodicGraph;
35
+ readonly consolidator?: VeracityConsolidator;
36
+ readonly sessionId?: string | null;
37
+ readonly channelId?: string | null;
38
+ }
39
+ export declare function polyphonicRecallIsEnabled(env?: Env): boolean;
40
+ export declare class PolyphonicRecallEngine {
41
+ readonly dbPath: DatabasePath;
42
+ readonly db: Database;
43
+ readonly ownsConnection: boolean;
44
+ readonly graph: EpisodicGraph;
45
+ readonly consolidator: VeracityConsolidator;
46
+ readonly sessionId: string;
47
+ readonly channelId: string | null;
48
+ readonly voiceWeights: Readonly<Record<PolyphonicVoice, number>>;
49
+ constructor(options?: PolyphonicEngineOptions);
50
+ recall(query: string, queryEmbedding?: readonly number[] | Float32Array | null, topK?: number, contextBudget?: number): PolyphonicMemoryResult[];
51
+ vectorVoice(queryEmbedding: readonly number[] | Float32Array | null): VoiceRecallResult[];
52
+ graphVoice(query: string): VoiceRecallResult[];
53
+ factVoice(query: string): VoiceRecallResult[];
54
+ temporalVoice(query: string): VoiceRecallResult[];
55
+ combineVoices(...voiceResults: readonly VoiceRecallResult[][]): Map<string, PolyphonicResult>;
56
+ diversityRerank(results: ReadonlyMap<string, PolyphonicResult>, topK: number): PolyphonicResult[];
57
+ estimateSimilarity(a: PolyphonicResult, b: PolyphonicResult): number;
58
+ assembleContext(results: readonly PolyphonicResult[], budget: number): PolyphonicResult[];
59
+ getStats(): Record<string, JsonValue>;
60
+ close(): void;
61
+ private hydrateResults;
62
+ private lookupMemory;
63
+ }
64
+ export declare function getPolyphonicEngine(beam: BeamMemoryState): PolyphonicRecallEngine;
65
+ export declare function polyphonicRecall(beam: BeamMemoryState, query: string, topK?: number, options?: PolyphonicRecallOptions): PolyphonicMemoryResult[];
66
+ export {};
@@ -0,0 +1,45 @@
1
+ import { type Env } from "../config.js";
2
+ export type QueryCacheResult = Record<string, unknown>;
3
+ export type QueryEmbedding = readonly number[];
4
+ export interface QueryCacheOptions {
5
+ readonly dbPath?: string | null;
6
+ readonly db_path?: string | null;
7
+ readonly maxSize?: number;
8
+ readonly max_size?: number;
9
+ readonly ttlSeconds?: number;
10
+ readonly ttl_seconds?: number;
11
+ }
12
+ export interface QueryCacheStats {
13
+ readonly hits: number;
14
+ readonly misses: number;
15
+ readonly hit_rate: number;
16
+ readonly tier1_hits: number;
17
+ readonly tier2_hits: number;
18
+ readonly tier3_hits: number;
19
+ readonly tier4_hits: number;
20
+ readonly size: number;
21
+ readonly max_size: number;
22
+ readonly version: number;
23
+ }
24
+ export declare function isEnhancedRecallEnabled(env?: Env): boolean;
25
+ export declare function isQueryCacheEnabled(useCache?: boolean, env?: Env): boolean;
26
+ export declare class QueryCache {
27
+ #private;
28
+ readonly maxSize: number;
29
+ readonly ttlSeconds: number;
30
+ hits: number;
31
+ misses: number;
32
+ tier1Hits: number;
33
+ tier2Hits: number;
34
+ tier3Hits: number;
35
+ tier4Hits: number;
36
+ constructor(options?: QueryCacheOptions | string | null, maxSize?: number, ttlSeconds?: number);
37
+ invalidate(): void;
38
+ get(query: string, embedding?: QueryEmbedding | null): readonly QueryCacheResult[] | null;
39
+ put(query: string, results: readonly QueryCacheResult[], embedding?: QueryEmbedding | null): void;
40
+ close(): void;
41
+ get hitRate(): number;
42
+ stats(): QueryCacheStats;
43
+ normalize(query: string): string;
44
+ jaccardWords(queryA: string, queryB: string): number;
45
+ }
@@ -0,0 +1,20 @@
1
+ export type QueryIntentCategory = "temporal" | "factual" | "entity" | "preference" | "procedural" | "general";
2
+ export interface QueryIntent {
3
+ readonly category: QueryIntentCategory;
4
+ readonly confidence: number;
5
+ readonly signals: QueryIntentCategory[];
6
+ readonly vec_bias: number;
7
+ readonly fts_bias: number;
8
+ readonly importance_bias: number;
9
+ }
10
+ export interface IntentWeights {
11
+ readonly vec_bias: number;
12
+ readonly fts_bias: number;
13
+ readonly importance_bias: number;
14
+ }
15
+ type IntentPatternGroup = readonly [QueryIntentCategory, readonly RegExp[]];
16
+ export declare const INTENT_PATTERNS: readonly IntentPatternGroup[];
17
+ export declare const INTENT_WEIGHTS: Record<QueryIntentCategory, IntentWeights>;
18
+ export declare function classifyIntent(query: string): QueryIntent;
19
+ export declare function adjustWeights(baseVec?: number, baseFts?: number, baseImportance?: number, intent?: QueryIntent | null): [number, number, number];
20
+ export {};
@@ -0,0 +1,48 @@
1
+ export declare const RECALL_TIERS: readonly ["wm_fts", "wm_vec", "wm_fallback", "em_fts", "em_vec", "em_fallback"];
2
+ export type RecallTier = (typeof RECALL_TIERS)[number];
3
+ export interface TierStatsSnapshot {
4
+ readonly calls_with_hits: number;
5
+ readonly total_hits: number;
6
+ }
7
+ export interface RecallDiagnosticsSnapshot {
8
+ readonly created_at: string;
9
+ readonly snapshot_at: string;
10
+ readonly totals: {
11
+ readonly calls: number;
12
+ readonly calls_using_wm_fallback: number;
13
+ readonly calls_using_em_fallback: number;
14
+ readonly calls_truly_empty: number;
15
+ readonly wm_fallback_rate: number;
16
+ readonly em_fallback_rate: number;
17
+ };
18
+ readonly by_tier: Record<RecallTier, TierStatsSnapshot>;
19
+ }
20
+ export declare class RecallDiagnostics {
21
+ private tierStats;
22
+ private totalCalls;
23
+ private callsUsingWmFallback;
24
+ private callsUsingEmFallback;
25
+ private callsTrulyEmpty;
26
+ private createdAt;
27
+ constructor();
28
+ private static validateTier;
29
+ recordTierHits(tier: RecallTier | string, hitCount: number): void;
30
+ recordFallbackUsed(options?: {
31
+ readonly wm?: boolean;
32
+ readonly em?: boolean;
33
+ }): void;
34
+ recordCall(options?: {
35
+ readonly trulyEmpty?: boolean;
36
+ readonly truly_empty?: boolean;
37
+ }): void;
38
+ fallbackRate(): {
39
+ readonly wm: number;
40
+ readonly em: number;
41
+ };
42
+ snapshot(): RecallDiagnosticsSnapshot;
43
+ reset(): void;
44
+ }
45
+ export declare function getDiagnostics(): RecallDiagnostics;
46
+ export declare function getRecallDiagnostics(): RecallDiagnosticsSnapshot;
47
+ export declare function resetRecallDiagnostics(): void;
48
+ export declare function explainRecallDiagnostics(snapshot: RecallDiagnosticsSnapshot): string[];
@@ -0,0 +1,76 @@
1
+ import type { Api, ApiKey, Model } from "@linxiraos/pi-ai";
2
+ export interface MnemopiLlmCompleteOptions {
3
+ maxTokens?: number;
4
+ temperature?: number;
5
+ timeout?: number;
6
+ provider?: string | null;
7
+ model?: string | null;
8
+ }
9
+ export type MnemopiLlmCompletion = (prompt: string, opts?: MnemopiLlmCompleteOptions) => string | null | Promise<string | null>;
10
+ /**
11
+ * What an embedding provider's `embed` returns: the embedding matrix streamed as async batches,
12
+ * matching fastembed's `embed()` (`AsyncGenerator<number[][]>`). Each yielded batch is a list of
13
+ * rows; each row is one number per dimension. Yield the whole matrix as a single batch when not
14
+ * streaming: `async *embed(texts) { yield texts.map(embedOne); }`.
15
+ */
16
+ export type EmbeddingOutput = AsyncIterable<number[][]>;
17
+ export interface MnemopiEmbeddingProvider {
18
+ embed(texts: readonly string[]): EmbeddingOutput | Promise<EmbeddingOutput>;
19
+ available?(): boolean | Promise<boolean>;
20
+ }
21
+ export interface MnemopiEmbeddingRuntimeOptions {
22
+ disabled?: boolean;
23
+ model?: string;
24
+ apiUrl?: string;
25
+ apiKey?: ApiKey;
26
+ provider?: MnemopiEmbeddingProvider | ((texts: readonly string[]) => EmbeddingOutput | Promise<EmbeddingOutput>);
27
+ /** Override `MNEMOPI_EMBEDDING_MAX_INPUT_CHARS`. `0` disables the cap. See `config.embeddingMaxInputChars`. */
28
+ maxInputChars?: number;
29
+ }
30
+ export interface MnemopiLlmRuntimeOptions {
31
+ enabled?: boolean;
32
+ baseUrl?: string;
33
+ apiKey?: ApiKey;
34
+ model?: string | Model<Api>;
35
+ maxTokens?: number;
36
+ complete?: MnemopiLlmCompletion;
37
+ /** Override the fact-extraction prompt template ({text}/{lang}). Used to feed small local models a friendlier format. */
38
+ extractionPrompt?: string;
39
+ /** Override the consolidation/sleep prompt template ({memories}/{source}/{memory_count}). */
40
+ consolidationPrompt?: string;
41
+ }
42
+ export interface MnemopiRuntimeOptions {
43
+ embeddings?: false | MnemopiEmbeddingRuntimeOptions;
44
+ llm?: false | MnemopiLlmRuntimeOptions | Model<Api> | MnemopiLlmCompletion;
45
+ /** Verbose diagnostics: escalates best-effort failure logs from debug to warn. */
46
+ debug?: boolean;
47
+ }
48
+ export interface ResolvedMnemopiEmbeddingRuntimeOptions {
49
+ disabled?: boolean;
50
+ model?: string;
51
+ apiUrl?: string;
52
+ apiKey?: ApiKey;
53
+ provider?: MnemopiEmbeddingProvider;
54
+ maxInputChars?: number;
55
+ }
56
+ export interface ResolvedMnemopiLlmRuntimeOptions {
57
+ enabled?: boolean;
58
+ baseUrl?: string;
59
+ apiKey?: ApiKey;
60
+ model?: string | Model<Api>;
61
+ maxTokens?: number;
62
+ complete?: MnemopiLlmCompletion;
63
+ extractionPrompt?: string;
64
+ consolidationPrompt?: string;
65
+ }
66
+ export interface ResolvedMnemopiRuntimeOptions {
67
+ embeddings?: ResolvedMnemopiEmbeddingRuntimeOptions;
68
+ llm?: ResolvedMnemopiLlmRuntimeOptions;
69
+ debug?: boolean;
70
+ }
71
+ export declare function withMnemopiRuntimeOptions<T>(options: ResolvedMnemopiRuntimeOptions | undefined, fn: () => T): T;
72
+ export declare function getMnemopiRuntimeOptions(): ResolvedMnemopiRuntimeOptions | undefined;
73
+ /** Whether the active runtime scope requested verbose diagnostics (`mnemopi.debug`). */
74
+ export declare function mnemopiDebugEnabled(): boolean;
75
+ export declare function resolveEmbeddingProvider(provider: MnemopiEmbeddingProvider | ((texts: readonly string[]) => EmbeddingOutput | Promise<EmbeddingOutput>) | undefined): MnemopiEmbeddingProvider | undefined;
76
+ export declare function isPiAiModel(value: unknown): value is Model<Api>;
@@ -0,0 +1,62 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { cosineSimilarity } from "./vector-math.js";
3
+ export { cosineSimilarity };
4
+ export declare const SHMR_BATCH_SIZE: number;
5
+ export declare const SHMR_MAX_ITERATIONS: number;
6
+ export declare const SHMR_SIMILARITY_THRESHOLD: number;
7
+ export declare const SHMR_HARMONY_THRESHOLD: number;
8
+ export declare const SHMR_MIN_CLUSTER_SIZE: number;
9
+ export declare const EMBEDDING_DIM = 384;
10
+ export type Vector = Float32Array;
11
+ export interface ShmrItem {
12
+ readonly fact_id?: string;
13
+ readonly subject?: string;
14
+ readonly predicate?: string;
15
+ readonly object?: string;
16
+ readonly content?: string;
17
+ readonly confidence?: number;
18
+ readonly timestamp?: string;
19
+ readonly source?: string;
20
+ readonly embedding?: Vector;
21
+ }
22
+ export interface Belief {
23
+ readonly subject: string;
24
+ readonly predicate: string;
25
+ readonly object: string;
26
+ readonly confidence: number;
27
+ readonly action?: "create" | "update" | "dampen";
28
+ readonly target_fact_id?: string | null;
29
+ readonly rationale?: string;
30
+ }
31
+ export interface HarmonizeStats {
32
+ readonly clusters_found: number;
33
+ readonly beliefs_generated: number;
34
+ readonly contradictions_resolved: number;
35
+ readonly harmony_score_avg: number;
36
+ readonly duration_ms: number;
37
+ readonly status: "insufficient_candidates" | "harmonized" | "no_convergence";
38
+ }
39
+ type BeamLike = {
40
+ readonly conn?: Database;
41
+ readonly db?: Database;
42
+ readonly session_id?: string;
43
+ readonly sessionId?: string;
44
+ };
45
+ export declare const FACTS_SCHEMA_SQL = "\nCREATE TABLE IF NOT EXISTS harmonic_beliefs (\n\tbelief_id TEXT PRIMARY KEY,\n\tsubject TEXT,\n\tpredicate TEXT,\n\tobject TEXT NOT NULL,\n\tconfidence REAL DEFAULT 0.5,\n\tprovenance TEXT,\n\tcluster_id TEXT,\n\titeration INTEGER DEFAULT 0,\n\tcreated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n\tupdated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\nCREATE TABLE IF NOT EXISTS memory_resonance_log (\n\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\tsession_id TEXT,\n\tcluster_count INTEGER,\n\tbeliefs_generated INTEGER,\n\tcontradictions_resolved INTEGER,\n\tharmony_score_avg REAL,\n\tduration_ms INTEGER,\n\tcreated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\nCREATE INDEX IF NOT EXISTS idx_beliefs_subject ON harmonic_beliefs(subject);\nCREATE INDEX IF NOT EXISTS idx_beliefs_predicate ON harmonic_beliefs(predicate);\nCREATE INDEX IF NOT EXISTS idx_beliefs_confidence ON harmonic_beliefs(confidence);\n";
46
+ export declare function initSchema(db: Database): void;
47
+ /**
48
+ * Embed a batch of texts with the configured embedding provider. Falls back to the
49
+ * deterministic SHA1 bag-of-words hash for the entire batch when no provider is
50
+ * available or the provider fails, so every returned vector shares one space.
51
+ */
52
+ export declare function embedBatch(texts: readonly string[]): Promise<Vector[]>;
53
+ export declare function embed(text: string): Promise<Vector>;
54
+ export declare function clusterBySimilarity(items: readonly ShmrItem[], threshold: number): Promise<ShmrItem[][]>;
55
+ export declare function formatClusterForLlm(cluster: readonly ShmrItem[]): string;
56
+ export declare function extractJsonFromLlmOutput(text: string): Belief[];
57
+ export declare function computeHarmonyScore(beliefs: readonly Belief[], cluster: readonly ShmrItem[]): Promise<number>;
58
+ export declare function applyBeliefs(db: Database, beliefs: readonly Belief[], cluster: readonly ShmrItem[], clusterId: string): void;
59
+ export declare function harmonize(beam: BeamLike, batchSize?: number, maxIterations?: number, similarityThreshold?: number): Promise<HarmonizeStats>;
60
+ export declare function recallBeliefs(beam: BeamLike, query: string, topK?: number): Promise<Array<Record<string, unknown>>>;
61
+ export declare function reflect(_beam: BeamLike | null, _question: string, facts?: Array<Record<string, unknown>> | null, topK?: number): string | null;
62
+ export declare function getResonanceLog(beam: BeamLike, limit?: number): Array<Record<string, unknown>>;
@@ -0,0 +1,136 @@
1
+ import type { Database } from "bun:sqlite";
2
+ export declare const ALLOWED_DELTA_TABLES: Set<"episodic_memory" | "working_memory">;
3
+ export type DeltaTable = "working_memory" | "episodic_memory";
4
+ export declare enum EventType {
5
+ MEMORY_ADDED = "MEMORY_ADDED",
6
+ MEMORY_RECALLED = "MEMORY_RECALLED",
7
+ MEMORY_INVALIDATED = "MEMORY_INVALIDATED",
8
+ MEMORY_CONSOLIDATED = "MEMORY_CONSOLIDATED",
9
+ MEMORY_UPDATED = "MEMORY_UPDATED"
10
+ }
11
+ export interface MemoryEventInit {
12
+ readonly eventType?: string;
13
+ readonly event_type?: string;
14
+ readonly memoryId?: string;
15
+ readonly memory_id?: string;
16
+ readonly timestamp?: string;
17
+ readonly sessionId?: string | null;
18
+ readonly session_id?: string | null;
19
+ readonly content?: string | null;
20
+ readonly source?: string | null;
21
+ readonly importance?: number | null;
22
+ readonly metadata?: Record<string, unknown> | null;
23
+ readonly delta?: Record<string, unknown> | null;
24
+ }
25
+ export type MemoryEventDict = {
26
+ event_type: string;
27
+ memory_id: string;
28
+ timestamp: string;
29
+ session_id?: string | null;
30
+ content?: string | null;
31
+ source?: string | null;
32
+ importance?: number | null;
33
+ metadata?: Record<string, unknown> | null;
34
+ delta?: Record<string, unknown> | null;
35
+ };
36
+ export declare class MemoryEvent {
37
+ readonly eventType: EventType;
38
+ readonly memoryId: string;
39
+ readonly timestamp: string;
40
+ readonly sessionId: string | null;
41
+ readonly content: string | null;
42
+ readonly source: string | null;
43
+ readonly importance: number | null;
44
+ readonly metadata: Record<string, unknown> | null;
45
+ readonly delta: Record<string, unknown> | null;
46
+ constructor(init: MemoryEventInit);
47
+ toDict(): MemoryEventDict;
48
+ toJSON(): string;
49
+ static fromDict(data: MemoryEventDict | MemoryEventInit): MemoryEvent;
50
+ }
51
+ export type MemoryEventHandler = (event: MemoryEvent) => void;
52
+ export declare class StreamIterator implements AsyncIterable<MemoryEvent>, AsyncIterator<MemoryEvent> {
53
+ private readonly stream;
54
+ private readonly eventTypes;
55
+ private readonly queue;
56
+ private readonly waiters;
57
+ private closed;
58
+ constructor(stream: MemoryStream, eventTypes?: readonly EventType[] | null);
59
+ push(event: MemoryEvent): void;
60
+ next(): Promise<IteratorResult<MemoryEvent>>;
61
+ return(): Promise<IteratorResult<MemoryEvent>>;
62
+ [Symbol.asyncIterator](): AsyncIterator<MemoryEvent>;
63
+ }
64
+ export declare class MemoryStream {
65
+ private readonly maxBuffer;
66
+ private readonly callbacks;
67
+ private readonly anyCallbacks;
68
+ private readonly buffer;
69
+ private readonly iterators;
70
+ constructor(maxBuffer?: number);
71
+ on(eventType: EventType, callback: MemoryEventHandler): void;
72
+ onAny(callback: MemoryEventHandler): void;
73
+ off(eventType: EventType, callback: MemoryEventHandler): void;
74
+ offAny(callback: MemoryEventHandler): void;
75
+ emit(event: MemoryEvent): void;
76
+ listen(eventTypes?: readonly EventType[] | null): StreamIterator;
77
+ removeIterator(iterator: StreamIterator): void;
78
+ getBuffer(eventTypes?: readonly EventType[] | null, since?: string | null): MemoryEvent[];
79
+ clearBuffer(): void;
80
+ }
81
+ export interface SyncCheckpointInit {
82
+ readonly peerId?: string;
83
+ readonly peer_id?: string;
84
+ readonly lastSyncAt?: string;
85
+ readonly last_sync_at?: string;
86
+ readonly lastRowid?: number;
87
+ readonly last_rowid?: number;
88
+ readonly checksum?: string;
89
+ }
90
+ export declare class SyncCheckpoint {
91
+ readonly peerId: string;
92
+ readonly lastSyncAt: string;
93
+ readonly lastRowid: number;
94
+ readonly checksum: string | null;
95
+ constructor(init: SyncCheckpointInit);
96
+ toDict(): Record<string, unknown>;
97
+ toJson(): string;
98
+ static fromJSON(text: string): SyncCheckpoint;
99
+ }
100
+ type MemoryHost = {
101
+ readonly conn?: Database;
102
+ readonly db?: Database;
103
+ readonly dbPath?: string;
104
+ readonly db_path?: string;
105
+ };
106
+ export declare class DeltaSync {
107
+ readonly mnemopi: MemoryHost;
108
+ readonly checkpointDir: string;
109
+ private readonly db;
110
+ constructor(mnemopi: MemoryHost, checkpointDir?: string);
111
+ private checkpointPath;
112
+ private legacyCheckpointPath;
113
+ getCheckpoint(peerId: string, table?: DeltaTable): SyncCheckpoint | null;
114
+ saveCheckpoint(checkpoint: SyncCheckpoint, table?: DeltaTable): void;
115
+ setCheckpoint(peerId: string, checkpoint: SyncCheckpoint, table?: DeltaTable): void;
116
+ computeDelta(peerId: string, table?: DeltaTable): Record<string, unknown>[];
117
+ applyDelta(peerId: string, delta: readonly Record<string, unknown>[], table?: DeltaTable): {
118
+ inserted: number;
119
+ updated: number;
120
+ skipped: number;
121
+ filtered_keys: number;
122
+ };
123
+ syncTo(peerId: string, table?: DeltaTable): {
124
+ delta: Record<string, unknown>[];
125
+ count: number;
126
+ };
127
+ syncFrom(peerId: string, delta: readonly Record<string, unknown>[], table?: DeltaTable): {
128
+ stats: {
129
+ inserted: number;
130
+ updated: number;
131
+ skipped: number;
132
+ filtered_keys: number;
133
+ };
134
+ };
135
+ }
136
+ export {};