claude-brain 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/VERSION +1 -1
  2. package/assets/CLAUDE-unified.md +11 -0
  3. package/package.json +2 -1
  4. package/packs/backend/node.json +173 -0
  5. package/packs/core/javascript.json +176 -0
  6. package/packs/core/typescript.json +222 -0
  7. package/packs/frontend/react.json +254 -0
  8. package/packs/meta/testing.json +172 -0
  9. package/src/cli/bin.ts +14 -0
  10. package/src/cli/commands/chroma.ts +53 -17
  11. package/src/cli/commands/hooks.ts +214 -0
  12. package/src/cli/commands/pack.ts +197 -0
  13. package/src/cli/commands/serve.ts +34 -0
  14. package/src/config/defaults.ts +1 -1
  15. package/src/config/schema.ts +85 -2
  16. package/src/hooks/brain-hook.ts +110 -0
  17. package/src/hooks/capture.ts +161 -0
  18. package/src/hooks/deduplicator.ts +72 -0
  19. package/src/hooks/index.ts +19 -0
  20. package/src/hooks/installer.ts +181 -0
  21. package/src/hooks/passive-classifier.ts +366 -0
  22. package/src/hooks/queue.ts +122 -0
  23. package/src/hooks/session-tracker.ts +199 -0
  24. package/src/hooks/types.ts +47 -0
  25. package/src/memory/chroma/client.ts +1 -1
  26. package/src/memory/chroma/index.ts +1 -1
  27. package/src/memory/chroma/store.ts +29 -9
  28. package/src/memory/index.ts +1 -0
  29. package/src/memory/store.ts +1 -0
  30. package/src/packs/index.ts +9 -0
  31. package/src/packs/loader.ts +134 -0
  32. package/src/packs/manager.ts +204 -0
  33. package/src/packs/ranker.ts +78 -0
  34. package/src/packs/types.ts +81 -0
  35. package/src/routing/entity-extractor.ts +410 -0
  36. package/src/routing/intent-classifier.ts +229 -0
  37. package/src/routing/response-filter.ts +221 -0
  38. package/src/routing/router.ts +671 -0
  39. package/src/server/handlers/call-tool.ts +7 -0
  40. package/src/server/handlers/list-tools.ts +22 -5
  41. package/src/server/handlers/tools/brain.ts +85 -0
  42. package/src/server/handlers/tools/init-project.ts +47 -0
  43. package/src/server/handlers/tools/schemas.ts +12 -0
  44. package/src/server/http-api.ts +188 -0
  45. package/src/tools/registry.ts +9 -0
  46. package/src/tools/schemas.ts +33 -1
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Phase 17: Capture Engine
3
+ * Orchestrates passive classification + entity extraction with privacy filters.
4
+ */
5
+
6
+ import type { HookInput, CapturedKnowledge } from './types'
7
+ import type { HooksConfig } from '@/config/schema'
8
+ import { PassiveClassifier } from './passive-classifier'
9
+
10
+ // Reuse tech dictionaries from entity extractor for enrichment
11
+ const COMMON_TECH: Set<string> = new Set([
12
+ 'typescript', 'javascript', 'python', 'rust', 'go', 'java', 'ruby', 'php', 'swift', 'kotlin',
13
+ 'react', 'vue', 'angular', 'svelte', 'nextjs', 'nuxt', 'remix', 'astro', 'solid',
14
+ 'express', 'fastify', 'hono', 'nestjs', 'django', 'flask', 'fastapi', 'rails', 'spring',
15
+ 'mongodb', 'redis', 'postgresql', 'postgres', 'mysql', 'sqlite', 'dynamodb', 'firebase', 'supabase',
16
+ 'prisma', 'drizzle', 'typeorm', 'sequelize', 'chromadb', 'pinecone',
17
+ 'docker', 'kubernetes', 'aws', 'gcp', 'azure', 'vercel', 'netlify',
18
+ 'webpack', 'vite', 'esbuild', 'bun', 'deno', 'node', 'npm', 'yarn', 'pnpm',
19
+ 'jest', 'vitest', 'cypress', 'playwright',
20
+ 'tailwind', 'bootstrap', 'zod', 'trpc', 'graphql', 'rest',
21
+ 'jwt', 'oauth', 'openai', 'anthropic', 'langchain',
22
+ 'git', 'github', 'gitlab', 'eslint', 'prettier',
23
+ 'zustand', 'redux', 'pinia', 'mobx', 'jotai', 'recoil',
24
+ 'storybook', 'turborepo', 'nx',
25
+ 'microservices', 'serverless', 'monolith', 'ssr', 'ssg', 'spa', 'pwa', 'mcp', 'rag'
26
+ ])
27
+
28
+ const TECH_ALIASES: Record<string, string> = {
29
+ 'ts': 'typescript', 'js': 'javascript', 'py': 'python',
30
+ 'react.js': 'react', 'reactjs': 'react', 'vue.js': 'vue', 'vuejs': 'vue',
31
+ 'next.js': 'nextjs', 'nuxt.js': 'nuxt', 'nest.js': 'nestjs',
32
+ 'express.js': 'express', 'node.js': 'node', 'nodejs': 'node',
33
+ 'mongo': 'mongodb', 'pg': 'postgresql', 'k8s': 'kubernetes',
34
+ 'tailwindcss': 'tailwind', 'tailwind-css': 'tailwind',
35
+ 'gql': 'graphql', 'golang': 'go',
36
+ }
37
+
38
+ export class BrainCapture {
39
+ private classifier: PassiveClassifier
40
+ private config: HooksConfig
41
+
42
+ constructor(config?: Partial<HooksConfig>) {
43
+ this.config = {
44
+ enabled: config?.enabled ?? false,
45
+ capture: {
46
+ toolUse: config?.capture?.toolUse ?? true,
47
+ fileEdits: config?.capture?.fileEdits ?? true,
48
+ bashCommands: config?.capture?.bashCommands ?? true,
49
+ userMessages: config?.capture?.userMessages ?? true,
50
+ },
51
+ privacy: {
52
+ ignorePaths: config?.privacy?.ignorePaths ?? [],
53
+ ignoreProjects: config?.privacy?.ignoreProjects ?? [],
54
+ minConfidence: config?.privacy?.minConfidence ?? 0.7,
55
+ },
56
+ sessions: {
57
+ enabled: config?.sessions?.enabled ?? true,
58
+ idleTimeoutMinutes: config?.sessions?.idleTimeoutMinutes ?? 30,
59
+ minEventsForSummary: config?.sessions?.minEventsForSummary ?? 3,
60
+ },
61
+ deduplication: {
62
+ skipThreshold: config?.deduplication?.skipThreshold ?? 0.95,
63
+ mergeThreshold: config?.deduplication?.mergeThreshold ?? 0.85,
64
+ },
65
+ }
66
+ this.classifier = new PassiveClassifier()
67
+ }
68
+
69
+ /**
70
+ * Process a hook input event.
71
+ * Returns captured knowledge or null if nothing worth capturing.
72
+ */
73
+ process(input: HookInput): CapturedKnowledge | null {
74
+ if (!this.config.enabled) return null
75
+
76
+ // Privacy: check ignored paths
77
+ if (this.isPathIgnored(input.cwd)) return null
78
+
79
+ // Check capture toggles by tool type
80
+ if (!this.shouldCapture(input)) return null
81
+
82
+ // Classify tool output
83
+ const knowledge = this.classifier.classify(input)
84
+ if (!knowledge) return null
85
+
86
+ // Privacy: check ignored projects
87
+ if (knowledge.project && this.config.privacy.ignoreProjects.includes(knowledge.project)) {
88
+ return null
89
+ }
90
+
91
+ // Enrich with additional technology detection from content
92
+ knowledge.technologies = this.enrichTechnologies(knowledge)
93
+
94
+ // Filter by minimum confidence
95
+ if (knowledge.confidence < this.config.privacy.minConfidence) {
96
+ return null
97
+ }
98
+
99
+ return knowledge
100
+ }
101
+
102
+ /** Check if a path matches any ignore pattern */
103
+ private isPathIgnored(cwd: string): boolean {
104
+ if (!cwd || this.config.privacy.ignorePaths.length === 0) return false
105
+ const lowerCwd = cwd.toLowerCase()
106
+ return this.config.privacy.ignorePaths.some(pattern => {
107
+ const lowerPattern = pattern.toLowerCase()
108
+ // Simple glob: just check if pattern appears in path
109
+ if (lowerPattern.includes('*')) {
110
+ const regex = new RegExp(lowerPattern.replace(/\*/g, '.*'))
111
+ return regex.test(lowerCwd)
112
+ }
113
+ return lowerCwd.includes(lowerPattern)
114
+ })
115
+ }
116
+
117
+ /** Check if this tool type should be captured based on config */
118
+ private shouldCapture(input: HookInput): boolean {
119
+ const toolName = input.tool_name?.toLowerCase()
120
+ if (!toolName) return false
121
+
122
+ switch (toolName) {
123
+ case 'edit':
124
+ case 'write':
125
+ return this.config.capture.fileEdits
126
+ case 'bash':
127
+ return this.config.capture.bashCommands
128
+ default:
129
+ return this.config.capture.toolUse
130
+ }
131
+ }
132
+
133
+ /** Enrich technologies by scanning content text for known tech names */
134
+ private enrichTechnologies(knowledge: CapturedKnowledge): string[] {
135
+ const existing = new Set(knowledge.technologies)
136
+ const lower = knowledge.content.toLowerCase()
137
+ const words = lower.split(/[\s,;:()[\]{}"'`|/\\]+/)
138
+
139
+ for (const word of words) {
140
+ const cleaned = word.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')
141
+ if (cleaned.length < 2) continue
142
+
143
+ if (COMMON_TECH.has(cleaned) && !existing.has(cleaned)) {
144
+ existing.add(cleaned)
145
+ }
146
+ const alias = TECH_ALIASES[cleaned]
147
+ if (alias && !existing.has(alias)) {
148
+ existing.add(alias)
149
+ }
150
+ }
151
+
152
+ // Check multi-word aliases
153
+ for (const [alias, normalized] of Object.entries(TECH_ALIASES)) {
154
+ if ((alias.includes('.') || alias.includes('-')) && lower.includes(alias) && !existing.has(normalized)) {
155
+ existing.add(normalized)
156
+ }
157
+ }
158
+
159
+ return Array.from(existing)
160
+ }
161
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Phase 17: Smart Deduplicator
3
+ * Three-tier dedup before storage:
4
+ * >0.95 similarity → skip (exact duplicate)
5
+ * 0.85–0.95 similarity → merge (update existing)
6
+ * <0.85 similarity → store_new
7
+ */
8
+
9
+ import type { MemoryManager } from '@/memory'
10
+ import type { CapturedKnowledge, StoreAction } from './types'
11
+ import type { HooksConfig } from '@/config/schema'
12
+
13
+ export class SmartDeduplicator {
14
+ private skipThreshold: number
15
+ private mergeThreshold: number
16
+
17
+ constructor(config?: HooksConfig['deduplication']) {
18
+ this.skipThreshold = config?.skipThreshold ?? 0.95
19
+ this.mergeThreshold = config?.mergeThreshold ?? 0.85
20
+ }
21
+
22
+ /**
23
+ * Check captured knowledge against existing memory
24
+ * and decide: store_new, merge, or skip
25
+ */
26
+ async beforeStore(
27
+ knowledge: CapturedKnowledge,
28
+ memoryManager: MemoryManager
29
+ ): Promise<StoreAction> {
30
+ try {
31
+ const results = await memoryManager.searchRaw(knowledge.content, {
32
+ project: knowledge.project,
33
+ limit: 3,
34
+ minSimilarity: this.mergeThreshold,
35
+ })
36
+
37
+ if (!results || results.length === 0) {
38
+ return { action: 'store_new' }
39
+ }
40
+
41
+ const topResult = results[0]
42
+ const similarity = topResult.similarity ?? 0
43
+
44
+ if (similarity >= this.skipThreshold) {
45
+ return {
46
+ action: 'skip',
47
+ reason: `Duplicate (similarity: ${similarity.toFixed(3)})`,
48
+ }
49
+ }
50
+
51
+ if (similarity >= this.mergeThreshold) {
52
+ const existingId = topResult.memory?.id || topResult.id
53
+ const existingContent = topResult.memory?.content ||
54
+ topResult.decision?.decision ||
55
+ ''
56
+ const datestamp = new Date().toISOString().split('T')[0]
57
+ const mergedContent = `${existingContent}\n[Updated ${datestamp}]: ${knowledge.content}`
58
+
59
+ return {
60
+ action: 'merge',
61
+ existingId,
62
+ mergedContent,
63
+ }
64
+ }
65
+
66
+ return { action: 'store_new' }
67
+ } catch {
68
+ // If search fails, store as new to avoid data loss
69
+ return { action: 'store_new' }
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Phase 17: Passive Learning via Hooks
3
+ * Module re-exports
4
+ */
5
+
6
+ export type {
7
+ HookInput,
8
+ CapturedKnowledge,
9
+ KnowledgeType,
10
+ StoreAction,
11
+ HookStats,
12
+ } from './types'
13
+
14
+ export { PassiveClassifier } from './passive-classifier'
15
+ export { BrainCapture } from './capture'
16
+ export { SmartDeduplicator } from './deduplicator'
17
+ export { HookSessionTracker } from './session-tracker'
18
+ export { appendToQueue, readQueue, clearQueue, drainQueue, getQueuePath } from './queue'
19
+ export { installHooks, uninstallHooks, isHooksInstalled, getHookScriptPath } from './installer'
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Phase 17: Hook Installer
3
+ * Manages installation/removal of Claude Code hooks in ~/.claude/settings.json.
4
+ */
5
+
6
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs'
7
+ import { join, dirname } from 'node:path'
8
+ import { homedir } from 'node:os'
9
+ import { getClaudeBrainHome } from '@/config/home'
10
+
11
+ const CLAUDE_SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
12
+ const HOOK_MARKER = 'claude-brain-hook'
13
+
14
+ /** Get the path where the hook script should be installed */
15
+ export function getHookScriptPath(): string {
16
+ return join(getClaudeBrainHome(), 'hooks', 'brain-hook.ts')
17
+ }
18
+
19
+ /** Read Claude Code settings.json, creating if needed */
20
+ function readSettings(): Record<string, any> {
21
+ if (!existsSync(CLAUDE_SETTINGS_PATH)) return {}
22
+ try {
23
+ return JSON.parse(readFileSync(CLAUDE_SETTINGS_PATH, 'utf-8'))
24
+ } catch {
25
+ return {}
26
+ }
27
+ }
28
+
29
+ /** Write settings.json atomically (write temp → rename) */
30
+ function writeSettings(settings: Record<string, any>): void {
31
+ const dir = dirname(CLAUDE_SETTINGS_PATH)
32
+ if (!existsSync(dir)) {
33
+ mkdirSync(dir, { recursive: true })
34
+ }
35
+
36
+ const tmpPath = CLAUDE_SETTINGS_PATH + '.tmp'
37
+ writeFileSync(tmpPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8')
38
+ renameSync(tmpPath, CLAUDE_SETTINGS_PATH)
39
+ }
40
+
41
+ /** Build the hook command string */
42
+ function buildHookCommand(event: string): string {
43
+ const scriptPath = getHookScriptPath()
44
+ return `bun "${scriptPath}" --event ${event} # ${HOOK_MARKER}`
45
+ }
46
+
47
+ /**
48
+ * Install Claude Brain hooks into Claude Code settings.
49
+ * Adds PostToolUse and Stop hook entries.
50
+ */
51
+ export function installHooks(): { installed: boolean; message: string } {
52
+ if (isHooksInstalled()) {
53
+ return { installed: true, message: 'Hooks already installed' }
54
+ }
55
+
56
+ const settings = readSettings()
57
+
58
+ // Ensure hooks object exists
59
+ if (!settings.hooks) settings.hooks = {}
60
+
61
+ // PostToolUse hook — runs on every tool completion
62
+ if (!settings.hooks.PostToolUse) settings.hooks.PostToolUse = []
63
+ settings.hooks.PostToolUse.push({
64
+ matcher: '',
65
+ hooks: [{
66
+ type: 'command',
67
+ command: buildHookCommand('PostToolUse'),
68
+ }],
69
+ })
70
+
71
+ // Stop hook — triggers session-end summary
72
+ if (!settings.hooks.Stop) settings.hooks.Stop = []
73
+ settings.hooks.Stop.push({
74
+ matcher: '',
75
+ hooks: [{
76
+ type: 'command',
77
+ command: buildHookCommand('Stop'),
78
+ }],
79
+ })
80
+
81
+ writeSettings(settings)
82
+
83
+ // Copy hook script to install location
84
+ copyHookScript()
85
+
86
+ return { installed: true, message: 'Hooks installed successfully' }
87
+ }
88
+
89
+ /**
90
+ * Remove Claude Brain hooks from Claude Code settings.
91
+ */
92
+ export function uninstallHooks(): { uninstalled: boolean; message: string } {
93
+ if (!isHooksInstalled()) {
94
+ return { uninstalled: true, message: 'Hooks not installed' }
95
+ }
96
+
97
+ const settings = readSettings()
98
+
99
+ if (settings.hooks) {
100
+ // Remove our entries from PostToolUse
101
+ if (Array.isArray(settings.hooks.PostToolUse)) {
102
+ settings.hooks.PostToolUse = settings.hooks.PostToolUse.filter(
103
+ (entry: any) => !isOurHookEntry(entry)
104
+ )
105
+ if (settings.hooks.PostToolUse.length === 0) {
106
+ delete settings.hooks.PostToolUse
107
+ }
108
+ }
109
+
110
+ // Remove our entries from Stop
111
+ if (Array.isArray(settings.hooks.Stop)) {
112
+ settings.hooks.Stop = settings.hooks.Stop.filter(
113
+ (entry: any) => !isOurHookEntry(entry)
114
+ )
115
+ if (settings.hooks.Stop.length === 0) {
116
+ delete settings.hooks.Stop
117
+ }
118
+ }
119
+
120
+ // Clean up empty hooks object
121
+ if (Object.keys(settings.hooks).length === 0) {
122
+ delete settings.hooks
123
+ }
124
+ }
125
+
126
+ writeSettings(settings)
127
+
128
+ return { uninstalled: true, message: 'Hooks uninstalled successfully' }
129
+ }
130
+
131
+ /**
132
+ * Check if hooks are already installed.
133
+ */
134
+ export function isHooksInstalled(): boolean {
135
+ const settings = readSettings()
136
+ if (!settings.hooks) return false
137
+
138
+ const hasPostToolUse = Array.isArray(settings.hooks.PostToolUse) &&
139
+ settings.hooks.PostToolUse.some((entry: any) => isOurHookEntry(entry))
140
+
141
+ const hasStop = Array.isArray(settings.hooks.Stop) &&
142
+ settings.hooks.Stop.some((entry: any) => isOurHookEntry(entry))
143
+
144
+ return hasPostToolUse || hasStop
145
+ }
146
+
147
+ /** Check if a hook entry belongs to us (by marker in command) */
148
+ function isOurHookEntry(entry: any): boolean {
149
+ if (!entry || !Array.isArray(entry.hooks)) return false
150
+ return entry.hooks.some(
151
+ (h: any) => typeof h.command === 'string' && h.command.includes(HOOK_MARKER)
152
+ )
153
+ }
154
+
155
+ /** Copy the hook script to the install location */
156
+ function copyHookScript(): void {
157
+ const destPath = getHookScriptPath()
158
+ const destDir = dirname(destPath)
159
+
160
+ if (!existsSync(destDir)) {
161
+ mkdirSync(destDir, { recursive: true })
162
+ }
163
+
164
+ // Find source script relative to this file
165
+ // In development: src/hooks/brain-hook.ts
166
+ // In production: dist/hooks/brain-hook.js
167
+ const srcPath = join(dirname(new URL(import.meta.url).pathname), 'brain-hook.ts')
168
+
169
+ if (existsSync(srcPath)) {
170
+ const content = readFileSync(srcPath, 'utf-8')
171
+ writeFileSync(destPath, content, 'utf-8')
172
+ } else {
173
+ // Try .js extension for compiled version
174
+ const jsSrcPath = srcPath.replace('.ts', '.js')
175
+ if (existsSync(jsSrcPath)) {
176
+ const content = readFileSync(jsSrcPath, 'utf-8')
177
+ writeFileSync(destPath, content, 'utf-8')
178
+ }
179
+ // If neither exists, the hook script will need to be installed separately
180
+ }
181
+ }