@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,95 @@
1
+ /**
2
+ * Pattern Extractor Service
3
+ *
4
+ * Extracts file paths and tool usage statistics from tool uses
5
+ * using pattern matching (not LLM-based extraction).
6
+ */
7
+ import type { ToolUse } from "../../domain/entities/tool-use.js";
8
+ import { Entity } from "../../domain/entities/entity.js";
9
+ /**
10
+ * Represents a file modification operation
11
+ */
12
+ export interface FileModification {
13
+ /** The file path that was modified */
14
+ path: string;
15
+ /** The type of modification operation */
16
+ operation: "Write" | "Edit" | "NotebookEdit";
17
+ /** When the modification occurred */
18
+ timestamp: Date;
19
+ }
20
+ /**
21
+ * Statistics for a specific tool
22
+ */
23
+ export interface ToolStats {
24
+ /** The tool name */
25
+ name: string;
26
+ /** Total number of invocations */
27
+ count: number;
28
+ /** Number of successful invocations */
29
+ successCount: number;
30
+ /** Number of failed invocations */
31
+ errorCount: number;
32
+ }
33
+ /**
34
+ * Pattern-based extractor for file paths and tool statistics.
35
+ *
36
+ * Provides static methods for extracting structured data from tool uses
37
+ * without requiring LLM inference.
38
+ */
39
+ export declare class PatternExtractor {
40
+ /**
41
+ * Extract file paths from tool uses.
42
+ *
43
+ * Handles:
44
+ * - Read, Write, Edit tools (input.file_path)
45
+ * - Glob, Grep tools (input.path)
46
+ * - Glob results (newline-separated file paths in result)
47
+ *
48
+ * @param toolUses Array of tool uses to extract from
49
+ * @returns Deduplicated array of file paths
50
+ */
51
+ static extractFilePaths(toolUses: ToolUse[]): string[];
52
+ /**
53
+ * Extract file modifications (Write, Edit, NotebookEdit).
54
+ *
55
+ * Only includes successful operations.
56
+ *
57
+ * @param toolUses Array of tool uses to extract from
58
+ * @returns Array of file modifications with operation type
59
+ */
60
+ static extractFileModifications(toolUses: ToolUse[]): FileModification[];
61
+ /**
62
+ * Extract tool usage statistics.
63
+ *
64
+ * Groups by tool name with success/error counts.
65
+ *
66
+ * @param toolUses Array of tool uses to extract from
67
+ * @returns Array of tool statistics
68
+ */
69
+ static extractToolStats(toolUses: ToolUse[]): ToolStats[];
70
+ /**
71
+ * Extract unique tool names used in session.
72
+ *
73
+ * @param toolUses Array of tool uses to extract from
74
+ * @returns Array of unique tool names
75
+ */
76
+ static extractToolNames(toolUses: ToolUse[]): string[];
77
+ /**
78
+ * Convert extracted file paths to Entity objects.
79
+ *
80
+ * File paths become 'file' entities with path as name.
81
+ *
82
+ * @param paths Array of file paths
83
+ * @returns Array of file Entity objects
84
+ */
85
+ static toFileEntities(paths: string[]): Entity[];
86
+ /**
87
+ * Convert file modifications to Entity objects with metadata.
88
+ *
89
+ * Includes operation type in metadata.
90
+ *
91
+ * @param modifications Array of file modifications
92
+ * @returns Array of file Entity objects with metadata
93
+ */
94
+ static toFileModificationEntities(modifications: FileModification[]): Entity[];
95
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * RecoveryService
3
+ *
4
+ * Detects sessions that haven't been synced and optionally syncs them.
5
+ * Useful for crash recovery when hooks failed or were disabled.
6
+ *
7
+ * Features:
8
+ * - Scan for pending sessions (not synced or incomplete)
9
+ * - Dry run mode for reporting without syncing
10
+ * - Limit sync count for controlled recovery
11
+ * - Integration with config for recoveryOnStartup setting
12
+ */
13
+ import type { ISessionSource } from "../../domain/ports/sources.js";
14
+ import type { IExtractionStateRepository } from "../../domain/ports/repositories.js";
15
+ import type { ISyncLogger } from "../../domain/ports/signals.js";
16
+ import type { SyncService } from "./sync-service.js";
17
+ /**
18
+ * Result of a recovery operation
19
+ */
20
+ export interface RecoveryResult {
21
+ /** Paths of sessions that haven't been synced */
22
+ pendingSessions: string[];
23
+ /** Number of sessions successfully synced */
24
+ syncedSessions: number;
25
+ /** Errors encountered during sync */
26
+ errors: Array<{
27
+ sessionPath: string;
28
+ error: string;
29
+ }>;
30
+ /** True if recovery was skipped due to config */
31
+ skipped: boolean;
32
+ }
33
+ /**
34
+ * Options for recovery operation
35
+ */
36
+ export interface RecoveryOptions {
37
+ /** Just report pending, don't sync */
38
+ dryRun?: boolean;
39
+ /** Limit number of sessions to sync */
40
+ maxSessions?: number;
41
+ }
42
+ /**
43
+ * Service for detecting and recovering unsynced sessions.
44
+ *
45
+ * Called on startup when recoveryOnStartup is enabled, or manually
46
+ * via CLI. Useful for crash recovery when hooks failed.
47
+ */
48
+ export declare class RecoveryService {
49
+ private readonly sessionSource;
50
+ private readonly extractionStateRepo;
51
+ private readonly syncService;
52
+ private readonly syncLogger;
53
+ private readonly recoveryEnabled;
54
+ constructor(sessionSource: ISessionSource, extractionStateRepo: IExtractionStateRepository, syncService: SyncService, syncLogger: ISyncLogger, recoveryEnabled: boolean);
55
+ /**
56
+ * Check for sessions that haven't been synced and optionally sync them.
57
+ *
58
+ * Called on startup when recoveryOnStartup is enabled, or manually
59
+ * via CLI. Useful for crash recovery when hooks failed.
60
+ *
61
+ * @param options Recovery options
62
+ * @returns Recovery result with pending sessions and sync counts
63
+ */
64
+ recover(options?: RecoveryOptions): Promise<RecoveryResult>;
65
+ /**
66
+ * Get count of pending sessions without syncing.
67
+ * Fast operation for status display.
68
+ *
69
+ * @returns Number of sessions not yet synced
70
+ */
71
+ getPendingCount(): Promise<number>;
72
+ }
73
+ /**
74
+ * Extract session ID from a session file path.
75
+ *
76
+ * Handles both Unix and Windows path separators.
77
+ *
78
+ * @param sessionPath Full path to session JSONL file
79
+ * @returns Session ID (filename without .jsonl extension)
80
+ */
81
+ export declare function extractSessionId(sessionPath: string): string;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Reciprocal Rank Fusion
3
+ *
4
+ * Pure function implementing RRF to combine ranked result lists
5
+ * from FTS5 and vector search. Uses rank positions (not raw scores)
6
+ * to avoid score normalization problems between rankers.
7
+ *
8
+ * Formula: score(d) = sum(1 / (k + rank_i(d))) for each ranker i
9
+ * Reference: Cormack, Clarke, Buettcher (2009)
10
+ */
11
+ /**
12
+ * A candidate from a single ranker with its rank position.
13
+ */
14
+ export interface RankedCandidate {
15
+ /** The message rowid */
16
+ rowid: number;
17
+ /** Rank position (1 = best match) */
18
+ rank: number;
19
+ /** Which ranker produced this candidate */
20
+ source: "fts" | "vector";
21
+ /** Raw score from the ranker (BM25 or cosine distance) */
22
+ rawScore: number;
23
+ }
24
+ /**
25
+ * A fused result after RRF combining multiple ranker outputs.
26
+ */
27
+ export interface FusedResult {
28
+ /** The message rowid */
29
+ rowid: number;
30
+ /** Raw RRF score (sum of 1/(k+rank) across rankers) */
31
+ rrfScore: number;
32
+ /** Normalized score (0-1, highest RRF maps to 1.0) */
33
+ normalizedScore: number;
34
+ /** Sources that contributed to this result with their rank and raw score */
35
+ sources: Array<{
36
+ source: "fts" | "vector";
37
+ rank: number;
38
+ rawScore: number;
39
+ }>;
40
+ }
41
+ /**
42
+ * Combine ranked result lists using Reciprocal Rank Fusion.
43
+ *
44
+ * Takes pre-ranked candidates from FTS5 and vector search,
45
+ * computes RRF scores, filters noise, normalizes to 0-1,
46
+ * and returns the top results.
47
+ *
48
+ * @param ftsResults Ranked candidates from FTS5 (rank 1 = best BM25)
49
+ * @param vectorResults Ranked candidates from vector search (rank 1 = lowest distance)
50
+ * @param limit Maximum number of results to return
51
+ * @returns Fused results sorted by RRF score descending, normalized to 0-1
52
+ */
53
+ export declare function reciprocalRankFusion(ftsResults: RankedCandidate[], vectorResults: RankedCandidate[], limit: number): FusedResult[];
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Smart Context Service
3
+ *
4
+ * Application-layer service that composes memory files, friction entries,
5
+ * and session data into structured briefings. Produces ordered sections
6
+ * with priority-based token budget allocation.
7
+ *
8
+ * Data source priority (1 = highest):
9
+ * 1. Active Decisions (project DECISIONS.md)
10
+ * 2. Recent Learnings (project LEARNINGS.md)
11
+ * 3. Recent Activity (daily log files)
12
+ * 4. Cross-Project Decisions (global DECISIONS.md, when crossProject=true)
13
+ * 5. Cross-Project Learnings (tagged learnings, when crossProject=true)
14
+ * 6. Open Friction (filtered by project when possible)
15
+ * 7. Session Summary (legacy fallback)
16
+ *
17
+ * Dependencies injected via constructor for hexagonal architecture.
18
+ * Zero imports from infrastructure layer.
19
+ */
20
+ import type { IFactRepository, IFrictionRepository } from "../../domain/ports/repositories.js";
21
+ /**
22
+ * Options for smart context retrieval.
23
+ */
24
+ export interface SmartContextOptions {
25
+ /** Project name or filter string */
26
+ projectFilter: string;
27
+ /** Maximum token budget (0 or undefined = no limit) */
28
+ budget?: number | undefined;
29
+ /** Limit daily logs to last N days */
30
+ days?: number | undefined;
31
+ /** Include cross-project sections (default: false) */
32
+ crossProject?: boolean | undefined;
33
+ }
34
+ /**
35
+ * Result of smart context retrieval.
36
+ */
37
+ export interface SmartContextResult {
38
+ /** Resolved project display name */
39
+ projectName: string;
40
+ /** Resolved encoded project path (null if not found) */
41
+ projectEncoded: string | null;
42
+ /** Ordered context sections */
43
+ sections: ContextSection[];
44
+ /** Total estimated tokens across all sections */
45
+ totalTokensEstimate: number;
46
+ /** Whether any section was truncated due to budget */
47
+ truncated: boolean;
48
+ }
49
+ /**
50
+ * A single section of context output.
51
+ */
52
+ export interface ContextSection {
53
+ /** Section identifier */
54
+ key: string;
55
+ /** Human-readable section title */
56
+ title: string;
57
+ /** Priority (1 = highest) */
58
+ priority: number;
59
+ /** Section content text */
60
+ content: string;
61
+ /** Whether this section was truncated */
62
+ truncated: boolean;
63
+ /** Estimated token count for this section */
64
+ tokenEstimate: number;
65
+ }
66
+ /**
67
+ * Port for resolving project names to encoded paths.
68
+ */
69
+ export interface IProjectResolver {
70
+ /**
71
+ * Resolve a human-readable project name to its encoded path.
72
+ * Returns null if no sessions match the project name.
73
+ */
74
+ resolveProjectEncoded(projectFilter: string): string | null;
75
+ /**
76
+ * Get the display name for a resolved project.
77
+ */
78
+ resolveProjectName(projectFilter: string): string | null;
79
+ }
80
+ /**
81
+ * Dependencies for SmartContextService (constructor injection).
82
+ */
83
+ export interface SmartContextDeps {
84
+ projectResolver: IProjectResolver;
85
+ factRepo: IFactRepository;
86
+ frictionRepo: IFrictionRepository;
87
+ /** Optional legacy session summary provider */
88
+ getSessionSummary?: (projectFilter: string, days?: number) => Promise<string | null>;
89
+ now?: () => Date;
90
+ }
91
+ /**
92
+ * Smart Context Service.
93
+ *
94
+ * Composes data from facts, friction entries, and legacy session
95
+ * data into structured briefings with optional token budget allocation.
96
+ */
97
+ export declare class SmartContextService {
98
+ private readonly projectResolver;
99
+ private readonly factRepo;
100
+ private readonly frictionRepo;
101
+ private readonly getSessionSummary?;
102
+ constructor(deps: SmartContextDeps);
103
+ /**
104
+ * Get structured context for a project.
105
+ *
106
+ * Resolves the project, assembles sections from available data sources
107
+ * in priority order, and optionally applies token budget allocation.
108
+ *
109
+ * @param options Context retrieval options
110
+ * @returns SmartContextResult or null if project not found
111
+ */
112
+ getContext(options: SmartContextOptions): Promise<SmartContextResult | null>;
113
+ /**
114
+ * Build a context section from content.
115
+ */
116
+ private buildSection;
117
+ /**
118
+ * Build friction section content from open entries.
119
+ * Returns null if no friction entries exist.
120
+ */
121
+ private buildFrictionContent;
122
+ /**
123
+ * Apply budget allocation and return result with truncation info.
124
+ */
125
+ private applyBudget;
126
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * SyncService Application Layer
3
+ *
4
+ * Orchestrates session discovery, parsing, and storage for the sync workflow.
5
+ * Implements incremental sync detection using file mtime and size comparison.
6
+ *
7
+ * Per-session transaction boundary ensures atomicity and error isolation.
8
+ * Supports checkpoint-based recovery from interrupted syncs.
9
+ */
10
+ import type { Database } from "bun:sqlite";
11
+ import type { ISessionSource, IEventParser, IProjectNameResolver, ISyncAbortSignal, ICheckpointManager, IRedactor } from "../../domain/ports/index.js";
12
+ import type { ISessionRepository, IMessageRepository, IToolUseRepository, IExtractionStateRepository } from "../../domain/ports/repositories.js";
13
+ /**
14
+ * Options for controlling sync behavior
15
+ */
16
+ export interface SyncOptions {
17
+ /** Re-extract all sessions regardless of state */
18
+ force?: boolean;
19
+ /** Filter by project path substring */
20
+ projectFilter?: string;
21
+ /** Sync specific session only */
22
+ sessionFilter?: string;
23
+ /** Progress callback invoked for each session */
24
+ onProgress?: (progress: SyncProgress) => void;
25
+ /** Enable checkpoint-based recovery (default: true) */
26
+ checkpointEnabled?: boolean;
27
+ /** Callback invoked after each session completes */
28
+ onSessionComplete?: (sessionId: string) => void;
29
+ }
30
+ /**
31
+ * Progress information for sync operations
32
+ */
33
+ export interface SyncProgress {
34
+ /** Current session index (1-based) */
35
+ current: number;
36
+ /** Total sessions to process */
37
+ total: number;
38
+ /** Current session being processed */
39
+ sessionId: string;
40
+ /** Current phase of sync */
41
+ phase: "discovering" | "extracting" | "complete";
42
+ }
43
+ /**
44
+ * Result of a sync operation
45
+ */
46
+ export interface SyncResult {
47
+ /** Overall success (true if no errors) */
48
+ success: boolean;
49
+ /** Total sessions found */
50
+ sessionsDiscovered: number;
51
+ /** Sessions successfully processed */
52
+ sessionsProcessed: number;
53
+ /** Sessions skipped (already up-to-date) */
54
+ sessionsSkipped: number;
55
+ /** Total messages inserted */
56
+ messagesInserted: number;
57
+ /** Total tool uses inserted */
58
+ toolUsesInserted: number;
59
+ /** Errors encountered during sync */
60
+ errors: Array<{
61
+ sessionPath: string;
62
+ error: string;
63
+ }>;
64
+ /** Duration in milliseconds */
65
+ durationMs: number;
66
+ /** Whether sync was aborted via signal */
67
+ aborted?: boolean;
68
+ /** Number of sessions recovered from checkpoint */
69
+ recoveredFromCheckpoint?: number;
70
+ }
71
+ /**
72
+ * Application service that orchestrates the sync workflow.
73
+ *
74
+ * Responsibilities:
75
+ * - Discover sessions via ISessionSource
76
+ * - Filter sessions based on options
77
+ * - Detect sessions needing extraction (incremental sync)
78
+ * - Parse events via IEventParser
79
+ * - Extract messages and tool uses from events
80
+ * - Persist to repositories within per-session transactions
81
+ * - Track extraction state for incremental sync
82
+ * - Support checkpoint-based recovery from interruption
83
+ */
84
+ export declare class SyncService {
85
+ private readonly sessionSource;
86
+ private readonly eventParser;
87
+ private readonly sessionRepo;
88
+ private readonly messageRepo;
89
+ private readonly toolUseRepo;
90
+ private readonly extractionStateRepo;
91
+ private readonly db;
92
+ private readonly abortSignal;
93
+ private readonly checkpointManager;
94
+ private readonly redactor;
95
+ constructor(sessionSource: ISessionSource, eventParser: IEventParser, sessionRepo: ISessionRepository, messageRepo: IMessageRepository, toolUseRepo: IToolUseRepository, extractionStateRepo: IExtractionStateRepository, db: Database, abortSignal: ISyncAbortSignal, checkpointManager: ICheckpointManager, redactor?: IRedactor);
96
+ /**
97
+ * Sync sessions to the database.
98
+ *
99
+ * Discovers all sessions, applies filters, checks for changes,
100
+ * and extracts sessions that need processing. Each session is
101
+ * processed in its own transaction for error isolation.
102
+ *
103
+ * Supports checkpoint-based recovery from interrupted syncs.
104
+ * Respects abort signals for graceful shutdown.
105
+ *
106
+ * @param options Configuration for sync behavior
107
+ * @returns Result with counts and any errors
108
+ */
109
+ sync(options?: SyncOptions): Promise<SyncResult>;
110
+ /**
111
+ * Fix project names in existing sessions by resolving them via filesystem lookup.
112
+ *
113
+ * Queries all distinct encoded project paths from the database, resolves the
114
+ * correct project name for each via the filesystem resolver, and updates
115
+ * all sessions with that encoded path.
116
+ *
117
+ * @param resolver The filesystem-based project name resolver
118
+ * @returns Total number of session rows updated
119
+ */
120
+ fixProjectNames(resolver: IProjectNameResolver): Promise<number>;
121
+ /**
122
+ * Wrap an error in MemoryError with appropriate code and context.
123
+ */
124
+ private wrapError;
125
+ /**
126
+ * Filter sessions based on options and extraction state.
127
+ *
128
+ * Applies projectFilter and sessionFilter, then checks extraction
129
+ * state to skip sessions that are already up-to-date.
130
+ */
131
+ private filterSessions;
132
+ /**
133
+ * Determine if a session needs extraction.
134
+ *
135
+ * A session needs extraction if:
136
+ * - force=true
137
+ * - No existing extraction state
138
+ * - Existing state is not "complete"
139
+ * - File metadata has changed (mtime or size differs)
140
+ * - Stored metadata is null (legacy state)
141
+ */
142
+ private needsExtraction;
143
+ /**
144
+ * Extract a single session within a transaction.
145
+ *
146
+ * Parses events, creates entities, and persists everything atomically.
147
+ * On error, saves error state and re-throws.
148
+ */
149
+ private extractSession;
150
+ /**
151
+ * Extract Message and ToolUse entities from parsed events.
152
+ *
153
+ * Iterates through events and creates domain entities for
154
+ * user messages, assistant messages, and tool uses with results.
155
+ */
156
+ private extractEntities;
157
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Temporal Decay
3
+ *
4
+ * Pure function applying exponential time-based decay to search scores.
5
+ * Recent results are ranked higher than older results.
6
+ *
7
+ * Formula: finalScore = score * 0.5^(ageDays / halfLifeDays)
8
+ * Inspired by OpenClaw's memory decay pattern.
9
+ */
10
+ /**
11
+ * A result with a score that can be decayed.
12
+ */
13
+ export interface DecayableResult {
14
+ /** The message rowid */
15
+ rowid: number;
16
+ /** The base score before decay */
17
+ score: number;
18
+ }
19
+ /**
20
+ * A result after temporal decay has been applied.
21
+ */
22
+ export interface DecayedResult extends DecayableResult {
23
+ /** The score after temporal decay */
24
+ decayedScore: number;
25
+ }
26
+ /**
27
+ * Apply temporal decay to search results based on message age.
28
+ *
29
+ * Messages closer to `now` retain more of their score.
30
+ * Messages without a timestamp in the map are unaffected.
31
+ * Results are re-sorted by decayed score descending.
32
+ *
33
+ * @param results Array of results with base scores
34
+ * @param timestamps Map of rowid to message timestamp
35
+ * @param halfLifeDays Number of days for score to halve (default 30)
36
+ * @param now Reference time for age calculation (default: current time)
37
+ * @returns Results with decayedScore, sorted descending
38
+ */
39
+ export declare function applyTemporalDecay<T extends DecayableResult>(results: T[], timestamps: Map<number, Date>, halfLifeDays?: number, now?: Date): Array<T & {
40
+ decayedScore: number;
41
+ }>;
42
+ /**
43
+ * Memory file types exempt from temporal decay.
44
+ * These files contain evergreen knowledge that remains relevant regardless of age.
45
+ */
46
+ export declare const CURATED_FILE_TYPES: readonly string[];
47
+ /**
48
+ * Apply temporal decay with exemptions for curated content.
49
+ *
50
+ * Identical to applyTemporalDecay but skips decay for rowids in the
51
+ * exemptions set. Exempt results retain their original score.
52
+ *
53
+ * @param results Array of results with base scores
54
+ * @param timestamps Map of rowid to message timestamp
55
+ * @param exemptRowids Set of rowids that should not be decayed
56
+ * @param halfLifeDays Number of days for score to halve (default 30)
57
+ * @param now Reference time for age calculation (default: current time)
58
+ * @returns Results with decayedScore, sorted descending
59
+ */
60
+ export declare function applyTemporalDecayWithExemptions<T extends DecayableResult>(results: T[], timestamps: Map<number, Date>, exemptRowids: Set<number>, halfLifeDays?: number, now?: Date): Array<T & {
61
+ decayedScore: number;
62
+ }>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * BackfillState Entity
3
+ *
4
+ * Tracks the state of backfilling a session (generating daily log via Agent SDK).
5
+ * Enables idempotent backfill: processed sessions are skipped on re-run.
6
+ *
7
+ * Entity properties:
8
+ * - Has unique identity (sessionId)
9
+ * - Immutable after construction
10
+ * - Two terminal states: success or error (no lifecycle transitions)
11
+ */
12
+ interface BackfillStateParams {
13
+ sessionId: string;
14
+ backfilledAt: Date;
15
+ dailyLogPath: string;
16
+ success?: boolean | undefined;
17
+ errorMessage?: string | undefined;
18
+ }
19
+ export declare class BackfillState {
20
+ private readonly _sessionId;
21
+ private readonly _backfilledAt;
22
+ private readonly _dailyLogPath;
23
+ private readonly _success;
24
+ private readonly _errorMessage?;
25
+ private constructor();
26
+ /**
27
+ * Create a BackfillState entity.
28
+ * @throws Error if sessionId or dailyLogPath is empty
29
+ */
30
+ static create(params: BackfillStateParams): BackfillState;
31
+ /**
32
+ * The session UUID that was backfilled.
33
+ */
34
+ get sessionId(): string;
35
+ /**
36
+ * When the backfill was performed.
37
+ */
38
+ get backfilledAt(): Date;
39
+ /**
40
+ * Path to the daily log file produced by backfill.
41
+ */
42
+ get dailyLogPath(): string;
43
+ /**
44
+ * Whether the backfill succeeded.
45
+ */
46
+ get success(): boolean;
47
+ /**
48
+ * Error message if the backfill failed.
49
+ */
50
+ get errorMessage(): string | undefined;
51
+ /**
52
+ * Convenience getter: whether the backfill succeeded.
53
+ */
54
+ get isSuccess(): boolean;
55
+ }
56
+ export {};