Commit Graph

84 Commits

Author SHA1 Message Date
Alex Newman
9855ccf66d Refactor context-hook to use execSync for fetching context and simplify output structure; migrate from bun:sqlite to better-sqlite3 in Database and migrations; update SearchRoutes to dynamically import context generator for improved context handling. 2025-12-07 17:23:30 -05:00
Alex Newman
0a667afc0f built files for plugin 2025-12-05 19:11:33 -05:00
Alex Newman
375dd1c3d6 feat: Add Context Settings Modal with Terminal Preview and UI Enhancements (#161)
* feat: Add Context Injection Settings modal with terminal preview

Adds a new settings modal accessible from the viewer UI header that allows users to configure context injection parameters with a live terminal preview showing how observations will appear.

Changes:
- New ContextSettingsModal component with auto-saving settings
- TerminalPreview component for live context visualization
- useContextPreview hook for fetching preview data
- Modal positioned to left of color mode button
- Settings sync with backend via worker service API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: Add demo data and modify contextHook for cm_demo_content project

- Introduced DEMO_OBSERVATIONS and DEMO_SUMMARIES for the cm_demo_content project to provide mock data for testing and demonstration purposes.
- Updated contextHook to utilize demo data when the project is cm_demo_content, filtering observations based on configured types and concepts.
- Adjusted the worker service to use the contextHook with demo data, ensuring ANSI rendering for terminal output.
- Enhanced error handling and ensured proper closure of database connections.

* feat: add GitHub stars button with dynamic star count

- Implemented a new GitHubStarsButton component that fetches and displays the star count for a specified GitHub repository.
- Added useGitHubStars hook to handle API requests and state management for star count.
- Created formatStarCount utility function to format the star count into compact notation (k/M suffixes).
- Styled the GitHub stars button to match existing UI components, including hover and active states.
- Updated Header component to include the new GitHubStarsButton, replacing the static GitHub link.
- Added responsive styles to hide the GitHub stars button on mobile devices.

* feat: add API endpoint to fetch distinct projects and update context settings modal

- Implemented a new API endpoint `/api/projects` in `worker-service.ts` to retrieve a list of distinct projects from the observations.
- Modified `ContextSettingsModal.tsx` to replace the current project display with a dropdown for selecting projects, utilizing the fetched project list.
- Updated `useContextPreview.ts` to fetch projects on mount and manage the selected project state.
- Removed the `currentProject` prop from `ContextSettingsModal` and `App` components as it is now managed internally within the modal.

* Enhance Context Settings Modal and Terminal Preview

- Updated the styling of the Context Settings Modal for a modern clean design, including improved backdrop, header, and body layout.
- Introduced responsive design adjustments for smaller screens.
- Added custom scrollbar styles for better user experience.
- Refactored the TerminalPreview component to utilize `ansi-to-html` for rendering ANSI content, improving text display.
- Implemented new font variables for terminal styling across the application.
- Enhanced checkbox and input styles in the settings panel for better usability and aesthetics.
- Improved the layout and structure of settings groups and chips for a more organized appearance.

* Refactor UI components for compact design and enhance MCP toggle functionality

- Updated grid layout in viewer.html and viewer-template.html for better space utilization.
- Reduced padding and font sizes in settings groups, filter chips, and form controls for a more compact appearance.
- Implemented MCP toggle state management in ContextSettingsModal with API integration for status fetching and toggling.
- Reorganized settings groups for clarity, renaming and consolidating sections for improved user experience.
- Added feedback mechanism for MCP toggle status to inform users of changes and errors.

* feat: add collapsible sections, chip groups, form fields with tooltips, and toggle switches in settings modal

- Implemented collapsible sections for better organization of settings.
- Added chip groups with select all/none functionality for observation types and concepts.
- Enhanced form fields with optional tooltips for better user guidance.
- Introduced toggle switches for various settings, improving user interaction.
- Updated styles for new components to ensure consistency and responsiveness.
- Refactored ContextSettingsModal to utilize new components and improve readability.
- Improved TerminalPreview component styling for better layout and usability.

* Refactor modal header and preview selector styles; enhance terminal preview functionality

- Updated modal header padding and added gap for better spacing.
- Introduced a new header-controls section to include a project preview selector.
- Enhanced the preview selector styles for improved usability and aesthetics.
- Adjusted the preview column styles for a cleaner look.
- Implemented word wrap toggle functionality in the TerminalPreview component, allowing users to switch between wrapped and scrollable text.
- Improved scroll position handling in TerminalPreview to maintain user experience during content updates.

* feat: enhance modal settings with new icon links and update header controls

- Added new modal icon links for documentation and social media in ContextSettingsModal.
- Updated the header to remove sidebar toggle functionality and replaced it with context preview toggle.
- Refactored styles for modal icon links to improve UI/UX.
- Removed sidebar component from App and adjusted related state management.

* chore: remove abandoned cm_demo_content demo data approach

The demo data feature was prototyped but didn't work out. Removes:
- DEMO_OBSERVATIONS and DEMO_SUMMARIES arrays
- Conditional logic that bypassed DB for demo project
- Demo mode check in prior message extraction

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-03 21:34:41 -05:00
Alex Newman
c768a80bf0 Refactor context configuration and settings handling
- Updated context configuration loading path from ~/.claude/settings.json to ~/.claude-mem/settings.json.
- Modified the extractPriorMessages function to focus on retrieving the last assistant message only, removing user message extraction.
- Enhanced output formatting for displaying prior assistant messages in the context hook.
- Added new settings related to token economics and observation filtering in the useSettings hook.
2025-12-01 19:26:33 -05:00
Alex Newman
6dc648f07c feat: add functionality to extract and display prior session messages
- Implemented `cwdToDashed` helper function to format current working directory for transcript file paths.
- Added `extractPriorMessages` function to read and parse the last user and assistant messages from a transcript file.
- Enhanced `contextHook` to retrieve and display prior session messages if enabled in the configuration.
- Updated output formatting to include a "Previously" section showing last messages from the prior session.
2025-12-01 18:10:55 -05:00
Alex Newman
b116681529 refactor: improve context economics display logic and logging
- Updated logging category from 'CONTEXT' to 'HOOK' for context settings loading failure.
- Simplified the display logic for the Context Economics section to show only when relevant settings are enabled.
- Enhanced readability by consolidating repeated code for displaying token savings.
- Adjusted footer logic to conditionally display token savings message based on visibility of context economics.
2025-12-01 17:43:04 -05:00
Alex Newman
d1876cb6e0 Refactor observation handling: centralize constants and improve context settings
- Introduced `observation-metadata.ts` to define valid observation types and concepts, along with their corresponding emoji mappings.
- Updated `context-hook.ts` to utilize new constants for observation types and concepts, enhancing maintainability.
- Refactored `worker-service.ts` to validate observation types and concepts against the new centralized constants.
- Consolidated settings management in `Sidebar.tsx` to streamline state handling for context settings.
- Improved error handling and logging for context loading failures.
2025-12-01 17:29:48 -05:00
Alex Newman
e1017b483b feat: Enhance context settings with validation and UI options
- Added ContextConfig interface and loadContextConfig function to manage context settings.
- Implemented validation for context settings in WorkerService.
- Updated Sidebar component to include new context settings for token economics, observation filtering, display configuration, and feature toggles.
- Introduced default settings for new context features.
- Adjusted types to accommodate new settings in the application state.
2025-12-01 16:53:35 -05:00
Alex Newman
2b223b7cd9 feat: Add dual-tag system for meta-observation control (#153)
* feat: Add dual-tag system for meta-observation control

Implements <private> and <claude-mem-context> tag stripping at hook layer
to give users fine-grained control over what gets persisted in observations
and enable future real-time context injection without recursive storage.

**Features:**
- stripMemoryTags() function in save-hook.ts
- Strips both <private> and <claude-mem-context> tags before sending to worker
- Always active (no configuration needed)
- Comprehensive test suite (19 tests, all passing)
- User documentation for <private> tag
- Technical architecture documentation

**Architecture:**
- Edge processing pattern (filter at hook, not worker)
- Defensive type handling with silentDebug
- Supports multiline, nested, and multiple tags
- Enables strategic orchestration for internal tools

**User-Facing:**
- <private> tag for manual privacy control (documented)
- Prevents sensitive data from persisting in observations

**Infrastructure:**
- <claude-mem-context> tag ready for real-time context feature
- Prevents recursive storage when context injection ships

**Files:**
- src/hooks/save-hook.ts: Core implementation
- tests/strip-memory-tags.test.ts: Test suite (19/19 passing)
- docs/public/usage/private-tags.mdx: User guide
- docs/public/docs.json: Navigation update
- docs/context/dual-tag-system-architecture.md: Technical docs
- plugin/scripts/save-hook.js: Built hook

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Strip private tags from user prompts and skip memory ops for fully private prompts

Fixes critical privacy bug where <private> tags were not being stripped from
user prompts before storage in user_prompts table, making private content
searchable via mem-search.

Changes:

1. new-hook.ts: Skip memory operations for fully private prompts
   - If cleaned prompt is empty after stripping tags, skip saveUserPrompt
   - Skip worker init to avoid wasting resources on empty prompts
   - Logs: "(fully private - skipped)"

2. save-hook.ts: Skip observations for fully private prompts
   - Check if user prompt was entirely private before creating observations
   - Respects user intent: fully private prompt = no observations at all
   - Prevents "thoughts pop up" issue where private prompts create public observations

3. SessionStore.ts: Add getUserPrompt() method
   - Retrieves prompt text by session_id and prompt_number
   - Used by save-hook to check if prompt was private

4. Tests: Added 4 new tests for fully private prompt detection (16 total, all passing)

5. Docs: Updated private-tags.mdx to reflect correct behavior
   - User prompts ARE now filtered before storage
   - Private content never reaches database or search indices

Privacy Protection:
- Fully private prompts: No user_prompt saved, no worker init, no observations
- Partially private prompts: Tags stripped, content sanitized before storage
- Zero leaks: Private content never indexed or searchable

Addresses reviewer feedback on PR #153 about user prompt filtering.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: Enhance memory tag handling and indexing in user prompts

- Added a new index `idx_user_prompts_lookup` on `user_prompts` for improved query performance based on `claude_session_id` and `prompt_number`.
- Refactored memory tag stripping functionality into dedicated utility functions: `stripMemoryTagsFromJson` and `stripMemoryTagsFromPrompt` for better separation of concerns and reusability.
- Updated hooks (`new-hook.ts` and `save-hook.ts`) to utilize the new tag stripping functions, ensuring private content is not stored or searchable.
- Removed redundant inline tag stripping functions from hooks to streamline code.
- Added tests for the new tag stripping utilities to ensure functionality and prevent regressions.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-30 22:57:26 -05:00
Dmytro Gaivoronsky
69b17e15a2 feat: Auto-detect and rebuild native modules on Node.js version changes (#149)
Implements three-layer defense against native module version mismatches:

Layer 1: Node.js Version Tracking
- Track Node.js version alongside package version in .install-version marker
- Auto-trigger npm install when Node.js version changes
- Backward compatible with old plain-text version marker format

Layer 2: Native Module Verification
- Add verifyNativeModules() function to test better-sqlite3 loads correctly
- Verify after install completes to catch corrupted builds
- Retry with force flag if initial install verification fails

Layer 3: Graceful Failure
- Catch ERR_DLOPEN_FAILED in context-hook and delete version marker
- Exit cleanly to avoid error spam in Claude Code UI
- Auto-fix on next session start

Changes:
- scripts/smart-install.js: Add Node.js version tracking and verification
- src/hooks/context-hook.ts: Add graceful failure handling for native module errors
- tests/smart-install.test.js: Add tests for version marker format compatibility
- plugin/scripts/context-hook.js: Built output from TypeScript source

Fixes the issue where users see ERR_DLOPEN_FAILED errors after Node.js upgrades,
requiring manual npm install. Now automatically detects and fixes the issue.

Related design doc: docs/context/native-module-auto-fix-design.md
Implementation plan: docs/context/native-module-auto-fix-implementation.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Alex Newman <thedotmack@gmail.com>
2025-11-30 17:28:07 -05:00
Alex Newman
01be3156fb fix: context hook updates and cleanup (#150)
* fix(context-hook): update savings message to reference mem-search skill

Changed "Use claude-mem search" to "Use the mem-search skill" for clarity.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: delete outdated docs, experiments, and test results

Removed:
- docs/context/ (moved to private/)
- experiment/ (obsolete)
- test-results/ (stale)
- tests/ (outdated)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(user-message-hook): update support link to Discord community

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-28 20:17:44 -05:00
Alex Newman
5d23c60b76 fix: Update project name when session already exists in createSDKSession
**Problem:**
- Sessions created with empty project names couldn't be updated
- INSERT OR IGNORE skipped updates when session already existed
- Context-hook couldn't find observations (WHERE project = 'claude-mem')
- 364 observations had empty project names

**Root Cause:**
createSDKSession() used INSERT OR IGNORE for idempotency, but never
updated project/prompt fields when session already existed. If SAVE hook
created session first (with empty project), NEW hook couldn't fix it.

**Solution:**
When INSERT is ignored (session exists), UPDATE project and user_prompt
if we have non-empty values. This ensures project name gets set even
when session was created by SAVE hook or with incomplete data.

**Impact:**
- New sessions will always have correct project name
- Backfilled 364 historical observations with project='claude-mem'
- Context injection will now work (finds observations by project)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 16:06:46 -05:00
Alex Newman
bdf79a439b fix: Change discovery_tokens migration from version 7 to 11
Root cause: The ensureDiscoveryTokensColumn migration was using version 7,
which was already taken by removeSessionSummariesUniqueConstraint. This
duplicate version number caused migration tracking issues in some databases.

Changes:
- Updated migration version from 7 to 11 (next available)
- Added schema_versions check to prevent unnecessary re-runs
- Updated comments to clarify the version number conflict
- Added error propagation (already present, but now more reliable)

This resolves issue #121 where users were seeing "no such column: discovery_tokens"
errors after upgrading to v6.0.6.

Affected users can manually add the columns:
  ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0;
  ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0;

Or wait for v6.0.7 release which includes this fix.

Fixes #121

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 13:43:34 -05:00
Alex Newman
c0778bef00 docs: Align search documentation with hybrid ChromaDB architecture (#116)
* feat: Add discovery_tokens for ROI tracking in observations and session summaries

- Introduced `discovery_tokens` column in `observations` and `session_summaries` tables to track token costs associated with discovering and creating each observation and summary.
- Updated relevant services and hooks to calculate and display ROI metrics based on discovery tokens.
- Enhanced context economics reporting to include savings from reusing previous observations.
- Implemented migration to ensure the new column is added to existing tables.
- Adjusted data models and sync processes to accommodate the new `discovery_tokens` field.

* refactor: streamline context hook by removing unused functions and updating terminology

- Removed the estimateTokens and getObservations helper functions as they were not utilized.
- Updated the legend and output messages to replace "discovery" with "work" for clarity.
- Changed the emoji representation for different observation types to better reflect their purpose.
- Enhanced output formatting for improved readability and understanding of token usage.

* Refactor user-message-hook and context-hook for improved clarity and functionality

- Updated user-message-hook.js to enhance error messaging and improve variable naming for clarity.
- Modified context-hook.ts to include a new column key section, improved context index instructions, and added emoji icons for observation types.
- Adjusted footer messages in context-hook.ts to emphasize token savings and access to past research.
- Changed user-message-hook.ts to update the feedback and support message for clarity.

* fix: Critical ROI tracking fixes from PR review

Addresses critical findings from PR #111 review:

1. **Fixed incorrect discovery token calculation** (src/services/worker/SDKAgent.ts)
   - Changed from passing cumulative total to per-response delta
   - Now correctly tracks token cost for each observation/summary
   - Captures token state before/after response processing
   - Prevents all observations getting inflated cumulative values

2. **Fixed schema version mismatch** (src/services/sqlite/SessionStore.ts)
   - Changed ensureDiscoveryTokensColumn() from version 11 to version 7
   - Now matches migration007 definition in migrations.ts
   - Ensures consistent version tracking across migration system

These fixes ensure ROI metrics accurately reflect token costs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Update search documentation to reflect hybrid ChromaDB architecture

The backend correctly implements ChromaDB-first semantic search with SQLite
temporal ordering and FTS5 fallback, but documentation incorrectly described
it as "FTS5 full-text search". This fix aligns all skill guides and tool
descriptions with the actual implementation.

Changes:
- Update SKILL.md to describe hybrid architecture with ChromaDB primary
- Update observations.md title and query parameter descriptions
- Update all three search tool descriptions in search-server.ts:
  * search_observations
  * search_sessions
  * search_user_prompts

All tools now correctly document:
- ChromaDB semantic search (primary ranking)
- 90-day recency filter
- SQLite temporal ordering
- FTS5 fallback (when ChromaDB unavailable)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Add discovery_tokens column to observations and session_summaries tables

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-16 13:36:17 -05:00
Alex Newman
3cbc041c8b feat: Add ROI tracking with discovery_tokens for observations and session summaries (#111)
* feat: Add discovery_tokens for ROI tracking in observations and session summaries

- Introduced `discovery_tokens` column in `observations` and `session_summaries` tables to track token costs associated with discovering and creating each observation and summary.
- Updated relevant services and hooks to calculate and display ROI metrics based on discovery tokens.
- Enhanced context economics reporting to include savings from reusing previous observations.
- Implemented migration to ensure the new column is added to existing tables.
- Adjusted data models and sync processes to accommodate the new `discovery_tokens` field.

* refactor: streamline context hook by removing unused functions and updating terminology

- Removed the estimateTokens and getObservations helper functions as they were not utilized.
- Updated the legend and output messages to replace "discovery" with "work" for clarity.
- Changed the emoji representation for different observation types to better reflect their purpose.
- Enhanced output formatting for improved readability and understanding of token usage.

* Refactor user-message-hook and context-hook for improved clarity and functionality

- Updated user-message-hook.js to enhance error messaging and improve variable naming for clarity.
- Modified context-hook.ts to include a new column key section, improved context index instructions, and added emoji icons for observation types.
- Adjusted footer messages in context-hook.ts to emphasize token savings and access to past research.
- Changed user-message-hook.ts to update the feedback and support message for clarity.

* fix: Critical ROI tracking fixes from PR review

Addresses critical findings from PR #111 review:

1. **Fixed incorrect discovery token calculation** (src/services/worker/SDKAgent.ts)
   - Changed from passing cumulative total to per-response delta
   - Now correctly tracks token cost for each observation/summary
   - Captures token state before/after response processing
   - Prevents all observations getting inflated cumulative values

2. **Fixed schema version mismatch** (src/services/sqlite/SessionStore.ts)
   - Changed ensureDiscoveryTokensColumn() from version 11 to version 7
   - Now matches migration007 definition in migrations.ts
   - Ensures consistent version tracking across migration system

These fixes ensure ROI metrics accurately reflect token costs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-15 19:34:53 -05:00
Alex Newman
0475a57fb1 feat: Migrate to Skill-Based Search and enhance context handling
- Implemented a new skill-based search approach, replacing MCP search tools to reduce session start context from ~2,500 tokens to ~250 tokens.
- Added 10 new HTTP API endpoints to the worker service for various search functionalities.
- Created a new search skill with detailed instructions and examples for users.
- Removed MCP search server references and updated documentation to reflect the new skill-based approach.
- Enhanced context handling in the context hook to conditionally display the most recent summary based on observations.
- Introduced comprehensive documentation for Agent Skills, including creation, management, and best practices.
2025-11-09 17:34:00 -05:00
Alex Newman
fda069bb07 Fix GitHub issues #76, #74, #75 + session lifecycle improvements (#77)
* Refactor context-hook: Fix anti-patterns and improve maintainability

This refactor addresses all anti-patterns documented in CLAUDE.md, improving code quality without changing behavior.

**Dead Code Removed:**
- Eliminated unused useIndexView parameter throughout
- Cleaned up entry point logic

**Magic Numbers → Named Constants:**
- CHARS_PER_TOKEN_ESTIMATE = 4 (token estimation)
- SUMMARY_LOOKAHEAD = 1 (explains +1 in query)
- Added clarifying comment for DISPLAY_SESSION_COUNT

**Code Duplication Eliminated:**
- Reduced 34 lines to 4 lines with renderSummaryField() helper
- Replaced 4 identical summary field rendering blocks

**Error Handling Added:**
- parseJsonArray() now catches JSON.parse exceptions
- Prevents session crashes from malformed data

**Type Safety Improved:**
- Added SessionSummary interface (replaced inline type cast)
- Added SummaryTimelineItem for timeline items
- Proper Map typing: Map<string, TimelineItem[]>

**Variable Naming Clarity:**
- summariesWithOffset → summariesForTimeline
- isMostRecent → shouldShowLink (explains purpose)
- dayTimelines → itemsByDay
- nextSummary → olderSummary (correct chronology)

**Better Documentation:**
- Explained confusing timeline offset logic
- Removed apologetic comments, added clarifying ones

**Impact:**
- 28 lines saved from duplication elimination
- Zero behavioral changes (output identical)
- Improved maintainability and type safety

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix context-hook to respect settings.json contextDepth

The context-hook was ignoring the user's contextDepth setting from the web UI (stored in ~/.claude-mem/settings.json) and always using the default of 50 observations.

**Problem:**
- Web UI sets contextDepth in ~/.claude-mem/settings.json
- Context-hook only read from process.env.CLAUDE_MEM_CONTEXT_OBSERVATIONS
- User's preference of 7 observations was ignored, always showing 50

**Solution:**
- Added getContextDepth() function following same pattern as getWorkerPort()
- Priority: settings.json > env var > default (50)
- Validates contextDepth is a positive number

**Testing:**
- Verified with contextDepth: 7 → shows 7 observations ✓
- Verified with contextDepth: 3 → shows 3 observations ✓
- Settings properly respected on every session start

**Files Changed:**
- src/hooks/context-hook.ts: Added getContextDepth() + imports
- plugin/scripts/context-hook.js: Built output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix context-hook to read from correct settings file location

**Critical Bug Fix:**
Previous commit read from completely wrong location with wrong field name.

**What was wrong:**
- Reading from: ~/.claude-mem/settings.json (doesn't exist)
- Looking for: contextDepth (wrong field)
- Result: Always falling back to default of 50

**What's fixed:**
- Reading from: ~/.claude/settings.json (correct location)
- Looking for: env.CLAUDE_MEM_CONTEXT_OBSERVATIONS (correct field)
- Matches pattern used in worker-service.ts

**Testing:**
- With CLAUDE_MEM_CONTEXT_OBSERVATIONS: "15" → shows 15 observations ✓
- With CLAUDE_MEM_CONTEXT_OBSERVATIONS: "5" → shows 5 observations ✓
- Web UI settings now properly respected

**Files Changed:**
- src/hooks/context-hook.ts: Fixed path and field name in getContextDepth()
- plugin/scripts/context-hook.js: Built output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix GitHub issues #76, #74, #75 + session lifecycle improvements

Bug Fixes:
- Fix PM2 'Process 0 not found' error (#76): Changed pm2 restart to pm2 start (idempotent)
- Fix troubleshooting skill distribution (#74, #75): Moved from .claude/skills/ to plugin/skills/

Session Lifecycle Improvements:
- Added session lifecycle context to SDK agent prompt
- Changed summary framing from "final report" to "progress checkpoint"
- Updated summary prompts to use progressive tense ("so far", "actively working on")
- Added buildContinuationPrompt() for prompt #2+ to avoid re-initialization
- SessionManager now restores prompt counter from database
- SDKAgent conditionally uses init vs continuation prompt based on prompt number

These changes improve context-loading task handling and reduce incorrect "file not found" reports in summaries (partial fix for #73 - awaiting user feedback).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Release v5.3.0: Session lifecycle improvements and bug fixes

Improvements:
- Session prompt counter now restored from DB on worker restart
- Continuation prompts for prompt #2+ (lightweight, avoids re-init)
- Summary framing changed from "final report" to "progress checkpoint"
- PM2 start command (idempotent, fixes "Process 0 not found" error)
- Troubleshooting skill moved to plugin/skills/ for proper distribution

Technical changes:
- SessionManager loads prompt_counter from DB on initialization
- SDKAgent uses buildContinuationPrompt() for requests #2+
- Updated summary prompt to clarify mid-session checkpoints
- Fixed worker-utils.ts to use pm2 start instead of pm2 restart
- Moved .claude/skills/troubleshoot → plugin/skills/troubleshoot

Fixes:
- GitHub issue #76: PM2 "Process 0 not found" error
- GitHub issue #74, #75: Troubleshooting skill not distributed
- GitHub issue #73 (partial): Context-loading tasks reported as failed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-09 16:44:58 -05:00
Alex Newman
5482052c16 Release v5.2.2: Context hook now displays investigated and learned fields
Improvements:
- Context hook now displays 'investigated' and 'learned' fields from session summaries
- Enhanced SQL query to SELECT these fields from database
- Added color-coded display formatting (blue for investigated, yellow for learned)
- Updated TypeScript types to include nullable investigated and learned fields

Technical changes:
- Updated src/hooks/context-hook.ts to query and display new fields
- Updated built plugin/scripts/context-hook.js
- Bumped version to 5.2.2 in all metadata files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-08 12:55:53 -05:00
Alex Newman
f27c73b469 Fix project filter synchronization issues in viewer UI (#70)
* feat: Enhance session and summary handling

- Update SQL query in SessionStore to exclude null or empty projects.
- Add 'investigated' field to Summary interface for better tracking.
- Modify App component to handle pagination more efficiently based on current filters.
- Update SummaryCard to display the 'investigated' field if present.
- Refactor usePagination hook to reset pagination state when filters change.
- Adjust mergeAndDeduplicateByProject function to ensure it only merges unfiltered data.

* refactor: address PR feedback - remove redundancies and fix dependency cycles

Fixes based on PR #70 review feedback:

Required:
- Fixed useEffect dependency cycle in App.tsx (removed handleLoadMore from deps)

Recommended:
- Removed redundant filter detection from App.tsx (usePagination handles this)
- Removed redundant stateRef update effect from usePagination.ts
- Simplified mergeAndDeduplicateByProject by removing defensive validation
- Removed unused imports (useRef, useEffect)

All changes follow CLAUDE.md principles: DRY, fail-fast, no defensive programming.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: Reset paginated data arrays when filter changes

Critical fix for data mixing bug identified in PR review follow-up.

Problem:
When filter changes, usePagination correctly resets its offset to 0, but
the paginated state arrays (observations, summaries, prompts) were NOT
being reset. This caused data from different projects to mix together
because setState appends to the existing array.

Example:
- User views Project A: [A1, A2, A3]
- User switches to Project B
- API fetches [B1, B2, B3]
- setState does: [...prev, ...new] = [A1, A2, A3, B1, B2, B3] 

Solution:
Added a separate useEffect that resets all three paginated arrays when
currentFilter changes. This happens BEFORE handleLoadMore fetches new
data, ensuring clean state for the new filter.

Files changed:
- src/ui/viewer/App.tsx: Added useEffect to reset arrays on filter change
- plugin/ui/viewer-bundle.js: Built UI bundle

Testing:
1. Select Project A, verify data loads
2. Switch to Project B
3. Verify ONLY Project B data is shown (no mixing)
4. Switch back to "All Projects"
5. Verify all data appears correctly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: Combine filter change useEffect hooks for guaranteed order

Merged two separate useEffect hooks into one to:
1. Guarantee execution order (reset THEN load)
2. Reduce complexity (one hook instead of two)
3. Make intent clearer with single comment

Before:
- useEffect #1: handleLoadMore() on filter change
- useEffect #2: Reset arrays on filter change
- React could run these in any order

After:
- Single useEffect: Reset arrays THEN handleLoadMore()
- Execution order is now guaranteed

Files changed:
- src/ui/viewer/App.tsx: Combined useEffect hooks
- plugin/ui/viewer-bundle.js: Built UI bundle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-07 20:28:12 -05:00
Alex Newman
740d65b5a5 Add TypeScript Agent SDK reference documentation
- Introduced comprehensive API reference for the TypeScript Agent SDK.
- Documented installation instructions for the SDK.
- Detailed the main functions: `query()`, `tool()`, and `createSdkMcpServer()`.
- Defined various types including `Options`, `Query`, `AgentDefinition`, and more.
- Included message types and their structures, such as `SDKMessage`, `SDKAssistantMessage`, and `SDKUserMessage`.
- Explained hook types and their usage within the SDK.
- Provided detailed documentation for tool input and output types.
- Added sections on permission types and other relevant types for better clarity.
2025-11-07 15:05:31 -05:00
Alex Newman
4bc467f7ed feat: Implement Worker Service for long-running HTTP service with PM2 management
- Introduced WorkerService class to handle HTTP requests and manage sessions.
- Added endpoints for health check, session management, and data retrieval.
- Integrated ChromaSync for background data synchronization.
- Implemented SSE for real-time updates to connected clients.
- Added error handling and logging throughout the service.
- Cached Claude executable path for improved performance.
- Included settings management for user configuration.
- Established database interactions for session and observation management.
2025-11-07 13:26:13 -05:00
Alex Newman
3030f518b5 refactor: Complete rewrite of worker-utils.ts and cleanup of worker-service.ts
- Removed fragile PM2 string parsing and replaced with direct PM2 restart logic.
- Eliminated silent error handling in worker-utils.ts for better error visibility.
- Extracted duplicated session auto-creation logic into a new helper method getOrCreateSession() in worker-service.ts.
- Centralized configuration values and replaced magic numbers with named constants.
- Updated health check logic to ensure worker is restarted if unhealthy.
- Removed unnecessary getWorkerPort() wrapper function.
- Improved overall code quality and maintainability by applying DRY and YAGNI principles.
2025-11-06 22:00:07 -05:00
Alex Newman
79ff1849f0 feat: Add web-based viewer UI for real-time memory stream (#58)
* Add viewer HTML for claude-mem with live stream and settings interface

- Implemented a responsive layout with left and right columns for observations and settings.
- Added status indicators for connection state.
- Integrated server-sent events (SSE) for real-time updates on observations and summaries.
- Created dynamic project filter dropdown based on available observations.
- Developed settings section for environment variables and worker stats.
- Included functionality to save settings and load current stats from the server.
- Enhanced UI with custom styles for better user experience.

* Remove draft implementation plan for v5.1 web UI

* feat: Implement viewer UI with sidebar, feed, and settings management

- Add main viewer template (HTML) with styling for dark mode.
- Create App component to manage state and render Header, Feed, and Sidebar.
- Implement Feed component to display observations and summaries with filtering.
- Develop Header component for project selection and connection status.
- Create ObservationCard and SummaryCard components for displaying individual items.
- Implement Sidebar for settings management and displaying worker/database stats.
- Add hooks for managing SSE connections, settings, and stats fetching.
- Define types for observations, summaries, settings, and stats.

* Enhance UI components and improve layout

- Updated padding and layout for the feed and card components in viewer.html, viewer-template.html, and viewer.html to improve visual spacing and alignment.
- Increased card margins and padding for better readability and aesthetics.
- Adjusted font sizes, weights, and line heights for card titles and subtitles to enhance text clarity and hierarchy.
- Added a new feed-content class to center the feed items and limit their maximum width.
- Modified the Header component to improve the settings icon's SVG structure for better rendering.
- Enhanced the Sidebar component by adding a close button with an SVG icon, improving user experience for closing settings.
- Updated the Sidebar component's props to include an onClose function for handling sidebar closure.

* feat: Add user prompts feature with UI integration

- Implemented a new method in SessionStore to retrieve recent user prompts.
- Updated WorkerService to fetch and broadcast user prompts to clients.
- Enhanced the Feed component to display user prompts alongside observations and summaries.
- Created a new PromptCard component for rendering individual user prompts.
- Modified useSSE hook to handle new prompt events and processing status.
- Updated viewer templates and styles to accommodate the new prompts feature.

* feat: Add project filtering and pagination for observations

- Implemented `getAllProjects` method in `SessionStore` to retrieve unique projects from the database.
- Added `/api/observations` endpoint in `WorkerService` for paginated observations fetching.
- Enhanced `App` component to manage paginated observations and integrate with the new API.
- Updated `Feed` component to support infinite scrolling and loading more observations.
- Modified `Header` to display processing status.
- Refactored `PromptCard` to remove unnecessary processing indicator.
- Introduced `usePagination` hook to handle pagination logic for observations.
- Updated `useSSE` hook to include projects in the state.
- Adjusted types to accommodate new project data.

* Refactor viewer build process and remove deprecated HTML template

- Updated build-viewer.js to copy HTML template to build output with improved logging.
- Removed src/ui/viewer.html as it is no longer needed.
- Enhanced App component to merge observations while removing duplicates using useMemo.
- Improved Feed component to utilize a ref for onLoadMore callback and adjusted infinite scroll logic.
- Updated Sidebar component to use default settings from constants and removed redundant formatting functions.
- Refactored usePagination hook to streamline loading logic and prevent concurrent requests.
- Updated useSSE hook to use centralized API endpoints and improved reconnection logic.
- Refactored useSettings and useStats hooks to utilize constants for API endpoints and timing.
- Introduced ErrorBoundary component for better error handling in the viewer.
- Centralized API endpoint paths, default settings, timing constants, and UI-related constants into dedicated files.
- Added utility functions for formatting uptime and bytes for consistent display across components.

* feat: Enhance session management and pagination for user prompts, summaries, and observations

- Added project field to user prompts in the database and API responses.
- Implemented new API endpoints for fetching summaries and prompts with pagination.
- Updated WorkerService to handle new endpoints and filter results by project.
- Modified App component to manage paginated data for prompts and summaries.
- Refactored Feed component to remove unnecessary filtering and handle combined data.
- Improved usePagination hook to support multiple data types and project filtering.
- Adjusted useSSE hook to only load projects initially, with data fetched via pagination.
- Updated types to include project information for user prompts.

* feat: add SummarySkeleton component and data utility for merging items

- Introduced SummarySkeleton component for displaying loading state in the UI.
- Implemented mergeAndDeduplicateByProject utility function to merge real-time and paginated data while removing duplicates based on project filtering.

* Enhance UI and functionality of the viewer component

- Updated sidebar transition effects to use translate3d for improved performance.
- Added a sidebar header with title and connection status indicators.
- Modified the PromptCard to display project name instead of prompt number.
- Introduced a GitHub and X (Twitter) link in the header for easy access.
- Improved styling for setting descriptions and card hover effects.
- Enhanced Sidebar component to include connection status and updated layout.

* fix: reduce timeout for worker health checks and ensure proper responsiveness
2025-11-05 22:54:38 -05:00
copilot-swe-agent[bot]
7e75c0b22f Add proper error handling to PM2 process spawning
Co-authored-by: thedotmack <683968+thedotmack@users.noreply.github.com>
2025-11-05 02:42:19 +00:00
copilot-swe-agent[bot]
c506390007 Make ensureWorkerRunning async with health checks
Co-authored-by: thedotmack <683968+thedotmack@users.noreply.github.com>
2025-11-05 02:38:47 +00:00
Alex Newman
9fb43d8b06 Refactor hooks and worker service for improved session management and logging
- Updated new-hook.js, save-hook.js, and summary-hook.js to enhance logging and session handling.
- Simplified session auto-creation logic in worker-service.ts to prioritize observation data preservation.
- Added a blocking wait in ensureWorkerRunning function to prevent race conditions during worker startup.
- Improved error handling and logging consistency across hooks.
2025-11-04 15:28:45 -05:00
Alex Newman
c8a206b682 Enhance worker management and logging in summary-hook.js and worker-utils.ts
- Refactored logging functionality in summary-hook.js to improve clarity and consistency.
- Added checks in worker-utils.ts to prevent unnecessary restarts of the worker service, ensuring it only starts if not already running.
2025-11-04 14:40:34 -05:00
Alex Newman
c03457d2d4 Refactor hooks to ensure worker is running before processing
- Updated `save-hook.js`, `summary-hook.js`, `context-hook.ts`, `new-hook.ts`, and `save-hook.ts` to include a call to `ensureWorkerRunning()` at the beginning of their main functions. This ensures that the worker is active before any operations are performed.
- Cleaned up import statements in the affected files to include the new utility function from `worker-utils.js`.
- Minor adjustments to logging and error handling to improve robustness and clarity.
2025-11-04 14:28:53 -05:00
Alex Newman
a46a028ddb Refactor worker management and cleanup hooks
- Removed ensureWorkerRunning calls from multiple hooks (cleanup, context, new, save, summary) to streamline code and avoid unnecessary checks.
- Introduced fixed port usage for worker communication across hooks.
- Enhanced error handling in newHook, saveHook, and summaryHook to provide clearer messages for worker connection issues.
- Updated worker service to start without health checks, relying on PM2 for management.
- Cached Claude executable path to optimize repeated calls.
- Improved logging for better traceability of worker actions and errors.
2025-11-04 14:21:19 -05:00
Alex Newman
633f89a5fb feat: Implement user prompt syncing to Chroma and enhance timeline querying
- Added `getObservationById` method to retrieve observations by ID in SessionStore.
- Introduced `getSessionSummariesByIds` and `getUserPromptsByIds` methods for fetching session summaries and user prompts by IDs.
- Developed `getTimelineAroundTimestamp` and `getTimelineAroundObservation` methods to provide a unified timeline of observations, sessions, and prompts around a specified anchor point.
- Enhanced ChromaSync to format and sync user prompts, including a new `syncUserPrompt` method.
- Updated WorkerService to sync the latest user prompt to Chroma after updating the worker port.
- Created tests for timeline querying and MCP handler logic to ensure functionality.
- Documented the implementation plan for user prompts and timeline context tool in the Chroma search completion plan.
2025-11-03 16:55:33 -05:00
Alex Newman
c6bf72ca72 Simplify context display to type-only legend with color dots
Changes:
- Updated legend to show only observation types (bugfix, feature, refactor, change, discovery, decision)
- Mapped each type to a color dot emoji (🔴 bugfix, 🟢 feature, 🔵 refactor,  change, 🟡 discovery, 🟤 decision)
- Removed concept-based filtering and icon selection
- Simplified progressive disclosure instructions to reference types instead of concepts
- All observations now shown in timeline (no concept filtering)

Technical details:
- Modified: src/hooks/context-hook.ts:203-207 (legend)
- Modified: src/hooks/context-hook.ts:210-223 (progressive disclosure text)
- Modified: src/hooks/context-hook.ts:344-369 (icon mapping switched from concepts to types)
- Modified: src/hooks/context-hook.ts:168-173 (removed concept filtering)
- Rebuilt: plugin/scripts/context-hook.js

Rationale: Types are mutually exclusive and core to categorization, while concepts are multi-select metadata better accessed through MCP search tools. This simplifies the display and reduces visual noise.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-03 14:25:35 -05:00
Alex Newman
02130c49d1 close to win 2025-11-01 21:33:08 -04:00
Alex Newman
309e8a7139 Implement hybrid search: Chroma semantic + SQLite temporal
Core implementation:
- Added Chroma MCP client integration to search-server.ts
- Implemented queryChroma() helper with Python dict parsing
- Added VECTOR_DB_DIR constant to paths.ts
- Added SessionStore.getObservationsByIds() method

Search handlers updated:
- search_observations: Semantic-first with 90-day temporal filter
- find_by_concept/type/file: Metadata-first, semantic-enhanced ranking
- All handlers fall back to FTS5 if Chroma unavailable

Technical details:
- Direct MCP client usage (no abstractions)
- Regex parsing of Chroma Python dict responses
- Semantic ranking preserved in final results
- Graceful degradation to FTS5-only search

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 23:00:04 -04:00
Alex Newman
3bbacb8fa4 Release v4.3.3: Configurable session display and first-time setup UX
Improvements:
- Made session display count configurable (DISPLAY_SESSION_COUNT = 8)
- Added first-time setup detection with helpful user messaging
- Improved UX: First install message clarifies Plugin Hook Error display
- Cleaned up code comments

Technical changes:
- Updated src/hooks/context-hook.ts (configurable session count)
- Updated src/hooks/user-message-hook.ts (first-time setup detection)
- Rebuilt plugin/scripts/context-hook.js
- Rebuilt plugin/scripts/user-message-hook.js
- Bumped version to 4.3.3 in all metadata files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 01:22:47 -04:00
Alex Newman
15c55a57a3 Rename stderr-test-hook to user-message-hook for production
Changes:
- Renamed src/hooks/stderr-test-hook.ts to user-message-hook.ts
- Updated user-message-hook with production-ready messaging
- Updated scripts/build-hooks.js to build user-message-hook
- Updated plugin/hooks/hooks.json to reference user-message-hook.js
- Cleaned up old stderr-test-hook.js files
- Built and deployed user-message-hook.js to plugin directory

This hook displays context information to users via stderr, which is
currently the only way to show messages in Claude Code UI. It runs in
parallel with context-hook during SessionStart.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-26 23:14:19 -04:00
Alex Newman
df44bd8fd3 Fix double shebang: remove shebang from TS source files (esbuild adds it) 2025-10-26 00:01:04 -04:00
Alex Newman
e9c0ec45db Consolidate hooks: merge bin/hooks and hooks into single hooks/ directory
- Removed bin/hooks/ wrapper layer
- Moved all hook logic into consolidated hooks/*-hook.ts files
- Each hook now handles its own stdin/stdout/JSON wrapping
- Removed ALL try-catch blocks from context-hook (let errors surface)
- Updated build script to reference new src/hooks/ paths
- Reduced from 12+ files to 6 hook files

This simplifies the architecture and makes debugging actually possible.
2025-10-25 23:59:43 -04:00
Alex Newman
d363dfd668 Fix: Restore hookSpecificOutput JSON format for SessionStart hook
The previous 'fix' to output plain text broke context injection.
SessionStart hooks require hookSpecificOutput JSON format.

Changes:
- Restore JSON output with hookSpecificOutput wrapper
- Keep improved error handling with JSON error output
- Tested with real SessionStart hook input format
2025-10-25 23:53:14 -04:00
Alex Newman
c06abbc6f2 Fix: Add proper error handling to context hook stdin processing
- Wrap stdin event handler in try/catch to catch async errors
- Output errors to stdout so Claude can see them
- Show input preview and stack trace for debugging
- Remove outer try/catch that wasn't catching async errors
2025-10-25 23:51:53 -04:00
Alex Newman
609d8f5c88 Fix SessionStart hook to output plain text instead of JSON 2025-10-25 23:37:06 -04:00
Alex Newman
77885db345 feat: Add progressive disclosure usage instructions to context hook output 2025-10-25 01:36:39 -04:00
Alex Newman
50d504715d Refactor contextHook to improve session summary handling and timeline rendering
- Updated logic to retrieve recent summaries and observations, focusing on the last 4 summaries for better context.
- Simplified the extraction of unique session IDs from the recent summaries.
- Enhanced the timeline rendering to include both observations and summaries, grouped by day and file.
- Removed redundant queries for recent summaries and observations, streamlining the data retrieval process.
- Improved output formatting for better readability, including color-coded sections and clearer headers.
- Added detailed display of the most recent session's completed status and next steps.
2025-10-25 01:23:47 -04:00
Alex Newman
28d9c43f85 feat: Enhance context hook with detailed session observations and timeline
- Introduced new helper functions for parsing JSON, formatting dates, and estimating token counts.
- Implemented retrieval of recent session IDs and observations from the database.
- Added filtering of observations based on key concepts for a more relevant timeline.
- Enhanced output formatting to include a chronological timeline of recent activities grouped by day and file.
- Included a legend for better understanding of the timeline icons.
- Displayed recent session summaries with improved formatting and details.
- Added footer instructions for accessing records via MCP search.
2025-10-24 23:37:03 -04:00
Alex Newman
81fdf28347 Fix critical bug: getSessionById missing claude_session_id
Critical bugfix for NOT NULL constraint violation.

Problem:
- Worker service calls getSessionById(sessionDbId) to fetch session data
- Worker then uses dbSession.claude_session_id to create ActiveSession
- But getSessionById was NOT selecting claude_session_id from database
- Result: claudeSessionId = undefined in worker
- Caused: "NOT NULL constraint failed: sdk_sessions.claude_session_id" errors
- Impact: Observations and summaries couldn't be stored

Root cause:
- SessionStore.getSessionById() SQL query missing claude_session_id column
- Line 710-713: "SELECT id, sdk_session_id, project, user_prompt"
- Should be: "SELECT id, claude_session_id, sdk_session_id, project, user_prompt"

Fix:
- Added claude_session_id to SELECT query in getSessionById
- Updated return type to include claude_session_id: string
- Now worker correctly receives claude_session_id from database
- Session ID from hook flows properly through entire system

Files changed:
- src/services/sqlite/SessionStore.ts (getSessionById method)

Testing:
- Build succeeded
- Ready for PM2 restart and live testing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 22:18:03 -04:00
Alex Newman
322cb94c43 Release v4.2.6: Critical bugfix for observation validation
Critical Bugfix:
- Fixed overly defensive observation validation blocking observations from being saved
- Parser now NEVER skips observations - always saves them
- Invalid or missing type defaults to "change" (generic catch-all type)
- Removed validation requiring title, subtitle, and narrative fields
- Prevents critical data loss - partial observations better than no observations

Impact:
- Before: Missing title, subtitle, OR narrative caused entire observation to be discarded
- After: ALL observations preserved regardless of field completeness
- Even partial observations contain valuable data: concepts, files_read, files_modified, facts
- LLMs make mistakes - system must be resilient and save everything
- Consistent with v4.2.5 summary fix

Technical changes:
- Updated src/sdk/parser.ts:52-67 to never skip observations
- Uses "change" as fallback type for invalid/missing types (no schema change)
- Updated ParsedObservation interface to allow null for title, subtitle, narrative
- Updated SessionStore.storeObservation signature to accept nullable fields
- Updated built worker-service.cjs
- Bumped version to 4.2.6 in all metadata files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-24 21:25:44 -04:00
Alex Newman
0adbf38c39 fix: update getDirname function to support both ESM and CJS contexts 2025-10-23 23:03:48 -04:00
Alex Newman
15362d1aed Refactor getDirname function to only return __dirname for CJS context 2025-10-23 23:00:34 -04:00
Alex Newman
f556546994 feat: Optimize context hook file listings to save tokens
Improvements to SessionStart context hook file display:

1. **Remove redundant files**: Files in "Modified" list are now excluded from "Read" list
   - Prevents duplication when a file was both read and modified
   - Reduces token usage by eliminating redundant information

2. **Use relative paths**: Convert absolute paths to project-relative paths
   - Example: /Users/alexnewman/Scripts/claude-mem/src/hooks/context.ts → src/hooks/context.ts
   - Significantly reduces token consumption in context injection
   - Makes file references more readable and portable

Implementation:
- Added toRelativePath() helper function to convert paths
- Added filesModifiedSet.forEach(file => filesReadSet.delete(file)) to remove duplicates
- Applied to both files_read and files_modified when building Sets

Impact: Reduces token usage in Tier 1 summaries (most recent session) where file lists are displayed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-22 17:23:44 -04:00
Alex Newman
a57aba82a4 fix(context-hook): remove Learned from Tier 2
Tier 2 should only show Request + Completed + Date, not Learned.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 23:08:54 -04:00
Alex Newman
7b7a53ee19 feat(context-hook): simplify to 3-tier system with 10 sessions
New structure (10 sessions total):
- Tier 3 (oldest 6): Request + Date only
- Tier 2 (middle 3): Request + Learned + Completed + Date
- Tier 1 (most recent): Full verbosity (all fields)

This provides cleaner, more focused context with less redundancy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-21 23:07:23 -04:00