claude-memory-layer 1.0.30 ā 1.0.32
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.
- package/README.md +12 -5
- package/dist/cli/index.js +4 -3
- package/dist/cli/index.js.map +2 -2
- package/dist/core/index.js +3 -2
- package/dist/core/index.js.map +2 -2
- package/dist/hooks/post-tool-use.js +3 -2
- package/dist/hooks/post-tool-use.js.map +2 -2
- package/dist/hooks/semantic-daemon.js +3 -2
- package/dist/hooks/semantic-daemon.js.map +2 -2
- package/dist/hooks/session-end.js +3 -2
- package/dist/hooks/session-end.js.map +2 -2
- package/dist/hooks/session-start.js +3 -2
- package/dist/hooks/session-start.js.map +2 -2
- package/dist/hooks/stop.js +3 -2
- package/dist/hooks/stop.js.map +2 -2
- package/dist/hooks/user-prompt-submit.js +3 -2
- package/dist/hooks/user-prompt-submit.js.map +2 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +2 -2
- package/dist/mcp/index.js +3 -2
- package/dist/mcp/index.js.map +2 -2
- package/dist/server/api/index.js +3 -2
- package/dist/server/api/index.js.map +2 -2
- package/dist/server/index.js +3 -2
- package/dist/server/index.js.map +2 -2
- package/dist/services/memory-service.js +3 -2
- package/dist/services/memory-service.js.map +2 -2
- package/package.json +10 -3
- package/scripts/postinstall-embedding-backend.cjs +18 -16
- package/AGENTS.md +0 -71
- package/CLAUDE.md +0 -30
- package/HANDOFF.md +0 -92
- package/Memo.txt +0 -558
- package/benchmarks/replay/anonymized-real-sessions.json +0 -48
- package/config/kpi-thresholds.json +0 -7
- package/context.md +0 -636
- package/docs/ARCHITECTURE_COMPARISON_AND_RECOMMENDATIONS.md +0 -627
- package/docs/HERMES_MEMORY_INGESTION_ANALYSIS.md +0 -440
- package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +0 -271
- package/docs/MEMORY_USEFULNESS_AUDIT.md +0 -371
- package/docs/MEMORY_USEFULNESS_AUDIT_RAW.json +0 -80
- package/docs/MEMSEARCH_PROJECT_STRUCTURE_ANALYSIS.md +0 -333
- package/docs/MEMU_ADOPTION.md +0 -40
- package/docs/OPERATIONS.md +0 -18
- package/docs/PRODUCT_VALIDATION_MATRIX.md +0 -82
- package/docs/PROJECT_STRUCTURE_ANALYSIS.md +0 -421
- package/docs/REFACTORING_MILESTONES_AND_ISSUES.md +0 -501
- package/docs/REFACTORING_PLAN_THIN_CORE.md +0 -414
- package/docs/REFERENCE_PROJECT_ANALYSES.md +0 -25
- package/docs/SUPERLOCALMEMORY_PROJECT_STRUCTURE_ANALYSIS.md +0 -452
- package/docs/TARGET_ARCHITECTURE_AND_FOLDER_STRUCTURE.md +0 -446
- package/docs/architecture/comparison-index.md +0 -47
- package/docs/reports/codex-real-data-validation-20260505T040447Z.md +0 -46
- package/plan.md +0 -1642
- package/scripts/build.ts +0 -159
- package/scripts/bump-patch-version.sh +0 -18
- package/scripts/delete-unknown-projects.js +0 -154
- package/scripts/fix-sync-gap.js +0 -32
- package/scripts/generate-session-qrels.ts +0 -126
- package/scripts/heartbeat-memory-orchestrator.sh +0 -28
- package/scripts/replay-retrieval-benchmark.ts +0 -69
- package/scripts/report-sync-gap.js +0 -26
- package/scripts/review-queue-auto-resolve.js +0 -21
- package/scripts/sync-gap-auto-heal.sh +0 -17
- package/spec.md +0 -624
- package/specs/20260207-dashboard-upgrade/context.md +0 -38
- package/specs/20260207-dashboard-upgrade/spec.md +0 -96
- package/specs/citations-system/context.md +0 -243
- package/specs/citations-system/plan.md +0 -495
- package/specs/citations-system/spec.md +0 -371
- package/specs/endless-mode/context.md +0 -305
- package/specs/endless-mode/plan.md +0 -620
- package/specs/endless-mode/spec.md +0 -455
- package/specs/entity-edge-model/context.md +0 -401
- package/specs/entity-edge-model/plan.md +0 -459
- package/specs/entity-edge-model/spec.md +0 -391
- package/specs/evidence-aligner-v2/context.md +0 -401
- package/specs/evidence-aligner-v2/plan.md +0 -303
- package/specs/evidence-aligner-v2/spec.md +0 -312
- package/specs/mcp-desktop-integration/context.md +0 -278
- package/specs/mcp-desktop-integration/plan.md +0 -550
- package/specs/mcp-desktop-integration/spec.md +0 -494
- package/specs/memory-utilization-improvements/context.md +0 -145
- package/specs/memory-utilization-improvements/plan.md +0 -361
- package/specs/memory-utilization-improvements/spec.md +0 -361
- package/specs/post-tool-use-hook/context.md +0 -319
- package/specs/post-tool-use-hook/plan.md +0 -469
- package/specs/post-tool-use-hook/spec.md +0 -364
- package/specs/private-tags/context.md +0 -288
- package/specs/private-tags/plan.md +0 -412
- package/specs/private-tags/spec.md +0 -345
- package/specs/progressive-disclosure/context.md +0 -346
- package/specs/progressive-disclosure/plan.md +0 -663
- package/specs/progressive-disclosure/spec.md +0 -415
- package/specs/selective-tool-observation/context.md +0 -100
- package/specs/selective-tool-observation/plan.md +0 -158
- package/specs/selective-tool-observation/spec.md +0 -127
- package/specs/task-entity-system/context.md +0 -297
- package/specs/task-entity-system/plan.md +0 -301
- package/specs/task-entity-system/spec.md +0 -314
- package/specs/thin-core-refactor/context.md +0 -275
- package/specs/thin-core-refactor/plan.md +0 -536
- package/specs/thin-core-refactor/spec.md +0 -465
- package/specs/vector-outbox-v2/context.md +0 -470
- package/specs/vector-outbox-v2/plan.md +0 -562
- package/specs/vector-outbox-v2/spec.md +0 -466
- package/specs/web-viewer-ui/context.md +0 -384
- package/specs/web-viewer-ui/plan.md +0 -797
- package/specs/web-viewer-ui/spec.md +0 -516
- package/src/adapters/claude/capture/index.ts +0 -3
- package/src/adapters/claude/context/index.ts +0 -3
- package/src/adapters/claude/hooks/index.ts +0 -21
- package/src/adapters/claude/hooks/post-tool-use.ts +0 -239
- package/src/adapters/claude/hooks/prompt-injection-policy.ts +0 -104
- package/src/adapters/claude/hooks/semantic-daemon-client.ts +0 -209
- package/src/adapters/claude/hooks/semantic-daemon.ts +0 -283
- package/src/adapters/claude/hooks/session-end.ts +0 -59
- package/src/adapters/claude/hooks/session-start.ts +0 -73
- package/src/adapters/claude/hooks/stop.ts +0 -128
- package/src/adapters/claude/hooks/user-prompt-submit.ts +0 -361
- package/src/adapters/claude/index.ts +0 -4
- package/src/adapters/claude/transcript/index.ts +0 -4
- package/src/adapters/claude/transcript/transcript-reader.ts +0 -57
- package/src/adapters/claude/transcript/turn-reconstructor.ts +0 -65
- package/src/apps/cli/claude-settings-hooks.ts +0 -138
- package/src/apps/cli/codex-import-runner.ts +0 -125
- package/src/apps/cli/codex-validation-output.ts +0 -95
- package/src/apps/cli/hermes-import-runner.ts +0 -130
- package/src/apps/cli/hermes-validation-output.ts +0 -91
- package/src/apps/cli/index.ts +0 -1735
- package/src/apps/cli/mcp-install.ts +0 -106
- package/src/apps/cli/retrieval-disclosure-output.ts +0 -196
- package/src/apps/dashboard/assets/js/bootstrap.js +0 -244
- package/src/apps/dashboard/assets/js/chat.js +0 -373
- package/src/apps/dashboard/assets/js/disclosure.js +0 -232
- package/src/apps/dashboard/assets/js/modals.js +0 -298
- package/src/apps/dashboard/assets/js/overview.js +0 -655
- package/src/apps/dashboard/assets/js/state.js +0 -72
- package/src/apps/dashboard/assets/js/views.js +0 -468
- package/src/apps/dashboard/index.html +0 -543
- package/src/apps/dashboard/index.ts +0 -3
- package/src/apps/dashboard/style.css +0 -1750
- package/src/apps/index.ts +0 -5
- package/src/apps/server/api/chat.ts +0 -244
- package/src/apps/server/api/citations.ts +0 -105
- package/src/apps/server/api/events.ts +0 -137
- package/src/apps/server/api/health.ts +0 -53
- package/src/apps/server/api/index.ts +0 -26
- package/src/apps/server/api/projects.ts +0 -74
- package/src/apps/server/api/search.ts +0 -184
- package/src/apps/server/api/sessions.ts +0 -115
- package/src/apps/server/api/stats.ts +0 -723
- package/src/apps/server/api/turns.ts +0 -143
- package/src/apps/server/api/utils.ts +0 -65
- package/src/apps/server/index.ts +0 -111
- package/src/cli/index.ts +0 -3
- package/src/cli/retrieval-disclosure-output.ts +0 -2
- package/src/compat/index.ts +0 -5
- package/src/core/canonical-key.ts +0 -186
- package/src/core/citation-generator.ts +0 -63
- package/src/core/consolidated-store.ts +0 -356
- package/src/core/consolidation-worker.ts +0 -493
- package/src/core/context-formatter.ts +0 -276
- package/src/core/continuity-manager.ts +0 -341
- package/src/core/db-wrapper.ts +0 -64
- package/src/core/derive/fact-deriver.ts +0 -170
- package/src/core/derive/index.ts +0 -2
- package/src/core/derive/summary-deriver.ts +0 -76
- package/src/core/edge-repo.ts +0 -333
- package/src/core/embedder.ts +0 -4
- package/src/core/engine/embedding-maintenance-service.ts +0 -187
- package/src/core/engine/endless-memory-services.ts +0 -4
- package/src/core/engine/index.ts +0 -19
- package/src/core/engine/memory-engine-services.ts +0 -170
- package/src/core/engine/memory-ingest-service.ts +0 -317
- package/src/core/engine/memory-query-service.ts +0 -173
- package/src/core/engine/memory-runtime-service.ts +0 -162
- package/src/core/engine/memory-service-composition.ts +0 -231
- package/src/core/engine/retrieval-analytics-service.ts +0 -181
- package/src/core/engine/retrieval-disclosure-service.ts +0 -420
- package/src/core/engine/retrieval-orchestrator.ts +0 -377
- package/src/core/engine/retrieval-services.ts +0 -176
- package/src/core/engine/shared-memory-services.ts +0 -4
- package/src/core/entity-repo.ts +0 -349
- package/src/core/event-store.ts +0 -779
- package/src/core/evidence-aligner.ts +0 -635
- package/src/core/external-market-context.ts +0 -582
- package/src/core/graduation-worker.ts +0 -171
- package/src/core/graduation.ts +0 -377
- package/src/core/index.ts +0 -64
- package/src/core/ingest-interceptor.ts +0 -80
- package/src/core/markdown-mirror.ts +0 -70
- package/src/core/matcher.ts +0 -208
- package/src/core/md-mirror.ts +0 -92
- package/src/core/metadata-extractor.ts +0 -203
- package/src/core/model/memory-fact.ts +0 -30
- package/src/core/model/memory-rule.ts +0 -14
- package/src/core/model/memory-summary.ts +0 -21
- package/src/core/model/raw-event.ts +0 -28
- package/src/core/model/retrieval-result.ts +0 -35
- package/src/core/mongo-sync-config.ts +0 -165
- package/src/core/mongo-sync-worker.ts +0 -381
- package/src/core/privacy/filter.ts +0 -190
- package/src/core/privacy/index.ts +0 -20
- package/src/core/privacy/tag-parser.ts +0 -145
- package/src/core/product-validation-matrix.ts +0 -314
- package/src/core/progressive-retriever.ts +0 -414
- package/src/core/registry/project-path.ts +0 -54
- package/src/core/registry/session-registry.ts +0 -69
- package/src/core/replay-evaluator.ts +0 -625
- package/src/core/retrieval-benchmark.ts +0 -117
- package/src/core/retrieval-quality.ts +0 -109
- package/src/core/retriever.ts +0 -800
- package/src/core/session-qrels.ts +0 -360
- package/src/core/shared-event-store.ts +0 -114
- package/src/core/shared-promoter.ts +0 -249
- package/src/core/shared-store.ts +0 -289
- package/src/core/shared-vector-store.ts +0 -203
- package/src/core/sqlite-event-store.ts +0 -1846
- package/src/core/sqlite-wrapper.ts +0 -116
- package/src/core/sync-worker.ts +0 -228
- package/src/core/tag-taxonomy.ts +0 -51
- package/src/core/task/blocker-resolver.ts +0 -333
- package/src/core/task/index.ts +0 -9
- package/src/core/task/task-matcher.ts +0 -240
- package/src/core/task/task-projector.ts +0 -358
- package/src/core/task/task-resolver.ts +0 -421
- package/src/core/turn-state.ts +0 -207
- package/src/core/types.ts +0 -952
- package/src/core/vector-outbox.ts +0 -299
- package/src/core/vector-store.ts +0 -231
- package/src/core/vector-worker.ts +0 -521
- package/src/core/working-set-store.ts +0 -257
- package/src/extensions/endless-memory/endless-memory-services.ts +0 -350
- package/src/extensions/endless-memory/index.ts +0 -1
- package/src/extensions/index.ts +0 -5
- package/src/extensions/mcp/handlers.ts +0 -960
- package/src/extensions/mcp/index.ts +0 -48
- package/src/extensions/mcp/tools.ts +0 -252
- package/src/extensions/shared-memory/index.ts +0 -1
- package/src/extensions/shared-memory/shared-memory-services.ts +0 -211
- package/src/extensions/vector/embedder.ts +0 -233
- package/src/extensions/vector/index.ts +0 -1
- package/src/hooks/post-tool-use.ts +0 -9
- package/src/hooks/semantic-daemon-client.ts +0 -1
- package/src/hooks/semantic-daemon.ts +0 -11
- package/src/hooks/session-end.ts +0 -9
- package/src/hooks/session-start.ts +0 -9
- package/src/hooks/stop.ts +0 -9
- package/src/hooks/user-prompt-submit.ts +0 -9
- package/src/index.ts +0 -13
- package/src/mcp/handlers.ts +0 -2
- package/src/mcp/index.ts +0 -4
- package/src/mcp/tools.ts +0 -2
- package/src/server/api/chat.ts +0 -2
- package/src/server/api/citations.ts +0 -2
- package/src/server/api/events.ts +0 -2
- package/src/server/api/health.ts +0 -2
- package/src/server/api/index.ts +0 -2
- package/src/server/api/projects.ts +0 -2
- package/src/server/api/search.ts +0 -2
- package/src/server/api/sessions.ts +0 -2
- package/src/server/api/stats.ts +0 -2
- package/src/server/api/turns.ts +0 -2
- package/src/server/api/utils.ts +0 -2
- package/src/server/index.ts +0 -2
- package/src/services/bootstrap-organizer.ts +0 -463
- package/src/services/codex-session-history-importer.ts +0 -966
- package/src/services/hermes-session-history-importer.ts +0 -733
- package/src/services/memory-service-config.ts +0 -36
- package/src/services/memory-service-registry.ts +0 -150
- package/src/services/memory-service.ts +0 -688
- package/src/services/session-history-importer.ts +0 -629
- package/tests/README.md +0 -23
- package/tests/adapters/claude/claude-semantic-daemon-adapter.test.ts +0 -54
- package/tests/adapters/claude/claude-transcript-reconstructor.test.ts +0 -98
- package/tests/adapters/claude-hook-prompt-injection-policy.test.ts +0 -99
- package/tests/apps/app-layer-boundary.test.ts +0 -48
- package/tests/apps/claude-settings-hooks.test.ts +0 -107
- package/tests/apps/cli-disclosure-output.test.ts +0 -212
- package/tests/apps/codex-import-runner.test.ts +0 -99
- package/tests/apps/codex-validation-output.test.ts +0 -100
- package/tests/apps/hermes-import-runner.test.ts +0 -99
- package/tests/apps/mcp-install-command.test.ts +0 -59
- package/tests/apps/package-build-entrypoints.test.ts +0 -30
- package/tests/apps/postinstall-embedding-backend.test.ts +0 -175
- package/tests/apps/search-api-disclosure.test.ts +0 -162
- package/tests/apps/stats-api-lightweight.test.ts +0 -67
- package/tests/apps/ui-disclosure-output.test.ts +0 -140
- package/tests/core/bootstrap-organizer.test.ts +0 -111
- package/tests/core/canonical-key.test.ts +0 -101
- package/tests/core/codex-session-history-importer-validation.test.ts +0 -185
- package/tests/core/consolidation-worker.test.ts +0 -75
- package/tests/core/embedding-maintenance-service.test.ts +0 -282
- package/tests/core/evidence-aligner.test.ts +0 -152
- package/tests/core/external-market-context.test.ts +0 -209
- package/tests/core/fact-deriver.test.ts +0 -79
- package/tests/core/hermes-session-history-importer-validation.test.ts +0 -609
- package/tests/core/ingest-interceptor.test.ts +0 -38
- package/tests/core/markdown-mirror.test.ts +0 -85
- package/tests/core/matcher.test.ts +0 -112
- package/tests/core/md-mirror.test.ts +0 -50
- package/tests/core/memory-engine-services.test.ts +0 -240
- package/tests/core/memory-ingest-service.test.ts +0 -296
- package/tests/core/memory-query-service.test.ts +0 -129
- package/tests/core/memory-runtime-service.test.ts +0 -201
- package/tests/core/memory-service-composition.test.ts +0 -192
- package/tests/core/memory-service-config.test.ts +0 -41
- package/tests/core/memory-service-facade.test.ts +0 -30
- package/tests/core/memory-service-registry.test.ts +0 -206
- package/tests/core/product-validation-matrix.test.ts +0 -61
- package/tests/core/project-registry.test.ts +0 -78
- package/tests/core/replay-evaluator.test.ts +0 -181
- package/tests/core/retrieval-analytics-service.test.ts +0 -210
- package/tests/core/retrieval-benchmark.test.ts +0 -93
- package/tests/core/retrieval-disclosure-service.test.ts +0 -264
- package/tests/core/retrieval-orchestrator.test.ts +0 -403
- package/tests/core/retrieval-quality.test.ts +0 -31
- package/tests/core/retrieval-services.test.ts +0 -185
- package/tests/core/retriever-fallback-chain.test.ts +0 -223
- package/tests/core/retriever-strategy-scope.test.ts +0 -164
- package/tests/core/retriever.memu-adoption.test.ts +0 -122
- package/tests/core/session-history-importer-filter.test.ts +0 -78
- package/tests/core/session-qrels.test.ts +0 -250
- package/tests/core/sqlite-event-store-replication.test.ts +0 -127
- package/tests/core/summary-deriver.test.ts +0 -66
- package/tests/extensions/embedder-warning-suppression.test.ts +0 -83
- package/tests/extensions/endless-memory-extension-boundary.test.ts +0 -17
- package/tests/extensions/endless-memory-services.test.ts +0 -325
- package/tests/extensions/mcp-context-tools.test.ts +0 -905
- package/tests/extensions/mcp-extension-boundary.test.ts +0 -21
- package/tests/extensions/mcp-package-build.test.ts +0 -22
- package/tests/extensions/mcp-project-aware-tools.test.ts +0 -102
- package/tests/extensions/shared-memory-extension-boundary.test.ts +0 -24
- package/tests/extensions/shared-memory-services.test.ts +0 -309
- package/tests/extensions/vector-extension-boundary.test.ts +0 -21
- package/tsconfig.json +0 -24
- package/vitest.config.ts +0 -15
package/src/apps/cli/index.ts
DELETED
|
@@ -1,1735 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* Code Memory CLI
|
|
4
|
-
* Command-line interface for memory operations
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { Command } from 'commander';
|
|
8
|
-
import { exec } from 'child_process';
|
|
9
|
-
import * as fs from 'fs';
|
|
10
|
-
import * as path from 'path';
|
|
11
|
-
import * as os from 'os';
|
|
12
|
-
import {
|
|
13
|
-
getDefaultMemoryService,
|
|
14
|
-
getMemoryServiceForProject,
|
|
15
|
-
getLightweightMemoryServiceForProject
|
|
16
|
-
} from '../../services/memory-service.js';
|
|
17
|
-
import { getProjectStoragePath } from '../../core/registry/project-path.js';
|
|
18
|
-
import { createSessionHistoryImporter, type ProgressEvent } from '../../services/session-history-importer.js';
|
|
19
|
-
import {
|
|
20
|
-
createCodexSessionHistoryImporter,
|
|
21
|
-
validateCodexSessions
|
|
22
|
-
} from '../../services/codex-session-history-importer.js';
|
|
23
|
-
import {
|
|
24
|
-
createHermesSessionHistoryImporter,
|
|
25
|
-
validateHermesSessions
|
|
26
|
-
} from '../../services/hermes-session-history-importer.js';
|
|
27
|
-
import { bootstrapKnowledgeBase } from '../../services/bootstrap-organizer.js';
|
|
28
|
-
import { startServer, stopServer, isServerRunning } from '../server/index.js';
|
|
29
|
-
import { SQLiteEventStore } from '../../core/sqlite-event-store.js';
|
|
30
|
-
import { MongoSyncWorker, type MongoSyncDirection } from '../../core/mongo-sync-worker.js';
|
|
31
|
-
import {
|
|
32
|
-
formatDisclosureExpansion,
|
|
33
|
-
formatDisclosureSearch,
|
|
34
|
-
formatDisclosureSource,
|
|
35
|
-
formatPlainSearchResults
|
|
36
|
-
} from './retrieval-disclosure-output.js';
|
|
37
|
-
import { installMcpServer } from './mcp-install.js';
|
|
38
|
-
import {
|
|
39
|
-
hasHook,
|
|
40
|
-
mergePluginHooksIntoSettings,
|
|
41
|
-
removePluginHooksFromSettings,
|
|
42
|
-
REQUIRED_HOOK_FILES,
|
|
43
|
-
type ClaudeSettingsWithHooks
|
|
44
|
-
} from './claude-settings-hooks.js';
|
|
45
|
-
import {
|
|
46
|
-
formatCodexValidationReport,
|
|
47
|
-
writeCodexValidationReport,
|
|
48
|
-
type CodexValidationReportFormat
|
|
49
|
-
} from './codex-validation-output.js';
|
|
50
|
-
import {
|
|
51
|
-
formatHermesValidationReport,
|
|
52
|
-
writeHermesValidationReport,
|
|
53
|
-
type HermesValidationReportFormat
|
|
54
|
-
} from './hermes-validation-output.js';
|
|
55
|
-
import { runCodexImportOnce } from './codex-import-runner.js';
|
|
56
|
-
import { runHermesImportOnce } from './hermes-import-runner.js';
|
|
57
|
-
import {
|
|
58
|
-
fetchExternalMarketContext,
|
|
59
|
-
renderExternalMarketContextReport,
|
|
60
|
-
type ExternalMarketProvider
|
|
61
|
-
} from '../../core/external-market-context.js';
|
|
62
|
-
import {
|
|
63
|
-
DEFAULT_EMBEDDING_FALLBACK_MODEL,
|
|
64
|
-
DEFAULT_EMBEDDING_MODEL
|
|
65
|
-
} from '../../extensions/vector/embedder.js';
|
|
66
|
-
|
|
67
|
-
// ============================================================
|
|
68
|
-
// Hook Installation Utilities
|
|
69
|
-
// ============================================================
|
|
70
|
-
|
|
71
|
-
const CLAUDE_SETTINGS_PATH = path.join(os.homedir(), '.claude', 'settings.json');
|
|
72
|
-
|
|
73
|
-
type ClaudeSettings = ClaudeSettingsWithHooks;
|
|
74
|
-
|
|
75
|
-
function getPluginPath(): string {
|
|
76
|
-
// Try to find the dist directory
|
|
77
|
-
const possiblePaths = [
|
|
78
|
-
path.join(__dirname, '..'), // When running from dist/cli
|
|
79
|
-
path.join(__dirname, '../..', 'dist'), // When running from src
|
|
80
|
-
path.join(process.cwd(), 'dist'), // Current working directory
|
|
81
|
-
];
|
|
82
|
-
|
|
83
|
-
for (const p of possiblePaths) {
|
|
84
|
-
const hooksPath = path.join(p, 'hooks', 'user-prompt-submit.js');
|
|
85
|
-
if (fs.existsSync(hooksPath)) {
|
|
86
|
-
return p;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// Fallback to npm global installation path
|
|
91
|
-
return path.join(os.homedir(), '.npm-global', 'lib', 'node_modules', 'claude-memory-layer', 'dist');
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function loadClaudeSettings(): ClaudeSettings {
|
|
95
|
-
try {
|
|
96
|
-
if (fs.existsSync(CLAUDE_SETTINGS_PATH)) {
|
|
97
|
-
const content = fs.readFileSync(CLAUDE_SETTINGS_PATH, 'utf-8');
|
|
98
|
-
return JSON.parse(content);
|
|
99
|
-
}
|
|
100
|
-
} catch (error) {
|
|
101
|
-
console.error('Warning: Could not read existing settings:', error);
|
|
102
|
-
}
|
|
103
|
-
return {};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function saveClaudeSettings(settings: ClaudeSettings): void {
|
|
107
|
-
const dir = path.dirname(CLAUDE_SETTINGS_PATH);
|
|
108
|
-
if (!fs.existsSync(dir)) {
|
|
109
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// Atomic write
|
|
113
|
-
const tempPath = CLAUDE_SETTINGS_PATH + '.tmp';
|
|
114
|
-
fs.writeFileSync(tempPath, JSON.stringify(settings, null, 2));
|
|
115
|
-
fs.renameSync(tempPath, CLAUDE_SETTINGS_PATH);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
type CodexValidateCommandOptions = {
|
|
119
|
-
project?: string;
|
|
120
|
-
sessionsDir?: string;
|
|
121
|
-
limit?: string;
|
|
122
|
-
format?: string;
|
|
123
|
-
output?: string;
|
|
124
|
-
dryRun?: boolean;
|
|
125
|
-
anonymizeProjects?: boolean;
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
type HermesValidateCommandOptions = {
|
|
129
|
-
project?: string;
|
|
130
|
-
stateDb?: string;
|
|
131
|
-
limit?: string;
|
|
132
|
-
format?: string;
|
|
133
|
-
output?: string;
|
|
134
|
-
dryRun?: boolean;
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
type MarketContextCommandOptions = {
|
|
138
|
-
company?: string;
|
|
139
|
-
dartCorpCode?: string;
|
|
140
|
-
symbol?: string;
|
|
141
|
-
providers?: string;
|
|
142
|
-
fredSeries?: string;
|
|
143
|
-
json?: boolean;
|
|
144
|
-
snapshot?: boolean;
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
function parseCommaList(value: string | undefined): string[] | undefined {
|
|
148
|
-
if (!value) return undefined;
|
|
149
|
-
const selected = value.split(',').map((item) => item.trim()).filter(Boolean);
|
|
150
|
-
return selected.length > 0 ? Array.from(new Set(selected)) : undefined;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function parseMarketProviders(value: string | undefined): ExternalMarketProvider[] | undefined {
|
|
154
|
-
const entries = parseCommaList(value);
|
|
155
|
-
if (!entries) return undefined;
|
|
156
|
-
const allowed = new Set<ExternalMarketProvider>(['dart', 'fred', 'finnhub']);
|
|
157
|
-
const selected: ExternalMarketProvider[] = [];
|
|
158
|
-
for (const entry of entries) {
|
|
159
|
-
const normalized = entry.toLowerCase() as ExternalMarketProvider;
|
|
160
|
-
if (!allowed.has(normalized)) throw new Error('Invalid --providers: expected comma-separated dart,fred,finnhub');
|
|
161
|
-
if (!selected.includes(normalized)) selected.push(normalized);
|
|
162
|
-
}
|
|
163
|
-
return selected;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function parsePositiveIntegerOption(value: string | undefined, optionName: string): number | undefined {
|
|
167
|
-
if (value === undefined) return undefined;
|
|
168
|
-
const normalized = value.trim();
|
|
169
|
-
if (!/^\d+$/.test(normalized)) {
|
|
170
|
-
throw new Error(`Invalid --${optionName}: expected a positive integer`);
|
|
171
|
-
}
|
|
172
|
-
const parsed = Number.parseInt(normalized, 10);
|
|
173
|
-
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
174
|
-
throw new Error(`Invalid --${optionName}: expected a positive integer`);
|
|
175
|
-
}
|
|
176
|
-
return parsed;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function parseCodexValidationReportFormat(value: string | undefined): CodexValidationReportFormat {
|
|
180
|
-
const normalized = (value ?? 'markdown').toLowerCase();
|
|
181
|
-
if (normalized !== 'json' && normalized !== 'markdown') {
|
|
182
|
-
throw new Error('Invalid --format: expected json or markdown');
|
|
183
|
-
}
|
|
184
|
-
return normalized;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function parseHermesValidationReportFormat(value: string | undefined): HermesValidationReportFormat {
|
|
188
|
-
const normalized = (value ?? 'markdown').toLowerCase();
|
|
189
|
-
if (normalized !== 'json' && normalized !== 'markdown') {
|
|
190
|
-
throw new Error('Invalid --format: expected json or markdown');
|
|
191
|
-
}
|
|
192
|
-
return normalized;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async function runCodexValidationCommand(options: CodexValidateCommandOptions): Promise<void> {
|
|
196
|
-
if (options.dryRun === false) {
|
|
197
|
-
throw new Error('Codex validation is read-only; use explicit import commands for mutation');
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
const format = parseCodexValidationReportFormat(options.format);
|
|
201
|
-
const report = await validateCodexSessions({
|
|
202
|
-
sessionsDir: options.sessionsDir,
|
|
203
|
-
projectPath: options.project,
|
|
204
|
-
limit: parsePositiveIntegerOption(options.limit, 'limit'),
|
|
205
|
-
anonymizeProjects: options.anonymizeProjects === true
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
const rendered = formatCodexValidationReport(report, format);
|
|
209
|
-
process.stdout.write(rendered.endsWith('\n') ? rendered : `${rendered}\n`);
|
|
210
|
-
|
|
211
|
-
if (options.output) {
|
|
212
|
-
const outputPath = path.resolve(options.output);
|
|
213
|
-
writeCodexValidationReport(outputPath, report, format);
|
|
214
|
-
console.log(`\nReport written to ${outputPath}`);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
async function runHermesValidationCommand(options: HermesValidateCommandOptions): Promise<void> {
|
|
219
|
-
if (options.dryRun === false) {
|
|
220
|
-
throw new Error('Hermes validation is read-only; use explicit import commands for mutation');
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const format = parseHermesValidationReportFormat(options.format);
|
|
224
|
-
const report = await validateHermesSessions({
|
|
225
|
-
stateDbPath: options.stateDb,
|
|
226
|
-
projectPath: options.project,
|
|
227
|
-
limit: parsePositiveIntegerOption(options.limit, 'limit')
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
const rendered = formatHermesValidationReport(report, format);
|
|
231
|
-
process.stdout.write(rendered.endsWith('\n') ? rendered : `${rendered}\n`);
|
|
232
|
-
|
|
233
|
-
if (options.output) {
|
|
234
|
-
const outputPath = path.resolve(options.output);
|
|
235
|
-
writeHermesValidationReport(outputPath, report, format);
|
|
236
|
-
console.log(`\nReport written to ${outputPath}`);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
async function runMarketContextCommand(options: MarketContextCommandOptions): Promise<void> {
|
|
241
|
-
const report = await fetchExternalMarketContext({
|
|
242
|
-
company: options.company,
|
|
243
|
-
dartCorpCode: options.dartCorpCode,
|
|
244
|
-
symbol: options.symbol,
|
|
245
|
-
providers: parseMarketProviders(options.providers),
|
|
246
|
-
fredSeries: parseCommaList(options.fredSeries),
|
|
247
|
-
includeSnapshot: options.snapshot !== false
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
if (options.json) {
|
|
251
|
-
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
252
|
-
} else {
|
|
253
|
-
process.stdout.write(`${renderExternalMarketContextReport(report)}\n`);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
const program = new Command();
|
|
258
|
-
|
|
259
|
-
program
|
|
260
|
-
.name('claude-memory-layer')
|
|
261
|
-
.description('Claude Code Memory Plugin CLI')
|
|
262
|
-
.version(process.env.CLAUDE_MEMORY_LAYER_VERSION || '0.0.0');
|
|
263
|
-
|
|
264
|
-
program
|
|
265
|
-
.command('market-context')
|
|
266
|
-
.description('Fetch read-only DART/FRED/Finnhub context with structured MarketContextSnapshot bull/bear/risk/catalyst analysis')
|
|
267
|
-
.option('--company <name>', 'Company name for DART fallback search and report subject')
|
|
268
|
-
.option('--dart-corp-code <code>', 'Exact DART corp_code for issuer-specific filings')
|
|
269
|
-
.option('--symbol <ticker>', 'Listed ticker for Finnhub company profile')
|
|
270
|
-
.option('--providers <list>', 'Comma-separated providers: dart,fred,finnhub')
|
|
271
|
-
.option('--fred-series <list>', 'Comma-separated FRED series IDs')
|
|
272
|
-
.option('--json', 'Print structured JSON including analysis.marketSnapshot')
|
|
273
|
-
.option('--no-snapshot', 'Disable MarketContextSnapshot and DART company snapshot analysis')
|
|
274
|
-
.action(async (options: MarketContextCommandOptions) => {
|
|
275
|
-
try {
|
|
276
|
-
await runMarketContextCommand(options);
|
|
277
|
-
} catch (error) {
|
|
278
|
-
console.error(error instanceof Error ? error.message : String(error));
|
|
279
|
-
process.exit(1);
|
|
280
|
-
}
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
// ============================================================
|
|
284
|
-
// Install / Uninstall Commands
|
|
285
|
-
// ============================================================
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* Install command - register hooks with Claude Code
|
|
289
|
-
*/
|
|
290
|
-
program
|
|
291
|
-
.command('install')
|
|
292
|
-
.description('Install hooks into Claude Code settings')
|
|
293
|
-
.option('--path <path>', 'Custom plugin path (defaults to auto-detect)')
|
|
294
|
-
.action(async (options) => {
|
|
295
|
-
try {
|
|
296
|
-
const pluginPath = options.path || getPluginPath();
|
|
297
|
-
|
|
298
|
-
// Verify hooks exist
|
|
299
|
-
const missingHooks = REQUIRED_HOOK_FILES.filter((file) =>
|
|
300
|
-
!fs.existsSync(path.join(pluginPath, 'hooks', file))
|
|
301
|
-
);
|
|
302
|
-
if (missingHooks.length > 0) {
|
|
303
|
-
console.error(`\nā Hook files not found at: ${pluginPath}`);
|
|
304
|
-
console.error(` Missing: ${missingHooks.join(', ')}`);
|
|
305
|
-
console.error(' Make sure you have built the plugin with "npm run build"');
|
|
306
|
-
process.exit(1);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// Load existing settings
|
|
310
|
-
const settings = loadClaudeSettings();
|
|
311
|
-
|
|
312
|
-
// Add hooks while preserving unrelated Claude Code hooks in the same categories.
|
|
313
|
-
const nextSettings = mergePluginHooksIntoSettings(settings, pluginPath);
|
|
314
|
-
|
|
315
|
-
// Save settings
|
|
316
|
-
saveClaudeSettings(nextSettings);
|
|
317
|
-
|
|
318
|
-
console.log('\nā
Claude Memory Layer installed!\n');
|
|
319
|
-
console.log('Hooks registered:');
|
|
320
|
-
console.log(' - SessionStart: Register session -> project mapping');
|
|
321
|
-
console.log(' - UserPromptSubmit: Memory retrieval on user input');
|
|
322
|
-
console.log(' - PostToolUse: Store tool observations');
|
|
323
|
-
console.log(' - Stop: Store assistant responses');
|
|
324
|
-
console.log(' - SessionEnd: Persist session summary\n');
|
|
325
|
-
console.log('Plugin path:', pluginPath);
|
|
326
|
-
console.log('\nā ļø Restart Claude Code for changes to take effect.\n');
|
|
327
|
-
console.log('Commands:');
|
|
328
|
-
console.log(' claude-memory-layer dashboard - Open web dashboard');
|
|
329
|
-
console.log(' claude-memory-layer search - Search memories');
|
|
330
|
-
console.log(' claude-memory-layer stats - View statistics');
|
|
331
|
-
console.log(' claude-memory-layer uninstall - Remove hooks\n');
|
|
332
|
-
} catch (error) {
|
|
333
|
-
console.error('Install failed:', error);
|
|
334
|
-
process.exit(1);
|
|
335
|
-
}
|
|
336
|
-
});
|
|
337
|
-
|
|
338
|
-
/**
|
|
339
|
-
* Uninstall command - remove hooks from Claude Code
|
|
340
|
-
*/
|
|
341
|
-
program
|
|
342
|
-
.command('uninstall')
|
|
343
|
-
.description('Remove hooks from Claude Code settings')
|
|
344
|
-
.action(async () => {
|
|
345
|
-
try {
|
|
346
|
-
// Load existing settings
|
|
347
|
-
const settings = loadClaudeSettings();
|
|
348
|
-
|
|
349
|
-
if (!settings.hooks) {
|
|
350
|
-
console.log('\nš No hooks installed.\n');
|
|
351
|
-
return;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
const nextSettings = removePluginHooksFromSettings(settings, getPluginPath());
|
|
355
|
-
|
|
356
|
-
// Save settings
|
|
357
|
-
saveClaudeSettings(nextSettings);
|
|
358
|
-
|
|
359
|
-
console.log('\nā
Claude Memory Layer uninstalled!\n');
|
|
360
|
-
console.log('Hooks removed from Claude Code settings.');
|
|
361
|
-
console.log('Your memory data is preserved and can be accessed with:');
|
|
362
|
-
console.log(' claude-memory-layer dashboard\n');
|
|
363
|
-
console.log('ā ļø Restart Claude Code for changes to take effect.\n');
|
|
364
|
-
} catch (error) {
|
|
365
|
-
console.error('Uninstall failed:', error);
|
|
366
|
-
process.exit(1);
|
|
367
|
-
}
|
|
368
|
-
});
|
|
369
|
-
|
|
370
|
-
/**
|
|
371
|
-
* Status command - check installation status
|
|
372
|
-
*/
|
|
373
|
-
program
|
|
374
|
-
.command('status')
|
|
375
|
-
.description('Check plugin installation status')
|
|
376
|
-
.action(async () => {
|
|
377
|
-
try {
|
|
378
|
-
const settings = loadClaudeSettings();
|
|
379
|
-
const pluginPath = getPluginPath();
|
|
380
|
-
|
|
381
|
-
console.log('\nš§ Claude Memory Layer Status\n');
|
|
382
|
-
|
|
383
|
-
// Check hooks
|
|
384
|
-
const hasSessionStartHook = hasHook(settings, 'SessionStart', 'session-start');
|
|
385
|
-
const hasUserPromptHook = hasHook(settings, 'UserPromptSubmit', 'user-prompt-submit');
|
|
386
|
-
const hasPostToolHook = hasHook(settings, 'PostToolUse', 'post-tool-use');
|
|
387
|
-
const hasStopHook = hasHook(settings, 'Stop', 'stop');
|
|
388
|
-
const hasSessionEndHook = hasHook(settings, 'SessionEnd', 'session-end');
|
|
389
|
-
|
|
390
|
-
console.log('Hooks:');
|
|
391
|
-
console.log(` SessionStart: ${hasSessionStartHook ? 'ā
Installed' : 'ā Not installed'}`);
|
|
392
|
-
console.log(` UserPromptSubmit: ${hasUserPromptHook ? 'ā
Installed' : 'ā Not installed'}`);
|
|
393
|
-
console.log(` PostToolUse: ${hasPostToolHook ? 'ā
Installed' : 'ā Not installed'}`);
|
|
394
|
-
console.log(` Stop: ${hasStopHook ? 'ā
Installed' : 'ā Not installed'}`);
|
|
395
|
-
console.log(` SessionEnd: ${hasSessionEndHook ? 'ā
Installed' : 'ā Not installed'}`);
|
|
396
|
-
|
|
397
|
-
// Check plugin files
|
|
398
|
-
const hooksExist = REQUIRED_HOOK_FILES
|
|
399
|
-
.every((file) => fs.existsSync(path.join(pluginPath, 'hooks', file)));
|
|
400
|
-
console.log(`\nPlugin files: ${hooksExist ? 'ā
Found' : 'ā Not found'}`);
|
|
401
|
-
console.log(` Path: ${pluginPath}`);
|
|
402
|
-
|
|
403
|
-
// Check dashboard
|
|
404
|
-
const dashboardRunning = await isServerRunning(37777);
|
|
405
|
-
console.log(`\nDashboard: ${dashboardRunning ? 'ā
Running at http://localhost:37777' : 'ā¹ļø Not running'}`);
|
|
406
|
-
|
|
407
|
-
if (!hasSessionStartHook || !hasUserPromptHook || !hasPostToolHook || !hasStopHook || !hasSessionEndHook) {
|
|
408
|
-
console.log('\nš” Run "claude-memory-layer install" to set up hooks.\n');
|
|
409
|
-
} else {
|
|
410
|
-
console.log('\nā
Plugin is fully installed and configured.\n');
|
|
411
|
-
}
|
|
412
|
-
} catch (error) {
|
|
413
|
-
console.error('Status check failed:', error);
|
|
414
|
-
process.exit(1);
|
|
415
|
-
}
|
|
416
|
-
});
|
|
417
|
-
|
|
418
|
-
/**
|
|
419
|
-
* Search command
|
|
420
|
-
*/
|
|
421
|
-
program
|
|
422
|
-
.command('search <query>')
|
|
423
|
-
.description('Search memories using semantic search')
|
|
424
|
-
.option('-k, --top-k <number>', 'Number of results', '5')
|
|
425
|
-
.option('-s, --min-score <number>', 'Minimum similarity score', '0.7')
|
|
426
|
-
.option('--session <id>', 'Filter by session ID')
|
|
427
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
428
|
-
.option('--disclosure', 'Use progressive search -> expand -> source output')
|
|
429
|
-
.option('--include-shared', 'Include shared cross-project memory results')
|
|
430
|
-
.option('--strategy <mode>', 'Retrieval strategy: auto, fast, or deep', 'auto')
|
|
431
|
-
.action(async (query: string, options) => {
|
|
432
|
-
const projectPath = options.project || process.cwd();
|
|
433
|
-
const useLightweightRead = options.strategy === 'fast' && options.includeShared !== true;
|
|
434
|
-
const service = useLightweightRead
|
|
435
|
-
? getLightweightMemoryServiceForProject(projectPath)
|
|
436
|
-
: getMemoryServiceForProject(projectPath);
|
|
437
|
-
|
|
438
|
-
try {
|
|
439
|
-
if (options.disclosure) {
|
|
440
|
-
const result = await service.searchDisclosure(query, {
|
|
441
|
-
topK: parseInt(options.topK),
|
|
442
|
-
minScore: parseFloat(options.minScore),
|
|
443
|
-
sessionId: options.session,
|
|
444
|
-
includeShared: options.includeShared === true,
|
|
445
|
-
strategy: options.strategy
|
|
446
|
-
});
|
|
447
|
-
|
|
448
|
-
console.log(formatDisclosureSearch(result));
|
|
449
|
-
return;
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
const result = await service.retrieveMemories(query, {
|
|
453
|
-
topK: parseInt(options.topK),
|
|
454
|
-
minScore: parseFloat(options.minScore),
|
|
455
|
-
sessionId: options.session,
|
|
456
|
-
includeShared: options.includeShared === true,
|
|
457
|
-
strategy: options.strategy
|
|
458
|
-
});
|
|
459
|
-
|
|
460
|
-
console.log(formatPlainSearchResults(result));
|
|
461
|
-
} catch (error) {
|
|
462
|
-
console.error('Search failed:', error);
|
|
463
|
-
process.exitCode = 1;
|
|
464
|
-
} finally {
|
|
465
|
-
await service.shutdown();
|
|
466
|
-
}
|
|
467
|
-
});
|
|
468
|
-
|
|
469
|
-
/**
|
|
470
|
-
* Expand command - progressive retrieval layer 2
|
|
471
|
-
*/
|
|
472
|
-
program
|
|
473
|
-
.command('expand <resultId>')
|
|
474
|
-
.description('Expand a progressive retrieval result with surrounding context')
|
|
475
|
-
.option('-w, --window-size <number>', 'Number of surrounding events on each side', '3')
|
|
476
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
477
|
-
.action(async (resultId: string, options) => {
|
|
478
|
-
const projectPath = options.project || process.cwd();
|
|
479
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
480
|
-
|
|
481
|
-
try {
|
|
482
|
-
const expansion = await service.expandDisclosure(resultId, {
|
|
483
|
-
windowSize: parseInt(options.windowSize)
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
if (!expansion) {
|
|
487
|
-
console.error(`Expansion target not found: ${resultId}`);
|
|
488
|
-
process.exitCode = 1;
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
console.log(formatDisclosureExpansion(expansion));
|
|
493
|
-
} catch (error) {
|
|
494
|
-
console.error('Expand failed:', error);
|
|
495
|
-
process.exitCode = 1;
|
|
496
|
-
} finally {
|
|
497
|
-
await service.shutdown();
|
|
498
|
-
}
|
|
499
|
-
});
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Source command - progressive retrieval layer 3
|
|
503
|
-
*/
|
|
504
|
-
program
|
|
505
|
-
.command('source <resultId>')
|
|
506
|
-
.description('Show raw source details for a progressive retrieval result')
|
|
507
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
508
|
-
.action(async (resultId: string, options) => {
|
|
509
|
-
const projectPath = options.project || process.cwd();
|
|
510
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
511
|
-
|
|
512
|
-
try {
|
|
513
|
-
const source = await service.sourceDisclosure(resultId);
|
|
514
|
-
|
|
515
|
-
if (!source) {
|
|
516
|
-
console.error(`Source not found: ${resultId}`);
|
|
517
|
-
process.exitCode = 1;
|
|
518
|
-
return;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
console.log(formatDisclosureSource(source));
|
|
522
|
-
} catch (error) {
|
|
523
|
-
console.error('Source failed:', error);
|
|
524
|
-
process.exitCode = 1;
|
|
525
|
-
} finally {
|
|
526
|
-
await service.shutdown();
|
|
527
|
-
}
|
|
528
|
-
});
|
|
529
|
-
|
|
530
|
-
/**
|
|
531
|
-
* History command
|
|
532
|
-
*/
|
|
533
|
-
program
|
|
534
|
-
.command('history')
|
|
535
|
-
.description('View conversation history')
|
|
536
|
-
.option('-l, --limit <number>', 'Number of events', '20')
|
|
537
|
-
.option('--session <id>', 'Filter by session ID')
|
|
538
|
-
.option('--type <type>', 'Filter by event type')
|
|
539
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
540
|
-
.action(async (options) => {
|
|
541
|
-
const projectPath = options.project || process.cwd();
|
|
542
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
543
|
-
|
|
544
|
-
try {
|
|
545
|
-
let events;
|
|
546
|
-
|
|
547
|
-
if (options.session) {
|
|
548
|
-
events = await service.getSessionHistory(options.session);
|
|
549
|
-
} else {
|
|
550
|
-
events = await service.getRecentEvents(parseInt(options.limit));
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
if (options.type) {
|
|
554
|
-
events = events.filter(e => e.eventType === options.type);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
console.log('\nš Memory History\n');
|
|
558
|
-
console.log(`Total events: ${events.length}\n`);
|
|
559
|
-
|
|
560
|
-
for (const event of events.slice(0, parseInt(options.limit))) {
|
|
561
|
-
const date = event.timestamp.toISOString();
|
|
562
|
-
const icon = event.eventType === 'user_prompt' ? 'š¤' :
|
|
563
|
-
event.eventType === 'agent_response' ? 'š¤' : 'š';
|
|
564
|
-
|
|
565
|
-
console.log(`${icon} [${date}] ${event.eventType}`);
|
|
566
|
-
console.log(` Session: ${event.sessionId.slice(0, 8)}...`);
|
|
567
|
-
console.log(` ${event.content.slice(0, 150)}${event.content.length > 150 ? '...' : ''}`);
|
|
568
|
-
console.log('');
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
await service.shutdown();
|
|
572
|
-
} catch (error) {
|
|
573
|
-
console.error('History failed:', error);
|
|
574
|
-
process.exit(1);
|
|
575
|
-
}
|
|
576
|
-
});
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* Stats command
|
|
580
|
-
*/
|
|
581
|
-
program
|
|
582
|
-
.command('stats')
|
|
583
|
-
.description('View memory statistics')
|
|
584
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
585
|
-
.action(async (options) => {
|
|
586
|
-
const projectPath = options.project || process.cwd();
|
|
587
|
-
const service = getLightweightMemoryServiceForProject(projectPath);
|
|
588
|
-
|
|
589
|
-
try {
|
|
590
|
-
const stats = await service.getStats();
|
|
591
|
-
|
|
592
|
-
console.log('\nš Memory Statistics\n');
|
|
593
|
-
console.log(`Total Events: ${stats.totalEvents}`);
|
|
594
|
-
console.log(`Vector Count: ${stats.vectorCount}`);
|
|
595
|
-
console.log('\nMemory Levels:');
|
|
596
|
-
|
|
597
|
-
for (const level of stats.levelStats) {
|
|
598
|
-
const bar = 'ā'.repeat(Math.min(20, Math.ceil(level.count / 10)));
|
|
599
|
-
console.log(` ${level.level}: ${bar} ${level.count}`);
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
await service.shutdown();
|
|
603
|
-
} catch (error) {
|
|
604
|
-
console.error('Stats failed:', error);
|
|
605
|
-
process.exit(1);
|
|
606
|
-
}
|
|
607
|
-
});
|
|
608
|
-
|
|
609
|
-
/**
|
|
610
|
-
* Forget command
|
|
611
|
-
*/
|
|
612
|
-
program
|
|
613
|
-
.command('forget [eventId]')
|
|
614
|
-
.description('Remove memories from storage')
|
|
615
|
-
.option('--session <id>', 'Forget all events from a session')
|
|
616
|
-
.option('--before <date>', 'Forget events before date (YYYY-MM-DD)')
|
|
617
|
-
.option('--confirm', 'Skip confirmation')
|
|
618
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
619
|
-
.action(async (eventId: string | undefined, options) => {
|
|
620
|
-
const projectPath = options.project || process.cwd();
|
|
621
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
622
|
-
|
|
623
|
-
try {
|
|
624
|
-
if (!eventId && !options.session && !options.before) {
|
|
625
|
-
console.error('Please specify an event ID, --session, or --before option');
|
|
626
|
-
process.exit(1);
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
if (!options.confirm) {
|
|
630
|
-
console.log('ā ļø This will remove memories from storage.');
|
|
631
|
-
console.log('Add --confirm to proceed.');
|
|
632
|
-
process.exit(0);
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
// Note: Full forget implementation would require additional EventStore methods
|
|
636
|
-
console.log('šļø Forget functionality requires additional implementation.');
|
|
637
|
-
console.log('Events are append-only; soft-delete markers would be added.');
|
|
638
|
-
|
|
639
|
-
await service.shutdown();
|
|
640
|
-
} catch (error) {
|
|
641
|
-
console.error('Forget failed:', error);
|
|
642
|
-
process.exit(1);
|
|
643
|
-
}
|
|
644
|
-
});
|
|
645
|
-
|
|
646
|
-
/**
|
|
647
|
-
* Process command - manually process pending embeddings
|
|
648
|
-
*/
|
|
649
|
-
program
|
|
650
|
-
.command('process')
|
|
651
|
-
.description('Process pending embeddings')
|
|
652
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
653
|
-
.action(async (options) => {
|
|
654
|
-
const projectPath = options.project || process.cwd();
|
|
655
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
656
|
-
|
|
657
|
-
try {
|
|
658
|
-
await service.initialize();
|
|
659
|
-
console.log('ā³ Processing pending embeddings...');
|
|
660
|
-
const count = await service.processPendingEmbeddings();
|
|
661
|
-
console.log(`ā
Processed ${count} embeddings`);
|
|
662
|
-
|
|
663
|
-
await service.shutdown();
|
|
664
|
-
} catch (error) {
|
|
665
|
-
console.error('Process failed:', error);
|
|
666
|
-
process.exit(1);
|
|
667
|
-
}
|
|
668
|
-
});
|
|
669
|
-
|
|
670
|
-
/**
|
|
671
|
-
* Mongo Sync command - sync local SQLite events with a shared MongoDB database (optional)
|
|
672
|
-
*/
|
|
673
|
-
program
|
|
674
|
-
.command('mongo-sync')
|
|
675
|
-
.description('Sync events with MongoDB for multi-server collaboration (optional)')
|
|
676
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
677
|
-
.option('--mongo-uri <uri>', 'MongoDB connection URI (env: CLAUDE_MEMORY_MONGO_URI)')
|
|
678
|
-
.option('--mongo-db <name>', 'MongoDB database name (env: CLAUDE_MEMORY_MONGO_DB)')
|
|
679
|
-
.option('--mongo-project <key>', 'Remote project key (env: CLAUDE_MEMORY_MONGO_PROJECT, default: basename(projectPath))')
|
|
680
|
-
.option('--direction <dir>', 'push|pull|both', 'both')
|
|
681
|
-
.option('--batch-size <n>', 'Batch size', '500')
|
|
682
|
-
.option('--interval <ms>', 'Watch interval ms', '30000')
|
|
683
|
-
.option('--watch', 'Run continuously')
|
|
684
|
-
.action(async (options) => {
|
|
685
|
-
const projectPath = options.project || process.cwd();
|
|
686
|
-
const mongoUri = options.mongoUri || process.env.CLAUDE_MEMORY_MONGO_URI;
|
|
687
|
-
const mongoDb = options.mongoDb || process.env.CLAUDE_MEMORY_MONGO_DB;
|
|
688
|
-
const projectKey = options.mongoProject || process.env.CLAUDE_MEMORY_MONGO_PROJECT || path.basename(projectPath);
|
|
689
|
-
const direction = String(options.direction || 'both').toLowerCase() as MongoSyncDirection;
|
|
690
|
-
|
|
691
|
-
if (!mongoUri || !mongoDb) {
|
|
692
|
-
console.error('\nā MongoDB sync is not configured.');
|
|
693
|
-
console.error(' Set --mongo-uri/--mongo-db or env CLAUDE_MEMORY_MONGO_URI/CLAUDE_MEMORY_MONGO_DB.\n');
|
|
694
|
-
process.exit(1);
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
if (!['push', 'pull', 'both'].includes(direction)) {
|
|
698
|
-
console.error('\nā Invalid --direction. Use: push | pull | both\n');
|
|
699
|
-
process.exit(1);
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
const storagePath = getProjectStoragePath(projectPath);
|
|
703
|
-
if (!fs.existsSync(storagePath)) {
|
|
704
|
-
fs.mkdirSync(storagePath, { recursive: true });
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
const batchSizeParsed = parseInt(options.batchSize, 10);
|
|
708
|
-
const intervalParsed = parseInt(options.interval, 10);
|
|
709
|
-
const batchSize = (Number.isFinite(batchSizeParsed) && batchSizeParsed > 0) ? batchSizeParsed : 500;
|
|
710
|
-
const intervalMs = (Number.isFinite(intervalParsed) && intervalParsed > 0) ? intervalParsed : 30000;
|
|
711
|
-
|
|
712
|
-
const sqliteStore = new SQLiteEventStore(path.join(storagePath, 'events.sqlite'));
|
|
713
|
-
const worker = new MongoSyncWorker(sqliteStore, {
|
|
714
|
-
uri: mongoUri,
|
|
715
|
-
dbName: mongoDb,
|
|
716
|
-
projectKey,
|
|
717
|
-
direction,
|
|
718
|
-
batchSize,
|
|
719
|
-
intervalMs
|
|
720
|
-
});
|
|
721
|
-
|
|
722
|
-
const runOnce = async () => {
|
|
723
|
-
const { pushed, pulled } = await worker.syncNow();
|
|
724
|
-
const ts = new Date().toISOString();
|
|
725
|
-
process.stdout.write(`[mongo-sync] ${ts} project=${projectKey} pushed=${pushed} pulled=${pulled}\n`);
|
|
726
|
-
};
|
|
727
|
-
|
|
728
|
-
try {
|
|
729
|
-
if (!options.watch) {
|
|
730
|
-
await runOnce();
|
|
731
|
-
await worker.shutdown();
|
|
732
|
-
sqliteStore.close();
|
|
733
|
-
return;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
console.log(`[mongo-sync] Watch mode started (interval=${intervalMs}ms, project=${projectKey})`);
|
|
737
|
-
|
|
738
|
-
const handle = setInterval(() => {
|
|
739
|
-
runOnce().catch((err) => {
|
|
740
|
-
console.error('[mongo-sync] Sync failed:', err);
|
|
741
|
-
});
|
|
742
|
-
}, intervalMs);
|
|
743
|
-
|
|
744
|
-
const shutdown = async () => {
|
|
745
|
-
clearInterval(handle);
|
|
746
|
-
console.log('\n[mongo-sync] Shutting down...');
|
|
747
|
-
try {
|
|
748
|
-
await worker.shutdown();
|
|
749
|
-
} finally {
|
|
750
|
-
sqliteStore.close();
|
|
751
|
-
}
|
|
752
|
-
process.exit(0);
|
|
753
|
-
};
|
|
754
|
-
|
|
755
|
-
process.on('SIGINT', () => { void shutdown(); });
|
|
756
|
-
process.on('SIGTERM', () => { void shutdown(); });
|
|
757
|
-
|
|
758
|
-
// Run immediately, then keep alive
|
|
759
|
-
await runOnce();
|
|
760
|
-
await new Promise(() => {});
|
|
761
|
-
} catch (error) {
|
|
762
|
-
console.error('[mongo-sync] Failed:', error);
|
|
763
|
-
process.exit(1);
|
|
764
|
-
}
|
|
765
|
-
});
|
|
766
|
-
|
|
767
|
-
/**
|
|
768
|
-
* Render import progress to terminal
|
|
769
|
-
*/
|
|
770
|
-
function renderProgress(event: ProgressEvent): void {
|
|
771
|
-
switch (event.phase) {
|
|
772
|
-
case 'scan':
|
|
773
|
-
console.log(` š ${event.message}`);
|
|
774
|
-
break;
|
|
775
|
-
case 'session-start': {
|
|
776
|
-
const pct = Math.round(((event.sessionIndex) / event.totalSessions) * 100);
|
|
777
|
-
const sessionName = path.basename(event.filePath, '.jsonl').slice(0, 8);
|
|
778
|
-
process.stdout.write(
|
|
779
|
-
`\r š [${event.sessionIndex + 1}/${event.totalSessions}] ${pct}% | Session ${sessionName}... `
|
|
780
|
-
);
|
|
781
|
-
break;
|
|
782
|
-
}
|
|
783
|
-
case 'session-progress': {
|
|
784
|
-
process.stdout.write(
|
|
785
|
-
`\r š [${event.sessionIndex + 1}/...] ${event.messagesProcessed} msgs | +${event.imported} imported, ~${event.skipped} skipped `
|
|
786
|
-
);
|
|
787
|
-
break;
|
|
788
|
-
}
|
|
789
|
-
case 'session-done': {
|
|
790
|
-
const imported = event.importedPrompts + event.importedResponses;
|
|
791
|
-
if (imported > 0) {
|
|
792
|
-
process.stdout.write(
|
|
793
|
-
`\r ā
[${event.sessionIndex + 1}] +${event.importedPrompts} prompts, +${event.importedResponses} responses${event.skipped > 0 ? `, ~${event.skipped} skipped` : ''} \n`
|
|
794
|
-
);
|
|
795
|
-
} else if (event.skipped > 0) {
|
|
796
|
-
process.stdout.write(
|
|
797
|
-
`\r āļø [${event.sessionIndex + 1}] All ${event.skipped} already imported \n`
|
|
798
|
-
);
|
|
799
|
-
} else {
|
|
800
|
-
process.stdout.write(
|
|
801
|
-
`\r āļø [${event.sessionIndex + 1}] Empty session \n`
|
|
802
|
-
);
|
|
803
|
-
}
|
|
804
|
-
break;
|
|
805
|
-
}
|
|
806
|
-
case 'embedding':
|
|
807
|
-
process.stdout.write(
|
|
808
|
-
`\r š§ Embeddings: ${event.processed}/${event.total} processed `
|
|
809
|
-
);
|
|
810
|
-
if (event.processed >= event.total) {
|
|
811
|
-
process.stdout.write('\n');
|
|
812
|
-
}
|
|
813
|
-
break;
|
|
814
|
-
case 'done':
|
|
815
|
-
break;
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
function printImportSummary(result: import('../../services/session-history-importer.js').ImportResult, embedCount: number): void {
|
|
820
|
-
console.log('\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā');
|
|
821
|
-
console.log('ā ā
Import Complete ā');
|
|
822
|
-
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤');
|
|
823
|
-
console.log(`ā Sessions processed: ${String(result.totalSessions).padStart(8)} ā`);
|
|
824
|
-
console.log(`ā Total messages: ${String(result.totalMessages).padStart(8)} ā`);
|
|
825
|
-
console.log(`ā Imported prompts: ${String(result.importedPrompts).padStart(8)} ā`);
|
|
826
|
-
console.log(`ā Imported responses: ${String(result.importedResponses).padStart(8)} ā`);
|
|
827
|
-
console.log(`ā Skipped duplicates: ${String(result.skippedDuplicates).padStart(8)} ā`);
|
|
828
|
-
console.log(`ā Embeddings queued: ${String(embedCount).padStart(8)} ā`);
|
|
829
|
-
console.log('āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā');
|
|
830
|
-
|
|
831
|
-
if (result.errors.length > 0) {
|
|
832
|
-
console.log(`\nā ļø Errors (${result.errors.length}):`);
|
|
833
|
-
for (const error of result.errors.slice(0, 5)) {
|
|
834
|
-
console.log(` - ${error}`);
|
|
835
|
-
}
|
|
836
|
-
if (result.errors.length > 5) {
|
|
837
|
-
console.log(` ... and ${result.errors.length - 5} more`);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
function sanitizeSegment(input: string | undefined, fallback: string): string {
|
|
843
|
-
const v = (input || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
844
|
-
return v || fallback;
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
async function listMarkdownFiles(root: string): Promise<string[]> {
|
|
848
|
-
const out: string[] = [];
|
|
849
|
-
const stack = [root];
|
|
850
|
-
|
|
851
|
-
while (stack.length > 0) {
|
|
852
|
-
const dir = stack.pop()!;
|
|
853
|
-
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
854
|
-
for (const e of entries) {
|
|
855
|
-
const full = path.join(dir, e.name);
|
|
856
|
-
if (e.isDirectory()) stack.push(full);
|
|
857
|
-
else if (e.isFile() && e.name.endsWith('.md') && e.name !== '_index.md') out.push(full);
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
return out.sort();
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
function deriveNamespaceCategory(sourceRoot: string, filePath: string): { namespace: string; categoryPath: string[] } {
|
|
865
|
-
const rel = path.relative(sourceRoot, filePath);
|
|
866
|
-
const dirSeg = path.dirname(rel).split(path.sep).filter(Boolean);
|
|
867
|
-
|
|
868
|
-
if (dirSeg.length >= 2) {
|
|
869
|
-
const namespace = sanitizeSegment(dirSeg[0], 'default');
|
|
870
|
-
const categoryPath = dirSeg.slice(1).map((s) => sanitizeSegment(s, 'uncategorized'));
|
|
871
|
-
return { namespace, categoryPath: categoryPath.length > 0 ? categoryPath : ['uncategorized'] };
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
return { namespace: 'default', categoryPath: ['uncategorized'] };
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
function extractImportEvidence(markdown: string): { confidence?: string; sources: string[] } {
|
|
878
|
-
const confidenceMatch = markdown.match(/^-\s*confidence:\s*([^\n]+)/m);
|
|
879
|
-
const sources = markdown
|
|
880
|
-
.split(/\r?\n/)
|
|
881
|
-
.map((line) => line.trim())
|
|
882
|
-
.filter((line) => line.startsWith('- source:'))
|
|
883
|
-
.map((line) => line.replace(/^-\s*source:\s*/i, '').trim())
|
|
884
|
-
.filter(Boolean)
|
|
885
|
-
.slice(0, 30);
|
|
886
|
-
|
|
887
|
-
return {
|
|
888
|
-
confidence: confidenceMatch ? confidenceMatch[1].trim() : undefined,
|
|
889
|
-
sources
|
|
890
|
-
};
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
/**
|
|
894
|
-
* Organize-import command - import legacy markdown memories into structured mirror
|
|
895
|
-
*/
|
|
896
|
-
program
|
|
897
|
-
.command('organize-import [sourceDir]')
|
|
898
|
-
.description('Import existing markdown memory files, or bootstrap knowledge docs from codebase/git when markdown is missing')
|
|
899
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
900
|
-
.option('--session <id>', 'Session id for imported events (default: import:organized)')
|
|
901
|
-
.option('--limit <n>', 'Limit number of files to import')
|
|
902
|
-
.option('--dry-run', 'Preview mapping without writing')
|
|
903
|
-
.option('--bootstrap', 'Force-generate structured markdown from codebase + git history before import')
|
|
904
|
-
.option('--bootstrap-if-empty', 'Auto-bootstrap when source has no markdown files (default: true)', true)
|
|
905
|
-
.option('--no-bootstrap-if-empty', 'Disable auto-bootstrap when source has no markdown files')
|
|
906
|
-
.option('--force-bootstrap', 'Run bootstrap even when markdown files exist')
|
|
907
|
-
.option('--repo <path>', 'Repository root for bootstrap analysis (default: project path)')
|
|
908
|
-
.option('--out <path>', 'Output directory for generated bootstrap markdown (default: <sourceDir>/bootstrap-kb)')
|
|
909
|
-
.option('--since <range>', 'Git history range for bootstrap (default: "180 days ago")')
|
|
910
|
-
.option('--max-commits <n>', 'Max commits to analyze for bootstrap (default: 1000)')
|
|
911
|
-
.option('--incremental', 'Use previous bootstrap manifest as baseline for incremental updates (default: true)', true)
|
|
912
|
-
.option('--no-incremental', 'Disable incremental bootstrap; regenerate full snapshot')
|
|
913
|
-
.action(async (sourceDir: string | undefined, options) => {
|
|
914
|
-
const projectPath = options.project || process.cwd();
|
|
915
|
-
const sessionId = options.session || 'import:organized';
|
|
916
|
-
const sourceRoot = path.resolve(sourceDir || options.out || projectPath);
|
|
917
|
-
const repoPath = path.resolve(options.repo || projectPath);
|
|
918
|
-
|
|
919
|
-
if (!fs.existsSync(sourceRoot)) {
|
|
920
|
-
fs.mkdirSync(sourceRoot, { recursive: true });
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
924
|
-
|
|
925
|
-
try {
|
|
926
|
-
let activeSourceRoot = sourceRoot;
|
|
927
|
-
let importRoot = sourceRoot;
|
|
928
|
-
let files = await listMarkdownFiles(importRoot);
|
|
929
|
-
const hasMarkdown = files.length > 0;
|
|
930
|
-
const shouldBootstrap = Boolean(options.forceBootstrap || options.bootstrap || (!hasMarkdown && options.bootstrapIfEmpty));
|
|
931
|
-
|
|
932
|
-
if (shouldBootstrap) {
|
|
933
|
-
const outDir = path.resolve(options.out || path.join(sourceRoot, 'bootstrap-kb'));
|
|
934
|
-
const since = options.since || '180 days ago';
|
|
935
|
-
const maxCommits = options.maxCommits ? Math.max(1, parseInt(options.maxCommits, 10)) : 1000;
|
|
936
|
-
|
|
937
|
-
console.log('\nš§ Bootstrapping markdown knowledge base...');
|
|
938
|
-
const bootstrap = await bootstrapKnowledgeBase({
|
|
939
|
-
repoPath,
|
|
940
|
-
outDir,
|
|
941
|
-
since,
|
|
942
|
-
maxCommits,
|
|
943
|
-
incremental: options.incremental
|
|
944
|
-
});
|
|
945
|
-
console.log(` Repo: ${repoPath}`);
|
|
946
|
-
console.log(` Output: ${bootstrap.outDir}`);
|
|
947
|
-
console.log(` Files analyzed: ${bootstrap.fileCount}`);
|
|
948
|
-
console.log(` Commits analyzed: ${bootstrap.commitCount}`);
|
|
949
|
-
console.log(` Modules: ${bootstrap.moduleCount}`);
|
|
950
|
-
|
|
951
|
-
activeSourceRoot = outDir;
|
|
952
|
-
importRoot = outDir;
|
|
953
|
-
files = await listMarkdownFiles(importRoot);
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
if (files.length === 0) {
|
|
957
|
-
console.error('\nā organize-import found no markdown files to import.\n');
|
|
958
|
-
process.exit(1);
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
const limit = options.limit ? Math.max(1, parseInt(options.limit, 10)) : files.length;
|
|
962
|
-
const targets = files.slice(0, limit);
|
|
963
|
-
|
|
964
|
-
console.log(`\nš¦ organize-import`);
|
|
965
|
-
console.log(` Source: ${activeSourceRoot}`);
|
|
966
|
-
console.log(` Project: ${projectPath}`);
|
|
967
|
-
console.log(` Files: ${targets.length}${targets.length < files.length ? `/${files.length}` : ''}`);
|
|
968
|
-
console.log(` Dry-run: ${options.dryRun ? 'yes' : 'no'}\n`);
|
|
969
|
-
|
|
970
|
-
if (!options.dryRun) {
|
|
971
|
-
await service.initialize();
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
let imported = 0;
|
|
975
|
-
let skipped = 0;
|
|
976
|
-
|
|
977
|
-
for (const file of targets) {
|
|
978
|
-
const text = await fs.promises.readFile(file, 'utf8');
|
|
979
|
-
if (!text.trim()) {
|
|
980
|
-
skipped += 1;
|
|
981
|
-
continue;
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
const { namespace, categoryPath } = deriveNamespaceCategory(activeSourceRoot, file);
|
|
985
|
-
const rel = path.relative(activeSourceRoot, file);
|
|
986
|
-
const evidence = extractImportEvidence(text);
|
|
987
|
-
|
|
988
|
-
if (options.dryRun) {
|
|
989
|
-
console.log(`- ${rel} -> namespace=${namespace} category=${categoryPath.join('/')} confidence=${evidence.confidence || 'n/a'} sources=${evidence.sources.length}`);
|
|
990
|
-
continue;
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
await service.storeSessionSummary(sessionId, text, {
|
|
994
|
-
namespace,
|
|
995
|
-
categoryPath,
|
|
996
|
-
confidence: evidence.confidence,
|
|
997
|
-
sources: evidence.sources,
|
|
998
|
-
import: {
|
|
999
|
-
sourceFile: rel,
|
|
1000
|
-
importedAt: new Date().toISOString(),
|
|
1001
|
-
bootstrap: shouldBootstrap === true
|
|
1002
|
-
}
|
|
1003
|
-
});
|
|
1004
|
-
imported += 1;
|
|
1005
|
-
}
|
|
1006
|
-
|
|
1007
|
-
if (!options.dryRun) {
|
|
1008
|
-
const embed = await service.processPendingEmbeddings();
|
|
1009
|
-
await service.shutdown();
|
|
1010
|
-
console.log(`\nā
Imported: ${imported}, skipped-empty: ${skipped}, embeddings: ${embed}\n`);
|
|
1011
|
-
} else {
|
|
1012
|
-
console.log(`\nā
Dry-run complete (planned imports: ${targets.length - skipped}, skipped-empty: ${skipped})\n`);
|
|
1013
|
-
}
|
|
1014
|
-
} catch (error) {
|
|
1015
|
-
console.error('\nā organize-import failed:', error);
|
|
1016
|
-
process.exit(1);
|
|
1017
|
-
}
|
|
1018
|
-
});
|
|
1019
|
-
|
|
1020
|
-
/**
|
|
1021
|
-
* Import command - import existing Claude Code sessions
|
|
1022
|
-
*/
|
|
1023
|
-
program
|
|
1024
|
-
.command('import')
|
|
1025
|
-
.description('Import existing Claude Code conversation history')
|
|
1026
|
-
.option('-p, --project <path>', 'Import from specific project path')
|
|
1027
|
-
.option('-s, --session <file>', 'Import specific session file (JSONL)')
|
|
1028
|
-
.option('-a, --all', 'Import all sessions from all projects')
|
|
1029
|
-
.option('-l, --limit <number>', 'Limit messages per session')
|
|
1030
|
-
.option('--session-limit <number>', 'Limit recent matching sessions to import')
|
|
1031
|
-
.option('-f, --force', 'Force reimport: delete existing events and reimport with turn_id grouping')
|
|
1032
|
-
.option('--embedding-model <name>', `Embedding model override (default: ${DEFAULT_EMBEDDING_MODEL}, or env CLAUDE_MEMORY_EMBEDDING_MODEL; fallback: ${DEFAULT_EMBEDDING_FALLBACK_MODEL} or env CLAUDE_MEMORY_EMBEDDING_FALLBACK_MODEL)`)
|
|
1033
|
-
.option('-v, --verbose', 'Show detailed progress')
|
|
1034
|
-
.action(async (options) => {
|
|
1035
|
-
const startTime = Date.now();
|
|
1036
|
-
|
|
1037
|
-
// Determine target project path for storage
|
|
1038
|
-
const targetProjectPath = options.project || process.cwd();
|
|
1039
|
-
|
|
1040
|
-
if (options.embeddingModel) {
|
|
1041
|
-
process.env.CLAUDE_MEMORY_EMBEDDING_MODEL = options.embeddingModel;
|
|
1042
|
-
}
|
|
1043
|
-
|
|
1044
|
-
// Use project-specific memory service
|
|
1045
|
-
const service = getMemoryServiceForProject(targetProjectPath);
|
|
1046
|
-
const importer = createSessionHistoryImporter(service);
|
|
1047
|
-
|
|
1048
|
-
const importOpts = {
|
|
1049
|
-
limit: parsePositiveIntegerOption(options.limit, 'limit'),
|
|
1050
|
-
sessionLimit: parsePositiveIntegerOption(options.sessionLimit, 'session-limit'),
|
|
1051
|
-
force: options.force,
|
|
1052
|
-
verbose: options.verbose,
|
|
1053
|
-
onProgress: renderProgress
|
|
1054
|
-
};
|
|
1055
|
-
|
|
1056
|
-
try {
|
|
1057
|
-
console.log('\nā³ Initializing memory service...');
|
|
1058
|
-
await service.initialize();
|
|
1059
|
-
console.log(` ā
Ready (embedder: ${service.getEmbeddingModelName()})\n`);
|
|
1060
|
-
|
|
1061
|
-
const migration = await service.ensureEmbeddingModelForImport({ autoMigrate: true });
|
|
1062
|
-
if (migration.changed) {
|
|
1063
|
-
console.log('š Embedding model migration detected/required');
|
|
1064
|
-
console.log(` Previous: ${migration.previousModel || 'legacy-unknown'}`);
|
|
1065
|
-
console.log(` Current: ${migration.currentModel}`);
|
|
1066
|
-
console.log(` Re-queued embeddings: ${migration.enqueued}`);
|
|
1067
|
-
console.log(' (Import will continue and process embeddings with the new model)\n');
|
|
1068
|
-
}
|
|
1069
|
-
|
|
1070
|
-
if (options.force) {
|
|
1071
|
-
console.log('š Force mode: existing events will be deleted and reimported with turn_id grouping\n');
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
let result;
|
|
1075
|
-
|
|
1076
|
-
if (options.session) {
|
|
1077
|
-
// Import specific session file
|
|
1078
|
-
console.log(`š„ Importing session: ${options.session}`);
|
|
1079
|
-
console.log(` Target: ${targetProjectPath}\n`);
|
|
1080
|
-
result = await importer.importSessionFile(options.session, {
|
|
1081
|
-
...importOpts,
|
|
1082
|
-
projectPath: targetProjectPath,
|
|
1083
|
-
});
|
|
1084
|
-
} else if (options.project) {
|
|
1085
|
-
// Import all sessions from a project
|
|
1086
|
-
console.log(`š„ Importing project: ${options.project}\n`);
|
|
1087
|
-
result = await importer.importProject(options.project, importOpts);
|
|
1088
|
-
} else if (options.all) {
|
|
1089
|
-
// Import all sessions from all projects
|
|
1090
|
-
console.log('š„ Importing all sessions from all projects');
|
|
1091
|
-
console.log(' ā ļø Using global storage (use -p for project-specific)\n');
|
|
1092
|
-
const globalService = getDefaultMemoryService();
|
|
1093
|
-
const globalImporter = createSessionHistoryImporter(globalService);
|
|
1094
|
-
await globalService.initialize();
|
|
1095
|
-
console.log(` ā
Global service ready (embedder: ${globalService.getEmbeddingModelName()})`);
|
|
1096
|
-
const globalMigration = await globalService.ensureEmbeddingModelForImport({ autoMigrate: true });
|
|
1097
|
-
if (globalMigration.changed) {
|
|
1098
|
-
console.log('š Global embedding migration detected');
|
|
1099
|
-
console.log(` Previous: ${globalMigration.previousModel || 'legacy-unknown'}`);
|
|
1100
|
-
console.log(` Current: ${globalMigration.currentModel}`);
|
|
1101
|
-
console.log(` Re-queued embeddings: ${globalMigration.enqueued}`);
|
|
1102
|
-
}
|
|
1103
|
-
result = await globalImporter.importAll(importOpts);
|
|
1104
|
-
|
|
1105
|
-
// Process embeddings
|
|
1106
|
-
console.log('\nš§ Processing embeddings...');
|
|
1107
|
-
const embedCount = await globalService.processPendingEmbeddings();
|
|
1108
|
-
|
|
1109
|
-
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
1110
|
-
printImportSummary(result, embedCount);
|
|
1111
|
-
console.log(`\nā±ļø Completed in ${elapsed}s`);
|
|
1112
|
-
|
|
1113
|
-
await globalService.shutdown();
|
|
1114
|
-
return;
|
|
1115
|
-
} else {
|
|
1116
|
-
// Default: import current project
|
|
1117
|
-
const cwd = process.cwd();
|
|
1118
|
-
console.log(`š„ Importing sessions for: ${cwd}\n`);
|
|
1119
|
-
result = await importer.importProject(cwd, {
|
|
1120
|
-
...importOpts,
|
|
1121
|
-
projectPath: cwd,
|
|
1122
|
-
});
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
// Process embeddings
|
|
1126
|
-
console.log('\nš§ Processing embeddings...');
|
|
1127
|
-
const embedCount = await service.processPendingEmbeddings();
|
|
1128
|
-
|
|
1129
|
-
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
1130
|
-
printImportSummary(result, embedCount);
|
|
1131
|
-
console.log(`\nā±ļø Completed in ${elapsed}s`);
|
|
1132
|
-
|
|
1133
|
-
await service.shutdown();
|
|
1134
|
-
} catch (error) {
|
|
1135
|
-
console.error('\nā Import failed:', error);
|
|
1136
|
-
process.exit(1);
|
|
1137
|
-
}
|
|
1138
|
-
});
|
|
1139
|
-
|
|
1140
|
-
/**
|
|
1141
|
-
* List command - list available sessions for import
|
|
1142
|
-
*/
|
|
1143
|
-
program
|
|
1144
|
-
.command('list')
|
|
1145
|
-
.description('List available Claude Code sessions')
|
|
1146
|
-
.option('-p, --project <path>', 'Filter by project path')
|
|
1147
|
-
.action(async (options) => {
|
|
1148
|
-
const service = getDefaultMemoryService();
|
|
1149
|
-
const importer = createSessionHistoryImporter(service);
|
|
1150
|
-
|
|
1151
|
-
try {
|
|
1152
|
-
const sessions = await importer.listAvailableSessions(options.project);
|
|
1153
|
-
|
|
1154
|
-
console.log('\nš Available Sessions\n');
|
|
1155
|
-
console.log(`Found ${sessions.length} session(s)\n`);
|
|
1156
|
-
|
|
1157
|
-
for (const session of sessions.slice(0, 20)) {
|
|
1158
|
-
const date = session.modifiedAt.toISOString().split('T')[0];
|
|
1159
|
-
const sizeKB = (session.size / 1024).toFixed(1);
|
|
1160
|
-
console.log(`š ${session.sessionId.slice(0, 16)}...`);
|
|
1161
|
-
console.log(` Modified: ${date}`);
|
|
1162
|
-
console.log(` Size: ${sizeKB} KB`);
|
|
1163
|
-
console.log(` Path: ${session.filePath}`);
|
|
1164
|
-
console.log('');
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
if (sessions.length > 20) {
|
|
1168
|
-
console.log(`... and ${sessions.length - 20} more sessions`);
|
|
1169
|
-
}
|
|
1170
|
-
|
|
1171
|
-
console.log('\nUse "claude-memory-layer import --session <path>" to import a specific session');
|
|
1172
|
-
} catch (error) {
|
|
1173
|
-
console.error('List failed:', error);
|
|
1174
|
-
process.exit(1);
|
|
1175
|
-
}
|
|
1176
|
-
});
|
|
1177
|
-
|
|
1178
|
-
// ============================================================
|
|
1179
|
-
// Codex Validation Commands
|
|
1180
|
-
// ============================================================
|
|
1181
|
-
|
|
1182
|
-
const codexCmd = program
|
|
1183
|
-
.command('codex')
|
|
1184
|
-
.description('Read-only Codex session scan/replay validation');
|
|
1185
|
-
|
|
1186
|
-
codexCmd
|
|
1187
|
-
.command('validate')
|
|
1188
|
-
.description('Dry-run validate Codex JSONL sessions without importing or mutating memory')
|
|
1189
|
-
.option('-p, --project <path>', 'Filter sessions by session_meta.payload.cwd')
|
|
1190
|
-
.option('--sessions-dir <path>', 'Codex sessions directory (default: ~/.codex/sessions)')
|
|
1191
|
-
.option('-l, --limit <number>', 'Limit number of session files to scan')
|
|
1192
|
-
.option('--format <format>', 'Report format: json or markdown', 'markdown')
|
|
1193
|
-
.option('-o, --output <path>', 'Write report to file')
|
|
1194
|
-
.option('--dry-run', 'Read-only validation mode (default; no imports or writes)', true)
|
|
1195
|
-
.option('--anonymize-projects', 'Show hashed project labels instead of raw cwd paths')
|
|
1196
|
-
.action(async (options: CodexValidateCommandOptions) => {
|
|
1197
|
-
try {
|
|
1198
|
-
await runCodexValidationCommand(options);
|
|
1199
|
-
} catch (error) {
|
|
1200
|
-
console.error('Codex validation failed:', error instanceof Error ? error.message : error);
|
|
1201
|
-
process.exit(1);
|
|
1202
|
-
}
|
|
1203
|
-
});
|
|
1204
|
-
|
|
1205
|
-
codexCmd
|
|
1206
|
-
.command('replay')
|
|
1207
|
-
.description('Alias for read-only Codex validation/replay report')
|
|
1208
|
-
.option('-p, --project <path>', 'Filter sessions by session_meta.payload.cwd')
|
|
1209
|
-
.option('--sessions-dir <path>', 'Codex sessions directory (default: ~/.codex/sessions)')
|
|
1210
|
-
.option('-l, --limit <number>', 'Limit number of session files to scan')
|
|
1211
|
-
.option('--format <format>', 'Report format: json or markdown', 'markdown')
|
|
1212
|
-
.option('-o, --output <path>', 'Write report to file')
|
|
1213
|
-
.option('--dry-run', 'Read-only validation mode (default; no imports or writes)', true)
|
|
1214
|
-
.option('--anonymize-projects', 'Show hashed project labels instead of raw cwd paths')
|
|
1215
|
-
.action(async (options: CodexValidateCommandOptions) => {
|
|
1216
|
-
try {
|
|
1217
|
-
await runCodexValidationCommand(options);
|
|
1218
|
-
} catch (error) {
|
|
1219
|
-
console.error('Codex replay failed:', error instanceof Error ? error.message : error);
|
|
1220
|
-
process.exit(1);
|
|
1221
|
-
}
|
|
1222
|
-
});
|
|
1223
|
-
|
|
1224
|
-
codexCmd
|
|
1225
|
-
.command('import')
|
|
1226
|
-
.description('Explicitly import Codex JSONL sessions into claude-memory-layer memory (mutates memory)')
|
|
1227
|
-
.option('-p, --project <path>', 'Import sessions whose session_meta.payload.cwd matches this project (default: cwd)')
|
|
1228
|
-
.option('-s, --session <file>', 'Import one Codex session JSONL file')
|
|
1229
|
-
.option('-a, --all', 'Import all Codex sessions into global memory unless --project is supplied')
|
|
1230
|
-
.option('--sessions-dir <path>', 'Codex sessions directory (default: ~/.codex/sessions)')
|
|
1231
|
-
.option('-l, --limit <number>', 'Limit memories imported across selected matching sessions')
|
|
1232
|
-
.option('--session-limit <number>', 'Limit recent matching sessions to import')
|
|
1233
|
-
.option('-f, --force', 'Delete existing events for each imported session before reimporting')
|
|
1234
|
-
.option('-v, --verbose', 'Show detailed progress')
|
|
1235
|
-
.option('--no-process-embeddings', 'Skip processing pending embeddings after import')
|
|
1236
|
-
.action(async (options) => {
|
|
1237
|
-
const startTime = Date.now();
|
|
1238
|
-
try {
|
|
1239
|
-
if (options.all && !options.project && !options.session) {
|
|
1240
|
-
console.log('\nš„ Importing all Codex sessions into global memory');
|
|
1241
|
-
console.log(' ā ļø Use --project to keep memory scoped to one project.\n');
|
|
1242
|
-
} else {
|
|
1243
|
-
console.log(`\nš„ Importing Codex sessions for: ${options.project || process.cwd()}\n`);
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
const outcome = await runCodexImportOnce(options, {
|
|
1247
|
-
cwd: () => process.cwd(),
|
|
1248
|
-
getDefaultMemoryService,
|
|
1249
|
-
getMemoryServiceForProject,
|
|
1250
|
-
createImporter: createCodexSessionHistoryImporter,
|
|
1251
|
-
onProgress: renderProgress
|
|
1252
|
-
});
|
|
1253
|
-
|
|
1254
|
-
printImportSummary(outcome.result, outcome.embedCount);
|
|
1255
|
-
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
1256
|
-
console.log(`\nā±ļø Codex import completed in ${elapsed}s (${outcome.mode}, ${outcome.storageScope} storage)`);
|
|
1257
|
-
} catch (error) {
|
|
1258
|
-
console.error('Codex import failed:', error instanceof Error ? error.message : error);
|
|
1259
|
-
process.exit(1);
|
|
1260
|
-
}
|
|
1261
|
-
});
|
|
1262
|
-
|
|
1263
|
-
// ============================================================
|
|
1264
|
-
// Hermes Validation Commands
|
|
1265
|
-
// ============================================================
|
|
1266
|
-
|
|
1267
|
-
const hermesCmd = program
|
|
1268
|
-
.command('hermes')
|
|
1269
|
-
.description('Read-only Hermes SessionDB scan/replay validation and explicit import');
|
|
1270
|
-
|
|
1271
|
-
hermesCmd
|
|
1272
|
-
.command('validate')
|
|
1273
|
-
.description('Dry-run validate Hermes ~/.hermes/state.db sessions without importing or mutating memory')
|
|
1274
|
-
.option('-p, --project <path>', 'Filter sessions by project path in Hermes session context')
|
|
1275
|
-
.option('--state-db <path>', 'Hermes state database path (default: ~/.hermes/state.db)')
|
|
1276
|
-
.option('-l, --limit <number>', 'Limit number of matching sessions to scan')
|
|
1277
|
-
.option('--format <format>', 'Report format: json or markdown', 'markdown')
|
|
1278
|
-
.option('-o, --output <path>', 'Write report to file')
|
|
1279
|
-
.option('--dry-run', 'Read-only validation mode (default; no imports or writes)', true)
|
|
1280
|
-
.action(async (options: HermesValidateCommandOptions) => {
|
|
1281
|
-
try {
|
|
1282
|
-
await runHermesValidationCommand(options);
|
|
1283
|
-
} catch (error) {
|
|
1284
|
-
console.error('Hermes validation failed:', error instanceof Error ? error.message : error);
|
|
1285
|
-
process.exit(1);
|
|
1286
|
-
}
|
|
1287
|
-
});
|
|
1288
|
-
|
|
1289
|
-
hermesCmd
|
|
1290
|
-
.command('replay')
|
|
1291
|
-
.description('Alias for read-only Hermes SessionDB validation/replay report')
|
|
1292
|
-
.option('-p, --project <path>', 'Filter sessions by project path in Hermes session context')
|
|
1293
|
-
.option('--state-db <path>', 'Hermes state database path (default: ~/.hermes/state.db)')
|
|
1294
|
-
.option('-l, --limit <number>', 'Limit number of matching sessions to scan')
|
|
1295
|
-
.option('--format <format>', 'Report format: json or markdown', 'markdown')
|
|
1296
|
-
.option('-o, --output <path>', 'Write report to file')
|
|
1297
|
-
.option('--dry-run', 'Read-only validation mode (default; no imports or writes)', true)
|
|
1298
|
-
.action(async (options: HermesValidateCommandOptions) => {
|
|
1299
|
-
try {
|
|
1300
|
-
await runHermesValidationCommand(options);
|
|
1301
|
-
} catch (error) {
|
|
1302
|
-
console.error('Hermes replay failed:', error instanceof Error ? error.message : error);
|
|
1303
|
-
process.exit(1);
|
|
1304
|
-
}
|
|
1305
|
-
});
|
|
1306
|
-
|
|
1307
|
-
hermesCmd
|
|
1308
|
-
.command('import')
|
|
1309
|
-
.description('Explicitly import Hermes SessionDB sessions into claude-memory-layer memory (mutates memory)')
|
|
1310
|
-
.option('-p, --project <path>', 'Import sessions whose Hermes context matches this project (default: cwd)')
|
|
1311
|
-
.option('-s, --session <id>', 'Import one Hermes session id')
|
|
1312
|
-
.option('-a, --all', 'Import all Hermes sessions into global memory unless --project is supplied')
|
|
1313
|
-
.option('--state-db <path>', 'Hermes state database path (default: ~/.hermes/state.db)')
|
|
1314
|
-
.option('-l, --limit <number>', 'Limit messages imported per selected Hermes session')
|
|
1315
|
-
.option('--session-limit <number>', 'Limit recent matching sessions to import')
|
|
1316
|
-
.option('-f, --force', 'Delete existing events for each imported session before reimporting')
|
|
1317
|
-
.option('-v, --verbose', 'Show detailed progress')
|
|
1318
|
-
.option('--no-process-embeddings', 'Skip processing pending embeddings after import')
|
|
1319
|
-
.action(async (options) => {
|
|
1320
|
-
const startTime = Date.now();
|
|
1321
|
-
try {
|
|
1322
|
-
if (options.all && !options.project && !options.session) {
|
|
1323
|
-
console.log('\nš„ Importing all Hermes sessions into global memory');
|
|
1324
|
-
console.log(' ā ļø Use --project to keep memory scoped to one project.\n');
|
|
1325
|
-
} else {
|
|
1326
|
-
console.log(`\nš„ Importing Hermes sessions for: ${options.project || process.cwd()}\n`);
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
const outcome = await runHermesImportOnce(options, {
|
|
1330
|
-
cwd: () => process.cwd(),
|
|
1331
|
-
getDefaultMemoryService,
|
|
1332
|
-
getMemoryServiceForProject,
|
|
1333
|
-
createImporter: createHermesSessionHistoryImporter,
|
|
1334
|
-
onProgress: renderProgress
|
|
1335
|
-
});
|
|
1336
|
-
|
|
1337
|
-
printImportSummary(outcome.result, outcome.embedCount);
|
|
1338
|
-
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
1339
|
-
console.log(`\nā±ļø Hermes import completed in ${elapsed}s (${outcome.mode}, ${outcome.storageScope} storage)`);
|
|
1340
|
-
} catch (error) {
|
|
1341
|
-
console.error('Hermes import failed:', error instanceof Error ? error.message : error);
|
|
1342
|
-
process.exit(1);
|
|
1343
|
-
}
|
|
1344
|
-
});
|
|
1345
|
-
|
|
1346
|
-
// ============================================================
|
|
1347
|
-
// Endless Mode Commands
|
|
1348
|
-
// ============================================================
|
|
1349
|
-
|
|
1350
|
-
/**
|
|
1351
|
-
* Endless Mode parent command
|
|
1352
|
-
*/
|
|
1353
|
-
const endlessCmd = program
|
|
1354
|
-
.command('endless')
|
|
1355
|
-
.description('Manage Endless Mode (biomimetic continuous memory)');
|
|
1356
|
-
|
|
1357
|
-
/**
|
|
1358
|
-
* Enable Endless Mode
|
|
1359
|
-
*/
|
|
1360
|
-
endlessCmd
|
|
1361
|
-
.command('enable')
|
|
1362
|
-
.description('Enable Endless Mode')
|
|
1363
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1364
|
-
.action(async (options) => {
|
|
1365
|
-
const projectPath = options.project || process.cwd();
|
|
1366
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1367
|
-
|
|
1368
|
-
try {
|
|
1369
|
-
await service.initialize();
|
|
1370
|
-
await service.setMode('endless');
|
|
1371
|
-
|
|
1372
|
-
console.log('\nā¾ļø Endless Mode Enabled\n');
|
|
1373
|
-
console.log('Your conversations will now be continuously integrated');
|
|
1374
|
-
console.log('across session boundaries.\n');
|
|
1375
|
-
console.log('Features:');
|
|
1376
|
-
console.log(' - Working Set: Recent context kept active');
|
|
1377
|
-
console.log(' - Consolidation: Automatic memory integration');
|
|
1378
|
-
console.log(' - Continuity: Seamless context transitions\n');
|
|
1379
|
-
console.log('Use "claude-memory-layer endless status" to view current state');
|
|
1380
|
-
|
|
1381
|
-
await service.shutdown();
|
|
1382
|
-
} catch (error) {
|
|
1383
|
-
console.error('Enable failed:', error);
|
|
1384
|
-
process.exit(1);
|
|
1385
|
-
}
|
|
1386
|
-
});
|
|
1387
|
-
|
|
1388
|
-
/**
|
|
1389
|
-
* Disable Endless Mode
|
|
1390
|
-
*/
|
|
1391
|
-
endlessCmd
|
|
1392
|
-
.command('disable')
|
|
1393
|
-
.description('Disable Endless Mode (return to Session Mode)')
|
|
1394
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1395
|
-
.action(async (options) => {
|
|
1396
|
-
const projectPath = options.project || process.cwd();
|
|
1397
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1398
|
-
|
|
1399
|
-
try {
|
|
1400
|
-
await service.initialize();
|
|
1401
|
-
await service.setMode('session');
|
|
1402
|
-
|
|
1403
|
-
console.log('\nš Session Mode Enabled\n');
|
|
1404
|
-
console.log('Returned to traditional session-based memory.');
|
|
1405
|
-
console.log('Existing Endless Mode data is preserved for future use.');
|
|
1406
|
-
|
|
1407
|
-
await service.shutdown();
|
|
1408
|
-
} catch (error) {
|
|
1409
|
-
console.error('Disable failed:', error);
|
|
1410
|
-
process.exit(1);
|
|
1411
|
-
}
|
|
1412
|
-
});
|
|
1413
|
-
|
|
1414
|
-
/**
|
|
1415
|
-
* Endless Mode Status
|
|
1416
|
-
*/
|
|
1417
|
-
endlessCmd
|
|
1418
|
-
.command('status')
|
|
1419
|
-
.description('Show Endless Mode status')
|
|
1420
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1421
|
-
.action(async (options) => {
|
|
1422
|
-
const projectPath = options.project || process.cwd();
|
|
1423
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1424
|
-
|
|
1425
|
-
try {
|
|
1426
|
-
await service.initialize();
|
|
1427
|
-
const status = await service.getEndlessModeStatus();
|
|
1428
|
-
|
|
1429
|
-
const modeIcon = status.mode === 'endless' ? 'ā¾ļø' : 'š';
|
|
1430
|
-
const modeName = status.mode === 'endless' ? 'Endless Mode' : 'Session Mode';
|
|
1431
|
-
|
|
1432
|
-
console.log(`\n${modeIcon} ${modeName}\n`);
|
|
1433
|
-
|
|
1434
|
-
if (status.mode === 'endless') {
|
|
1435
|
-
// Continuity score bar
|
|
1436
|
-
const continuityBars = 'ā'.repeat(Math.round(status.continuityScore * 10));
|
|
1437
|
-
const continuityEmpty = 'ā'.repeat(10 - Math.round(status.continuityScore * 10));
|
|
1438
|
-
|
|
1439
|
-
console.log('š Status:');
|
|
1440
|
-
console.log(` Working Set: ${status.workingSetSize} events`);
|
|
1441
|
-
console.log(` Continuity: [${continuityBars}${continuityEmpty}] ${(status.continuityScore * 100).toFixed(0)}%`);
|
|
1442
|
-
console.log(` Consolidated: ${status.consolidatedCount} memories`);
|
|
1443
|
-
|
|
1444
|
-
if (status.lastConsolidation) {
|
|
1445
|
-
const ago = Math.round((Date.now() - status.lastConsolidation.getTime()) / 60000);
|
|
1446
|
-
console.log(` Last Consolidation: ${ago} minutes ago`);
|
|
1447
|
-
} else {
|
|
1448
|
-
console.log(' Last Consolidation: Never');
|
|
1449
|
-
}
|
|
1450
|
-
} else {
|
|
1451
|
-
console.log('Endless Mode is disabled.');
|
|
1452
|
-
console.log('Use "claude-memory-layer endless enable" to activate.');
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
await service.shutdown();
|
|
1456
|
-
} catch (error) {
|
|
1457
|
-
console.error('Status failed:', error);
|
|
1458
|
-
process.exit(1);
|
|
1459
|
-
}
|
|
1460
|
-
});
|
|
1461
|
-
|
|
1462
|
-
/**
|
|
1463
|
-
* Consolidate command - manually trigger consolidation
|
|
1464
|
-
*/
|
|
1465
|
-
endlessCmd
|
|
1466
|
-
.command('consolidate')
|
|
1467
|
-
.description('Manually trigger memory consolidation')
|
|
1468
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1469
|
-
.action(async (options) => {
|
|
1470
|
-
const projectPath = options.project || process.cwd();
|
|
1471
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1472
|
-
|
|
1473
|
-
try {
|
|
1474
|
-
await service.initialize();
|
|
1475
|
-
|
|
1476
|
-
if (!service.isEndlessModeActive()) {
|
|
1477
|
-
console.log('\nā ļø Endless Mode is not active');
|
|
1478
|
-
console.log('Use "claude-memory-layer endless enable" first');
|
|
1479
|
-
process.exit(1);
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
console.log('\nā³ Running memory consolidation...');
|
|
1483
|
-
const count = await service.forceConsolidation();
|
|
1484
|
-
|
|
1485
|
-
if (count > 0) {
|
|
1486
|
-
console.log(`\nā
Consolidated ${count} memory group(s)`);
|
|
1487
|
-
} else {
|
|
1488
|
-
console.log('\nš No memories to consolidate');
|
|
1489
|
-
console.log('(Working set may not have enough events yet)');
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
await service.shutdown();
|
|
1493
|
-
} catch (error) {
|
|
1494
|
-
console.error('Consolidation failed:', error);
|
|
1495
|
-
process.exit(1);
|
|
1496
|
-
}
|
|
1497
|
-
});
|
|
1498
|
-
|
|
1499
|
-
/**
|
|
1500
|
-
* Working Set command - view current working set
|
|
1501
|
-
*/
|
|
1502
|
-
endlessCmd
|
|
1503
|
-
.command('working-set')
|
|
1504
|
-
.alias('ws')
|
|
1505
|
-
.description('View current working set')
|
|
1506
|
-
.option('-l, --limit <number>', 'Number of events to show', '10')
|
|
1507
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1508
|
-
.action(async (options) => {
|
|
1509
|
-
const projectPath = options.project || process.cwd();
|
|
1510
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1511
|
-
|
|
1512
|
-
try {
|
|
1513
|
-
await service.initialize();
|
|
1514
|
-
|
|
1515
|
-
if (!service.isEndlessModeActive()) {
|
|
1516
|
-
console.log('\nā ļø Endless Mode is not active');
|
|
1517
|
-
console.log('Use "claude-memory-layer endless enable" first');
|
|
1518
|
-
process.exit(1);
|
|
1519
|
-
}
|
|
1520
|
-
|
|
1521
|
-
const workingSet = await service.getWorkingSet();
|
|
1522
|
-
|
|
1523
|
-
if (!workingSet || workingSet.recentEvents.length === 0) {
|
|
1524
|
-
console.log('\nš Working Set is empty');
|
|
1525
|
-
console.log('Events will be added as you interact with Claude');
|
|
1526
|
-
process.exit(0);
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
console.log('\nš§ Working Set\n');
|
|
1530
|
-
console.log(`Total events: ${workingSet.recentEvents.length}`);
|
|
1531
|
-
console.log(`Continuity score: ${(workingSet.continuityScore * 100).toFixed(0)}%`);
|
|
1532
|
-
console.log(`Last activity: ${workingSet.lastActivity.toISOString()}\n`);
|
|
1533
|
-
|
|
1534
|
-
const limit = parseInt(options.limit);
|
|
1535
|
-
const events = workingSet.recentEvents.slice(0, limit);
|
|
1536
|
-
|
|
1537
|
-
for (const event of events) {
|
|
1538
|
-
const icon = event.eventType === 'user_prompt' ? 'š¤' :
|
|
1539
|
-
event.eventType === 'agent_response' ? 'š¤' :
|
|
1540
|
-
event.eventType === 'tool_observation' ? 'š§' : 'š';
|
|
1541
|
-
const time = event.timestamp.toLocaleTimeString();
|
|
1542
|
-
const preview = event.content.slice(0, 80) + (event.content.length > 80 ? '...' : '');
|
|
1543
|
-
|
|
1544
|
-
console.log(`${icon} [${time}] ${event.eventType}`);
|
|
1545
|
-
console.log(` ${preview}`);
|
|
1546
|
-
console.log('');
|
|
1547
|
-
}
|
|
1548
|
-
|
|
1549
|
-
if (workingSet.recentEvents.length > limit) {
|
|
1550
|
-
console.log(`... and ${workingSet.recentEvents.length - limit} more events`);
|
|
1551
|
-
}
|
|
1552
|
-
|
|
1553
|
-
await service.shutdown();
|
|
1554
|
-
} catch (error) {
|
|
1555
|
-
console.error('Working set failed:', error);
|
|
1556
|
-
process.exit(1);
|
|
1557
|
-
}
|
|
1558
|
-
});
|
|
1559
|
-
|
|
1560
|
-
/**
|
|
1561
|
-
* Consolidated memories command
|
|
1562
|
-
*/
|
|
1563
|
-
endlessCmd
|
|
1564
|
-
.command('memories')
|
|
1565
|
-
.description('View consolidated memories')
|
|
1566
|
-
.option('-l, --limit <number>', 'Number of memories to show', '10')
|
|
1567
|
-
.option('-q, --query <text>', 'Search consolidated memories')
|
|
1568
|
-
.option('-p, --project <path>', 'Project path (defaults to cwd)')
|
|
1569
|
-
.action(async (options) => {
|
|
1570
|
-
const projectPath = options.project || process.cwd();
|
|
1571
|
-
const service = getMemoryServiceForProject(projectPath);
|
|
1572
|
-
|
|
1573
|
-
try {
|
|
1574
|
-
await service.initialize();
|
|
1575
|
-
|
|
1576
|
-
let memories;
|
|
1577
|
-
|
|
1578
|
-
if (options.query) {
|
|
1579
|
-
memories = await service.searchConsolidated(options.query, {
|
|
1580
|
-
topK: parseInt(options.limit)
|
|
1581
|
-
});
|
|
1582
|
-
console.log(`\nš Searching for: "${options.query}"\n`);
|
|
1583
|
-
} else {
|
|
1584
|
-
memories = await service.getConsolidatedMemories(parseInt(options.limit));
|
|
1585
|
-
console.log('\nš¾ Consolidated Memories\n');
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
if (memories.length === 0) {
|
|
1589
|
-
console.log('No consolidated memories found.');
|
|
1590
|
-
if (!service.isEndlessModeActive()) {
|
|
1591
|
-
console.log('Enable Endless Mode to start consolidating memories.');
|
|
1592
|
-
}
|
|
1593
|
-
process.exit(0);
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
console.log(`Showing ${memories.length} memory(ies)\n`);
|
|
1597
|
-
|
|
1598
|
-
for (const memory of memories) {
|
|
1599
|
-
const date = memory.createdAt.toISOString().split('T')[0];
|
|
1600
|
-
const confidenceBars = 'ā'.repeat(Math.round(memory.confidence * 5));
|
|
1601
|
-
|
|
1602
|
-
console.log(`š ${memory.topics.slice(0, 3).join(', ')}`);
|
|
1603
|
-
console.log(` Created: ${date}`);
|
|
1604
|
-
console.log(` Confidence: [${confidenceBars}] ${(memory.confidence * 100).toFixed(0)}%`);
|
|
1605
|
-
console.log(` Sources: ${memory.sourceEvents.length} events`);
|
|
1606
|
-
console.log(` Access count: ${memory.accessCount}`);
|
|
1607
|
-
console.log(` Summary: ${memory.summary.slice(0, 200)}${memory.summary.length > 200 ? '...' : ''}`);
|
|
1608
|
-
console.log('');
|
|
1609
|
-
}
|
|
1610
|
-
|
|
1611
|
-
await service.shutdown();
|
|
1612
|
-
} catch (error) {
|
|
1613
|
-
console.error('Memories failed:', error);
|
|
1614
|
-
process.exit(1);
|
|
1615
|
-
}
|
|
1616
|
-
});
|
|
1617
|
-
|
|
1618
|
-
/**
|
|
1619
|
-
* MCP command - configure Claude Desktop MCP integration
|
|
1620
|
-
*/
|
|
1621
|
-
const mcpCmd = program
|
|
1622
|
-
.command('mcp')
|
|
1623
|
-
.description('Manage MCP Desktop integration');
|
|
1624
|
-
|
|
1625
|
-
mcpCmd
|
|
1626
|
-
.command('install')
|
|
1627
|
-
.description('Install claude-memory-layer MCP server into Claude Desktop config')
|
|
1628
|
-
.option('-c, --config-path <path>', 'Claude Desktop config path')
|
|
1629
|
-
.option('-n, --server-name <name>', 'MCP server name', 'claude-memory-layer')
|
|
1630
|
-
.option('--command <command>', 'MCP server command', 'claude-memory-layer-mcp')
|
|
1631
|
-
.option('--arg <arg...>', 'Arguments for the MCP server command')
|
|
1632
|
-
.option('--dry-run', 'Print the updated config without writing it')
|
|
1633
|
-
.action((options: { configPath?: string; serverName: string; command: string; arg?: string[]; dryRun?: boolean }) => {
|
|
1634
|
-
try {
|
|
1635
|
-
const { configPath, config } = installMcpServer({
|
|
1636
|
-
configPath: options.configPath,
|
|
1637
|
-
serverName: options.serverName,
|
|
1638
|
-
command: options.command,
|
|
1639
|
-
args: options.arg ?? [],
|
|
1640
|
-
dryRun: options.dryRun ?? false
|
|
1641
|
-
});
|
|
1642
|
-
|
|
1643
|
-
if (options.dryRun) {
|
|
1644
|
-
console.log(JSON.stringify(config, null, 2));
|
|
1645
|
-
console.log(`\nDry run only. No changes written to ${configPath}`);
|
|
1646
|
-
return;
|
|
1647
|
-
}
|
|
1648
|
-
|
|
1649
|
-
console.log(`\nā
Installed MCP server '${options.serverName}' into Claude Desktop config.`);
|
|
1650
|
-
console.log(` Config: ${configPath}`);
|
|
1651
|
-
console.log(' Restart Claude Desktop to load the new MCP server.\n');
|
|
1652
|
-
} catch (error) {
|
|
1653
|
-
console.error('MCP install failed:', error);
|
|
1654
|
-
process.exit(1);
|
|
1655
|
-
}
|
|
1656
|
-
});
|
|
1657
|
-
|
|
1658
|
-
/**
|
|
1659
|
-
* Dashboard command - start web dashboard
|
|
1660
|
-
*/
|
|
1661
|
-
program
|
|
1662
|
-
.command('dashboard')
|
|
1663
|
-
.description('Open memory dashboard in browser')
|
|
1664
|
-
.option('-p, --port <port>', 'Server port', '37777')
|
|
1665
|
-
.option('--no-open', 'Do not auto-open browser')
|
|
1666
|
-
.action(async (options) => {
|
|
1667
|
-
const port = parseInt(options.port, 10);
|
|
1668
|
-
|
|
1669
|
-
try {
|
|
1670
|
-
// Check if server is already running
|
|
1671
|
-
const running = await isServerRunning(port);
|
|
1672
|
-
if (running) {
|
|
1673
|
-
console.log(`\nš§ Dashboard already running at http://localhost:${port}\n`);
|
|
1674
|
-
if (options.open) {
|
|
1675
|
-
openBrowser(`http://localhost:${port}`);
|
|
1676
|
-
}
|
|
1677
|
-
return;
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
// Start the server
|
|
1681
|
-
console.log('\nš§ Starting Code Memory Dashboard...\n');
|
|
1682
|
-
startServer(port);
|
|
1683
|
-
|
|
1684
|
-
// Open browser
|
|
1685
|
-
if (options.open) {
|
|
1686
|
-
setTimeout(() => {
|
|
1687
|
-
openBrowser(`http://localhost:${port}`);
|
|
1688
|
-
}, 500);
|
|
1689
|
-
}
|
|
1690
|
-
|
|
1691
|
-
console.log(`\nš Dashboard: http://localhost:${port}`);
|
|
1692
|
-
console.log('Press Ctrl+C to stop the server\n');
|
|
1693
|
-
|
|
1694
|
-
// Handle graceful shutdown
|
|
1695
|
-
const shutdown = () => {
|
|
1696
|
-
console.log('\n\nš Shutting down dashboard...');
|
|
1697
|
-
stopServer();
|
|
1698
|
-
process.exit(0);
|
|
1699
|
-
};
|
|
1700
|
-
|
|
1701
|
-
process.on('SIGINT', shutdown);
|
|
1702
|
-
process.on('SIGTERM', shutdown);
|
|
1703
|
-
|
|
1704
|
-
// Keep process alive
|
|
1705
|
-
await new Promise(() => {});
|
|
1706
|
-
} catch (error) {
|
|
1707
|
-
console.error('Dashboard failed:', error);
|
|
1708
|
-
process.exit(1);
|
|
1709
|
-
}
|
|
1710
|
-
});
|
|
1711
|
-
|
|
1712
|
-
/**
|
|
1713
|
-
* Open URL in default browser
|
|
1714
|
-
*/
|
|
1715
|
-
function openBrowser(url: string): void {
|
|
1716
|
-
const platform = process.platform;
|
|
1717
|
-
let command: string;
|
|
1718
|
-
|
|
1719
|
-
if (platform === 'darwin') {
|
|
1720
|
-
command = `open "${url}"`;
|
|
1721
|
-
} else if (platform === 'win32') {
|
|
1722
|
-
command = `start "" "${url}"`;
|
|
1723
|
-
} else {
|
|
1724
|
-
command = `xdg-open "${url}"`;
|
|
1725
|
-
}
|
|
1726
|
-
|
|
1727
|
-
exec(command, (error) => {
|
|
1728
|
-
if (error) {
|
|
1729
|
-
console.log(`\nā ļø Could not open browser automatically.`);
|
|
1730
|
-
console.log(` Please open ${url} manually.\n`);
|
|
1731
|
-
}
|
|
1732
|
-
});
|
|
1733
|
-
}
|
|
1734
|
-
|
|
1735
|
-
program.parse();
|