@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,44 @@
1
+ /**
2
+ * Uninstall Command Handler
3
+ *
4
+ * CLI command for removing Claude Code hooks.
5
+ * Removes hook entries from settings.json and deletes hook script.
6
+ */
7
+ import { Command } from "commander";
8
+ import type { CommandResult } from "../command-result.js";
9
+ /**
10
+ * Options for the uninstall command.
11
+ */
12
+ export interface UninstallOptions {
13
+ /** Restore settings.json from backup instead of removing hooks */
14
+ restore?: boolean;
15
+ }
16
+ /**
17
+ * Runtime dependencies for executeUninstallCommand.
18
+ *
19
+ * Operational dependencies that tests substitute for isolation.
20
+ * Defaults to production resolution when omitted.
21
+ */
22
+ export interface UninstallCommandDeps {
23
+ /**
24
+ * Override settings/backup/hook-script paths used by settings-manager.
25
+ */
26
+ hookOverrides?: import("../../../infrastructure/hooks/settings-manager.js").PathOverrides;
27
+ }
28
+ /**
29
+ * Create the uninstall command for Commander.js.
30
+ *
31
+ * @returns Configured Command instance
32
+ */
33
+ export declare function createUninstallCommand(): Command;
34
+ /**
35
+ * Execute the uninstall command programmatically.
36
+ *
37
+ * Removes Claude Code hooks installed by the install command. Deletes
38
+ * hook entries from settings.json and removes the hook script file.
39
+ * Returns exitCode 0 if hooks are not installed (idempotent).
40
+ *
41
+ * @param options - Uninstall command options
42
+ * @returns CommandResult with exitCode 0 (success/not installed)
43
+ */
44
+ export declare function executeUninstallCommand(options: UninstallOptions, deps?: UninstallCommandDeps): Promise<CommandResult>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Database Startup Utilities
3
+ *
4
+ * Handles database initialization with integrity checks and recovery options.
5
+ * Provides user-friendly prompts for corrupted database scenarios.
6
+ */
7
+ import { type DatabaseConfig, type DatabaseInitResult } from "../../infrastructure/database/index.js";
8
+ import { MemoryError } from "../../domain/index.js";
9
+ interface TtyLikeStream {
10
+ isTTY?: boolean | undefined;
11
+ }
12
+ /**
13
+ * Options for database startup.
14
+ */
15
+ export interface DbStartupOptions {
16
+ /** JSON output mode */
17
+ json?: boolean;
18
+ /** Verbose mode for error details */
19
+ verbose?: boolean;
20
+ /** Custom database path (defaults to getDefaultDbPath()) */
21
+ dbPath?: string;
22
+ /** Skip integrity check on startup */
23
+ skipCheck?: boolean;
24
+ }
25
+ /**
26
+ * Result of database startup.
27
+ */
28
+ export type DbStartupResult = {
29
+ success: true;
30
+ db: DatabaseInitResult["db"];
31
+ } | {
32
+ success: false;
33
+ error: MemoryError;
34
+ };
35
+ export interface DbStartupDeps {
36
+ existsSync?: (path: string) => boolean;
37
+ getDefaultDbPath?: () => string;
38
+ initializeDatabaseSafe?: (config: DatabaseConfig) => DatabaseInitResult;
39
+ isTTY?: () => boolean;
40
+ confirm?: (message: string) => Promise<boolean>;
41
+ backupCorruptedDatabase?: (dbPath: string) => string;
42
+ }
43
+ /**
44
+ * Check if running in an interactive TTY environment.
45
+ *
46
+ * @returns true if stdin and stdout are TTYs
47
+ */
48
+ export declare function isTTY(input?: TtyLikeStream, output?: TtyLikeStream): boolean;
49
+ /**
50
+ * Initialize database with startup checks and error handling.
51
+ *
52
+ * Performs:
53
+ * 1. Quick integrity check (for existing databases)
54
+ * 2. Error handling with user-friendly messages
55
+ * 3. Recovery prompt for corrupted databases (in TTY)
56
+ *
57
+ * @param options Startup options
58
+ * @returns Database startup result
59
+ */
60
+ export declare function initializeDatabaseForCli(options?: DbStartupOptions, deps?: DbStartupDeps): Promise<DbStartupResult>;
61
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * AI Formatter Utility
3
+ *
4
+ * Shared utility for producing clean, token-efficient text output.
5
+ * Used by --format ai across all commands and by the smart context
6
+ * service for budget estimation.
7
+ */
8
+ /**
9
+ * Strip all ANSI escape sequences from text.
10
+ *
11
+ * Removes SGR (color/style), CSI (cursor/screen), OSC (title),
12
+ * and charset selection sequences.
13
+ *
14
+ * @param text Input text potentially containing ANSI codes
15
+ * @returns Plain text with all escape sequences removed
16
+ */
17
+ export declare function stripAnsi(text: string): string;
18
+ /**
19
+ * Estimate token count using a chars-per-token heuristic.
20
+ *
21
+ * Default ratio of 4 characters per token approximates GPT/Claude
22
+ * tokenization for English text.
23
+ *
24
+ * @param text Input text to estimate
25
+ * @param charsPerToken Characters per token (default: 4)
26
+ * @returns Estimated token count (ceiling)
27
+ */
28
+ export declare function estimateTokens(text: string, charsPerToken?: number): number;
29
+ /**
30
+ * Format text for AI consumption.
31
+ *
32
+ * Strips ANSI codes, collapses multiple blank lines to a single
33
+ * blank line, and trims leading/trailing whitespace.
34
+ *
35
+ * @param text Input text with potential ANSI codes and irregular whitespace
36
+ * @returns Clean, normalized text suitable for AI processing
37
+ */
38
+ export declare function formatForAi(text: string): string;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Color Utilities
3
+ *
4
+ * TTY-aware color output for CLI commands.
5
+ * Respects NO_COLOR and FORCE_COLOR environment variables.
6
+ */
7
+ /**
8
+ * Options for color detection.
9
+ */
10
+ export interface ColorOptions {
11
+ isTTY?: boolean;
12
+ noColor?: boolean;
13
+ forceColor?: boolean;
14
+ }
15
+ /**
16
+ * Determine if color output should be used.
17
+ *
18
+ * Priority order:
19
+ * 1. NO_COLOR env var or noColor option (disables color)
20
+ * 2. FORCE_COLOR env var or forceColor option (enables color)
21
+ * 3. TTY detection (enables color if TTY)
22
+ *
23
+ * @param options Color detection options
24
+ * @returns True if color should be used
25
+ */
26
+ export declare function shouldUseColor(options?: ColorOptions): boolean;
27
+ /**
28
+ * Make text bold.
29
+ *
30
+ * @param text Text to make bold
31
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
32
+ * @returns Bold text or plain text
33
+ */
34
+ export declare function bold(text: string, useColor?: boolean): string;
35
+ /**
36
+ * Make text dim.
37
+ *
38
+ * @param text Text to make dim
39
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
40
+ * @returns Dim text or plain text
41
+ */
42
+ export declare function dim(text: string, useColor?: boolean): string;
43
+ /**
44
+ * Make text green.
45
+ *
46
+ * @param text Text to make green
47
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
48
+ * @returns Green text or plain text
49
+ */
50
+ export declare function green(text: string, useColor?: boolean): string;
51
+ /**
52
+ * Make text red.
53
+ *
54
+ * @param text Text to make red
55
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
56
+ * @returns Red text or plain text
57
+ */
58
+ export declare function red(text: string, useColor?: boolean): string;
59
+ /**
60
+ * Make text yellow.
61
+ *
62
+ * @param text Text to make yellow
63
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
64
+ * @returns Yellow text or plain text
65
+ */
66
+ export declare function yellow(text: string, useColor?: boolean): string;
67
+ /**
68
+ * Make text cyan (for highlighting matches).
69
+ *
70
+ * @param text Text to make cyan
71
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
72
+ * @returns Cyan text or plain text
73
+ */
74
+ export declare function cyan(text: string, useColor?: boolean): string;
75
+ /**
76
+ * Make text bold and cyan (for highly visible highlighting).
77
+ *
78
+ * @param text Text to make bold and cyan
79
+ * @param useColor Whether to apply color (defaults to shouldUseColor())
80
+ * @returns Bold cyan text or plain text
81
+ */
82
+ export declare function boldCyan(text: string, useColor?: boolean): string;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Context Formatter
3
+ *
4
+ * Strategy pattern for formatting project context output.
5
+ * Supports brief, detailed, JSON, quiet, and verbose output modes.
6
+ */
7
+ import type { ProjectContext } from "../../../infrastructure/database/services/context-service.js";
8
+ import type { SmartContextResult } from "../../../application/services/smart-context-service.js";
9
+ /**
10
+ * Output mode for context formatter.
11
+ */
12
+ export type ContextOutputMode = "default" | "json" | "brief" | "detailed" | "quiet" | "verbose" | "ai";
13
+ /**
14
+ * Options for formatting context.
15
+ */
16
+ export interface ContextFormatOptions {
17
+ /** Execution time in milliseconds */
18
+ executionTimeMs?: number;
19
+ /** List of filters that were applied */
20
+ filtersApplied?: string[];
21
+ }
22
+ /**
23
+ * Context formatter interface.
24
+ */
25
+ export interface ContextFormatter {
26
+ /**
27
+ * Format project context for display.
28
+ */
29
+ formatContext(context: ProjectContext, options?: ContextFormatOptions): string;
30
+ /**
31
+ * Format smart context result with structured sections.
32
+ * Only implemented by AI formatter; other formatters may leave undefined.
33
+ */
34
+ formatSmartContext?(result: SmartContextResult): string;
35
+ /**
36
+ * Format an error message.
37
+ */
38
+ formatError(error: Error): string;
39
+ /**
40
+ * Format empty result message (project not found).
41
+ */
42
+ formatEmpty(projectName: string): string;
43
+ /**
44
+ * Format message when no topics extracted yet.
45
+ */
46
+ formatNoTopics(): string;
47
+ }
48
+ /**
49
+ * Create a context formatter for the given mode.
50
+ *
51
+ * @param mode Output mode
52
+ * @param useColor Whether to use ANSI colors
53
+ * @returns ContextFormatter instance
54
+ */
55
+ export declare function createContextFormatter(mode: ContextOutputMode, useColor: boolean): ContextFormatter;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * DTO helpers for query command JSON output.
3
+ *
4
+ * Extracted from JsonOutputFormatter (per Codex MEDIUM-1) so each command
5
+ * can build its envelope `data` field using a pure, testable transformation.
6
+ *
7
+ * INVARIANT (Gemini LOW): highlight offsets MUST be computed BEFORE
8
+ * <mark> tags are stripped. Computing after-strip would always produce
9
+ * offset 0 (no tags remain). See toSearchResultDto.
10
+ *
11
+ * CONTEXT_BUDGET BOUNDARY (Codex MEDIUM-1): the iterative truncation loop
12
+ * that fits results within the 50K-char budget lives in
13
+ * JsonOutputFormatter (output-formatter.ts), NOT here. DTO helpers
14
+ * transform shape; the formatter owns truncation. Plan 32-02's envelope
15
+ * path skips truncation because envelope consumers expect a stable
16
+ * data array, not a heuristically-trimmed prefix.
17
+ */
18
+ import type { SearchResult } from "../../../domain/value-objects/search-result.js";
19
+ import type { Session } from "../../../domain/entities/session.js";
20
+ import type { QmdSearchResult } from "../../../domain/ports/services.js";
21
+ import type { ProjectContext } from "../../../infrastructure/database/services/context-service.js";
22
+ import type { ExtendedStatsResult } from "./stats-formatter.js";
23
+ import type { SessionDetail } from "./show-formatter.js";
24
+ import type { RelatedSession } from "./related-formatter.js";
25
+ /**
26
+ * DTO for a single search result in JSON output.
27
+ *
28
+ * Mirrors the legacy JsonOutputFormatter.formatResults() shape so
29
+ * existing consumers see the same fields wrapped in the envelope's
30
+ * `data` array.
31
+ */
32
+ export interface SearchResultDto {
33
+ sessionId: string;
34
+ messageId: string;
35
+ role: string;
36
+ score: number;
37
+ timestamp: string;
38
+ snippet: string;
39
+ rank?: number;
40
+ raw_scores?: {
41
+ bm25?: number | undefined;
42
+ cosine?: number | undefined;
43
+ rrf?: number | undefined;
44
+ } | undefined;
45
+ source?: "fts" | "vector" | "both";
46
+ highlights?: Array<{
47
+ offset: number;
48
+ length: number;
49
+ }>;
50
+ }
51
+ /**
52
+ * Convert a SearchResult value-object into a JSON-emitting DTO.
53
+ *
54
+ * - highlights are computed from the ORIGINAL snippet before <mark>
55
+ * stripping (Gemini LOW invariant).
56
+ * - hybrid-search-meta fields (rank, raw_scores, source, highlights)
57
+ * are only included when includeSearchMetaFields is true — preserving
58
+ * the legacy behavior where these were gated on options.searchMeta.
59
+ */
60
+ export declare function toSearchResultDto(result: SearchResult, opts?: {
61
+ rank?: number;
62
+ includeSearchMetaFields?: boolean;
63
+ }): SearchResultDto;
64
+ /**
65
+ * DTO for a single qmd file-search result.
66
+ *
67
+ * Mirrors the QmdSearchResult shape so consumers see the same fields
68
+ * wrapped in the envelope (instead of the bespoke bare array that
69
+ * leaked in the pre-Plan-32-02 code).
70
+ */
71
+ export interface FileResultDto {
72
+ docid?: string;
73
+ score: number;
74
+ file: string;
75
+ title: string;
76
+ context?: string;
77
+ snippet?: string;
78
+ }
79
+ export declare function toFileResultDto(result: QmdSearchResult): FileResultDto;
80
+ /**
81
+ * DTO for a session entry in the `list` command output.
82
+ *
83
+ * Mirrors the existing list-formatter JSON shape.
84
+ */
85
+ export interface SessionListDto {
86
+ id: string;
87
+ project: string;
88
+ projectPath: string;
89
+ startTime: string;
90
+ endTime?: string;
91
+ messageCount?: number;
92
+ summary?: string;
93
+ }
94
+ export declare function toSessionListDto(session: Session): SessionListDto;
95
+ /**
96
+ * DTO for a message in the `show` command output.
97
+ */
98
+ export interface ShowMessageDto {
99
+ id: string;
100
+ role: string;
101
+ timestamp: string;
102
+ content: string;
103
+ toolUseIds?: string[];
104
+ }
105
+ /**
106
+ * DTO for a tool use in the `show` command output.
107
+ */
108
+ export interface ShowToolUseDto {
109
+ id: string;
110
+ name: string;
111
+ status: string;
112
+ input: Record<string, unknown>;
113
+ result?: string;
114
+ }
115
+ /**
116
+ * DTO for `show` command — session + messages + tool uses.
117
+ */
118
+ export interface ShowSessionDto {
119
+ session: SessionListDto;
120
+ messages: ShowMessageDto[];
121
+ toolUses: ShowToolUseDto[];
122
+ }
123
+ export declare function toShowSessionDto(detail: SessionDetail): ShowSessionDto;
124
+ /**
125
+ * DTO for a related-session entry in the `related` command output.
126
+ */
127
+ export interface RelatedDto {
128
+ session: SessionListDto;
129
+ weight: number;
130
+ hops: number;
131
+ }
132
+ export declare function toRelatedDto(item: RelatedSession): RelatedDto;
133
+ /**
134
+ * DTO for the `stats` command output.
135
+ *
136
+ * Mirrors ExtendedStatsResult shape: totals plus per-project breakdown
137
+ * and optional hooks summary.
138
+ */
139
+ export interface StatsDto {
140
+ totalSessions: number;
141
+ totalMessages: number;
142
+ totalToolUses: number;
143
+ databaseSizeBytes: number;
144
+ projectBreakdown: Array<{
145
+ projectName: string;
146
+ sessionCount: number;
147
+ messageCount: number;
148
+ }>;
149
+ hooks?: {
150
+ installed: boolean;
151
+ autoSync: boolean;
152
+ pendingSessions: number;
153
+ };
154
+ }
155
+ export declare function toStatsDto(stats: ExtendedStatsResult): StatsDto;
156
+ /**
157
+ * DTO for the `context` command output.
158
+ *
159
+ * Mirrors ProjectContext shape so envelope `data` carries the same
160
+ * information the legacy formatter renders.
161
+ */
162
+ export interface ContextDto {
163
+ projectName: string;
164
+ projectPathDecoded: string;
165
+ sessionCount: number;
166
+ totalMessages: number;
167
+ userMessages: number;
168
+ assistantMessages: number;
169
+ recentTopics: string[];
170
+ recentToolUses: Array<{
171
+ name: string;
172
+ count: number;
173
+ }>;
174
+ lastActivity: string | null;
175
+ }
176
+ export declare function toContextDto(context: ProjectContext): ContextDto;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Uniform JSON envelope for query commands (CLI-02 foundation).
3
+ *
4
+ * SCHEMA VERSION POLICY:
5
+ * Bump ENVELOPE_SCHEMA_VERSION ONLY when the field set changes in a
6
+ * backward-incompatible way:
7
+ * - Renaming a top-level field (e.g., `data` → `payload`)
8
+ * - Changing a field type (e.g., `kind: string` → `kind: object`)
9
+ * - Removing a field
10
+ * - Changing semantics of an existing field
11
+ *
12
+ * Additive changes (new optional fields, new kinds in QUERY_RESULT_KINDS,
13
+ * new entries in EnvelopeScope union) do NOT bump the schema version.
14
+ * Consumers should ignore unknown fields gracefully.
15
+ *
16
+ * Phase 32.5 forward-compat: `kind` and `scope` are reserved for the
17
+ * unified query primitive (`memory query --scope <project|global>
18
+ * --kind <message|session|...>`). Phase 32 sets `kind` from the command
19
+ * name; Phase 32.5 will set `kind` from a CLI flag. No schema change.
20
+ */
21
+ /**
22
+ * Current envelope schema version. Bump only per the policy above.
23
+ */
24
+ export declare const ENVELOPE_SCHEMA_VERSION: "1";
25
+ /**
26
+ * Runtime tuple of query command names. Types derived from this so callers
27
+ * can use both the values (e.g. `QUERY_COMMAND_NAMES.includes(x)`) and the
28
+ * literal union type (`QueryCommandName`). Per Codex HIGH-1.
29
+ */
30
+ export declare const QUERY_COMMAND_NAMES: readonly ["search", "context", "show", "list", "related", "stats", "query"];
31
+ /**
32
+ * Union of valid query command names, derived from QUERY_COMMAND_NAMES.
33
+ */
34
+ export type QueryCommandName = (typeof QUERY_COMMAND_NAMES)[number];
35
+ /**
36
+ * Runtime tuple of result kinds. Includes `"file"` so `search --files`
37
+ * (HIGH-4) has a stable kind in the envelope. Phase 32.5 will route the
38
+ * unified query primitive's `--kind` flag through this same set.
39
+ */
40
+ export declare const QUERY_RESULT_KINDS: readonly ["message", "session", "context", "related", "stats", "file"];
41
+ /**
42
+ * Union of valid query result kinds, derived from QUERY_RESULT_KINDS.
43
+ */
44
+ export type QueryResultKind = (typeof QUERY_RESULT_KINDS)[number];
45
+ /**
46
+ * Discriminated union for envelope scope. Maps 1:1 to Phase 32.5's
47
+ * `--scope global|project [--project <name>]` without ambiguity.
48
+ * Per Codex MEDIUM-4.
49
+ */
50
+ export type EnvelopeScope = {
51
+ type: "global";
52
+ } | {
53
+ type: "project";
54
+ project: string;
55
+ };
56
+ /**
57
+ * Success envelope shape. `data` is generic so each command can carry
58
+ * its own payload type. `schema_version` is a literal "1" so consumers
59
+ * can branch on shape evolution.
60
+ */
61
+ export interface QueryResultEnvelope<T = unknown> {
62
+ schema_version: typeof ENVELOPE_SCHEMA_VERSION;
63
+ command: QueryCommandName;
64
+ kind: QueryResultKind;
65
+ scope?: EnvelopeScope;
66
+ meta?: Record<string, unknown>;
67
+ data: T;
68
+ }
69
+ /**
70
+ * Error envelope shape. `error.code` is a domain ErrorCode string
71
+ * (e.g. "DB_CONNECTION_FAILED"); `error.context` carries structured
72
+ * details from MemoryError instances.
73
+ */
74
+ export interface QueryErrorEnvelope {
75
+ schema_version: typeof ENVELOPE_SCHEMA_VERSION;
76
+ command: QueryCommandName;
77
+ error: {
78
+ code: string;
79
+ message: string;
80
+ context?: Record<string, unknown>;
81
+ };
82
+ }
83
+ /**
84
+ * Construct a success envelope. Optional fields are omitted from the
85
+ * resulting object when undefined (no `"scope": undefined` leakage in
86
+ * JSON.stringify output).
87
+ */
88
+ export declare function buildEnvelope<T>(args: {
89
+ command: QueryCommandName;
90
+ kind: QueryResultKind;
91
+ data: T;
92
+ scope?: EnvelopeScope;
93
+ meta?: Record<string, unknown>;
94
+ }): QueryResultEnvelope<T>;
95
+ /**
96
+ * Construct an error envelope. `error.context` is omitted when undefined.
97
+ */
98
+ export declare function buildErrorEnvelope(args: {
99
+ command: QueryCommandName;
100
+ code: string;
101
+ message: string;
102
+ context?: Record<string, unknown>;
103
+ }): QueryErrorEnvelope;
104
+ /**
105
+ * Emit a success envelope to stdout as pretty-printed JSON.
106
+ *
107
+ * Per Codex HIGH-2: this is the canonical write surface for Plan 02
108
+ * success/empty-result branches. Every query command's exit path routes
109
+ * through here so stdout shape stays uniform.
110
+ *
111
+ * Does NOT set process.exitCode — the caller still returns
112
+ * `{ exitCode: 0 }` (or whatever CommandResult shape it uses).
113
+ */
114
+ export declare function emitJsonEnvelope<T>(args: {
115
+ command: QueryCommandName;
116
+ kind: QueryResultKind;
117
+ data: T;
118
+ scope?: EnvelopeScope;
119
+ meta?: Record<string, unknown>;
120
+ }): void;
121
+ /**
122
+ * Emit an error envelope to stdout as pretty-printed JSON.
123
+ *
124
+ * Per Codex HIGH-2: this is the canonical write surface for Plan 02
125
+ * validation/not-found/catch branches. Every error exit path routes
126
+ * through here so stdout shape stays uniform regardless of failure mode.
127
+ *
128
+ * Does NOT set process.exitCode — the caller still returns
129
+ * `{ exitCode: 1 }` (or whatever CommandResult shape it uses).
130
+ */
131
+ export declare function emitJsonErrorEnvelope(args: {
132
+ command: QueryCommandName;
133
+ code: string;
134
+ message: string;
135
+ context?: Record<string, unknown>;
136
+ }): void;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Error Formatter
3
+ *
4
+ * Formats errors for CLI output with context, suggestions, and color.
5
+ */
6
+ import { MemoryError, type ErrorCodeType } from "../../../domain/index.js";
7
+ /**
8
+ * Options for error formatting.
9
+ */
10
+ export interface ErrorFormatOptions {
11
+ /**
12
+ * Include stack trace in output.
13
+ */
14
+ verbose?: boolean;
15
+ /**
16
+ * Override TTY detection for color.
17
+ */
18
+ useColor?: boolean;
19
+ }
20
+ /**
21
+ * Get a suggestion for corrective action based on error code.
22
+ *
23
+ * @param code Error code
24
+ * @returns Suggestion string or null if no suggestion available
25
+ */
26
+ export declare function getSuggestion(code: ErrorCodeType): string | null;
27
+ /**
28
+ * Format an error for human-readable CLI output.
29
+ *
30
+ * @param error Error to format
31
+ * @param options Formatting options
32
+ * @returns Formatted error string
33
+ */
34
+ export declare function formatError(error: Error | MemoryError, options?: ErrorFormatOptions): string;
35
+ /**
36
+ * Format an error as JSON for programmatic consumption.
37
+ *
38
+ * @param error Error to format
39
+ * @returns JSON string with structured error
40
+ */
41
+ export declare function formatErrorJson(error: Error | MemoryError): string;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Friction Dashboard Formatters
3
+ *
4
+ * Two formatters for friction data visualization:
5
+ * 1. formatFrictionDashboard - Rich terminal output with ASCII bars
6
+ * 2. generateFrictionHtml - Self-contained HTML with Chart.js charts
7
+ *
8
+ * Uses color.ts utilities for terminal coloring and reads Chart.js UMD
9
+ * source from node_modules at HTML generation time (no CDN dependency).
10
+ */
11
+ import type { FrictionStats, FrictionPattern } from "../../../domain/ports/repositories.js";
12
+ import type { FrictionEntry } from "../../../domain/entities/friction-entry.js";
13
+ /**
14
+ * Render a rich terminal dashboard for friction stats.
15
+ *
16
+ * Displays overview counts, severity/category breakdowns with ASCII
17
+ * bar charts, MTTR, oldest open entry, and weekly trends table.
18
+ *
19
+ * @param stats Aggregated friction statistics
20
+ * @param trends Weekly new/resolved counts
21
+ * @param openItems Currently open friction entries
22
+ * @param useColor Whether to apply ANSI color codes
23
+ * @returns Formatted dashboard string
24
+ */
25
+ export declare function formatFrictionDashboard(stats: FrictionStats, trends: Array<{
26
+ week: string;
27
+ newCount: number;
28
+ resolvedCount: number;
29
+ }>, _openItems: FrictionEntry[], useColor: boolean, patterns?: FrictionPattern[]): string;
30
+ /**
31
+ * Generate a self-contained HTML friction dashboard.
32
+ *
33
+ * The HTML file embeds Chart.js inline (no CDN), uses a dark theme,
34
+ * and includes 4 chart types: line (over time), doughnut (by category),
35
+ * horizontal bar (by severity), and grouped bar (resolution trend).
36
+ *
37
+ * @param stats Aggregated friction statistics
38
+ * @param trends Weekly new/resolved counts
39
+ * @param openItems Currently open friction entries
40
+ * @returns Complete HTML document string
41
+ */
42
+ export declare function generateFrictionHtml(stats: FrictionStats, trends: Array<{
43
+ week: string;
44
+ newCount: number;
45
+ resolvedCount: number;
46
+ }>, openItems: FrictionEntry[], patterns?: FrictionPattern[]): string;