@chude/memory 4.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 (184) hide show
  1. package/README.md +294 -0
  2. package/dist/application/index.d.ts +6 -0
  3. package/dist/application/services/ambient-context-service.d.ts +90 -0
  4. package/dist/application/services/backfill-service.d.ts +71 -0
  5. package/dist/application/services/budget-allocator.d.ts +57 -0
  6. package/dist/application/services/embedding-service.d.ts +131 -0
  7. package/dist/application/services/export-service.d.ts +225 -0
  8. package/dist/application/services/extraction-pipeline.d.ts +50 -0
  9. package/dist/application/services/friction-service.d.ts +148 -0
  10. package/dist/application/services/fts-sanitizer.d.ts +25 -0
  11. package/dist/application/services/index.d.ts +34 -0
  12. package/dist/application/services/llm-extractor.d.ts +96 -0
  13. package/dist/application/services/memory-file-sync-service.d.ts +58 -0
  14. package/dist/application/services/pattern-extractor.d.ts +95 -0
  15. package/dist/application/services/recovery-service.d.ts +81 -0
  16. package/dist/application/services/rrf-fusion.d.ts +53 -0
  17. package/dist/application/services/smart-context-service.d.ts +126 -0
  18. package/dist/application/services/sync-service.d.ts +157 -0
  19. package/dist/application/services/temporal-decay.d.ts +62 -0
  20. package/dist/domain/entities/backfill-state.d.ts +56 -0
  21. package/dist/domain/entities/entity.d.ts +131 -0
  22. package/dist/domain/entities/extraction-state.d.ts +128 -0
  23. package/dist/domain/entities/fact.d.ts +59 -0
  24. package/dist/domain/entities/friction-entry.d.ts +84 -0
  25. package/dist/domain/entities/index.d.ts +15 -0
  26. package/dist/domain/entities/link.d.ts +74 -0
  27. package/dist/domain/entities/memory-file.d.ts +78 -0
  28. package/dist/domain/entities/message.d.ts +70 -0
  29. package/dist/domain/entities/session.d.ts +93 -0
  30. package/dist/domain/entities/tool-use.d.ts +85 -0
  31. package/dist/domain/errors/error-codes.d.ts +37 -0
  32. package/dist/domain/errors/index.d.ts +8 -0
  33. package/dist/domain/errors/memory-error.d.ts +52 -0
  34. package/dist/domain/errors/unknown-error.d.ts +9 -0
  35. package/dist/domain/index.d.ts +11 -0
  36. package/dist/domain/ports/embedding.d.ts +96 -0
  37. package/dist/domain/ports/extraction.d.ts +13 -0
  38. package/dist/domain/ports/index.d.ts +14 -0
  39. package/dist/domain/ports/redactor.d.ts +17 -0
  40. package/dist/domain/ports/repositories.d.ts +658 -0
  41. package/dist/domain/ports/services.d.ts +180 -0
  42. package/dist/domain/ports/signals.d.ts +82 -0
  43. package/dist/domain/ports/sources.d.ts +122 -0
  44. package/dist/domain/ports/types.d.ts +150 -0
  45. package/dist/domain/services/content-extractor.d.ts +61 -0
  46. package/dist/domain/services/index.d.ts +8 -0
  47. package/dist/domain/services/path-decoder.d.ts +56 -0
  48. package/dist/domain/services/query-parser.d.ts +47 -0
  49. package/dist/domain/value-objects/embedding-config.d.ts +56 -0
  50. package/dist/domain/value-objects/embedding-result.d.ts +46 -0
  51. package/dist/domain/value-objects/index.d.ts +10 -0
  52. package/dist/domain/value-objects/project-path.d.ts +92 -0
  53. package/dist/domain/value-objects/search-query.d.ts +30 -0
  54. package/dist/domain/value-objects/search-result.d.ts +92 -0
  55. package/dist/index.d.ts +15 -0
  56. package/dist/index.js +1548 -0
  57. package/dist/infrastructure/database/connection.d.ts +161 -0
  58. package/dist/infrastructure/database/event-log.d.ts +22 -0
  59. package/dist/infrastructure/database/health-checker.d.ts +248 -0
  60. package/dist/infrastructure/database/index.d.ts +11 -0
  61. package/dist/infrastructure/database/repositories/backfill-state-repository.d.ts +19 -0
  62. package/dist/infrastructure/database/repositories/embedding-repository.d.ts +121 -0
  63. package/dist/infrastructure/database/repositories/entity-repository.d.ts +73 -0
  64. package/dist/infrastructure/database/repositories/extraction-log-repository.d.ts +17 -0
  65. package/dist/infrastructure/database/repositories/extraction-state-repository.d.ts +52 -0
  66. package/dist/infrastructure/database/repositories/fact-repository.d.ts +25 -0
  67. package/dist/infrastructure/database/repositories/friction-repository.d.ts +41 -0
  68. package/dist/infrastructure/database/repositories/index.d.ts +17 -0
  69. package/dist/infrastructure/database/repositories/link-repository.d.ts +64 -0
  70. package/dist/infrastructure/database/repositories/memory-file-repository.d.ts +28 -0
  71. package/dist/infrastructure/database/repositories/message-repository.d.ts +87 -0
  72. package/dist/infrastructure/database/repositories/session-repository.d.ts +125 -0
  73. package/dist/infrastructure/database/repositories/tool-use-repository.d.ts +72 -0
  74. package/dist/infrastructure/database/schema.d.ts +203 -0
  75. package/dist/infrastructure/database/services/context-service.d.ts +93 -0
  76. package/dist/infrastructure/database/services/hybrid-search-service.d.ts +156 -0
  77. package/dist/infrastructure/database/services/index.d.ts +10 -0
  78. package/dist/infrastructure/database/services/search-service.d.ts +57 -0
  79. package/dist/infrastructure/database/services/stats-service.d.ts +36 -0
  80. package/dist/infrastructure/embedding/background-embedder.d.ts +125 -0
  81. package/dist/infrastructure/embedding/embedding-provider-factory.d.ts +44 -0
  82. package/dist/infrastructure/embedding/index.d.ts +5 -0
  83. package/dist/infrastructure/embedding/ollama-provider.d.ts +41 -0
  84. package/dist/infrastructure/embedding/openai-provider.d.ts +38 -0
  85. package/dist/infrastructure/embedding/transformers-js-provider.d.ts +34 -0
  86. package/dist/infrastructure/external/index.d.ts +7 -0
  87. package/dist/infrastructure/external/qmd-runner.d.ts +36 -0
  88. package/dist/infrastructure/hooks/auto-memory-writer.d.ts +52 -0
  89. package/dist/infrastructure/hooks/config-manager.d.ts +237 -0
  90. package/dist/infrastructure/hooks/git-syncer.d.ts +44 -0
  91. package/dist/infrastructure/hooks/hook-runner.d.ts +126 -0
  92. package/dist/infrastructure/hooks/index.d.ts +12 -0
  93. package/dist/infrastructure/hooks/log-writer.d.ts +106 -0
  94. package/dist/infrastructure/hooks/settings-manager.d.ts +163 -0
  95. package/dist/infrastructure/hooks/sync-hook-script.d.ts +83 -0
  96. package/dist/infrastructure/hooks/sync-logger-adapter.d.ts +17 -0
  97. package/dist/infrastructure/index.d.ts +11 -0
  98. package/dist/infrastructure/llm/anthropic-extractor.d.ts +20 -0
  99. package/dist/infrastructure/llm/claude-cli-extractor.d.ts +14 -0
  100. package/dist/infrastructure/llm/claude-summary-generator.d.ts +14 -0
  101. package/dist/infrastructure/llm/extraction-helper.d.ts +16 -0
  102. package/dist/infrastructure/llm/ollama-extractor.d.ts +20 -0
  103. package/dist/infrastructure/llm/openai-extractor.d.ts +23 -0
  104. package/dist/infrastructure/migration.d.ts +103 -0
  105. package/dist/infrastructure/parsers/event-classifier.d.ts +111 -0
  106. package/dist/infrastructure/parsers/index.d.ts +8 -0
  107. package/dist/infrastructure/parsers/jsonl-parser.d.ts +25 -0
  108. package/dist/infrastructure/parsers/timestamp.d.ts +18 -0
  109. package/dist/infrastructure/paths.d.ts +129 -0
  110. package/dist/infrastructure/providers/provider-defaults.d.ts +11 -0
  111. package/dist/infrastructure/providers/provider-registry.d.ts +28 -0
  112. package/dist/infrastructure/security/pattern-redactor.d.ts +6 -0
  113. package/dist/infrastructure/signals/adapters.d.ts +27 -0
  114. package/dist/infrastructure/signals/checkpoint-manager.d.ts +83 -0
  115. package/dist/infrastructure/signals/index.d.ts +8 -0
  116. package/dist/infrastructure/signals/signal-handler.d.ts +113 -0
  117. package/dist/infrastructure/sources/index.d.ts +8 -0
  118. package/dist/infrastructure/sources/memory-file-scanner.d.ts +23 -0
  119. package/dist/infrastructure/sources/project-name-resolver.d.ts +67 -0
  120. package/dist/infrastructure/sources/session-source.d.ts +70 -0
  121. package/dist/presentation/cli/command-result.d.ts +10 -0
  122. package/dist/presentation/cli/commands/_helpers/capture-json.d.ts +36 -0
  123. package/dist/presentation/cli/commands/_helpers/deprecation-warning.d.ts +41 -0
  124. package/dist/presentation/cli/commands/backfill.d.ts +56 -0
  125. package/dist/presentation/cli/commands/browse.d.ts +55 -0
  126. package/dist/presentation/cli/commands/completion.d.ts +61 -0
  127. package/dist/presentation/cli/commands/context.d.ts +53 -0
  128. package/dist/presentation/cli/commands/doctor.d.ts +55 -0
  129. package/dist/presentation/cli/commands/export.d.ts +36 -0
  130. package/dist/presentation/cli/commands/extract.d.ts +40 -0
  131. package/dist/presentation/cli/commands/facts.d.ts +17 -0
  132. package/dist/presentation/cli/commands/friction/dashboard.d.ts +18 -0
  133. package/dist/presentation/cli/commands/friction/index.d.ts +12 -0
  134. package/dist/presentation/cli/commands/friction/list.d.ts +12 -0
  135. package/dist/presentation/cli/commands/friction/log.d.ts +12 -0
  136. package/dist/presentation/cli/commands/friction/purge.d.ts +12 -0
  137. package/dist/presentation/cli/commands/friction/resolve.d.ts +12 -0
  138. package/dist/presentation/cli/commands/friction/types.d.ts +86 -0
  139. package/dist/presentation/cli/commands/friction/wontfix.d.ts +12 -0
  140. package/dist/presentation/cli/commands/import.d.ts +38 -0
  141. package/dist/presentation/cli/commands/index.d.ts +51 -0
  142. package/dist/presentation/cli/commands/install.d.ts +67 -0
  143. package/dist/presentation/cli/commands/list.d.ts +61 -0
  144. package/dist/presentation/cli/commands/migrate.d.ts +36 -0
  145. package/dist/presentation/cli/commands/purge.d.ts +100 -0
  146. package/dist/presentation/cli/commands/query.d.ts +51 -0
  147. package/dist/presentation/cli/commands/related.d.ts +47 -0
  148. package/dist/presentation/cli/commands/remote.d.ts +36 -0
  149. package/dist/presentation/cli/commands/search.d.ts +100 -0
  150. package/dist/presentation/cli/commands/show.d.ts +51 -0
  151. package/dist/presentation/cli/commands/stats.d.ts +38 -0
  152. package/dist/presentation/cli/commands/status.d.ts +152 -0
  153. package/dist/presentation/cli/commands/sync/ambient.d.ts +22 -0
  154. package/dist/presentation/cli/commands/sync/background.d.ts +23 -0
  155. package/dist/presentation/cli/commands/sync/embedding-pass.d.ts +32 -0
  156. package/dist/presentation/cli/commands/sync/helpers.d.ts +25 -0
  157. package/dist/presentation/cli/commands/sync/index.d.ts +17 -0
  158. package/dist/presentation/cli/commands/sync/memory-files.d.ts +26 -0
  159. package/dist/presentation/cli/commands/sync/types.d.ts +163 -0
  160. package/dist/presentation/cli/commands/uninstall.d.ts +44 -0
  161. package/dist/presentation/cli/db-startup.d.ts +61 -0
  162. package/dist/presentation/cli/formatters/ai-formatter.d.ts +38 -0
  163. package/dist/presentation/cli/formatters/color.d.ts +82 -0
  164. package/dist/presentation/cli/formatters/context-formatter.d.ts +55 -0
  165. package/dist/presentation/cli/formatters/dto-helpers.d.ts +176 -0
  166. package/dist/presentation/cli/formatters/envelope.d.ts +136 -0
  167. package/dist/presentation/cli/formatters/error-formatter.d.ts +41 -0
  168. package/dist/presentation/cli/formatters/friction-dashboard.d.ts +46 -0
  169. package/dist/presentation/cli/formatters/index.d.ts +17 -0
  170. package/dist/presentation/cli/formatters/list-formatter.d.ts +48 -0
  171. package/dist/presentation/cli/formatters/output-formatter.d.ts +98 -0
  172. package/dist/presentation/cli/formatters/related-formatter.d.ts +57 -0
  173. package/dist/presentation/cli/formatters/show-formatter.d.ts +63 -0
  174. package/dist/presentation/cli/formatters/stats-formatter.d.ts +54 -0
  175. package/dist/presentation/cli/formatters/text-width.d.ts +37 -0
  176. package/dist/presentation/cli/formatters/timestamp-formatter.d.ts +38 -0
  177. package/dist/presentation/cli/index.d.ts +10 -0
  178. package/dist/presentation/cli/index.js +1664 -0
  179. package/dist/presentation/cli/parsers/date-parser.d.ts +28 -0
  180. package/dist/presentation/cli/parsers/index.d.ts +6 -0
  181. package/dist/presentation/cli/pickers/index.d.ts +6 -0
  182. package/dist/presentation/cli/pickers/session-picker.d.ts +59 -0
  183. package/dist/presentation/cli/progress-reporter.d.ts +199 -0
  184. package/package.json +94 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Background Embedder
3
+ *
4
+ * Manages background embedding processes with PID lock file lifecycle.
5
+ * The lock file prevents concurrent embedding runs and provides status
6
+ * information for the `memory status` command.
7
+ *
8
+ * Design:
9
+ * - Spawns a detached child process that runs `memory sync --embed --quiet`
10
+ * - PID lock file at {dataDir}/embedding.lock prevents double-run
11
+ * - Stale lock detection via process.kill(pid, 0) signal check
12
+ * - MEMORY_EMBED_BACKGROUND=1 env var signals background mode
13
+ * - Background process cleans up lock file on completion (success or failure)
14
+ */
15
+ /**
16
+ * PID lock file data structure.
17
+ */
18
+ export interface LockData {
19
+ pid: number;
20
+ startedAt: string;
21
+ totalMessages: number;
22
+ }
23
+ /**
24
+ * Result of a lock acquisition attempt.
25
+ */
26
+ export interface AcquireResult {
27
+ acquired: boolean;
28
+ staleRemoved?: boolean | undefined;
29
+ existingPid?: number | undefined;
30
+ startedAt?: string | undefined;
31
+ }
32
+ /**
33
+ * Result of spawning a background embedding process.
34
+ */
35
+ export interface SpawnResult {
36
+ started: boolean;
37
+ pid?: number | undefined;
38
+ reason?: "already_running" | "spawn_failed" | undefined;
39
+ }
40
+ /**
41
+ * Options for spawnBackgroundEmbedding.
42
+ */
43
+ export interface SpawnBackgroundOptions {
44
+ dataDir?: string;
45
+ logDir?: string;
46
+ command?: string;
47
+ }
48
+ /**
49
+ * Write a PID lock file with the given data.
50
+ *
51
+ * Creates the data directory if it does not exist.
52
+ *
53
+ * @param data Lock file data (pid, startedAt, totalMessages)
54
+ * @param dataDir Optional override for data directory
55
+ */
56
+ export declare function writeLock(data: LockData, dataDir?: string): void;
57
+ /**
58
+ * Read the PID lock file.
59
+ *
60
+ * @param dataDir Optional override for data directory
61
+ * @returns Parsed lock data, or null if file does not exist or is invalid
62
+ */
63
+ export declare function readLock(dataDir?: string): LockData | null;
64
+ /**
65
+ * Remove the PID lock file.
66
+ *
67
+ * No-op if the lock file does not exist.
68
+ *
69
+ * @param dataDir Optional override for data directory
70
+ */
71
+ export declare function removeLock(dataDir?: string): void;
72
+ /**
73
+ * Check if a process with the given PID is alive.
74
+ *
75
+ * Uses signal 0 (existence check) which does not actually kill the process.
76
+ *
77
+ * @param pid Process ID to check
78
+ * @returns true if the process exists, false otherwise
79
+ */
80
+ export declare function isProcessAlive(pid: number): boolean;
81
+ /**
82
+ * Attempt to acquire the embedding lock.
83
+ *
84
+ * - If no lock exists: creates lock and returns acquired:true
85
+ * - If lock held by alive process: returns acquired:false with existingPid
86
+ * - If lock held by dead process (stale): removes stale lock, creates new one
87
+ *
88
+ * @param pid Process ID to write into lock
89
+ * @param totalMessages Total message count (informational)
90
+ * @param dataDir Optional override for data directory
91
+ * @returns Acquisition result
92
+ */
93
+ export declare function acquireLock(pid: number, totalMessages: number, dataDir?: string): AcquireResult;
94
+ /**
95
+ * Spawn a background embedding process.
96
+ *
97
+ * Creates a detached child process that runs `memory sync --embed --quiet`
98
+ * with MEMORY_EMBED_BACKGROUND=1 in its environment. The parent process
99
+ * can exit immediately after spawning.
100
+ *
101
+ * If the lock is already held by an alive process, returns without spawning.
102
+ *
103
+ * @param options Configuration options
104
+ * @returns Spawn result with PID or failure reason
105
+ */
106
+ export declare function spawnBackgroundEmbedding(options?: SpawnBackgroundOptions): SpawnResult;
107
+ /**
108
+ * Clean up the PID lock file.
109
+ *
110
+ * Called by the background embedding process on completion (both success
111
+ * and failure) to release the lock.
112
+ *
113
+ * @param dataDir Optional override for data directory
114
+ */
115
+ export declare function cleanupLock(dataDir?: string): void;
116
+ /**
117
+ * Check if the current process is a background embedding process.
118
+ *
119
+ * The foreground sync command sets MEMORY_EMBED_BACKGROUND=1 when
120
+ * spawning the background process. This function checks that env var
121
+ * so the background process does NOT re-spawn another background process.
122
+ *
123
+ * @returns true if running as background embedding process
124
+ */
125
+ export declare function isBackgroundEmbedding(): boolean;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * EmbeddingProviderFactory
3
+ *
4
+ * Creates embedding providers from configuration. Caches provider instances
5
+ * to avoid redundant resource allocation. The factory does NOT call
6
+ * initialize() -- the caller controls when the ONNX runtime loads.
7
+ *
8
+ * Supported providers:
9
+ * - "local" -> TransformersJsProvider
10
+ * - "openai" -> OpenAiProvider
11
+ * - "ollama" -> OllamaProvider
12
+ */
13
+ import type { IEmbeddingProvider } from "../../domain/ports/embedding.js";
14
+ import type { EmbeddingConfigData } from "../hooks/config-manager.js";
15
+ export declare class EmbeddingProviderFactory {
16
+ private cache;
17
+ /**
18
+ * Generate a cache key from embedding config.
19
+ */
20
+ private cacheKey;
21
+ /**
22
+ * Create an embedding provider from config.
23
+ *
24
+ * The returned provider is NOT initialized -- call initialize()
25
+ * before embed(). Repeated calls with the same config return the
26
+ * cached instance.
27
+ *
28
+ * @throws Error if provider type is unsupported
29
+ */
30
+ create(config: EmbeddingConfigData): IEmbeddingProvider;
31
+ /**
32
+ * Create an embedding provider from a MemoryConfig object.
33
+ *
34
+ * Reads the embedding section and delegates to create().
35
+ * Returns null if embedding is disabled.
36
+ */
37
+ createFromConfig(memoryConfig: {
38
+ embedding?: EmbeddingConfigData;
39
+ }): IEmbeddingProvider | null;
40
+ /**
41
+ * Dispose all cached providers and clear the cache.
42
+ */
43
+ dispose(): Promise<void>;
44
+ }
@@ -0,0 +1,5 @@
1
+ export { TransformersJsProvider } from "./transformers-js-provider.js";
2
+ export { OpenAiProvider } from "./openai-provider.js";
3
+ export { OllamaProvider } from "./ollama-provider.js";
4
+ export { EmbeddingProviderFactory } from "./embedding-provider-factory.js";
5
+ export { writeLock, readLock, removeLock, isProcessAlive, acquireLock, spawnBackgroundEmbedding, cleanupLock, isBackgroundEmbedding, type LockData, type AcquireResult, type SpawnResult, type SpawnBackgroundOptions, } from "./background-embedder.js";
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Ollama Embedding Provider
3
+ *
4
+ * Infrastructure adapter implementing IEmbeddingProvider using the
5
+ * Ollama HTTP API. Communicates via native fetch() -- no npm
6
+ * dependencies required.
7
+ *
8
+ * Key design decisions:
9
+ * - Server reachability check during initialize(): GET /api/tags verifies
10
+ * the Ollama server is running. Failure throws an actionable error
11
+ * with recovery instructions.
12
+ * - Single-request batch: Ollama /api/embed accepts array input and
13
+ * returns embeddings[] in the same order.
14
+ * - Model-not-found detection: 404 responses include a hint to pull
15
+ * the model via `ollama pull`.
16
+ */
17
+ import type { IEmbeddingProvider, DownloadProgress } from "../../domain/ports/embedding.js";
18
+ import { EmbeddingResult } from "../../domain/value-objects/embedding-result.js";
19
+ interface OllamaProviderOptions {
20
+ model?: string | undefined;
21
+ dimensions?: number | undefined;
22
+ baseUrl?: string | undefined;
23
+ }
24
+ export declare class OllamaProvider implements IEmbeddingProvider {
25
+ readonly name = "ollama";
26
+ readonly model: string;
27
+ readonly dimensions: number;
28
+ private readonly baseUrl;
29
+ private _ready;
30
+ constructor(options?: OllamaProviderOptions);
31
+ initialize(_onProgress?: (progress: DownloadProgress) => void): Promise<void>;
32
+ embed(text: string): Promise<EmbeddingResult>;
33
+ embedBatch(texts: string[]): Promise<EmbeddingResult[]>;
34
+ isReady(): boolean;
35
+ dispose(): Promise<void>;
36
+ /**
37
+ * Throw an error with an actionable hint for model-not-found cases.
38
+ */
39
+ private throwWithHint;
40
+ }
41
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * OpenAI Embedding Provider
3
+ *
4
+ * Infrastructure adapter implementing IEmbeddingProvider using the
5
+ * OpenAI embeddings API. Communicates via native fetch() -- no npm
6
+ * dependencies required.
7
+ *
8
+ * Key design decisions:
9
+ * - No API health check during initialize(): mark ready immediately
10
+ * to avoid blocking on network calls during startup.
11
+ * - Single-request batch: OpenAI accepts array input, returns indexed
12
+ * data[] that we sort by index for deterministic ordering.
13
+ * - Error messages include HTTP status for programmatic handling.
14
+ */
15
+ import type { IEmbeddingProvider, DownloadProgress } from "../../domain/ports/embedding.js";
16
+ import { EmbeddingResult } from "../../domain/value-objects/embedding-result.js";
17
+ interface OpenAiProviderOptions {
18
+ apiKey: string;
19
+ model?: string | undefined;
20
+ dimensions?: number | undefined;
21
+ baseUrl?: string | undefined;
22
+ providerId?: string | undefined;
23
+ }
24
+ export declare class OpenAiProvider implements IEmbeddingProvider {
25
+ readonly name: string;
26
+ readonly model: string;
27
+ readonly dimensions: number;
28
+ private readonly apiKey;
29
+ private readonly baseUrl;
30
+ private _ready;
31
+ constructor(options: OpenAiProviderOptions);
32
+ initialize(_onProgress?: (progress: DownloadProgress) => void): Promise<void>;
33
+ embed(text: string): Promise<EmbeddingResult>;
34
+ embedBatch(texts: string[]): Promise<EmbeddingResult[]>;
35
+ isReady(): boolean;
36
+ dispose(): Promise<void>;
37
+ }
38
+ export {};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * TransformersJsProvider
3
+ *
4
+ * Infrastructure adapter implementing IEmbeddingProvider using
5
+ * @huggingface/transformers v3 with all-MiniLM-L6-v2 as the default model.
6
+ *
7
+ * Key design decisions:
8
+ * - Dynamic import: The @huggingface/transformers module is loaded lazily
9
+ * inside initialize() via `await import(...)`. This ensures FTS5-only
10
+ * searches never load the ONNX runtime.
11
+ * - WASM fallback: When native ONNX runtime fails, falls back to WASM
12
+ * backend with numThreads=1 for maximum compatibility.
13
+ * - Progress reporting: Forwards Transformers.js progress events to the
14
+ * onProgress callback as DownloadProgress objects.
15
+ */
16
+ import type { IEmbeddingProvider, DownloadProgress } from "../../domain/ports/embedding.js";
17
+ import { EmbeddingResult } from "../../domain/value-objects/embedding-result.js";
18
+ interface TransformersJsProviderOptions {
19
+ model?: string;
20
+ dimensions?: number;
21
+ }
22
+ export declare class TransformersJsProvider implements IEmbeddingProvider {
23
+ readonly name = "transformers-js";
24
+ readonly model: string;
25
+ readonly dimensions: number;
26
+ private _pipeline;
27
+ constructor(options?: TransformersJsProviderOptions);
28
+ initialize(onProgress?: (progress: DownloadProgress) => void): Promise<void>;
29
+ embed(text: string): Promise<EmbeddingResult>;
30
+ embedBatch(texts: string[]): Promise<EmbeddingResult[]>;
31
+ isReady(): boolean;
32
+ dispose(): Promise<void>;
33
+ }
34
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * External tool adapters barrel export.
3
+ *
4
+ * Infrastructure adapters that delegate to external CLI tools
5
+ * via subprocess invocation.
6
+ */
7
+ export { QmdRunner, isQmdAvailable, getQmdInfo } from "./qmd-runner.js";
@@ -0,0 +1,36 @@
1
+ /**
2
+ * QmdRunner
3
+ *
4
+ * Infrastructure adapter that shells out to the qmd CLI for searching
5
+ * markdown files. Implements the IExternalSearchProvider domain port.
6
+ *
7
+ * qmd is an optional peer dependency -- this adapter gracefully handles
8
+ * the case where qmd is not installed.
9
+ */
10
+ import type { IExternalSearchProvider, QmdSearchResult, QmdHealthInfo } from "../../domain/ports/index.js";
11
+ export declare class QmdRunner implements IExternalSearchProvider {
12
+ /**
13
+ * Execute a search query against qmd and return parsed results.
14
+ *
15
+ * Spawns `qmd search <query> --json` and parses the JSON output.
16
+ */
17
+ search(query: string): Promise<QmdSearchResult[]>;
18
+ /**
19
+ * Check if qmd binary is available in PATH.
20
+ */
21
+ isAvailable(): boolean;
22
+ /**
23
+ * Get health info including binary path.
24
+ */
25
+ getHealthInfo(): QmdHealthInfo;
26
+ }
27
+ /**
28
+ * Standalone convenience function: check if qmd is available.
29
+ * Used by doctor command and other non-DI contexts.
30
+ */
31
+ export declare function isQmdAvailable(): boolean;
32
+ /**
33
+ * Standalone convenience function: get qmd health info.
34
+ * Used by doctor command and other non-DI contexts.
35
+ */
36
+ export declare function getQmdInfo(): QmdHealthInfo;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * AutoMemoryWriter
3
+ *
4
+ * Infrastructure adapter implementing IAmbientContextWriter.
5
+ * Writes context.md (complete overwrite) and updates MEMORY.md
6
+ * using marker-based merge to preserve user content.
7
+ */
8
+ import type { IAmbientContextWriter } from "../../domain/ports/services.js";
9
+ /**
10
+ * Merge block content into existing MEMORY.md content using markers.
11
+ *
12
+ * Rules:
13
+ * - If markers exist: replace content between them, preserve everything else
14
+ * - If no markers: append block with markers at end
15
+ * - If empty: create block with markers
16
+ * - Content outside markers is never modified
17
+ *
18
+ * Exported as a pure function for direct unit testing.
19
+ *
20
+ * @param existing Current file content (may be empty)
21
+ * @param blockContent New content to place between markers
22
+ * @returns Merged content
23
+ */
24
+ export declare function mergeMemoryBlock(existing: string, blockContent: string): string;
25
+ /**
26
+ * Infrastructure adapter for writing ambient context artifacts.
27
+ *
28
+ * Implements the IAmbientContextWriter domain port.
29
+ * Uses synchronous filesystem operations wrapped in async methods
30
+ * to match the port contract.
31
+ */
32
+ export declare class AutoMemoryWriter implements IAmbientContextWriter {
33
+ /**
34
+ * Write the full context file (complete overwrite).
35
+ *
36
+ * Creates the directory recursively if it does not exist.
37
+ *
38
+ * @param autoMemoryDir Directory path for the auto-memory artifacts
39
+ * @param content Content to write as context.md
40
+ */
41
+ writeContextFile(autoMemoryDir: string, content: string): Promise<void>;
42
+ /**
43
+ * Update the MEMORY.md block using marker-based merge.
44
+ *
45
+ * Creates the directory and file if they do not exist.
46
+ * Replaces content between markers, preserves content outside.
47
+ *
48
+ * @param autoMemoryDir Directory path for the auto-memory artifacts
49
+ * @param blockContent Content to place between markers
50
+ */
51
+ updateMemoryBlock(autoMemoryDir: string, blockContent: string): Promise<void>;
52
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Configuration Manager
3
+ *
4
+ * Manages memory configuration with defaults.
5
+ * Configuration stored at the XDG config path via centralized paths module.
6
+ *
7
+ * Implements graceful handling of missing/invalid config files.
8
+ */
9
+ /**
10
+ * Embedding configuration data interface
11
+ *
12
+ * Plain object shape for embedding config stored in JSON.
13
+ * The factory validates via domain value objects when needed.
14
+ */
15
+ export interface EmbeddingConfigData {
16
+ /** Whether embedding generation is enabled */
17
+ enabled: boolean;
18
+ /** Provider identifier (e.g., "local", "openai", "ollama") */
19
+ provider: string;
20
+ /** Model identifier (e.g., "Xenova/all-MiniLM-L6-v2") */
21
+ model: string;
22
+ /** Number of dimensions in the embedding vectors */
23
+ dimensions: number;
24
+ /** Number of messages to embed per batch */
25
+ batchSize: number;
26
+ /** @deprecated Prefer apiKeyEnv or runtime environment injection. */
27
+ apiKey?: string;
28
+ /** Environment variable name that contains the provider API key */
29
+ apiKeyEnv?: string;
30
+ /** Opaque secret reference for external secret managers; never resolved here */
31
+ apiKeyRef?: string;
32
+ /** Base URL override for provider API endpoint */
33
+ baseUrl?: string;
34
+ }
35
+ export interface ApiKeyResolution {
36
+ apiKey?: string;
37
+ source: "environment" | "plaintext-config" | "missing";
38
+ envVar?: string;
39
+ ref?: string;
40
+ deprecatedPlaintext: boolean;
41
+ }
42
+ /**
43
+ * Search configuration data interface
44
+ *
45
+ * Plain object shape for search config stored in JSON.
46
+ */
47
+ export interface SearchConfigData {
48
+ /** Default search mode */
49
+ defaultMode: "auto" | "fts" | "vector" | "hybrid";
50
+ /** Temporal decay settings */
51
+ temporalDecay: {
52
+ /** Whether temporal decay is enabled */
53
+ enabled: boolean;
54
+ /** Half-life in days for temporal decay */
55
+ halfLifeDays: number;
56
+ };
57
+ /** Whether the embedding hint has been shown (one-time) */
58
+ hintShown?: boolean;
59
+ }
60
+ /**
61
+ * Default search configuration
62
+ *
63
+ * Auto mode with 30-day temporal decay half-life.
64
+ */
65
+ export declare const DEFAULT_SEARCH_CONFIG: SearchConfigData;
66
+ /**
67
+ * Ambient context configuration data interface
68
+ *
69
+ * Controls automatic context generation into Claude Code's
70
+ * auto memory directory during sync.
71
+ */
72
+ export interface AmbientContextConfigData {
73
+ /** Whether ambient context generation is enabled */
74
+ enabled: boolean;
75
+ /** Token budget for context.md generation */
76
+ budget: number;
77
+ }
78
+ /**
79
+ * Default ambient context configuration
80
+ *
81
+ * Enabled by default with 800 token budget.
82
+ */
83
+ export declare const DEFAULT_AMBIENT_CONTEXT_CONFIG: AmbientContextConfigData;
84
+ /**
85
+ * Remote sync configuration data interface
86
+ *
87
+ * Plain object shape for remote sync config stored in JSON.
88
+ */
89
+ export interface RemoteSyncConfigData {
90
+ /** Whether remote synchronization is enabled */
91
+ enabled: boolean;
92
+ /** Git repository URL for synchronization */
93
+ repositoryUrl?: string;
94
+ /** Whether to automatically push on sync */
95
+ autoPush: boolean;
96
+ /** Whether to automatically pull on sync */
97
+ autoPull: boolean;
98
+ }
99
+ /**
100
+ * Default remote sync configuration
101
+ */
102
+ export declare const DEFAULT_REMOTE_SYNC_CONFIG: RemoteSyncConfigData;
103
+ export interface LegacyMemoryFilesConfigData {
104
+ /** Whether legacy ~/.memory / MEMORY_HOME markdown indexing and writes are enabled */
105
+ enabled: boolean;
106
+ }
107
+ export declare const DEFAULT_LEGACY_MEMORY_FILES_CONFIG: LegacyMemoryFilesConfigData;
108
+ /**
109
+ * Memory configuration interface
110
+ *
111
+ * All options from CONTEXT.md:
112
+ * - autoSync: Enable automatic hook-based sync
113
+ * - recoveryOnStartup: Scan for unsaved sessions on first command
114
+ * - syncOnCompaction: Trigger sync on PreCompact event
115
+ * - timeout: Sync timeout in milliseconds
116
+ * - logLevel: Logging verbosity
117
+ * - logRetentionDays: Days to keep log files
118
+ * - showFailures: Show failure notifications to user
119
+ * - embedding: Embedding provider configuration
120
+ * - search: Hybrid search configuration
121
+ * - ambientContext: Ambient context generation configuration
122
+ * - machineId: Unique identifier for the local machine
123
+ * - remoteSync: Remote sync configuration
124
+ * - legacyMemoryFiles: Explicit opt-in for pre-v4 ~/.memory / MEMORY_HOME sidecar files
125
+ */
126
+ export interface MemoryConfig {
127
+ /** Enable automatic hook-based sync */
128
+ autoSync: boolean;
129
+ /** Scan for unsaved sessions on first command */
130
+ recoveryOnStartup: boolean;
131
+ /** Trigger sync on PreCompact event */
132
+ syncOnCompaction: boolean;
133
+ /** Sync timeout in milliseconds */
134
+ timeout: number;
135
+ /** Logging verbosity */
136
+ logLevel: "debug" | "info" | "warn" | "error";
137
+ /** Days to keep log files */
138
+ logRetentionDays: number;
139
+ /** Show failure notifications to user */
140
+ showFailures: boolean;
141
+ /** Embedding provider configuration */
142
+ embedding: EmbeddingConfigData;
143
+ /** Hybrid search configuration */
144
+ search: SearchConfigData;
145
+ /** Ambient context generation configuration */
146
+ ambientContext: AmbientContextConfigData;
147
+ /** Unique identifier for the local machine */
148
+ machineId: string;
149
+ /** Remote sync configuration */
150
+ remoteSync: RemoteSyncConfigData;
151
+ /** Legacy memory-file sidecar compatibility */
152
+ legacyMemoryFiles: LegacyMemoryFilesConfigData;
153
+ }
154
+ /**
155
+ * Provider-specific default model and dimensions
156
+ *
157
+ * Maps provider identifiers to their default model and dimensions.
158
+ * Used by resolveProviderDefaults() to apply correct defaults
159
+ * when a user sets provider without explicit model/dimensions.
160
+ */
161
+ export declare const PROVIDER_DEFAULTS: Record<string, {
162
+ model: string;
163
+ dimensions: number;
164
+ }>;
165
+ /**
166
+ * Resolve provider-specific defaults for model and dimensions
167
+ *
168
+ * After deep-merging user config with DEFAULT_EMBEDDING_CONFIG,
169
+ * checks if the provider was changed from "local" and whether
170
+ * model/dimensions were user-explicit. If not, applies provider-specific
171
+ * defaults from PROVIDER_DEFAULTS.
172
+ *
173
+ * Uses `in` operator to check field presence in the raw user JSON:
174
+ * - "model" in userEmbedding returns true even if value matches a default
175
+ * - This correctly preserves user-explicit values
176
+ *
177
+ * @param merged The deep-merged embedding config
178
+ * @param userEmbedding The raw user embedding section from JSON (before merge)
179
+ * @returns Resolved embedding config with correct provider defaults
180
+ */
181
+ export declare function resolveProviderDefaults(merged: EmbeddingConfigData, userEmbedding: Partial<EmbeddingConfigData> | undefined): EmbeddingConfigData;
182
+ export declare function resolveEmbeddingApiKey(config: Pick<EmbeddingConfigData, "apiKey" | "apiKeyEnv" | "apiKeyRef">, providerEnvVars: string[]): ApiKeyResolution;
183
+ /**
184
+ * Default embedding configuration
185
+ *
186
+ * Local provider with all-MiniLM-L6-v2 model (384 dimensions).
187
+ * Enabled by default so embedding features are opt-out.
188
+ */
189
+ export declare const DEFAULT_EMBEDDING_CONFIG: EmbeddingConfigData;
190
+ /**
191
+ * Default configuration with all features enabled
192
+ *
193
+ * Matches CONTEXT.md specification:
194
+ * - All sync features enabled (autoSync, recoveryOnStartup, syncOnCompaction)
195
+ * - 5 second timeout (matches OpenClaw pattern)
196
+ * - Info log level for reasonable verbosity
197
+ * - 7 day log retention
198
+ * - Silent failures by default (never interrupt user)
199
+ * - Local embedding provider with all-MiniLM-L6-v2
200
+ */
201
+ export declare const DEFAULT_CONFIG: MemoryConfig;
202
+ /**
203
+ * Get the path to the config directory.
204
+ *
205
+ * @param configPathOverride Optional explicit config file path (used by
206
+ * tests). The directory is derived from this path.
207
+ * @returns Path to the config directory
208
+ */
209
+ export declare function getConfigDir(configPathOverride?: string): string;
210
+ /**
211
+ * Get the path to the config file.
212
+ *
213
+ * @param configPathOverride Optional explicit config file path (used by tests)
214
+ * @returns Path to config.json
215
+ */
216
+ export declare function getConfigPath(configPathOverride?: string): string;
217
+ /**
218
+ * Load configuration from disk
219
+ *
220
+ * Gracefully handles:
221
+ * - Missing config file (returns defaults)
222
+ * - Invalid JSON (returns defaults with warning)
223
+ * - Partial config (merges with defaults)
224
+ *
225
+ * @returns Complete configuration with defaults applied
226
+ */
227
+ export declare function loadConfig(configPathOverride?: string): MemoryConfig;
228
+ /**
229
+ * Save configuration to disk
230
+ *
231
+ * Creates the config directory if it doesn't exist.
232
+ * Merges partial config with existing config (if present).
233
+ * Writes JSON with 2-space indent for readability.
234
+ *
235
+ * @param config Partial configuration to save (merged with existing)
236
+ */
237
+ export declare function saveConfig(config: Partial<MemoryConfig>, configPathOverride?: string): void;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Git Syncer Hook
3
+ *
4
+ * Secure, shell-less transport manager utilizing Bun's subprocess spawner
5
+ * to synchronize machine-specific log files via a private Git repository
6
+ * without user credential storage.
7
+ */
8
+ export interface SyncResult {
9
+ success: boolean;
10
+ rebuildNeeded: boolean;
11
+ error?: string;
12
+ }
13
+ export interface GitCommandResult {
14
+ success: boolean;
15
+ stdout: string;
16
+ stderr: string;
17
+ exitCode: number;
18
+ }
19
+ export interface GitSyncerDeps {
20
+ runGit?: (args: string[], cwd: string) => Promise<GitCommandResult>;
21
+ existsSync?: (path: string) => boolean;
22
+ readFileSync?: (path: string, encoding: BufferEncoding) => string;
23
+ getAllLogFiles?: (eventsDir?: string) => string[];
24
+ now?: () => Date;
25
+ }
26
+ /**
27
+ * Runs a git command securely using Bun's shell-less spawner.
28
+ */
29
+ export declare function runGit(args: string[], cwd: string, env?: NodeJS.ProcessEnv): Promise<GitCommandResult>;
30
+ /**
31
+ * GitSyncer infrastructure hook.
32
+ * Encapsulates Git transport operations for Multi-Device synchronization.
33
+ */
34
+ export declare class GitSyncer {
35
+ private readonly eventsDir;
36
+ private readonly deps;
37
+ constructor(eventsDir?: string, deps?: GitSyncerDeps);
38
+ isGitRepo(): Promise<boolean>;
39
+ initRepo(): Promise<boolean>;
40
+ configureRemote(remoteUrl: string): Promise<boolean>;
41
+ removeRemote(): Promise<boolean>;
42
+ getRemoteUrl(): Promise<string | null>;
43
+ sync(machineId: string, remoteUrl: string, autoPull?: boolean, autoPush?: boolean): Promise<SyncResult>;
44
+ }