@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,161 @@
1
+ /**
2
+ * Database Connection and Initialization
3
+ *
4
+ * Provides SQLite database initialization with WAL mode,
5
+ * performance pragmas, busy timeout, integrity checks, and FTS5 verification.
6
+ */
7
+ import { Database } from "bun:sqlite";
8
+ /**
9
+ * Database configuration options
10
+ */
11
+ export interface DatabaseConfig {
12
+ /** Path to the database file. Use ":memory:" for in-memory database. */
13
+ path: string;
14
+ /** Whether to create the database if it doesn't exist. Default: true */
15
+ create?: boolean;
16
+ /** Whether to apply schema on initialization. Default: true */
17
+ applySchema?: boolean;
18
+ /** Whether to enable WAL mode. Default: true */
19
+ walMode?: boolean;
20
+ /** Cache size in KB (negative) or pages (positive). Default: -64000 (64MB) */
21
+ cacheSize?: number;
22
+ /** Busy timeout in milliseconds for handling database locks. Default: 5000 */
23
+ busyTimeout?: number;
24
+ /** Whether to run quick integrity check on startup. Default: true for file DB, false for :memory: */
25
+ quickCheck?: boolean;
26
+ }
27
+ /**
28
+ * Result of database initialization
29
+ */
30
+ export interface DatabaseInitResult {
31
+ /** The initialized database instance */
32
+ db: Database;
33
+ /** Whether WAL mode was successfully enabled */
34
+ walEnabled: boolean;
35
+ /** Whether FTS5 extension is available */
36
+ fts5Available: boolean;
37
+ /** Whether sqlite-vec extension is loaded (vector search available) */
38
+ sqliteVecAvailable: boolean;
39
+ }
40
+ /**
41
+ * Attempt to load the sqlite-vec extension into a database.
42
+ *
43
+ * sqlite-vec enables vector similarity search via vec0 virtual tables.
44
+ * If the extension is not available (e.g., not installed), this returns false
45
+ * and the database continues to work with FTS5-only search.
46
+ *
47
+ * @param db - Database instance to load the extension into
48
+ * @returns true if loaded successfully, false otherwise
49
+ */
50
+ export declare function loadSqliteVecExtension(db: Database): boolean;
51
+ /**
52
+ * Get the default database path
53
+ *
54
+ * @returns Path to the database file
55
+ */
56
+ export declare function getDefaultDbPath(): string;
57
+ /**
58
+ * Initialize a SQLite database with optimal settings
59
+ *
60
+ * Configures:
61
+ * - Foreign keys enabled
62
+ * - WAL mode (for file-based databases)
63
+ * - Performance pragmas (synchronous, cache_size, temp_store)
64
+ * - FTS5 support verification
65
+ * - Schema creation (optional)
66
+ *
67
+ * @param config - Database configuration options
68
+ * @returns Database instance with initialization status
69
+ * @throws Error if FTS5 is not available
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * // In-memory database
74
+ * const { db } = initializeDatabase({ path: ":memory:" });
75
+ *
76
+ * // File-based database with custom cache
77
+ * const { db, walEnabled } = initializeDatabase({
78
+ * path: "./data/memory.db",
79
+ * cacheSize: -32000 // 32MB
80
+ * });
81
+ * ```
82
+ */
83
+ export declare function initializeDatabase(config: DatabaseConfig): DatabaseInitResult;
84
+ /**
85
+ * Close the database connection with proper cleanup
86
+ *
87
+ * Performs a WAL checkpoint before closing to ensure all changes are
88
+ * written to the main database file. Switches journal mode to DELETE
89
+ * to remove WAL/SHM files that would otherwise retain OS-level locks
90
+ * on Windows.
91
+ *
92
+ * initializeDatabase() re-enables WAL on the next open, so the
93
+ * journal mode switch has no functional impact on subsequent connections.
94
+ *
95
+ * Note: On Windows, Bun's SQLite binding may hold the .db file descriptor
96
+ * until garbage collection. Test code that needs to delete the database
97
+ * file immediately after close should use tests/helpers/test-database.ts
98
+ * which handles this with a conditional GC + retry strategy.
99
+ *
100
+ * @param db - Database instance to close
101
+ */
102
+ export declare function closeDatabase(db: Database): void;
103
+ /**
104
+ * Perform a passive WAL checkpoint
105
+ *
106
+ * Checkpoints as much of the WAL as possible without blocking.
107
+ * Use this for periodic checkpointing during long operations.
108
+ *
109
+ * @param db - Database instance to checkpoint
110
+ */
111
+ export declare function checkpointDatabase(db: Database): void;
112
+ /**
113
+ * Result of a WAL checkpoint operation
114
+ */
115
+ export interface CheckpointResult {
116
+ /** Number of WAL frames that could not be checkpointed (busy) */
117
+ busy: number;
118
+ /** Total number of frames in the WAL file */
119
+ log: number;
120
+ /** Number of frames successfully checkpointed */
121
+ checkpointed: number;
122
+ }
123
+ /**
124
+ * Perform a truncating WAL checkpoint after bulk operations
125
+ *
126
+ * Uses TRUNCATE mode which:
127
+ * 1. Checkpoints all frames from WAL to main database
128
+ * 2. Truncates the WAL file to zero size
129
+ * 3. May block briefly if other connections are active
130
+ *
131
+ * Call this after bulk insert operations to:
132
+ * - Reduce WAL file size
133
+ * - Ensure all changes are in main database file
134
+ * - Optimize subsequent read performance
135
+ *
136
+ * @param db - Database instance to checkpoint
137
+ * @returns Checkpoint result with frame counts
138
+ */
139
+ export declare function bulkOperationCheckpoint(db: Database): CheckpointResult;
140
+ /**
141
+ * Initialize a database with error wrapping
142
+ *
143
+ * Wraps initializeDatabase and ensures all errors are MemoryError instances.
144
+ * Use this for CLI entry points where structured error handling is needed.
145
+ *
146
+ * @param config - Database configuration options
147
+ * @returns Database instance with initialization status
148
+ * @throws MemoryError for any initialization failure
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * try {
153
+ * const { db } = initializeDatabaseSafe({ path: "./data/memory.db" });
154
+ * } catch (error) {
155
+ * if (error instanceof MemoryError) {
156
+ * console.error(`[${error.code}] ${error.message}`);
157
+ * }
158
+ * }
159
+ * ```
160
+ */
161
+ export declare function initializeDatabaseSafe(config: DatabaseConfig): DatabaseInitResult;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Event-Log SSOT Manager
3
+ *
4
+ * Manages the append-only JSONL event log as the source of truth (SSOT),
5
+ * and handles playing back events to rebuild database projections.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import { Fact } from "../../domain/entities/fact.js";
9
+ /**
10
+ * Append a serialized Fact entity into the plain-text event log.
11
+ */
12
+ export declare function appendEvent(fact: Fact, logPath?: string): Promise<void>;
13
+ /**
14
+ * Read all Fact events sequentially from the plain-text event log.
15
+ * Yields Fact entities.
16
+ */
17
+ export declare function readEvents(logPath?: string, eventsDir?: string): AsyncGenerator<Fact, void, unknown>;
18
+ /**
19
+ * Completely wipe the derived database projections and play back the entire
20
+ * plain-text events.jsonl timeline sequentially to rebuild the SQLite database.
21
+ */
22
+ export declare function rebuildProjections(db: Database, logPath?: string, eventsDir?: string): Promise<void>;
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Health Checker
3
+ *
4
+ * Provides database integrity checking and system health verification.
5
+ * Used by the doctor command for diagnostics.
6
+ *
7
+ * Features:
8
+ * - SQLite PRAGMA integrity_check and quick_check
9
+ * - Directory permission verification
10
+ * - Hook installation status
11
+ * - Configuration validation
12
+ */
13
+ import { Database } from "bun:sqlite";
14
+ import { type HookStatus } from "../hooks/index.js";
15
+ /**
16
+ * Database health status
17
+ */
18
+ export interface DatabaseHealth {
19
+ /** Database file exists */
20
+ exists: boolean;
21
+ /** Database file is readable */
22
+ readable: boolean;
23
+ /** Database file is writable */
24
+ writable: boolean;
25
+ /** Integrity check result */
26
+ integrity: "ok" | "corrupted" | "unknown";
27
+ /** Database file size in bytes */
28
+ size: number;
29
+ }
30
+ /**
31
+ * Directory permissions status
32
+ */
33
+ export interface PermissionsHealth {
34
+ /** Config directory is accessible */
35
+ configDir: boolean;
36
+ /** Logs directory is accessible */
37
+ logsDir: boolean;
38
+ /** Claude source directory (~/.claude/projects) is accessible */
39
+ sourceDir: boolean;
40
+ }
41
+ /**
42
+ * Hook status
43
+ */
44
+ export interface HooksHealth {
45
+ /** Hooks are installed in settings.json */
46
+ installed: boolean;
47
+ /** autoSync is enabled in config */
48
+ enabled: boolean;
49
+ /** Last hook run timestamp */
50
+ lastRun: Date | null;
51
+ }
52
+ /**
53
+ * Configuration validity status
54
+ */
55
+ export interface ConfigHealth {
56
+ /** Configuration is valid */
57
+ valid: boolean;
58
+ /** Issues found during validation */
59
+ issues: string[];
60
+ }
61
+ /**
62
+ * Embedding health status
63
+ */
64
+ export interface EmbeddingHealth {
65
+ /** Whether embedding config exists */
66
+ configured: boolean;
67
+ /** Provider identifier */
68
+ provider: string;
69
+ /** Model identifier */
70
+ model: string;
71
+ /** Embedding dimensions */
72
+ dimensions: number;
73
+ /** Whether embedding is enabled */
74
+ enabled: boolean;
75
+ /** Whether the provider is ready to generate embeddings */
76
+ ready: boolean;
77
+ /** Reason for readiness status (e.g., "API key not set") */
78
+ readyReason?: string | undefined;
79
+ }
80
+ /**
81
+ * sqlite-vec extension health status
82
+ */
83
+ export interface SqliteVecHealth {
84
+ /** Whether sqlite-vec extension is loadable */
85
+ available: boolean;
86
+ /** sqlite-vec version string, or null if not available */
87
+ version: string | null;
88
+ }
89
+ /**
90
+ * Search capability status
91
+ */
92
+ export interface SearchCapability {
93
+ /** FTS5 is available */
94
+ fts5: boolean;
95
+ /** sqlite-vec extension is loaded */
96
+ sqliteVec: boolean;
97
+ /** Number of messages with embeddings */
98
+ embeddedCount: number;
99
+ /** Total number of messages */
100
+ totalMessages: number;
101
+ /** Percentage of messages with embeddings */
102
+ coveragePercent: number;
103
+ /** Default search mode from config */
104
+ defaultMode: string;
105
+ /** Whether vector search is ready (extension + embeddings) */
106
+ vectorReady: boolean;
107
+ }
108
+ /**
109
+ * LLM Extraction health status
110
+ */
111
+ export interface LlmExtractionHealth {
112
+ /** The active LLM provider */
113
+ provider: string;
114
+ /** The active LLM model */
115
+ model: string;
116
+ /** Whether extraction is configured and ready */
117
+ ready: boolean;
118
+ /** Reason for readiness status */
119
+ readyReason?: string | undefined;
120
+ }
121
+ /**
122
+ * Complete health check result
123
+ */
124
+ export interface HealthCheckResult {
125
+ /** Database health status */
126
+ database: DatabaseHealth;
127
+ /** Directory permissions status */
128
+ permissions: PermissionsHealth;
129
+ /** Hook status */
130
+ hooks: HooksHealth;
131
+ /** Configuration validity status */
132
+ config: ConfigHealth;
133
+ /** Embedding configuration status */
134
+ embedding: EmbeddingHealth;
135
+ /** sqlite-vec extension availability */
136
+ sqliteVec: SqliteVecHealth;
137
+ /** Search capability status */
138
+ searchCapability: SearchCapability;
139
+ /** LLM extraction provider status */
140
+ llmExtraction: LlmExtractionHealth;
141
+ }
142
+ /**
143
+ * Test path overrides for testing
144
+ */
145
+ export interface HealthCheckOverrides {
146
+ /** Override database path */
147
+ dbPath?: string | undefined;
148
+ /** Override config directory */
149
+ configDir?: string | undefined;
150
+ /** Override logs directory */
151
+ logsDir?: string | undefined;
152
+ /** Override source directory */
153
+ sourceDir?: string | undefined;
154
+ /** Override hook-related paths (settings.json, backup, hook script) */
155
+ hookOverrides?: import("../hooks/settings-manager.js").PathOverrides | undefined;
156
+ /** Optional pre-calculated hook status to avoid redundant file reads */
157
+ preCalculatedHookStatus?: HookStatus | undefined;
158
+ }
159
+ /**
160
+ * Check database integrity using PRAGMA integrity_check
161
+ *
162
+ * Full integrity check that verifies:
163
+ * - All pages are reachable
164
+ * - All index entries exist
165
+ * - All UNIQUE/NOT NULL constraints
166
+ *
167
+ * @param db Database instance
168
+ * @returns "ok" if integrity check passes, "corrupted" otherwise
169
+ */
170
+ export declare function checkDatabaseIntegrity(db: Database): "ok" | "corrupted";
171
+ /**
172
+ * Check database integrity using PRAGMA quick_check
173
+ *
174
+ * Faster check that skips some verifications:
175
+ * - Verifies structural integrity
176
+ * - Skips index consistency checks
177
+ * - Good for startup verification
178
+ *
179
+ * @param db Database instance
180
+ * @returns "ok" if quick check passes, "corrupted" otherwise
181
+ */
182
+ export declare function checkQuickIntegrity(db: Database): "ok" | "corrupted";
183
+ /**
184
+ * Check directory permissions
185
+ *
186
+ * @param path Directory path to check
187
+ * @returns Readable and writable status
188
+ */
189
+ export declare function checkDirectoryPermissions(path: string): {
190
+ readable: boolean;
191
+ writable: boolean;
192
+ };
193
+ /**
194
+ * Check hook installation and configuration status
195
+ *
196
+ * @param logPath Optional explicit log file path (used by tests to point
197
+ * at a fixture; production reads from the XDG-resolved path)
198
+ * @param configPath Optional explicit config file path (used by tests)
199
+ * @returns Hook status including installation, enabled state, and last run
200
+ */
201
+ export declare function checkHookStatus(logPath?: string | undefined, configPath?: string | undefined, hookOverrides?: import("../hooks/settings-manager.js").PathOverrides | undefined, preCalculatedHookStatus?: HookStatus | undefined): HooksHealth;
202
+ /**
203
+ * Validate configuration and collect issues
204
+ *
205
+ * @param configPath Optional explicit config file path (used by tests)
206
+ * @returns Validity status and list of issues
207
+ */
208
+ export declare function checkConfigValidity(configPath?: string): ConfigHealth;
209
+ /**
210
+ * Check sqlite-vec extension availability
211
+ *
212
+ * Attempts to load sqlite-vec in a temporary in-memory database
213
+ * and query its version. Closes the database before returning.
214
+ *
215
+ * @returns sqlite-vec availability and version
216
+ */
217
+ export declare function checkSqliteVecAvailability(): SqliteVecHealth;
218
+ /**
219
+ * Check embedding configuration status
220
+ *
221
+ * Loads config and returns the embedding section values.
222
+ *
223
+ * @param configPath Optional explicit config file path (used by tests)
224
+ * @returns Embedding health status
225
+ */
226
+ export declare function checkEmbeddingConfig(configPath?: string): EmbeddingHealth;
227
+ /**
228
+ * Check LLM Fact Extraction provider health status
229
+ *
230
+ * @param configPath Optional explicit config file path
231
+ * @returns LLM extraction health status
232
+ */
233
+ export declare function checkLlmExtractionHealth(configPath?: string): LlmExtractionHealth;
234
+ /**
235
+ * Run comprehensive health check
236
+ *
237
+ * Orchestrates all health checks:
238
+ * - Database existence, permissions, and integrity
239
+ * - Directory permissions (config, logs, source)
240
+ * - Hook installation and configuration
241
+ * - Configuration validity
242
+ * - Embedding configuration
243
+ * - sqlite-vec extension availability
244
+ *
245
+ * @param overrides Optional path overrides for testing
246
+ * @returns Complete health check result
247
+ */
248
+ export declare function runHealthCheck(overrides?: HealthCheckOverrides): HealthCheckResult;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Database Infrastructure
3
+ *
4
+ * Provides SQLite database initialization, schema management,
5
+ * and connection utilities for memory.
6
+ */
7
+ export { SCHEMA_SQL, createSchema, checkFts5Support, SESSIONS_TABLE, MESSAGES_META_TABLE, MESSAGES_FTS_TABLE, TOOL_USES_TABLE, LINKS_TABLE, TOPICS_TABLE, EXTRACTION_STATE_TABLE, EMBEDDING_STATE_TABLE, EMBEDDING_STATE_ADD_MODEL_NAME, MESSAGE_EMBEDDINGS_TABLE, FRICTION_LOG_TABLE, BACKFILL_STATE_TABLE, type SchemaOptions, } from "./schema.js";
8
+ export { initializeDatabase, initializeDatabaseSafe, closeDatabase, checkpointDatabase, bulkOperationCheckpoint, getDefaultDbPath, type DatabaseConfig, type DatabaseInitResult, type CheckpointResult, } from "./connection.js";
9
+ export { SqliteSessionRepository, SqliteMessageRepository, SqliteExtractionStateRepository, SqliteToolUseRepository, SqliteLinkRepository, type BatchResult, type BatchOptions, type RelatedLink, EmbeddingRepository, type UnembeddedMessage, type EmbeddingBatchItem, SqliteFrictionRepository, SqliteBackfillStateRepository, } from "./repositories/index.js";
10
+ export { Fts5SearchService, HybridSearchService, type HybridSearchDeps, type SearchMeta, SqliteStatsService, SqliteContextService, SqliteProjectResolver, type ProjectContext, type ContextOptions, type ToolUsage, } from "./services/index.js";
11
+ export { checkDatabaseIntegrity, checkQuickIntegrity, checkDirectoryPermissions, checkConfigValidity, checkHookStatus, checkSqliteVecAvailability, checkEmbeddingConfig, runHealthCheck, type DatabaseHealth, type PermissionsHealth, type HooksHealth, type ConfigHealth, type EmbeddingHealth, type SqliteVecHealth, type HealthCheckResult, type HealthCheckOverrides, type SearchCapability, } from "./health-checker.js";
@@ -0,0 +1,19 @@
1
+ /**
2
+ * SQLite implementation of IBackfillStateRepository.
3
+ *
4
+ * Persists backfill state records tracking which sessions have been
5
+ * backfilled (daily log generated). Uses INSERT OR REPLACE for upsert
6
+ * semantics on the session_id primary key.
7
+ */
8
+ import type { Database } from "bun:sqlite";
9
+ import { BackfillState } from "../../../domain/entities/backfill-state.js";
10
+ import type { IBackfillStateRepository, BackfillStatusCounts } from "../../../domain/ports/repositories.js";
11
+ export declare class SqliteBackfillStateRepository implements IBackfillStateRepository {
12
+ private readonly db;
13
+ constructor(db: Database);
14
+ findBySessionId(sessionId: string): Promise<BackfillState | null>;
15
+ findAll(): Promise<BackfillState[]>;
16
+ save(state: BackfillState): Promise<void>;
17
+ countByStatus(): Promise<BackfillStatusCounts>;
18
+ private toEntity;
19
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Embedding Repository
3
+ *
4
+ * Data access layer for embedding storage. Manages the embedding_state
5
+ * and message_embeddings tables for incremental embedding and model
6
+ * change detection.
7
+ *
8
+ * The embedding_state table tracks which messages have been embedded
9
+ * and with which model (hash + human-readable name). The message_embeddings
10
+ * table is a vec0 virtual table storing the actual vector data.
11
+ */
12
+ import type { Database } from "bun:sqlite";
13
+ import type { IEmbeddingRepository, UnembeddedMessage, EmbeddingBatchItem } from "../../../domain/ports/repositories.js";
14
+ export type { UnembeddedMessage, EmbeddingBatchItem };
15
+ /**
16
+ * A vector KNN search result row.
17
+ */
18
+ export interface VectorSearchRow {
19
+ /** The rowid of the matching message embedding */
20
+ rowid: number;
21
+ /** Cosine distance (0 = identical, 2 = opposite) */
22
+ distance: number;
23
+ }
24
+ /**
25
+ * Repository for embedding data access.
26
+ *
27
+ * Provides methods for querying unembedded messages, storing embedding
28
+ * results, tracking model hashes for change detection, and managing
29
+ * the embedding lifecycle (clear + re-embed).
30
+ */
31
+ export declare class EmbeddingRepository implements IEmbeddingRepository {
32
+ private readonly db;
33
+ constructor(db: Database);
34
+ /**
35
+ * Find messages that have not yet been embedded.
36
+ *
37
+ * Uses LEFT JOIN on messages_meta and embedding_state to find
38
+ * messages without a corresponding embedding_state row.
39
+ *
40
+ * @param limit Maximum number of messages to return
41
+ * @returns Array of unembedded messages ordered by rowid ASC
42
+ */
43
+ findUnembedded(limit: number): UnembeddedMessage[];
44
+ /**
45
+ * Store a batch of embeddings in a single transaction.
46
+ *
47
+ * Inserts into both message_embeddings (vec0 virtual table) and
48
+ * embedding_state (tracking table) atomically. If any insert fails,
49
+ * the entire batch rolls back.
50
+ *
51
+ * @param items Array of embedding batch items (rowid + vector)
52
+ * @param modelHash Hash identifying the model configuration
53
+ * @param modelName Human-readable model name (e.g., "Xenova/all-MiniLM-L6-v2")
54
+ */
55
+ storeBatch(items: EmbeddingBatchItem[], modelHash: string, modelName: string): void;
56
+ /**
57
+ * Get the model hash currently stored in embedding_state.
58
+ *
59
+ * @returns The model hash string, or null if no embeddings exist
60
+ */
61
+ getStoredModelHash(): string | null;
62
+ /**
63
+ * Get the human-readable model name stored in embedding_state.
64
+ *
65
+ * Returns null if no embeddings exist or if model_name is empty
66
+ * (legacy data from before the model_name column was added).
67
+ *
68
+ * @returns The model name string, or null if unavailable
69
+ */
70
+ getStoredModelName(): string | null;
71
+ /**
72
+ * Delete all embeddings and embedding state.
73
+ *
74
+ * Used before re-embedding when the model has changed.
75
+ * Clears both message_embeddings (vec0) and embedding_state tables.
76
+ */
77
+ clearAllEmbeddings(): void;
78
+ /**
79
+ * Count the number of embedded messages.
80
+ *
81
+ * @returns The number of rows in embedding_state
82
+ */
83
+ getEmbeddedCount(): number;
84
+ /**
85
+ * Count the total number of messages in the database.
86
+ *
87
+ * @returns The number of rows in messages_meta
88
+ */
89
+ getTotalMessageCount(): number;
90
+ /**
91
+ * Search for nearest neighbors using sqlite-vec MATCH.
92
+ *
93
+ * Uses cosine distance via vec0 virtual table. Results are
94
+ * ordered by distance ASC (lower distance = more similar).
95
+ *
96
+ * @param queryEmbedding The query vector (Float32Array)
97
+ * @param limit Maximum number of results
98
+ * @returns Array of { rowid, distance } sorted by distance ASC
99
+ */
100
+ vectorKnnSearch(queryEmbedding: Float32Array, limit: number): VectorSearchRow[];
101
+ /**
102
+ * Get the dimension of currently stored embeddings.
103
+ *
104
+ * Queries a single embedding from message_embeddings and determines
105
+ * its dimension from the byte length (Float32 = 4 bytes per dimension).
106
+ *
107
+ * @returns The dimension count, or null if no embeddings are stored
108
+ */
109
+ getStoredEmbeddingDimensions(): number | null;
110
+ /**
111
+ * Drop and recreate the message_embeddings vec0 table with new dimensions.
112
+ *
113
+ * Used when the provider/model changes and the new model produces
114
+ * vectors of a different dimension than what is currently stored.
115
+ * Also clears embedding_state since the tracking data is logically
116
+ * paired with the vector data.
117
+ *
118
+ * @param dimensions The number of dimensions for the new vec0 table
119
+ */
120
+ recreateVecTable(dimensions: number): void;
121
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * SQLite Entity Repository Implementation
3
+ *
4
+ * Persists Entity domain objects to SQLite database.
5
+ * Implements IEntityRepository with deduplication using INSERT OR REPLACE.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import type { IEntityRepository, EntityListOptions } from "../../../domain/ports/repositories.js";
9
+ import { Entity, type ExtractedEntityType } from "../../../domain/entities/entity.js";
10
+ /**
11
+ * SQLite implementation of IEntityRepository
12
+ *
13
+ * Features:
14
+ * - INSERT OR REPLACE for deduplication on (type, name)
15
+ * - Max confidence preservation on upsert
16
+ * - Case-insensitive name matching
17
+ * - Batch insert with transaction support
18
+ */
19
+ export declare class SqliteEntityRepository implements IEntityRepository {
20
+ private readonly db;
21
+ private readonly findByIdStmt;
22
+ private readonly findByNameStmt;
23
+ private readonly findBySessionStmt;
24
+ private readonly insertStmt;
25
+ private readonly existsStmt;
26
+ private readonly updateConfidenceStmt;
27
+ private readonly linkSessionStmt;
28
+ private readonly linkEntityStmt;
29
+ constructor(db: Database);
30
+ /**
31
+ * Find an entity by its unique database identifier.
32
+ */
33
+ findById(id: number): Promise<Entity | null>;
34
+ /**
35
+ * Find an entity by type and name (unique constraint).
36
+ * Uses case-insensitive matching and trims whitespace from search name.
37
+ */
38
+ findByName(type: ExtractedEntityType, name: string): Promise<Entity | null>;
39
+ /**
40
+ * Find all entities linked to a specific session.
41
+ */
42
+ findBySession(sessionId: string): Promise<Entity[]>;
43
+ /**
44
+ * Find entities of a specific type with optional filtering.
45
+ * Builds dynamic query based on options.
46
+ */
47
+ findByType(type: ExtractedEntityType, options?: EntityListOptions): Promise<Entity[]>;
48
+ /**
49
+ * Save an entity to the repository.
50
+ * Uses INSERT OR REPLACE pattern with max confidence preservation.
51
+ * Returns entity with assigned id.
52
+ */
53
+ save(entity: Entity): Promise<Entity>;
54
+ /**
55
+ * Save multiple entities in a single transaction.
56
+ * Returns entities with assigned ids.
57
+ */
58
+ saveMany(entities: Entity[]): Promise<Entity[]>;
59
+ /**
60
+ * Create a link between an entity and a session.
61
+ * Increments frequency if link already exists.
62
+ */
63
+ linkToSession(entityId: number, sessionId: string, frequency?: number): Promise<void>;
64
+ /**
65
+ * Create a relationship link between two entities.
66
+ * Ignores duplicates (INSERT OR IGNORE).
67
+ */
68
+ linkEntities(sourceId: number, targetId: number, relationship: "related" | "implies" | "contradicts", weight?: number): Promise<void>;
69
+ /**
70
+ * Convert a database row to an Entity domain object.
71
+ */
72
+ private rowToEntity;
73
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * SQLite implementation of IExtractionLogRepository.
3
+ *
4
+ * Persists fact extraction run statistics and metadata.
5
+ * Uses INSERT OR REPLACE for idempotency on session_id primary key.
6
+ */
7
+ import type { Database } from "bun:sqlite";
8
+ import type { IExtractionLogRepository, ExtractionLogEntry } from "../../../domain/ports/repositories.js";
9
+ export declare class SqliteExtractionLogRepository implements IExtractionLogRepository {
10
+ private readonly db;
11
+ constructor(db: Database);
12
+ findById(sessionId: string): Promise<ExtractionLogEntry | null>;
13
+ save(entry: ExtractionLogEntry): Promise<void>;
14
+ findAll(): Promise<ExtractionLogEntry[]>;
15
+ clearAll(): Promise<void>;
16
+ private toEntry;
17
+ }