Skip to content

Comments

feat: hooks system, semantic search, metrics tool, and code review fixes#97

Merged
kevintseng merged 25 commits intomainfrom
develop
Feb 25, 2026
Merged

feat: hooks system, semantic search, metrics tool, and code review fixes#97
kevintseng merged 25 commits intomainfrom
develop

Conversation

@kevintseng
Copy link
Collaborator

@kevintseng kevintseng commented Feb 24, 2026

Summary

  • Claude Code Hooks System — 7 hooks for session lifecycle automation (smart routing, planning enforcement, dry-run gate, code review reminder, pattern detection, session archiving)
  • Semantic Search — KnowledgeGraph now supports vector similarity search via sqlite-vec with keyword fallback
  • memesh-metrics MCP Tool — Exposes session, routing, and memory metrics
  • Smart Task Analysisbuddy-do detects task type, extracts metadata, queries related context from KG
  • 14 Code Review Fixes — 6 CRITICAL + 8 MAJOR issues resolved across 3 rounds of comprehensive review

Key Fixes

  • getEntity() exact match instead of fuzzy FTS5 search
  • post-commit hook exit code 0 (never blocks Claude Code)
  • Entity name collision prevention with timestamps
  • sqliteQuery/sqliteBatch proper error propagation (null vs empty string)
  • Orphaned entity cleanup on batch failure
  • Metrics tool: PathResolver for DB path, bounded audit log read, os.homedir() fallback
  • UnifiedMemoryStore.update() TOCTOU race fix
  • Session file growth cap (1000 tool calls)
  • Windows compatibility (fileURLToPath)
  • Keyword fallback similarity 0.5 for honest hybrid search scoring

Stats

  • 29 commits, 56 source files changed (+6004 / -871)
  • 1817 unit tests + 15 hook tests passing
  • TypeScript compiles clean
  • Documentation updated (CHANGELOG, CONTRIBUTING, MIGRATION)

Test plan

  • npm test — 1817/1817 pass (112 test files)
  • node scripts/hooks/__tests__/hooks.test.js — 15/15 pass
  • npx tsc --noEmit — zero errors
  • npm run build — successful, dist synced with plugin mirror
  • Dogfood: memesh-metrics returns real data (session, routing, memory)
  • Dogfood: getEntity('test-auth') returns null (exact match works)
  • Dogfood: hybridSearch keyword results use 0.5 similarity

🤖 Generated with Claude Code

kevintseng and others added 18 commits February 16, 2026 16:26
- Add MIGRATION.md with comprehensive migration instructions
- Add migration notice to README.md and README.zh-TW.md
- Document package rename from @pcircle/claude-code-buddy-mcp to @pcircle/memesh
- Provide clear migration steps for CLI, MCP, and plugin users
- Include FAQ and backward compatibility information

Related:
- Old package deprecated on npm with migration message
- v2.8.11 published as @pcircle/memesh

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
**Problem 1: Cloud push fails with 400 error at limit > 46**
Root cause: Memory content too large or validation issues

Solution:
- Add content length validation (max 10KB per memory, 1KB per observation)
- Truncate long content with "[truncated]" suffix
- Limit tags to 20 per memory
- Add detailed error logging with batch offset tracking

**Problem 2: No MCP tool for agent registration**
CloudClient had registerAgent but not exposed

Solution:
- Create memesh-agent-register MCP tool
- Add tool definition with full schema
- Add output schema for agent info
- Wire up ToolRouter handler
- Support agentType, agentName, agentVersion, capabilities

Files changed:
- src/mcp/tools/memesh-cloud-sync.ts - Content validation
- src/mcp/tools/memesh-agent-register.ts - New tool (123 lines)
- src/mcp/ToolDefinitions.ts - Add agent register definition
- src/mcp/ToolRouter.ts - Add routing handler
- src/mcp/schemas/OutputSchemas.ts - Add output schema

Testing required:
1. Restart Claude Code
2. Test: memesh-cloud-sync push with limit 100
3. Test: memesh-agent-register with agentType="claude-code"

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Tags limit: 20 → 10 (API max)
- Agent registration: enforce valid agentType enum, sanitize agentName spaces
- Update tool descriptions with correct enum values
- Fix compliance test: tool count 8 → 9

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Update RELEASE_PROCESS.md with branch-based release flow
- Update CONTRIBUTING.md with branch strategy and PR rules
- Upgrade hookify rule from warn to block for push to main

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…roxy startup

setupStdinHandler() was called after await connectToDaemon(), causing a race
condition: when stopStdinBufferingAndReplay() resumed stdin, the buffered
'initialize' message fired before the listener was registered, losing the
message silently. Claude Code would wait 30s for a response, then close stdin.

Fix: move setupStdinHandler() before the first await so the listener is
registered synchronously before any event loop iteration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
A2A source code was previously removed from src/ but build artifacts
and demo files were left behind. Remove 167 tracked files (dist/a2a,
A2A tool handlers, hooks, and demo scene).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
…earch

Wire up the existing embeddings infrastructure (VectorExtension + EmbeddingService)
into KnowledgeGraph. Adds semanticSearch(), hybridSearch(), and auto-embedding
generation on entity creation. Graceful fallback to FTS5-only when sqlite-vec
is unavailable.

Also: remove unused axios dep, remove 4 dead scripts, upgrade ESLint 9→10.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ne bootstrap

Wrap MCP server creation and socket server start with try-catch in daemon mode.
Add proxy connection failure fallback to standalone. Classify bootstrap errors
(EACCES/ENOSPC) for clearer diagnostics. Add recovery hints for common failures.

Closes #18

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Mock fs.existsSync for credentials file reads so tests don't pick up
real API keys from the dev machine's credentials file. Fixes 7 pre-existing
test failures on machines with MEMESH_API_KEY configured.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
KnowledgeGraph (3 CRITICAL + 2 MAJOR):
- Track initVectorSearch() promise; search methods now await init completion
- Replace single pendingEmbeddings with Set to prevent promise overwrites
- Remove unsafe non-null assertion, add proper null check with fallback
- close() now awaits all pending embeddings before closing database
- Import SemanticSearchResult from KG instead of duplicate in buddy-remember

server-bootstrap.ts (1 CRITICAL + 3 MAJOR):
- Add transport.cleanup() and stopStdinBufferingAndReplay() on MCP init failure
- Move setMcpHandler() after mcpServer.start() to prevent handler race
- Add proxyClient.stop() on proxy connection failure
- Add socket error codes (EADDRINUSE, ECONNREFUSED) to error classification

MeMeshCloudClient.test.ts (1 CRITICAL + 1 MAJOR):
- Simplify fs mock to named exports only (remove fragile default export)
- Use exact path matching (endsWith) instead of broad includes()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
BuddyHandlers.handleBuddyRemember() was calling executeBuddyRemember()
without the knowledgeGraph parameter, causing all semantic/hybrid search
to fall back to keyword-only search via projectMemory.search().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…ipeline test

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@github-actions github-actions bot added enhancement New feature or request documentation Improvements or additions to documentation test Test improvements area: mcp MCP Server and tools area: memory Memory and Knowledge Graph area: tools MCP tool definitions and removed enhancement New feature or request labels Feb 24, 2026
…ed skills

Add 3 new Claude Code hooks and bundled skills installation:

- PreToolUse hook: enforces code review before git commit by checking
  session state and injecting reminder context if review not done
- SubagentStop hook: captures code reviewer results to MeMesh KG and
  marks review as complete for pre-commit enforcement
- PostCommit hook: saves git commit context (hash, files, stats) to KG
- PostToolUse: add code review tracking for Skill/Task tool invocations
- SessionStart: add CLAUDE.md reload into context on startup
- Bundled skills: postinstall now copies comprehensive-code-review skill
  to ~/.claude/skills/sa:comprehensive-code-review/
- Remove disabled hookify rule (block-unauthorized-publish)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@github-actions github-actions bot added scripts Scripts and tooling enhancement New feature or request labels Feb 24, 2026
Phase 1 of v2.9 Smart Hooks implementation:
- 1A: sqliteBatch for batched DB operations, session cache, async writes
- 1B: Smart Router with 4 PreToolUse handlers (code review, model routing,
  planning enforcement, dry-run gate), file/test tracking
- 1C: Smart buddy-do with KG context recall and task type detection,
  new memesh-metrics MCP tool for session observability

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
kevintseng and others added 4 commits February 25, 2026 08:10
5 CRITICAL fixes:
- Hook exit codes: process.exit(1) → exit(0) in post-tool-use, stop, session-start
  (exit(1) blocks Claude Code tool execution)
- Output schema tests aligned with new buddyDo schema format

10 MAJOR fixes:
- memesh-metrics: split STATE_DIR into correct paths (hooks→~/.claude/state, routing→~/.memesh)
- memesh-metrics: remove stateDir from output (info leak)
- post-tool-use: track async session write promise in pendingWrites
- hook-utils: sqliteBatch pipes SQL via stdin to avoid E2BIG on large batches
- hook-utils: escapeSQL handles numbers and booleans correctly
- hook-utils/stop: fix sqliteBatchEntity doc (2→3 spawns)
- session-start: replace pipe-split parsing with sqliteQueryJSON (safe for | in data)
- ToolDefinitions: buddy-do readOnlyHint false (writes to autoTracker)
- OutputSchemas: buddyDo schema matches actual handler output
- hooks.test.js: replace vacuous return-true fallbacks with proper assertions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
6 issues fixed:
- post-tool-use: track updateSessionContext async write promise in pendingWrites
- pre-tool-use: guard rule.subagentType against undefined (prevents TypeError on malformed config)
- post-tool-use: fix path comparison from substring (.includes) to path-prefix (startsWith)
- tests: add output schema validation for generateTests, cloudSync, agentRegister, memeshMetrics
- tests: tighten compliance audit outputSchema tolerance from 7 to 0
- post-commit: fix doc comment "2 spawns" → "3 spawns"

Test results: 1776/1776 pass, hook tests 15/15 pass, MCP compliance 100%

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
CRITICAL fixes:
- getEntity() now uses exact SQL match instead of fuzzy FTS5 search
- post-commit hook exits 0 instead of 1 to never block Claude Code
- subagent-stop entity names include timestamp to prevent daily collision
- sqliteQuery returns null on error (not '') so callers detect failures
- sqliteBatch propagates errors; sqliteBatchEntity cleans up orphans
- initVectorSearch/deleteEntity catch blocks now log error context

MAJOR fixes:
- memesh-metrics: bounded audit log read (256KB tail), PathResolver
  for DB path, os.homedir() fallback instead of /tmp
- UnifiedMemoryStore.update() returns false on concurrent delete
- post-tool-use toolCalls array capped at 1000
- pre-tool-use uses fileURLToPath for Windows compatibility
- readStdin fast-path for already-closed stdin
- Keyword fallback similarity 0.5 instead of 1.0 for honest scoring

Refactored subagent-stop to use sqliteBatchEntity (3 spawns vs N+2).
All 1817 tests + 15 hook tests pass.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- CHANGELOG: Add hooks system, metrics tool, semantic search, buddy-do
  task analysis, and all 14 code review fixes to Unreleased section
- CONTRIBUTING: Update version 2.8.10 → 2.8.11, date to 2026-02-25
- MIGRATION: Clarify data directory fallback behavior (~/.memesh first,
  then ~/.claude-code-buddy automatically)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@kevintseng kevintseng changed the title feat: semantic search integration & comprehensive stability fixes feat: hooks system, semantic search, metrics tool, and code review fixes Feb 25, 2026
if (!fs.existsSync(MEMESH_DB_PATH)) return false;
if (!lastMessage || lastMessage.length < 50) return false;

const now = new Date().toISOString();
Minor release: hooks system, semantic search, metrics tool,
14 code review fixes, documentation updates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@kevintseng kevintseng merged commit 014e697 into main Feb 25, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp MCP Server and tools area: memory Memory and Knowledge Graph area: tools MCP tool definitions documentation Improvements or additions to documentation enhancement New feature or request scripts Scripts and tooling test Test improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant