jeopi-mnemopi 16.2.13

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 +172 -0
  2. package/README.md +107 -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 +32 -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 +32 -0
  12. package/dist/types/core/beam/schema.d.ts +2 -0
  13. package/dist/types/core/beam/store.d.ts +56 -0
  14. package/dist/types/core/beam/types.d.ts +245 -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 +54 -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 +7 -0
  26. package/dist/types/core/fastembed-model-cache.d.ts +2 -0
  27. package/dist/types/core/fastembed-runtime.d.ts +14 -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 +178 -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 +16 -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 +457 -0
  74. package/src/core/banks.ts +133 -0
  75. package/src/core/beam/consolidate.ts +1068 -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 +1173 -0
  79. package/src/core/beam/schema.ts +423 -0
  80. package/src/core/beam/store.ts +936 -0
  81. package/src/core/beam/types.ts +280 -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 +103 -0
  86. package/src/core/embeddings.ts +531 -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 +338 -0
  93. package/src/core/fastembed-model-cache.ts +39 -0
  94. package/src/core/fastembed-runtime.ts +108 -0
  95. package/src/core/index.ts +38 -0
  96. package/src/core/llm-backends.ts +54 -0
  97. package/src/core/local-llm.ts +474 -0
  98. package/src/core/memory.ts +667 -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 +71 -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 +353 -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 +560 -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 +84 -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 +128 -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,66 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { type Env } from "../config";
3
+ import { type DatabasePath } from "../db";
4
+ import type { BeamMemoryState, JsonValue, Metadata, RecallResult } from "./beam/types";
5
+ import { EpisodicGraph } from "./episodic-graph";
6
+ import { VeracityConsolidator } from "./veracity-consolidation";
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";
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 "jeopi-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";
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 {};
@@ -0,0 +1,46 @@
1
+ export declare const SYNONYM_GROUPS: {
2
+ readonly database: readonly ["db", "datastore", "data_store"];
3
+ readonly password: readonly ["pass", "pwd", "passwd", "credential", "secret", "token"];
4
+ readonly config: readonly ["configuration", "settings", "cfg", "setup"];
5
+ readonly error: readonly ["bug", "issue", "fault", "failure", "crash", "exception", "traceback"];
6
+ readonly fix: readonly ["repair", "resolve", "solve", "patch", "correct", "address"];
7
+ readonly deploy: readonly ["deployment", "release", "ship", "push", "rollout"];
8
+ readonly server: readonly ["host", "machine", "vm", "instance", "node", "vps"];
9
+ readonly api: readonly ["endpoint", "interface", "service"];
10
+ readonly key: readonly ["token", "credential", "secret", "api_key"];
11
+ readonly user: readonly ["account", "profile", "identity", "person"];
12
+ readonly model: readonly ["llm", "ai", "provider", "gpt", "claude", "gemini"];
13
+ readonly speed: readonly ["fast", "quick", "performance", "latency", "throughput"];
14
+ readonly memory: readonly ["recall", "remember", "storage", "retention"];
15
+ readonly search: readonly ["find", "lookup", "query", "retrieve", "locate"];
16
+ readonly file: readonly ["document", "doc", "text", "note"];
17
+ readonly code: readonly ["script", "program", "source", "implementation"];
18
+ readonly test: readonly ["verify", "check", "validate", "probe", "examine"];
19
+ readonly backup: readonly ["snapshot", "copy", "save", "archive"];
20
+ readonly install: readonly ["setup", "configure", "bootstrap", "init"];
21
+ readonly update: readonly ["upgrade", "refresh", "renew", "sync"];
22
+ readonly delete: readonly ["remove", "destroy", "purge", "clean", "wipe", "erase"];
23
+ readonly list: readonly ["show", "display", "enumerate", "catalog"];
24
+ readonly time: readonly ["date", "when", "timestamp", "schedule"];
25
+ readonly url: readonly ["link", "address", "uri", "path"];
26
+ readonly health: readonly ["status", "check", "pulse", "alive", "up"];
27
+ readonly service: readonly ["daemon", "process", "systemd", "worker"];
28
+ readonly port: readonly ["socket", "bind", "listen"];
29
+ readonly network: readonly ["internet", "connection", "connectivity", "dns"];
30
+ readonly ssh: readonly ["terminal", "shell", "remote", "connect"];
31
+ readonly git: readonly ["commit", "push", "pull", "repo", "repository", "branch"];
32
+ readonly log: readonly ["output", "stdout", "stderr", "trace", "debug"];
33
+ readonly cron: readonly ["schedule", "job", "task", "timer", "periodic"];
34
+ readonly email: readonly ["mail", "message", "inbox", "smtp"];
35
+ readonly image: readonly ["picture", "photo", "screenshot", "graphic"];
36
+ readonly browser: readonly ["web", "page", "site", "navigate", "chrome"];
37
+ readonly monitor: readonly ["watch", "observe", "track", "survey"];
38
+ readonly alert: readonly ["notify", "notification", "warning", "ping"];
39
+ readonly migrate: readonly ["transfer", "move", "relocate", "port"];
40
+ readonly compare: readonly ["diff", "versus", "vs", "contrast"];
41
+ readonly save: readonly ["store", "persist", "preserve", "keep"];
42
+ };
43
+ export declare const STOP_WORDS: Set<string>;
44
+ export declare function normalizeQuery(query: string): string;
45
+ export declare function expandQuery(query: string): string;
46
+ export declare function getSynonyms(word: string): string[];
@@ -0,0 +1,16 @@
1
+ import { type QueryTime } from "../util/datetime";
2
+ export type DatePrecision = "day" | "week" | "month" | "year" | "relative" | "unknown";
3
+ export type ParsedNaturalDate = [eventDate: Date, precision: Exclude<DatePrecision, "unknown">, temporalTags: string[]];
4
+ export interface TemporalInfo {
5
+ event_date: string | null;
6
+ event_date_precision: DatePrecision;
7
+ temporal_tags: string[];
8
+ primary_signal: string | null;
9
+ }
10
+ export declare const DAY_MAP: Readonly<Record<string, number>>;
11
+ export declare const MONTH_MAP: Readonly<Record<string, number>>;
12
+ export declare const NAMED_TIMES: Readonly<Record<string, readonly [startHour: number, endHour: number]>>;
13
+ export declare function resolveRelativeDay(reference: Date, dayNameText: string, qualifier?: string): Date;
14
+ export declare function parseNlDate(text: string, reference?: QueryTime): ParsedNaturalDate | null;
15
+ export declare function extractTemporal(text: string, reference?: QueryTime): TemporalInfo;
16
+ export declare function extractDateFromText(text: string, reference?: QueryTime): string | null;
@@ -0,0 +1,8 @@
1
+ export interface CostEstimate {
2
+ tokens: number;
3
+ model: string;
4
+ cost_usd: number;
5
+ rate_per_1m: number;
6
+ }
7
+ export declare function estimateTokens(text: string, _model?: string): number;
8
+ export declare function estimateCost(tokens: number, model?: string): CostEstimate;
@@ -0,0 +1,63 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { type DatabasePath } from "../db";
3
+ export interface TripleRow {
4
+ id: number;
5
+ subject: string;
6
+ predicate: string;
7
+ object: string;
8
+ valid_from: string;
9
+ valid_until: string | null;
10
+ source: string | null;
11
+ confidence: number | null;
12
+ created_at: string | null;
13
+ }
14
+ export interface TripleWriteOptions {
15
+ readonly validFrom?: string | null;
16
+ readonly valid_from?: string | null;
17
+ readonly source?: string | null;
18
+ readonly confidence?: number | null;
19
+ }
20
+ export interface TripleQueryOptions {
21
+ readonly subject?: string | null;
22
+ readonly predicate?: string | null;
23
+ readonly object?: string | null;
24
+ readonly asOf?: string | null;
25
+ readonly as_of?: string | null;
26
+ }
27
+ export interface TripleImportStats {
28
+ inserted: number;
29
+ skipped: number;
30
+ overwritten: number;
31
+ imported_renumbered: number;
32
+ }
33
+ export type TripleImportRow = Partial<Omit<TripleRow, "id">> & {
34
+ readonly id?: number | null;
35
+ };
36
+ type ProcessEnv = Record<string, string | undefined>;
37
+ export declare function legacyDataDir(env?: ProcessEnv): string;
38
+ export declare function defaultDataDir(env?: ProcessEnv): string;
39
+ export declare function defaultTripleDbPath(env?: ProcessEnv): string;
40
+ export declare function legacyTripleDbPath(env?: ProcessEnv): string;
41
+ export declare function resolveDefaultTripleDb(env?: ProcessEnv): string;
42
+ export declare function initTriples(dbOrPath?: Database | DatabasePath | null): void;
43
+ export declare class TripleStore {
44
+ #private;
45
+ readonly dbPath: DatabasePath;
46
+ readonly conn: Database;
47
+ constructor(dbPath?: DatabasePath | Database | null);
48
+ close(): void;
49
+ add(subject: string, predicate: string, object: string, options?: TripleWriteOptions | string | null): number;
50
+ query(options?: TripleQueryOptions): TripleRow[];
51
+ query(subject?: string | null, predicate?: string | null, object?: string | null, asOf?: string | null): TripleRow[];
52
+ queryByPredicate(predicate: string, object?: string | null, subject?: string | null): TripleRow[];
53
+ getDistinctObjects(predicate: string): string[];
54
+ exportAll(): TripleRow[];
55
+ importAll(triples: readonly TripleImportRow[], force?: boolean): TripleImportStats;
56
+ }
57
+ export declare function addTriple(subject: string, predicate: string, object: string, options?: TripleWriteOptions & {
58
+ readonly dbPath?: DatabasePath | null;
59
+ }): number;
60
+ export declare function queryTriples(options?: TripleQueryOptions & {
61
+ readonly dbPath?: DatabasePath | null;
62
+ }): TripleRow[];
63
+ export {};
@@ -0,0 +1,39 @@
1
+ export declare const MemoryType: {
2
+ readonly FACT: "fact";
3
+ readonly PREFERENCE: "preference";
4
+ readonly DECISION: "decision";
5
+ readonly COMMITMENT: "commitment";
6
+ readonly GOAL: "goal";
7
+ readonly EVENT: "event";
8
+ readonly INSTRUCTION: "instruction";
9
+ readonly RELATIONSHIP: "relationship";
10
+ readonly CONTEXT: "context";
11
+ readonly LEARNING: "learning";
12
+ readonly OBSERVATION: "observation";
13
+ readonly ERROR: "error";
14
+ readonly ARTIFACT: "artifact";
15
+ readonly UNKNOWN: "unknown";
16
+ };
17
+ export type MemoryType = (typeof MemoryType)[keyof typeof MemoryType];
18
+ export type TypePriority = "stable" | "moderate" | "high" | "time_critical" | "decaying" | "accumulating" | "evolving" | "persistent" | "reference";
19
+ export interface TypeMatch {
20
+ memory_type: MemoryType;
21
+ memoryType: MemoryType;
22
+ confidence: number;
23
+ matched_pattern: string;
24
+ matchedPattern: string;
25
+ priority: TypePriority;
26
+ }
27
+ export type TypePattern = readonly [
28
+ pattern: string,
29
+ memoryType: MemoryType,
30
+ baseConfidence: number,
31
+ priority: TypePriority
32
+ ];
33
+ export declare const TYPE_PATTERNS: readonly TypePattern[];
34
+ export declare const CONFIDENCE_BOOSTERS: Readonly<Record<MemoryType, readonly string[]>>;
35
+ export declare function classifyMemory(content: string): TypeMatch;
36
+ export declare function classifyBatch(contents: readonly string[]): TypeMatch[];
37
+ export declare function getTypePriority(memoryType: MemoryType | string): number;
38
+ export declare function shouldConsolidate(memoryType: MemoryType | string): boolean;
39
+ export declare function getDecayRate(memoryType: MemoryType | string): number;
@@ -0,0 +1,16 @@
1
+ export interface ExactVectorSearchHit<TId> {
2
+ id: TId;
3
+ score: number;
4
+ }
5
+ export interface ExactVectorIndex<TId> {
6
+ readonly ids: readonly TId[];
7
+ readonly matrix: Float32Array;
8
+ readonly dimensions: number;
9
+ readonly count: number;
10
+ }
11
+ export interface VectorIndexRow<TId> {
12
+ id: TId;
13
+ vector: readonly number[] | null | undefined;
14
+ }
15
+ export declare function buildExactVectorIndex<TId>(rows: readonly VectorIndexRow<TId>[]): ExactVectorIndex<TId>;
16
+ export declare function searchExactVectorIndex<TId>(index: ExactVectorIndex<TId>, query: readonly number[], limit: number): ExactVectorSearchHit<TId>[];
@@ -0,0 +1 @@
1
+ export declare function cosineSimilarity(a: ArrayLike<number>, b: ArrayLike<number>): number;