neuralbrain 0.0.0-stage → 0.0.1
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/.dockerignore +11 -0
- package/.env.example +245 -0
- package/Dockerfile +65 -0
- package/LICENSE +44 -0
- package/README.md +312 -2
- package/dist/ai/chat.d.ts +45 -0
- package/dist/ai/chat.d.ts.map +1 -0
- package/dist/ai/chat.js +153 -0
- package/dist/ai/chat.js.map +1 -0
- package/dist/ai/circuitBreaker.d.ts +35 -0
- package/dist/ai/circuitBreaker.d.ts.map +1 -0
- package/dist/ai/circuitBreaker.js +95 -0
- package/dist/ai/circuitBreaker.js.map +1 -0
- package/dist/ai/config.d.ts +88 -0
- package/dist/ai/config.d.ts.map +1 -0
- package/dist/ai/config.js +255 -0
- package/dist/ai/config.js.map +1 -0
- package/dist/ai/vendors.d.ts +58 -0
- package/dist/ai/vendors.d.ts.map +1 -0
- package/dist/ai/vendors.js +223 -0
- package/dist/ai/vendors.js.map +1 -0
- package/dist/app.d.ts +4 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +1013 -0
- package/dist/app.js.map +1 -0
- package/dist/cli.d.ts +133 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +912 -0
- package/dist/cli.js.map +1 -0
- package/dist/consolidation/candidates.d.ts +34 -0
- package/dist/consolidation/candidates.d.ts.map +1 -0
- package/dist/consolidation/candidates.js +150 -0
- package/dist/consolidation/candidates.js.map +1 -0
- package/dist/consolidation/fixtures.d.ts +25 -0
- package/dist/consolidation/fixtures.d.ts.map +1 -0
- package/dist/consolidation/fixtures.js +400 -0
- package/dist/consolidation/fixtures.js.map +1 -0
- package/dist/consolidation/gate.d.ts +39 -0
- package/dist/consolidation/gate.d.ts.map +1 -0
- package/dist/consolidation/gate.js +286 -0
- package/dist/consolidation/gate.js.map +1 -0
- package/dist/consolidation/runner.d.ts +63 -0
- package/dist/consolidation/runner.d.ts.map +1 -0
- package/dist/consolidation/runner.js +171 -0
- package/dist/consolidation/runner.js.map +1 -0
- package/dist/dashboard/clientScript.d.ts +2 -0
- package/dist/dashboard/clientScript.d.ts.map +1 -0
- package/dist/dashboard/clientScript.js +4212 -0
- package/dist/dashboard/clientScript.js.map +1 -0
- package/dist/dashboard/html.d.ts +2 -0
- package/dist/dashboard/html.d.ts.map +1 -0
- package/dist/dashboard/html.js +554 -0
- package/dist/dashboard/html.js.map +1 -0
- package/dist/dashboard/styles.d.ts +2 -0
- package/dist/dashboard/styles.d.ts.map +1 -0
- package/dist/dashboard/styles.js +1283 -0
- package/dist/dashboard/styles.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +124 -0
- package/dist/index.js.map +1 -0
- package/dist/learning/embedWorker.d.ts +58 -0
- package/dist/learning/embedWorker.d.ts.map +1 -0
- package/dist/learning/embedWorker.js +552 -0
- package/dist/learning/embedWorker.js.map +1 -0
- package/dist/learning/embedding.d.ts +52 -0
- package/dist/learning/embedding.d.ts.map +1 -0
- package/dist/learning/embedding.js +511 -0
- package/dist/learning/embedding.js.map +1 -0
- package/dist/learning/engine.d.ts +20 -0
- package/dist/learning/engine.d.ts.map +1 -0
- package/dist/learning/engine.js +69 -0
- package/dist/learning/engine.js.map +1 -0
- package/dist/learning/search.d.ts +4 -0
- package/dist/learning/search.d.ts.map +1 -0
- package/dist/learning/search.js +509 -0
- package/dist/learning/search.js.map +1 -0
- package/dist/learning/storeMeta.d.ts +11 -0
- package/dist/learning/storeMeta.d.ts.map +1 -0
- package/dist/learning/storeMeta.js +100 -0
- package/dist/learning/storeMeta.js.map +1 -0
- package/dist/learning/types.d.ts +101 -0
- package/dist/learning/types.d.ts.map +1 -0
- package/dist/learning/types.js +3 -0
- package/dist/learning/types.js.map +1 -0
- package/dist/lib/brainHome.d.ts +28 -0
- package/dist/lib/brainHome.d.ts.map +1 -0
- package/dist/lib/brainHome.js +104 -0
- package/dist/lib/brainHome.js.map +1 -0
- package/dist/lib/db.d.ts +10 -0
- package/dist/lib/db.d.ts.map +1 -0
- package/dist/lib/db.js +589 -0
- package/dist/lib/db.js.map +1 -0
- package/dist/lib/logger.d.ts +3 -0
- package/dist/lib/logger.d.ts.map +1 -0
- package/dist/lib/logger.js +11 -0
- package/dist/lib/logger.js.map +1 -0
- package/dist/lib/projectSlug.d.ts +61 -0
- package/dist/lib/projectSlug.d.ts.map +1 -0
- package/dist/lib/projectSlug.js +273 -0
- package/dist/lib/projectSlug.js.map +1 -0
- package/dist/lib/redactSecrets.d.ts +7 -0
- package/dist/lib/redactSecrets.d.ts.map +1 -0
- package/dist/lib/redactSecrets.js +90 -0
- package/dist/lib/redactSecrets.js.map +1 -0
- package/dist/lib/scope.d.ts +54 -0
- package/dist/lib/scope.d.ts.map +1 -0
- package/dist/lib/scope.js +103 -0
- package/dist/lib/scope.js.map +1 -0
- package/dist/lib/spool.d.ts +23 -0
- package/dist/lib/spool.d.ts.map +1 -0
- package/dist/lib/spool.js +317 -0
- package/dist/lib/spool.js.map +1 -0
- package/dist/lib/sqlite.d.ts +50 -0
- package/dist/lib/sqlite.d.ts.map +1 -0
- package/dist/lib/sqlite.js +130 -0
- package/dist/lib/sqlite.js.map +1 -0
- package/dist/lib/tls.d.ts +34 -0
- package/dist/lib/tls.d.ts.map +1 -0
- package/dist/lib/tls.js +212 -0
- package/dist/lib/tls.js.map +1 -0
- package/dist/mcp/server.d.ts +231 -0
- package/dist/mcp/server.d.ts.map +1 -0
- package/dist/mcp/server.js +615 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/memory/actionStore.d.ts +75 -0
- package/dist/memory/actionStore.d.ts.map +1 -0
- package/dist/memory/actionStore.js +239 -0
- package/dist/memory/actionStore.js.map +1 -0
- package/dist/memory/deadLetterStore.d.ts +30 -0
- package/dist/memory/deadLetterStore.d.ts.map +1 -0
- package/dist/memory/deadLetterStore.js +91 -0
- package/dist/memory/deadLetterStore.js.map +1 -0
- package/dist/memory/embedQueueStore.d.ts +32 -0
- package/dist/memory/embedQueueStore.d.ts.map +1 -0
- package/dist/memory/embedQueueStore.js +143 -0
- package/dist/memory/embedQueueStore.js.map +1 -0
- package/dist/memory/failurePatternStore.d.ts +37 -0
- package/dist/memory/failurePatternStore.d.ts.map +1 -0
- package/dist/memory/failurePatternStore.js +179 -0
- package/dist/memory/failurePatternStore.js.map +1 -0
- package/dist/memory/graphStore.d.ts +38 -0
- package/dist/memory/graphStore.d.ts.map +1 -0
- package/dist/memory/graphStore.js +229 -0
- package/dist/memory/graphStore.js.map +1 -0
- package/dist/memory/noteStore.d.ts +58 -0
- package/dist/memory/noteStore.d.ts.map +1 -0
- package/dist/memory/noteStore.js +280 -0
- package/dist/memory/noteStore.js.map +1 -0
- package/dist/memory/observationStore.d.ts +40 -0
- package/dist/memory/observationStore.d.ts.map +1 -0
- package/dist/memory/observationStore.js +213 -0
- package/dist/memory/observationStore.js.map +1 -0
- package/dist/memory/projectRename.d.ts +14 -0
- package/dist/memory/projectRename.d.ts.map +1 -0
- package/dist/memory/projectRename.js +105 -0
- package/dist/memory/projectRename.js.map +1 -0
- package/dist/memory/rollupSweeper.d.ts +36 -0
- package/dist/memory/rollupSweeper.d.ts.map +1 -0
- package/dist/memory/rollupSweeper.js +235 -0
- package/dist/memory/rollupSweeper.js.map +1 -0
- package/dist/memory/sessionStore.d.ts +81 -0
- package/dist/memory/sessionStore.d.ts.map +1 -0
- package/dist/memory/sessionStore.js +285 -0
- package/dist/memory/sessionStore.js.map +1 -0
- package/dist/memory/trajectoryStore.d.ts +86 -0
- package/dist/memory/trajectoryStore.d.ts.map +1 -0
- package/dist/memory/trajectoryStore.js +528 -0
- package/dist/memory/trajectoryStore.js.map +1 -0
- package/dist/middleware/auth.d.ts +30 -0
- package/dist/middleware/auth.d.ts.map +1 -0
- package/dist/middleware/auth.js +387 -0
- package/dist/middleware/auth.js.map +1 -0
- package/dist/middleware/rateLimiter.d.ts +13 -0
- package/dist/middleware/rateLimiter.d.ts.map +1 -0
- package/dist/middleware/rateLimiter.js +153 -0
- package/dist/middleware/rateLimiter.js.map +1 -0
- package/dist/middleware/tracing.d.ts +15 -0
- package/dist/middleware/tracing.d.ts.map +1 -0
- package/dist/middleware/tracing.js +53 -0
- package/dist/middleware/tracing.js.map +1 -0
- package/dist/routes/dashboard.d.ts +2 -0
- package/dist/routes/dashboard.d.ts.map +1 -0
- package/dist/routes/dashboard.js +443 -0
- package/dist/routes/dashboard.js.map +1 -0
- package/dist/routes/learning.d.ts +2 -0
- package/dist/routes/learning.d.ts.map +1 -0
- package/dist/routes/learning.js +46 -0
- package/dist/routes/learning.js.map +1 -0
- package/dist/routes/mcp.d.ts +8 -0
- package/dist/routes/mcp.d.ts.map +1 -0
- package/dist/routes/mcp.js +316 -0
- package/dist/routes/mcp.js.map +1 -0
- package/dist/routes/memories.d.ts +2 -0
- package/dist/routes/memories.d.ts.map +1 -0
- package/dist/routes/memories.js +33 -0
- package/dist/routes/memories.js.map +1 -0
- package/dist/scripts/createApiKey.d.ts +2 -0
- package/dist/scripts/createApiKey.d.ts.map +1 -0
- package/dist/scripts/createApiKey.js +78 -0
- package/dist/scripts/createApiKey.js.map +1 -0
- package/dist/scripts/doctor.d.ts +24 -0
- package/dist/scripts/doctor.d.ts.map +1 -0
- package/dist/scripts/doctor.js +332 -0
- package/dist/scripts/doctor.js.map +1 -0
- package/dist/scripts/installAgent.d.ts +80 -0
- package/dist/scripts/installAgent.d.ts.map +1 -0
- package/dist/scripts/installAgent.js +1046 -0
- package/dist/scripts/installAgent.js.map +1 -0
- package/dist/scripts/migrateAgentMemory.d.ts +16 -0
- package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
- package/dist/scripts/migrateAgentMemory.js +209 -0
- package/dist/scripts/migrateAgentMemory.js.map +1 -0
- package/dist/scripts/smokeTest.d.ts +16 -0
- package/dist/scripts/smokeTest.d.ts.map +1 -0
- package/dist/scripts/smokeTest.js +150 -0
- package/dist/scripts/smokeTest.js.map +1 -0
- package/docker-compose.qdrant-port.yml +7 -0
- package/docker-compose.yml +107 -0
- package/npm-shrinkwrap.json +7635 -0
- package/package.json +106 -4
- package/plugin/hooks/postToolUse.js +513 -0
- package/plugin/hooks/sessionStart.js +416 -0
- package/plugin/hooks/sessionStop.js +346 -0
- package/plugin/hooks.json +30 -0
- package/plugin/mcp_config.json +13 -0
- package/plugin/plugin.json +15 -0
- package/plugin/rules/AGENTS.md +66 -0
- package/plugin/skills/brain-memory/REFERENCE.md +64 -0
- package/plugin/skills/brain-memory/SKILL.md +68 -0
- package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/digest/SKILL.md +54 -0
- package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/handoff/SKILL.md +59 -0
- package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/save/SKILL.md +76 -0
- package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
- package/plugin/skills/search/SKILL.md +60 -0
- package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
- package/src/ai/chat.ts +214 -0
- package/src/ai/circuitBreaker.ts +120 -0
- package/src/ai/config.ts +311 -0
- package/src/ai/vendors.ts +292 -0
- package/src/app.ts +1150 -0
- package/src/cli.ts +1080 -0
- package/src/consolidation/candidates.ts +219 -0
- package/src/consolidation/fixtures.ts +461 -0
- package/src/consolidation/gate.ts +408 -0
- package/src/consolidation/runner.ts +220 -0
- package/src/dashboard/clientScript.ts +4208 -0
- package/src/dashboard/html.ts +550 -0
- package/src/dashboard/styles.ts +1279 -0
- package/src/index.ts +139 -0
- package/src/learning/embedWorker.ts +651 -0
- package/src/learning/embedding.ts +522 -0
- package/src/learning/engine.ts +86 -0
- package/src/learning/search.ts +568 -0
- package/src/learning/storeMeta.ts +147 -0
- package/src/learning/types.ts +111 -0
- package/src/lib/brainHome.ts +101 -0
- package/src/lib/db.ts +627 -0
- package/src/lib/logger.ts +7 -0
- package/src/lib/projectSlug.ts +286 -0
- package/src/lib/redactSecrets.ts +87 -0
- package/src/lib/scope.ts +121 -0
- package/src/lib/spool.ts +372 -0
- package/src/lib/sqlite.ts +158 -0
- package/src/lib/tls.ts +252 -0
- package/src/mcp/server.ts +793 -0
- package/src/memory/actionStore.ts +378 -0
- package/src/memory/deadLetterStore.ts +141 -0
- package/src/memory/embedQueueStore.ts +176 -0
- package/src/memory/failurePatternStore.ts +221 -0
- package/src/memory/graphStore.ts +352 -0
- package/src/memory/noteStore.ts +403 -0
- package/src/memory/observationStore.ts +303 -0
- package/src/memory/projectRename.ts +147 -0
- package/src/memory/rollupSweeper.ts +309 -0
- package/src/memory/sessionStore.ts +410 -0
- package/src/memory/trajectoryStore.ts +775 -0
- package/src/middleware/auth.ts +450 -0
- package/src/middleware/rateLimiter.ts +186 -0
- package/src/middleware/tracing.ts +70 -0
- package/src/routes/dashboard.ts +496 -0
- package/src/routes/learning.ts +51 -0
- package/src/routes/mcp.ts +349 -0
- package/src/routes/memories.ts +33 -0
- package/src/scripts/createApiKey.ts +109 -0
- package/src/scripts/doctor.ts +359 -0
- package/src/scripts/installAgent.ts +1278 -0
- package/src/scripts/migrateAgentMemory.ts +263 -0
- package/src/scripts/smokeTest.ts +189 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,1278 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import dotenv from 'dotenv';
|
|
5
|
+
import { normalizeProjectId } from '../lib/scope';
|
|
6
|
+
import {
|
|
7
|
+
getBrainDataDir,
|
|
8
|
+
getBrainEnvCandidates,
|
|
9
|
+
getBrainHooksDir,
|
|
10
|
+
getBrainMcpDir,
|
|
11
|
+
} from '../lib/brainHome';
|
|
12
|
+
|
|
13
|
+
export interface InstallAgentOptions {
|
|
14
|
+
homeDir?: string; // defaults to os.homedir() (overridable in tests)
|
|
15
|
+
brainRepoDir?: string; // defaults to path.resolve(__dirname, '../..')
|
|
16
|
+
projectDir?: string; // optional target workspace directory to initialize .brainrc & rules
|
|
17
|
+
projectId?: string; // optional explicit canonical project_id slug
|
|
18
|
+
apiUrl?: string; // defaults to env, .env, or 'http://127.0.0.1:3737'
|
|
19
|
+
apiKey?: string; // optional API key (prefers env, .env, or <brainRepoDir>/data/api-key.txt)
|
|
20
|
+
targets?: Array<'antigravity' | 'claude' | 'cursor' | 'project'>; // defaults to global or project depending on projectDir
|
|
21
|
+
replaceAgentMemory?: boolean; // defaults to false (preserves other plugins/agentmemory unless opted in)
|
|
22
|
+
enableHooks?: boolean; // defaults to true
|
|
23
|
+
dryRun?: boolean; // defaults to false
|
|
24
|
+
global?: boolean; // if true alongside projectDir, installs both global and project
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface InstallAgentReport {
|
|
28
|
+
success: boolean;
|
|
29
|
+
dryRun: boolean;
|
|
30
|
+
configuredTargets: Array<'antigravity' | 'claude' | 'cursor' | 'project'>;
|
|
31
|
+
createdFiles: string[];
|
|
32
|
+
modifiedFiles: string[];
|
|
33
|
+
skippedFiles: string[];
|
|
34
|
+
warnings: string[];
|
|
35
|
+
projectId?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface McpServerDefinition {
|
|
39
|
+
command: string;
|
|
40
|
+
args: string[];
|
|
41
|
+
env: Record<string, string>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const BRAIN_BLOCK_START = '<!-- neuralbrain:start -->';
|
|
45
|
+
export const BRAIN_BLOCK_END = '<!-- neuralbrain:end -->';
|
|
46
|
+
export const AGENTMEMORY_BLOCK_START = '<!-- agentmemory:start -->';
|
|
47
|
+
export const AGENTMEMORY_BLOCK_END = '<!-- agentmemory:end -->';
|
|
48
|
+
|
|
49
|
+
const BRAIN_BLOCK_REGEX =
|
|
50
|
+
/<!-- neuralbrain:start -->[\s\S]*?<!-- neuralbrain:end -->/;
|
|
51
|
+
const AGENTMEMORY_BLOCK_REGEX = /<!-- agentmemory:start -->[\s\S]*?<!-- agentmemory:end -->/;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Generates the standardized instruction block teaching agents how to use neuralbrain.
|
|
55
|
+
*/
|
|
56
|
+
export function generateBrainRuleBlock(defaultProjectId?: string): string {
|
|
57
|
+
const projectScopeDesc = defaultProjectId
|
|
58
|
+
? `Use for repository-specific knowledge. You MUST supply project_id: the name of the project's ROOT folder: the folder with .brainrc, otherwise the git repository root (for a worktree, the main repository), otherwise the folder the session started in. Never a subfolder you are working in, never a filesystem path (current default: '${defaultProjectId}').`
|
|
59
|
+
: `Use for repository-specific knowledge. You MUST supply project_id: the name of the project's ROOT folder: the folder with .brainrc, otherwise the git repository root (for a worktree, the main repository), otherwise the folder the session started in. Never a subfolder you are working in, never a filesystem path. If the root is ambiguous, run \`neuralbrain init\` there rather than guessing.`;
|
|
60
|
+
const exampleProjectId = defaultProjectId || 'my-project';
|
|
61
|
+
|
|
62
|
+
return [
|
|
63
|
+
BRAIN_BLOCK_START,
|
|
64
|
+
'## Persistent Memory (neuralbrain)',
|
|
65
|
+
'',
|
|
66
|
+
'You have persistent memory via the `neuralbrain` MCP server.',
|
|
67
|
+
'Available tools: `brain_search`, `brain_save`, `brain_recent_failures`, `brain_consolidate_candidates`, `brain_submit_summary`.',
|
|
68
|
+
'',
|
|
69
|
+
'### Workflow & Rules',
|
|
70
|
+
'- **At the start of a task or session**:',
|
|
71
|
+
' - Call `brain_recent_failures` to check for active failure patterns or bugs in this project.',
|
|
72
|
+
' - Call `brain_search` with your task context to load relevant past architectural decisions, patterns, and conventions (default `record_types`: `["note", "trajectory"]`).',
|
|
73
|
+
' - **When to also search `summary` (`record_types: ["note", "trajectory", "summary"]` or `["summary"]`)**:',
|
|
74
|
+
' - Resuming work on a file or feature where you need to see what a previous session changed (`files_touched` and literal claims).',
|
|
75
|
+
' - Debugging a recurring or historical error (`error_verbatim` across past sessions).',
|
|
76
|
+
' - Default `brain_search` returns nothing because no curated `note` was saved yet.',
|
|
77
|
+
' - If `SessionStart` / `/inject` shows a `CONSOLIDATION REMINDER`, let the user know and suggest they start a new session with an example prompt (e.g., `"Consolidate the brain observations for this project."`).',
|
|
78
|
+
'- **When to save notes (`brain_save`) — DO NOT wait until session end**:',
|
|
79
|
+
' - **Bug / root cause fixed** (`type: "bug"` or `"lesson"`): You diagnosed a non-obvious error, race condition, or config mismatch.',
|
|
80
|
+
' - **Architectural or design decision** (`type: "architecture"`): You or the user chose a pattern, library, schema, or trade-off.',
|
|
81
|
+
' - **Gotcha / environment quirk** (`type: "fact"` or `"lesson"`): You hit an undocumented API behavior, build/deploy constraint, or silent failure.',
|
|
82
|
+
' - **Project convention or workflow** (`type: "pattern"` or `"workflow"`): You discovered or established a repo-specific convention or command sequence.',
|
|
83
|
+
' - **User correction or preference** (`type: "preference"` or `"lesson"`): The user corrected your approach or stated how they want things done.',
|
|
84
|
+
' - **Before concluding any non-trivial task**, ask yourself: *"What would save the next agent 10 minutes?"* If anything qualifies, call `brain_save` before your final response.',
|
|
85
|
+
' - **What NOT to save**: Routine file reads, obvious edits, or raw tool logs (observations are captured automatically).',
|
|
86
|
+
'- **Example `brain_save` call**:',
|
|
87
|
+
` \`brain_save({ type: "bug", title: "Cloud Functions require explicit CORS origin", content: "Firebase callable/HTTP functions fail preflight in staging unless...", scope: "project", project_id: "${exampleProjectId}", files: ["functions/src/index.ts"], concepts: ["cors", "firebase"] })\``,
|
|
88
|
+
'- **Scope Discipline (Rule 4)**: Explicit scope is mandatory (`project`, `global`, or `unknown`):',
|
|
89
|
+
` - \`scope: "project"\`: ${projectScopeDesc}`,
|
|
90
|
+
' - `scope: "global"`: Use ONLY for universal truths across all projects, environments, and languages.',
|
|
91
|
+
' - `scope: "unknown"`: Default fallback only when project scope is genuinely unknown.',
|
|
92
|
+
BRAIN_BLOCK_END,
|
|
93
|
+
].join('\n');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Generates the standardized brain-memory SKILL.md content for Antigravity.
|
|
98
|
+
*/
|
|
99
|
+
export function generateBrainSkillContent(): string {
|
|
100
|
+
return [
|
|
101
|
+
'---',
|
|
102
|
+
'name: brain-memory',
|
|
103
|
+
'description: Persistent memory and failure pattern injection via neuralbrain. Use to search past learnings, record durable project insights, and check known failure patterns.',
|
|
104
|
+
'---',
|
|
105
|
+
'',
|
|
106
|
+
'# neuralbrain Persistent Memory',
|
|
107
|
+
'',
|
|
108
|
+
'## At Task Start',
|
|
109
|
+
'1. Check `brain_recent_failures` to avoid repeating known mistakes.',
|
|
110
|
+
'2. Search prior solutions, conventions, and architecture with `brain_search` (defaults to `record_types: ["note", "trajectory"]`).',
|
|
111
|
+
'3. Include `"summary"` in `record_types` (e.g. `record_types: ["note", "trajectory", "summary"]`) when resuming work on a file, debugging a recurring error, or when no curated `note` exists yet.',
|
|
112
|
+
'4. If `CONSOLIDATION REMINDER` appears in session context, let the user know and suggest they start a new session with an example prompt (e.g., `"Consolidate the brain observations for this project."`).',
|
|
113
|
+
'',
|
|
114
|
+
'## When to Save Notes (`brain_save`)',
|
|
115
|
+
'Tool-call observations are captured automatically as telemetry, **not** as notes. Call `brain_save` immediately (or before finishing your task) whenever you:',
|
|
116
|
+
'- Fix a non-trivial bug or uncover a subtle root cause (`type: "bug"` or `"lesson"`).',
|
|
117
|
+
'- Make or change an architectural/design decision (`type: "architecture"`).',
|
|
118
|
+
'- Discover an undocumented gotcha, environment constraint, or API quirk (`type: "fact"` or `"lesson"`).',
|
|
119
|
+
'- Establish or uncover a project convention or workflow (`type: "pattern"` or `"workflow"`).',
|
|
120
|
+
'- Receive a correction or preference from the user (`type: "preference"` or `"lesson"`).',
|
|
121
|
+
'',
|
|
122
|
+
'Keep notes concise and factual, include `files` and `concepts`, and always pass explicit `scope` (`"project"` with `project_id` folder slug, `"global"`, or `"unknown"`).',
|
|
123
|
+
'',
|
|
124
|
+
'## Consolidation (`brain_consolidate_candidates` / `brain_submit_summary`)',
|
|
125
|
+
'When asked by the user to consolidate observations for a project, call `brain_consolidate_candidates` and submit strictly literal, observation-cited extractions via `brain_submit_summary`. Always redact any API keys, tokens, passwords, or other sensitive info before submitting.',
|
|
126
|
+
'',
|
|
127
|
+
].join('\n');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Idempotently updates or appends the neuralbrain rule block in markdown documentation.
|
|
132
|
+
* Replaces any existing neuralbrain block in place.
|
|
133
|
+
* If replaceAgentMemory is true, replaces legacy agentmemory blocks.
|
|
134
|
+
* Otherwise appends cleanly to the end of the file.
|
|
135
|
+
*/
|
|
136
|
+
export function upsertBrainRuleBlock(
|
|
137
|
+
markdownContent: string,
|
|
138
|
+
defaultProjectId?: string,
|
|
139
|
+
replaceAgentMemory = false
|
|
140
|
+
): string {
|
|
141
|
+
const block = generateBrainRuleBlock(defaultProjectId);
|
|
142
|
+
|
|
143
|
+
if (BRAIN_BLOCK_REGEX.test(markdownContent)) {
|
|
144
|
+
return markdownContent.replace(BRAIN_BLOCK_REGEX, block);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (replaceAgentMemory && AGENTMEMORY_BLOCK_REGEX.test(markdownContent)) {
|
|
148
|
+
return markdownContent.replace(AGENTMEMORY_BLOCK_REGEX, block);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const trimmed = markdownContent.trimEnd();
|
|
152
|
+
if (!trimmed) {
|
|
153
|
+
return `${block}\n`;
|
|
154
|
+
}
|
|
155
|
+
return `${trimmed}\n\n${block}\n`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Parses an environment file into key-value pairs without modifying process.env.
|
|
160
|
+
*/
|
|
161
|
+
function parseEnvFile(filePath: string): Record<string, string> {
|
|
162
|
+
if (!fs.existsSync(filePath)) {
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
167
|
+
return dotenv.parse(raw);
|
|
168
|
+
} catch {
|
|
169
|
+
return {};
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Returns prioritized candidates for .env file lookups.
|
|
175
|
+
*/
|
|
176
|
+
function getEnvCandidates(brainRepoDir: string, projectDir?: string, homeDir?: string): string[] {
|
|
177
|
+
const candidates: string[] = [];
|
|
178
|
+
if (projectDir) {
|
|
179
|
+
candidates.push(path.join(projectDir, '.env.local'));
|
|
180
|
+
candidates.push(path.join(projectDir, '.env'));
|
|
181
|
+
}
|
|
182
|
+
candidates.push(path.join(brainRepoDir, '.env.local'));
|
|
183
|
+
candidates.push(path.join(brainRepoDir, '.env'));
|
|
184
|
+
candidates.push(...getBrainEnvCandidates(homeDir));
|
|
185
|
+
return candidates;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Resolves optional API key in prioritized order:
|
|
190
|
+
* 1. options.apiKey (programmatic option)
|
|
191
|
+
* 2. process.env.BRAIN_API_KEY
|
|
192
|
+
* 3. Parsed from ${projectDir}/.env, ${brainRepoDir}/.env, or ~/.neuralbrain/.env (.env.local has priority)
|
|
193
|
+
* 4. ~/.neuralbrain/data/api-key.txt or <brainRepoDir>/data/api-key.txt
|
|
194
|
+
*/
|
|
195
|
+
export function resolveApiKey(
|
|
196
|
+
options: InstallAgentOptions,
|
|
197
|
+
brainRepoDir: string,
|
|
198
|
+
projectDir?: string,
|
|
199
|
+
homeDir?: string
|
|
200
|
+
): string | undefined {
|
|
201
|
+
if (options.apiKey && options.apiKey.trim()) {
|
|
202
|
+
return options.apiKey.trim();
|
|
203
|
+
}
|
|
204
|
+
if (process.env.BRAIN_API_KEY && process.env.BRAIN_API_KEY.trim()) {
|
|
205
|
+
return process.env.BRAIN_API_KEY.trim();
|
|
206
|
+
}
|
|
207
|
+
for (const envPath of getEnvCandidates(brainRepoDir, projectDir, homeDir)) {
|
|
208
|
+
const parsed = parseEnvFile(envPath);
|
|
209
|
+
if (parsed.BRAIN_API_KEY && parsed.BRAIN_API_KEY.trim()) {
|
|
210
|
+
return parsed.BRAIN_API_KEY.trim();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const keyFileCandidates = [
|
|
214
|
+
path.join(getBrainDataDir(homeDir), 'api-key.txt'),
|
|
215
|
+
path.join(brainRepoDir, 'data', 'api-key.txt'),
|
|
216
|
+
];
|
|
217
|
+
for (const keyFilePath of keyFileCandidates) {
|
|
218
|
+
if (fs.existsSync(keyFilePath)) {
|
|
219
|
+
try {
|
|
220
|
+
const content = fs.readFileSync(keyFilePath, 'utf8').trim();
|
|
221
|
+
if (content) {
|
|
222
|
+
return content;
|
|
223
|
+
}
|
|
224
|
+
} catch {
|
|
225
|
+
// Ignore file read errors
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Resolves API URL in prioritized order:
|
|
234
|
+
* 1. options.apiUrl (programmatic option)
|
|
235
|
+
* 2. process.env.BRAIN_API_URL
|
|
236
|
+
* 3. Parsed from ${projectDir}/.env, ${brainRepoDir}/.env, or ~/.neuralbrain/.env (BRAIN_API_URL, or http://127.0.0.1:${PORT})
|
|
237
|
+
* 4. process.env.PORT
|
|
238
|
+
* 5. Default 'http://127.0.0.1:3737'
|
|
239
|
+
*/
|
|
240
|
+
export function resolveApiUrl(
|
|
241
|
+
options: InstallAgentOptions,
|
|
242
|
+
brainRepoDir: string,
|
|
243
|
+
projectDir?: string,
|
|
244
|
+
homeDir?: string
|
|
245
|
+
): string {
|
|
246
|
+
if (options.apiUrl && options.apiUrl.trim()) {
|
|
247
|
+
return options.apiUrl.trim();
|
|
248
|
+
}
|
|
249
|
+
if (process.env.BRAIN_API_URL && process.env.BRAIN_API_URL.trim()) {
|
|
250
|
+
return process.env.BRAIN_API_URL.trim();
|
|
251
|
+
}
|
|
252
|
+
for (const envPath of getEnvCandidates(brainRepoDir, projectDir, homeDir)) {
|
|
253
|
+
const parsed = parseEnvFile(envPath);
|
|
254
|
+
if (parsed.BRAIN_API_URL && parsed.BRAIN_API_URL.trim()) {
|
|
255
|
+
return parsed.BRAIN_API_URL.trim();
|
|
256
|
+
}
|
|
257
|
+
if (parsed.PORT && parsed.PORT.trim()) {
|
|
258
|
+
const portNum = parseInt(parsed.PORT.trim(), 10);
|
|
259
|
+
if (!Number.isNaN(portNum) && portNum > 0) {
|
|
260
|
+
return `http://127.0.0.1:${portNum}`;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (process.env.PORT && process.env.PORT.trim()) {
|
|
265
|
+
const portNum = parseInt(process.env.PORT.trim(), 10);
|
|
266
|
+
if (!Number.isNaN(portNum) && portNum > 0) {
|
|
267
|
+
return `http://127.0.0.1:${portNum}`;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return 'http://127.0.0.1:3737';
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Derives and normalizes a canonical project_id slug from options or directory path.
|
|
275
|
+
*/
|
|
276
|
+
function resolveProjectSlug(rawDir: string, explicitId?: string): string {
|
|
277
|
+
if (explicitId && explicitId.trim()) {
|
|
278
|
+
const res = normalizeProjectId(explicitId);
|
|
279
|
+
if (!res.ok) {
|
|
280
|
+
throw new Error(`Invalid explicit projectId '${explicitId}': ${res.error}`);
|
|
281
|
+
}
|
|
282
|
+
return res.projectId;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const folderName = path.basename(path.resolve(rawDir));
|
|
286
|
+
const directRes = normalizeProjectId(folderName);
|
|
287
|
+
if (directRes.ok) {
|
|
288
|
+
return directRes.projectId;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Attempt sanitizing non-standard folder names (e.g. spaces, special chars)
|
|
292
|
+
const sanitized = folderName
|
|
293
|
+
.trim()
|
|
294
|
+
.toLowerCase()
|
|
295
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
296
|
+
.replace(/^-+|-+$/g, '');
|
|
297
|
+
|
|
298
|
+
const sanitizedRes = normalizeProjectId(sanitized);
|
|
299
|
+
if (sanitizedRes.ok) {
|
|
300
|
+
return sanitizedRes.projectId;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
throw new Error(
|
|
304
|
+
`Could not determine canonical project_id from directory '${rawDir}' (folder '${folderName}'): ${directRes.error}`
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function isClaudeHookRegistered(list: any[], scriptName: string): boolean {
|
|
309
|
+
return list.some((item: any) => {
|
|
310
|
+
if (typeof item === 'string') return item.includes(scriptName);
|
|
311
|
+
if (item && typeof item.command === 'string') return item.command.includes(scriptName);
|
|
312
|
+
if (item && Array.isArray(item.hooks)) {
|
|
313
|
+
return item.hooks.some(
|
|
314
|
+
(h: any) => h && typeof h.command === 'string' && h.command.includes(scriptName)
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
return false;
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Formats a `node <scriptPath>` hook command, quoting the script path when it
|
|
323
|
+
* contains whitespace (e.g., Windows user directories like `C:\Users\John Doe\...`).
|
|
324
|
+
*/
|
|
325
|
+
export function formatNodeHookCommand(scriptPath: string): string {
|
|
326
|
+
return /\s/.test(scriptPath) ? `node "${scriptPath}"` : `node ${scriptPath}`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function installRuntimeHooks(
|
|
330
|
+
homeDir: string,
|
|
331
|
+
brainRepoDir: string,
|
|
332
|
+
dryRun: boolean,
|
|
333
|
+
report: InstallAgentReport
|
|
334
|
+
): string {
|
|
335
|
+
const installedHooksDir = getBrainHooksDir(homeDir);
|
|
336
|
+
const installedHooksLibDir = path.join(installedHooksDir, 'lib');
|
|
337
|
+
|
|
338
|
+
const hookFiles = ['sessionStart.js', 'postToolUse.js', 'sessionStop.js'];
|
|
339
|
+
for (const file of hookFiles) {
|
|
340
|
+
let srcPath = path.join(brainRepoDir, 'plugin', 'hooks', file);
|
|
341
|
+
if (!fs.existsSync(srcPath)) {
|
|
342
|
+
const fallback = path.resolve(__dirname, '../../plugin/hooks', file);
|
|
343
|
+
if (fs.existsSync(fallback)) srcPath = fallback;
|
|
344
|
+
}
|
|
345
|
+
if (fs.existsSync(srcPath)) {
|
|
346
|
+
const content = fs.readFileSync(srcPath, 'utf8');
|
|
347
|
+
safeWriteFile(path.join(installedHooksDir, file), content, dryRun, report);
|
|
348
|
+
if (!dryRun) {
|
|
349
|
+
try {
|
|
350
|
+
fs.chmodSync(path.join(installedHooksDir, file), 0o755);
|
|
351
|
+
} catch {
|
|
352
|
+
// Ignore chmod errors on systems that don't support it
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Copy helper libraries to hooks/lib/
|
|
359
|
+
const libFiles = ['projectSlug.js', 'spool.js', 'scope.js', 'brainHome.js', 'logger.js'];
|
|
360
|
+
for (const file of libFiles) {
|
|
361
|
+
let srcPath = path.join(brainRepoDir, 'dist', 'lib', file);
|
|
362
|
+
if (!fs.existsSync(srcPath)) {
|
|
363
|
+
const fallback = path.resolve(__dirname, '../lib', file);
|
|
364
|
+
if (fs.existsSync(fallback)) {
|
|
365
|
+
srcPath = fallback;
|
|
366
|
+
} else {
|
|
367
|
+
const distFallback = path.resolve(__dirname, '../../dist/lib', file);
|
|
368
|
+
if (fs.existsSync(distFallback)) srcPath = distFallback;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (fs.existsSync(srcPath)) {
|
|
372
|
+
const content = fs.readFileSync(srcPath, 'utf8');
|
|
373
|
+
safeWriteFile(path.join(installedHooksLibDir, file), content, dryRun, report);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// Also copy dist/mcp/server.js to ~/.neuralbrain/mcp/
|
|
378
|
+
const installedMcpDir = getBrainMcpDir(homeDir);
|
|
379
|
+
let mcpSrc = path.join(brainRepoDir, 'dist', 'mcp', 'server.js');
|
|
380
|
+
if (!fs.existsSync(mcpSrc)) {
|
|
381
|
+
const fallback = path.resolve(__dirname, '../mcp/server.js');
|
|
382
|
+
if (fs.existsSync(fallback)) {
|
|
383
|
+
mcpSrc = fallback;
|
|
384
|
+
} else {
|
|
385
|
+
const distFallback = path.resolve(__dirname, '../../dist/mcp/server.js');
|
|
386
|
+
if (fs.existsSync(distFallback)) mcpSrc = distFallback;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (fs.existsSync(mcpSrc)) {
|
|
390
|
+
const content = fs.readFileSync(mcpSrc, 'utf8');
|
|
391
|
+
safeWriteFile(path.join(installedMcpDir, 'server.js'), content, dryRun, report);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return installedHooksDir;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Resolves the source skills directory from brainRepoDir/plugin/skills (or fallback).
|
|
399
|
+
*/
|
|
400
|
+
function resolveSourceSkillsDir(brainRepoDir: string): string | null {
|
|
401
|
+
const candidate = path.join(brainRepoDir, 'plugin', 'skills');
|
|
402
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
|
|
403
|
+
return candidate;
|
|
404
|
+
}
|
|
405
|
+
const fallback = path.resolve(__dirname, '../../plugin/skills');
|
|
406
|
+
if (fs.existsSync(fallback) && fs.statSync(fallback).isDirectory()) {
|
|
407
|
+
return fallback;
|
|
408
|
+
}
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Copies all skill directories from sourceSkillsDir into canonicalDestDir idempotently,
|
|
414
|
+
* returning the list of installed skill names.
|
|
415
|
+
*/
|
|
416
|
+
function syncCanonicalSkills(
|
|
417
|
+
brainRepoDir: string,
|
|
418
|
+
canonicalDestDir: string,
|
|
419
|
+
dryRun: boolean,
|
|
420
|
+
report: InstallAgentReport
|
|
421
|
+
): string[] {
|
|
422
|
+
const sourceSkillsDir = resolveSourceSkillsDir(brainRepoDir);
|
|
423
|
+
if (!sourceSkillsDir) {
|
|
424
|
+
// Fallback for mock test directories that lack plugin/skills/
|
|
425
|
+
safeWriteFile(
|
|
426
|
+
path.join(canonicalDestDir, 'brain-memory', 'SKILL.md'),
|
|
427
|
+
generateBrainSkillContent(),
|
|
428
|
+
dryRun,
|
|
429
|
+
report
|
|
430
|
+
);
|
|
431
|
+
return ['brain-memory'];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const skillDirs = fs
|
|
435
|
+
.readdirSync(sourceSkillsDir, { withFileTypes: true })
|
|
436
|
+
.filter((d) => d.isDirectory())
|
|
437
|
+
.map((d) => d.name)
|
|
438
|
+
.sort();
|
|
439
|
+
|
|
440
|
+
for (const skillName of skillDirs) {
|
|
441
|
+
const srcSkillPath = path.join(sourceSkillsDir, skillName);
|
|
442
|
+
const destSkillPath = path.join(canonicalDestDir, skillName);
|
|
443
|
+
const files = fs.readdirSync(srcSkillPath, { withFileTypes: true }).filter((f) => f.isFile());
|
|
444
|
+
for (const file of files) {
|
|
445
|
+
const content = fs.readFileSync(path.join(srcSkillPath, file.name), 'utf8');
|
|
446
|
+
safeWriteFile(path.join(destSkillPath, file.name), content, dryRun, report);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
return skillDirs;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Creates or verifies a symlink from linkSkillsDir/<skillName> -> canonicalSkillsDir/<skillName>.
|
|
455
|
+
* Falls back to copying files if symlinks are not supported.
|
|
456
|
+
*/
|
|
457
|
+
function linkSkillsIntoTarget(
|
|
458
|
+
skillNames: string[],
|
|
459
|
+
canonicalSkillsDir: string,
|
|
460
|
+
linkSkillsDir: string,
|
|
461
|
+
dryRun: boolean,
|
|
462
|
+
report: InstallAgentReport
|
|
463
|
+
): void {
|
|
464
|
+
for (const skillName of skillNames) {
|
|
465
|
+
const canonicalDir = path.join(canonicalSkillsDir, skillName);
|
|
466
|
+
const linkPath = path.join(linkSkillsDir, skillName);
|
|
467
|
+
|
|
468
|
+
let alreadyLinked = false;
|
|
469
|
+
let exists = false;
|
|
470
|
+
try {
|
|
471
|
+
const stat = fs.lstatSync(linkPath);
|
|
472
|
+
exists = true;
|
|
473
|
+
if (stat.isSymbolicLink()) {
|
|
474
|
+
const target = path.resolve(path.dirname(linkPath), fs.readlinkSync(linkPath));
|
|
475
|
+
if (target === path.resolve(canonicalDir)) {
|
|
476
|
+
alreadyLinked = true;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
} catch {
|
|
480
|
+
exists = false;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (alreadyLinked) {
|
|
484
|
+
report.skippedFiles.push(linkPath);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if (exists) {
|
|
489
|
+
report.modifiedFiles.push(linkPath);
|
|
490
|
+
} else {
|
|
491
|
+
report.createdFiles.push(linkPath);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (dryRun) {
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
|
|
499
|
+
if (exists) {
|
|
500
|
+
fs.rmSync(linkPath, { recursive: true, force: true });
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
fs.symlinkSync(canonicalDir, linkPath, 'dir');
|
|
504
|
+
} catch {
|
|
505
|
+
// Fallback to copying if symlinks are restricted
|
|
506
|
+
if (fs.existsSync(canonicalDir)) {
|
|
507
|
+
const files = fs.readdirSync(canonicalDir, { withFileTypes: true }).filter((f) => f.isFile());
|
|
508
|
+
for (const file of files) {
|
|
509
|
+
const content = fs.readFileSync(path.join(canonicalDir, file.name), 'utf8');
|
|
510
|
+
fs.mkdirSync(linkPath, { recursive: true });
|
|
511
|
+
fs.writeFileSync(path.join(linkPath, file.name), content, 'utf8');
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function safeReadJson<T = any>(filePath: string): T | null {
|
|
519
|
+
if (!fs.existsSync(filePath)) {
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
try {
|
|
523
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
524
|
+
return JSON.parse(raw) as T;
|
|
525
|
+
} catch {
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function safeWriteFile(
|
|
531
|
+
filePath: string,
|
|
532
|
+
content: string,
|
|
533
|
+
dryRun: boolean,
|
|
534
|
+
report: InstallAgentReport
|
|
535
|
+
): void {
|
|
536
|
+
const exists = fs.existsSync(filePath);
|
|
537
|
+
if (exists) {
|
|
538
|
+
try {
|
|
539
|
+
const existingContent = fs.readFileSync(filePath, 'utf8');
|
|
540
|
+
if (existingContent === content) {
|
|
541
|
+
report.skippedFiles.push(filePath);
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
} catch {
|
|
545
|
+
// Fall through to write
|
|
546
|
+
}
|
|
547
|
+
report.modifiedFiles.push(filePath);
|
|
548
|
+
} else {
|
|
549
|
+
report.createdFiles.push(filePath);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
if (!dryRun) {
|
|
553
|
+
const dir = path.dirname(filePath);
|
|
554
|
+
if (!fs.existsSync(dir)) {
|
|
555
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
556
|
+
}
|
|
557
|
+
fs.writeFileSync(filePath, content, 'utf8');
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function safeWriteJson(
|
|
562
|
+
filePath: string,
|
|
563
|
+
data: any,
|
|
564
|
+
dryRun: boolean,
|
|
565
|
+
report: InstallAgentReport
|
|
566
|
+
): void {
|
|
567
|
+
const content = JSON.stringify(data, null, 2) + '\n';
|
|
568
|
+
safeWriteFile(filePath, content, dryRun, report);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Safely merges neuralbrain MCP server into an existing or new MCP config object.
|
|
573
|
+
*/
|
|
574
|
+
function mergeMcpConfig(
|
|
575
|
+
existingConfig: any,
|
|
576
|
+
serverDef: McpServerDefinition,
|
|
577
|
+
replaceAgentMemory: boolean
|
|
578
|
+
): any {
|
|
579
|
+
const config = existingConfig && typeof existingConfig === 'object' ? { ...existingConfig } : {};
|
|
580
|
+
if (!config.mcpServers || typeof config.mcpServers !== 'object') {
|
|
581
|
+
config.mcpServers = {};
|
|
582
|
+
} else {
|
|
583
|
+
config.mcpServers = { ...config.mcpServers };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
config.mcpServers['neuralbrain'] = serverDef;
|
|
587
|
+
|
|
588
|
+
if (replaceAgentMemory && config.mcpServers['agentmemory']) {
|
|
589
|
+
delete config.mcpServers['agentmemory'];
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
return config;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Installs and configures multi-agent integration for neuralbrain.
|
|
597
|
+
*/
|
|
598
|
+
export function installAgentIntegration(options: InstallAgentOptions = {}): InstallAgentReport {
|
|
599
|
+
const homeDir = path.resolve(options.homeDir || os.homedir());
|
|
600
|
+
const brainRepoDir = path.resolve(options.brainRepoDir || path.resolve(__dirname, '../..'));
|
|
601
|
+
const projectDir = options.projectDir ? path.resolve(options.projectDir) : undefined;
|
|
602
|
+
const apiUrl = resolveApiUrl(options, brainRepoDir, projectDir, homeDir);
|
|
603
|
+
const apiKey = resolveApiKey(options, brainRepoDir, projectDir, homeDir);
|
|
604
|
+
const replaceAgentMemory = Boolean(options.replaceAgentMemory);
|
|
605
|
+
const enableHooks = options.enableHooks !== false;
|
|
606
|
+
const dryRun = Boolean(options.dryRun);
|
|
607
|
+
|
|
608
|
+
// Target selection logic:
|
|
609
|
+
// - If options.targets is explicitly passed, honor it.
|
|
610
|
+
// - Else if projectDir is provided: default to ['project'] ONLY (or add globals if options.global is true).
|
|
611
|
+
// - Else: default to global agents ['antigravity', 'claude', 'cursor'].
|
|
612
|
+
let requestedTargets: Array<'antigravity' | 'claude' | 'cursor' | 'project'>;
|
|
613
|
+
if (options.targets && options.targets.length > 0) {
|
|
614
|
+
requestedTargets = options.targets;
|
|
615
|
+
} else if (projectDir) {
|
|
616
|
+
requestedTargets = options.global
|
|
617
|
+
? ['antigravity', 'claude', 'cursor', 'project']
|
|
618
|
+
: ['project'];
|
|
619
|
+
} else {
|
|
620
|
+
requestedTargets = ['antigravity', 'claude', 'cursor'];
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const report: InstallAgentReport = {
|
|
624
|
+
success: true,
|
|
625
|
+
dryRun,
|
|
626
|
+
configuredTargets: [],
|
|
627
|
+
createdFiles: [],
|
|
628
|
+
modifiedFiles: [],
|
|
629
|
+
skippedFiles: [],
|
|
630
|
+
warnings: [],
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
if (options.apiKey) {
|
|
634
|
+
report.warnings.push(
|
|
635
|
+
'API key was provided directly. Setting BRAIN_API_KEY in .env is recommended to prevent credential leakage in command history or process listings.'
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const globalMcpServerDef: McpServerDefinition = {
|
|
640
|
+
command: 'neuralbrain',
|
|
641
|
+
args: ['mcp'],
|
|
642
|
+
env: {
|
|
643
|
+
BRAIN_API_URL: apiUrl,
|
|
644
|
+
...(apiKey ? { BRAIN_API_KEY: apiKey } : {}),
|
|
645
|
+
},
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
const installedHooksDir = getBrainHooksDir(homeDir);
|
|
649
|
+
const hasGlobalTargets = requestedTargets.some((t) => t !== 'project');
|
|
650
|
+
if (enableHooks && hasGlobalTargets) {
|
|
651
|
+
installRuntimeHooks(homeDir, brainRepoDir, dryRun, report);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const globalCanonicalSkillsDir = path.join(homeDir, '.agents', 'skills');
|
|
655
|
+
const globalSkillNames = hasGlobalTargets
|
|
656
|
+
? syncCanonicalSkills(brainRepoDir, globalCanonicalSkillsDir, dryRun, report)
|
|
657
|
+
: [];
|
|
658
|
+
|
|
659
|
+
// ---------------------------------------------------------------------------
|
|
660
|
+
// Target 1: Antigravity (Global)
|
|
661
|
+
// ---------------------------------------------------------------------------
|
|
662
|
+
if (requestedTargets.includes('antigravity')) {
|
|
663
|
+
const pluginDir = path.join(homeDir, '.gemini', 'config', 'plugins', 'neuralbrain');
|
|
664
|
+
|
|
665
|
+
// 1. plugin.json
|
|
666
|
+
const pluginManifestPath = path.join(pluginDir, 'plugin.json');
|
|
667
|
+
safeWriteJson(
|
|
668
|
+
pluginManifestPath,
|
|
669
|
+
{
|
|
670
|
+
name: 'neuralbrain',
|
|
671
|
+
displayName: 'neuralbrain',
|
|
672
|
+
version: '0.0.1',
|
|
673
|
+
description: 'neuralbrain persistent memory service integration for Antigravity',
|
|
674
|
+
},
|
|
675
|
+
dryRun,
|
|
676
|
+
report
|
|
677
|
+
);
|
|
678
|
+
|
|
679
|
+
// 2. mcp_config.json in plugin (Streamable HTTP /mcp endpoint, not stdio)
|
|
680
|
+
const mcpUrl = `${apiUrl.replace(/\/+$/, '')}/mcp`;
|
|
681
|
+
const antigravityMcpServerDef = {
|
|
682
|
+
serverUrl: mcpUrl,
|
|
683
|
+
...(apiKey ? { headers: { Authorization: `Bearer ${apiKey}` } } : {}),
|
|
684
|
+
};
|
|
685
|
+
const pluginMcpPath = path.join(pluginDir, 'mcp_config.json');
|
|
686
|
+
safeWriteJson(
|
|
687
|
+
pluginMcpPath,
|
|
688
|
+
{
|
|
689
|
+
mcpServers: {
|
|
690
|
+
neuralbrain: antigravityMcpServerDef,
|
|
691
|
+
},
|
|
692
|
+
},
|
|
693
|
+
dryRun,
|
|
694
|
+
report
|
|
695
|
+
);
|
|
696
|
+
|
|
697
|
+
// 3. hooks.json in plugin
|
|
698
|
+
const pluginHooksPath = path.join(pluginDir, 'hooks.json');
|
|
699
|
+
const sessionStartHook = formatNodeHookCommand(path.join(installedHooksDir, 'sessionStart.js'));
|
|
700
|
+
const postToolUseHook = formatNodeHookCommand(path.join(installedHooksDir, 'postToolUse.js'));
|
|
701
|
+
const sessionStopHook = formatNodeHookCommand(path.join(installedHooksDir, 'sessionStop.js'));
|
|
702
|
+
|
|
703
|
+
safeWriteJson(
|
|
704
|
+
pluginHooksPath,
|
|
705
|
+
{
|
|
706
|
+
neuralbrain: {
|
|
707
|
+
enabled: enableHooks,
|
|
708
|
+
SessionStart: [
|
|
709
|
+
{
|
|
710
|
+
type: 'command',
|
|
711
|
+
command: sessionStartHook,
|
|
712
|
+
timeout: 30,
|
|
713
|
+
},
|
|
714
|
+
],
|
|
715
|
+
PostToolUse: [
|
|
716
|
+
{
|
|
717
|
+
matcher: '*',
|
|
718
|
+
hooks: [
|
|
719
|
+
{
|
|
720
|
+
type: 'command',
|
|
721
|
+
command: postToolUseHook,
|
|
722
|
+
timeout: 30,
|
|
723
|
+
},
|
|
724
|
+
],
|
|
725
|
+
},
|
|
726
|
+
],
|
|
727
|
+
Stop: [
|
|
728
|
+
{
|
|
729
|
+
type: 'command',
|
|
730
|
+
command: sessionStopHook,
|
|
731
|
+
timeout: 30,
|
|
732
|
+
},
|
|
733
|
+
],
|
|
734
|
+
},
|
|
735
|
+
},
|
|
736
|
+
dryRun,
|
|
737
|
+
report
|
|
738
|
+
);
|
|
739
|
+
|
|
740
|
+
// 4. rules/AGENTS.md in plugin
|
|
741
|
+
const pluginRulesPath = path.join(pluginDir, 'rules', 'AGENTS.md');
|
|
742
|
+
const pluginRulesExisting = fs.existsSync(pluginRulesPath)
|
|
743
|
+
? fs.readFileSync(pluginRulesPath, 'utf8')
|
|
744
|
+
: '';
|
|
745
|
+
safeWriteFile(
|
|
746
|
+
pluginRulesPath,
|
|
747
|
+
upsertBrainRuleBlock(pluginRulesExisting, undefined, false),
|
|
748
|
+
dryRun,
|
|
749
|
+
report
|
|
750
|
+
);
|
|
751
|
+
|
|
752
|
+
// 5. Link canonical skills into plugin/skills/
|
|
753
|
+
linkSkillsIntoTarget(
|
|
754
|
+
globalSkillNames,
|
|
755
|
+
globalCanonicalSkillsDir,
|
|
756
|
+
path.join(pluginDir, 'skills'),
|
|
757
|
+
dryRun,
|
|
758
|
+
report
|
|
759
|
+
);
|
|
760
|
+
|
|
761
|
+
// 6. Global GEMINI.md
|
|
762
|
+
const geminiMdPath = path.join(homeDir, '.gemini', 'GEMINI.md');
|
|
763
|
+
const existingGeminiMd = fs.existsSync(geminiMdPath) ? fs.readFileSync(geminiMdPath, 'utf8') : '';
|
|
764
|
+
const updatedGeminiMd = upsertBrainRuleBlock(existingGeminiMd, undefined, replaceAgentMemory);
|
|
765
|
+
safeWriteFile(geminiMdPath, updatedGeminiMd, dryRun, report);
|
|
766
|
+
|
|
767
|
+
report.configuredTargets.push('antigravity');
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// ---------------------------------------------------------------------------
|
|
771
|
+
// Target 2: Claude Code (Global)
|
|
772
|
+
// ---------------------------------------------------------------------------
|
|
773
|
+
if (requestedTargets.includes('claude')) {
|
|
774
|
+
// 1. ~/.claude.json
|
|
775
|
+
const claudeJsonPath = path.join(homeDir, '.claude.json');
|
|
776
|
+
const existingClaudeJson = safeReadJson(claudeJsonPath) || { mcpServers: {} };
|
|
777
|
+
const mergedClaudeJson = mergeMcpConfig(existingClaudeJson, globalMcpServerDef, replaceAgentMemory);
|
|
778
|
+
safeWriteJson(claudeJsonPath, mergedClaudeJson, dryRun, report);
|
|
779
|
+
|
|
780
|
+
// 2. ~/.claude/settings.json (hooks)
|
|
781
|
+
if (enableHooks) {
|
|
782
|
+
const settingsPath = path.join(homeDir, '.claude', 'settings.json');
|
|
783
|
+
const settings = safeReadJson(settingsPath) || {};
|
|
784
|
+
if (!settings.hooks || typeof settings.hooks !== 'object') {
|
|
785
|
+
settings.hooks = {};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
const hookEvents: Array<{
|
|
789
|
+
event: 'SessionStart' | 'PostToolUse' | 'Stop' | 'SessionEnd';
|
|
790
|
+
script: string;
|
|
791
|
+
matcher: string;
|
|
792
|
+
}> = [
|
|
793
|
+
{ event: 'SessionStart', script: 'sessionStart.js', matcher: '' },
|
|
794
|
+
{ event: 'PostToolUse', script: 'postToolUse.js', matcher: '*' },
|
|
795
|
+
{ event: 'Stop', script: 'sessionStop.js', matcher: '' },
|
|
796
|
+
{ event: 'SessionEnd', script: 'sessionStop.js', matcher: '' },
|
|
797
|
+
];
|
|
798
|
+
|
|
799
|
+
for (const { event, script, matcher } of hookEvents) {
|
|
800
|
+
const cmd = formatNodeHookCommand(path.join(installedHooksDir, script));
|
|
801
|
+
const list = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : [];
|
|
802
|
+
const existingIdx = list.findIndex((item: any) => {
|
|
803
|
+
if (typeof item === 'string') return item.includes(script);
|
|
804
|
+
if (item && typeof item.command === 'string') return item.command.includes(script);
|
|
805
|
+
if (item && Array.isArray(item.hooks)) {
|
|
806
|
+
return item.hooks.some(
|
|
807
|
+
(h: any) => h && typeof h.command === 'string' && h.command.includes(script)
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
return false;
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
const hookEntry = {
|
|
814
|
+
matcher,
|
|
815
|
+
hooks: [
|
|
816
|
+
{
|
|
817
|
+
type: 'command',
|
|
818
|
+
command: cmd,
|
|
819
|
+
timeout: 30,
|
|
820
|
+
},
|
|
821
|
+
],
|
|
822
|
+
};
|
|
823
|
+
|
|
824
|
+
if (existingIdx >= 0) {
|
|
825
|
+
list[existingIdx] = hookEntry;
|
|
826
|
+
} else {
|
|
827
|
+
list.push(hookEntry);
|
|
828
|
+
}
|
|
829
|
+
settings.hooks[event] = list;
|
|
830
|
+
}
|
|
831
|
+
safeWriteJson(settingsPath, settings, dryRun, report);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// 3. ~/.claude/CLAUDE.md
|
|
835
|
+
const claudeMdPath = path.join(homeDir, '.claude', 'CLAUDE.md');
|
|
836
|
+
const existingClaudeMd = fs.existsSync(claudeMdPath) ? fs.readFileSync(claudeMdPath, 'utf8') : '';
|
|
837
|
+
const updatedClaudeMd = upsertBrainRuleBlock(existingClaudeMd, undefined, replaceAgentMemory);
|
|
838
|
+
safeWriteFile(claudeMdPath, updatedClaudeMd, dryRun, report);
|
|
839
|
+
|
|
840
|
+
// 3. Symlink skills into ~/.claude/skills/ only if ~/.claude exists
|
|
841
|
+
if (fs.existsSync(path.join(homeDir, '.claude'))) {
|
|
842
|
+
linkSkillsIntoTarget(
|
|
843
|
+
globalSkillNames,
|
|
844
|
+
globalCanonicalSkillsDir,
|
|
845
|
+
path.join(homeDir, '.claude', 'skills'),
|
|
846
|
+
dryRun,
|
|
847
|
+
report
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
report.configuredTargets.push('claude');
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// ---------------------------------------------------------------------------
|
|
855
|
+
// Target 3: Cursor (Global)
|
|
856
|
+
// ---------------------------------------------------------------------------
|
|
857
|
+
if (requestedTargets.includes('cursor')) {
|
|
858
|
+
const cursorMcpPath = path.join(homeDir, '.cursor', 'mcp.json');
|
|
859
|
+
const existingCursorJson = safeReadJson(cursorMcpPath) || { mcpServers: {} };
|
|
860
|
+
const mergedCursorJson = mergeMcpConfig(existingCursorJson, globalMcpServerDef, replaceAgentMemory);
|
|
861
|
+
safeWriteJson(cursorMcpPath, mergedCursorJson, dryRun, report);
|
|
862
|
+
|
|
863
|
+
report.configuredTargets.push('cursor');
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// ---------------------------------------------------------------------------
|
|
867
|
+
// Target 4: Workspace Project Directory
|
|
868
|
+
// ---------------------------------------------------------------------------
|
|
869
|
+
if (requestedTargets.includes('project')) {
|
|
870
|
+
if (projectDir) {
|
|
871
|
+
const normalizedSlug = resolveProjectSlug(projectDir, options.projectId);
|
|
872
|
+
report.projectId = normalizedSlug;
|
|
873
|
+
|
|
874
|
+
const projectMcpServerDef: McpServerDefinition = {
|
|
875
|
+
command: 'neuralbrain',
|
|
876
|
+
args: ['mcp'],
|
|
877
|
+
env: {
|
|
878
|
+
BRAIN_API_URL: apiUrl,
|
|
879
|
+
BRAIN_DEFAULT_PROJECT_ID: normalizedSlug,
|
|
880
|
+
...(apiKey ? { BRAIN_API_KEY: apiKey } : {}),
|
|
881
|
+
},
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
// 1. Write <projectDir>/.brainrc
|
|
885
|
+
const brainrcPath = path.join(projectDir, '.brainrc');
|
|
886
|
+
safeWriteJson(brainrcPath, { project_id: normalizedSlug }, dryRun, report);
|
|
887
|
+
|
|
888
|
+
// 2. Project-level Claude Code: <projectDir>/.mcp.json and <projectDir>/.claude/settings.json
|
|
889
|
+
const projectClaudeMcpPath = path.join(projectDir, '.mcp.json');
|
|
890
|
+
const existingClaudeMcp = safeReadJson(projectClaudeMcpPath) || { mcpServers: {} };
|
|
891
|
+
const mergedClaudeMcp = mergeMcpConfig(existingClaudeMcp, projectMcpServerDef, replaceAgentMemory);
|
|
892
|
+
safeWriteJson(projectClaudeMcpPath, mergedClaudeMcp, dryRun, report);
|
|
893
|
+
|
|
894
|
+
if (enableHooks) {
|
|
895
|
+
const projectClaudeSettingsPath = path.join(projectDir, '.claude', 'settings.json');
|
|
896
|
+
const projectClaudeSettings = safeReadJson(projectClaudeSettingsPath) || {};
|
|
897
|
+
if (!projectClaudeSettings.hooks || typeof projectClaudeSettings.hooks !== 'object') {
|
|
898
|
+
projectClaudeSettings.hooks = {};
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const hookEvents: Array<{
|
|
902
|
+
event: 'SessionStart' | 'PostToolUse' | 'Stop' | 'SessionEnd';
|
|
903
|
+
script: string;
|
|
904
|
+
matcher: string;
|
|
905
|
+
}> = [
|
|
906
|
+
{ event: 'SessionStart', script: 'sessionStart.js', matcher: '' },
|
|
907
|
+
{ event: 'PostToolUse', script: 'postToolUse.js', matcher: '*' },
|
|
908
|
+
{ event: 'Stop', script: 'sessionStop.js', matcher: '' },
|
|
909
|
+
{ event: 'SessionEnd', script: 'sessionStop.js', matcher: '' },
|
|
910
|
+
];
|
|
911
|
+
|
|
912
|
+
for (const { event, script, matcher } of hookEvents) {
|
|
913
|
+
const cmd = formatNodeHookCommand(path.join(installedHooksDir, script));
|
|
914
|
+
const list = Array.isArray(projectClaudeSettings.hooks[event])
|
|
915
|
+
? projectClaudeSettings.hooks[event]
|
|
916
|
+
: [];
|
|
917
|
+
const existingIdx = list.findIndex((item: any) => {
|
|
918
|
+
if (typeof item === 'string') return item.includes(script);
|
|
919
|
+
if (item && typeof item.command === 'string') return item.command.includes(script);
|
|
920
|
+
if (item && Array.isArray(item.hooks)) {
|
|
921
|
+
return item.hooks.some(
|
|
922
|
+
(h: any) => h && typeof h.command === 'string' && h.command.includes(script)
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
return false;
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
const hookEntry = {
|
|
929
|
+
matcher,
|
|
930
|
+
hooks: [
|
|
931
|
+
{
|
|
932
|
+
type: 'command',
|
|
933
|
+
command: cmd,
|
|
934
|
+
timeout: 30,
|
|
935
|
+
},
|
|
936
|
+
],
|
|
937
|
+
};
|
|
938
|
+
|
|
939
|
+
if (existingIdx >= 0) {
|
|
940
|
+
list[existingIdx] = hookEntry;
|
|
941
|
+
} else {
|
|
942
|
+
list.push(hookEntry);
|
|
943
|
+
}
|
|
944
|
+
projectClaudeSettings.hooks[event] = list;
|
|
945
|
+
}
|
|
946
|
+
safeWriteJson(projectClaudeSettingsPath, projectClaudeSettings, dryRun, report);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// 3. Project-level Antigravity: <projectDir>/.gemini/hooks.json and skills/brain-memory/SKILL.md
|
|
950
|
+
if (enableHooks) {
|
|
951
|
+
const projectGeminiHooksPath = path.join(projectDir, '.gemini', 'hooks.json');
|
|
952
|
+
const sessionStartHook = formatNodeHookCommand(path.join(installedHooksDir, 'sessionStart.js'));
|
|
953
|
+
const postToolUseHook = formatNodeHookCommand(path.join(installedHooksDir, 'postToolUse.js'));
|
|
954
|
+
const sessionStopHook = formatNodeHookCommand(path.join(installedHooksDir, 'sessionStop.js'));
|
|
955
|
+
|
|
956
|
+
const existingProjectHooksRaw = safeReadJson(projectGeminiHooksPath);
|
|
957
|
+
const existingProjectHooks =
|
|
958
|
+
existingProjectHooksRaw &&
|
|
959
|
+
typeof existingProjectHooksRaw === 'object' &&
|
|
960
|
+
!Array.isArray(existingProjectHooksRaw)
|
|
961
|
+
? existingProjectHooksRaw
|
|
962
|
+
: {};
|
|
963
|
+
|
|
964
|
+
safeWriteJson(
|
|
965
|
+
projectGeminiHooksPath,
|
|
966
|
+
{
|
|
967
|
+
...existingProjectHooks,
|
|
968
|
+
neuralbrain: {
|
|
969
|
+
enabled: true,
|
|
970
|
+
SessionStart: [
|
|
971
|
+
{
|
|
972
|
+
type: 'command',
|
|
973
|
+
command: sessionStartHook,
|
|
974
|
+
timeout: 30,
|
|
975
|
+
},
|
|
976
|
+
],
|
|
977
|
+
PostToolUse: [
|
|
978
|
+
{
|
|
979
|
+
matcher: '*',
|
|
980
|
+
hooks: [
|
|
981
|
+
{
|
|
982
|
+
type: 'command',
|
|
983
|
+
command: postToolUseHook,
|
|
984
|
+
timeout: 30,
|
|
985
|
+
},
|
|
986
|
+
],
|
|
987
|
+
},
|
|
988
|
+
],
|
|
989
|
+
Stop: [
|
|
990
|
+
{
|
|
991
|
+
type: 'command',
|
|
992
|
+
command: sessionStopHook,
|
|
993
|
+
timeout: 30,
|
|
994
|
+
},
|
|
995
|
+
],
|
|
996
|
+
},
|
|
997
|
+
},
|
|
998
|
+
dryRun,
|
|
999
|
+
report
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const projectCanonicalSkillsDir = path.join(projectDir, '.agents', 'skills');
|
|
1004
|
+
const projectSkillNames = syncCanonicalSkills(
|
|
1005
|
+
brainRepoDir,
|
|
1006
|
+
projectCanonicalSkillsDir,
|
|
1007
|
+
dryRun,
|
|
1008
|
+
report
|
|
1009
|
+
);
|
|
1010
|
+
linkSkillsIntoTarget(
|
|
1011
|
+
projectSkillNames,
|
|
1012
|
+
projectCanonicalSkillsDir,
|
|
1013
|
+
path.join(projectDir, '.gemini', 'skills'),
|
|
1014
|
+
dryRun,
|
|
1015
|
+
report
|
|
1016
|
+
);
|
|
1017
|
+
if (fs.existsSync(path.join(projectDir, '.claude'))) {
|
|
1018
|
+
linkSkillsIntoTarget(
|
|
1019
|
+
projectSkillNames,
|
|
1020
|
+
projectCanonicalSkillsDir,
|
|
1021
|
+
path.join(projectDir, '.claude', 'skills'),
|
|
1022
|
+
dryRun,
|
|
1023
|
+
report
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// 4. Project-level Cursor: <projectDir>/.cursor/mcp.json
|
|
1028
|
+
const projectCursorMcpPath = path.join(projectDir, '.cursor', 'mcp.json');
|
|
1029
|
+
const existingCursorMcp = safeReadJson(projectCursorMcpPath) || { mcpServers: {} };
|
|
1030
|
+
const mergedCursorMcp = mergeMcpConfig(existingCursorMcp, projectMcpServerDef, replaceAgentMemory);
|
|
1031
|
+
safeWriteJson(projectCursorMcpPath, mergedCursorMcp, dryRun, report);
|
|
1032
|
+
|
|
1033
|
+
// 5. Project-level Rules (<projectDir>/CLAUDE.md / AGENTS.md)
|
|
1034
|
+
const isBrainRepo = projectDir === brainRepoDir;
|
|
1035
|
+
if (!isBrainRepo) {
|
|
1036
|
+
const projectClaudeMd = path.join(projectDir, 'CLAUDE.md');
|
|
1037
|
+
const projectAgentsMd = path.join(projectDir, 'AGENTS.md');
|
|
1038
|
+
const hasClaudeMd = fs.existsSync(projectClaudeMd);
|
|
1039
|
+
const hasAgentsMd = fs.existsSync(projectAgentsMd);
|
|
1040
|
+
|
|
1041
|
+
if (hasClaudeMd) {
|
|
1042
|
+
const content = fs.readFileSync(projectClaudeMd, 'utf8');
|
|
1043
|
+
const updated = upsertBrainRuleBlock(content, normalizedSlug, replaceAgentMemory);
|
|
1044
|
+
safeWriteFile(projectClaudeMd, updated, dryRun, report);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
if (hasAgentsMd) {
|
|
1048
|
+
const content = fs.readFileSync(projectAgentsMd, 'utf8');
|
|
1049
|
+
const updated = upsertBrainRuleBlock(content, normalizedSlug, replaceAgentMemory);
|
|
1050
|
+
safeWriteFile(projectAgentsMd, updated, dryRun, report);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
// If neither exists, create CLAUDE.md with canonical project rule block
|
|
1054
|
+
if (!hasClaudeMd && !hasAgentsMd) {
|
|
1055
|
+
const newClaudeMd = upsertBrainRuleBlock('', normalizedSlug, replaceAgentMemory);
|
|
1056
|
+
safeWriteFile(projectClaudeMd, newClaudeMd, dryRun, report);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
report.configuredTargets.push('project');
|
|
1061
|
+
} else {
|
|
1062
|
+
if (options.targets && options.targets.includes('project')) {
|
|
1063
|
+
report.warnings.push('Target "project" was requested, but no options.projectDir was provided.');
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
return report;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// -----------------------------------------------------------------------------
|
|
1072
|
+
// CLI Argument Parsing & Runner
|
|
1073
|
+
// -----------------------------------------------------------------------------
|
|
1074
|
+
|
|
1075
|
+
export function parseCliArgs(argv: string[]): InstallAgentOptions {
|
|
1076
|
+
const options: InstallAgentOptions = {};
|
|
1077
|
+
|
|
1078
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1079
|
+
const arg = argv[i];
|
|
1080
|
+
|
|
1081
|
+
if (arg === '--help' || arg === '-h') {
|
|
1082
|
+
printUsage();
|
|
1083
|
+
process.exit(0);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
if (arg === '--project-dir') {
|
|
1087
|
+
options.projectDir = argv[++i];
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
if (arg === '--project-id') {
|
|
1092
|
+
options.projectId = argv[++i];
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
if (arg === '--global') {
|
|
1097
|
+
options.global = true;
|
|
1098
|
+
continue;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
if (arg === '--api-key') {
|
|
1102
|
+
options.apiKey = argv[++i];
|
|
1103
|
+
console.warn(
|
|
1104
|
+
'\n[SECURITY WARNING] Passing --api-key on the command line can expose secrets in shell history (~/.bash_history) and process tables (ps aux).' +
|
|
1105
|
+
'\nRecommended: Set BRAIN_API_KEY in your .env file instead and run `npm run install-agent`.\n'
|
|
1106
|
+
);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
if (arg === '--api-url') {
|
|
1111
|
+
options.apiUrl = argv[++i];
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
if (arg === '--no-hooks') {
|
|
1116
|
+
options.enableHooks = false;
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
if (arg === '--keep-agentmemory') {
|
|
1121
|
+
options.replaceAgentMemory = false;
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
if (arg === '--replace-agentmemory') {
|
|
1126
|
+
options.replaceAgentMemory = true;
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
if (arg === '--dry-run') {
|
|
1131
|
+
options.dryRun = true;
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
if (arg === '--target' || arg === '--targets') {
|
|
1136
|
+
const rawTargets = (argv[++i] || '').split(',').map((t) => t.trim().toLowerCase());
|
|
1137
|
+
const validTargets: Array<'antigravity' | 'claude' | 'cursor' | 'project'> = [];
|
|
1138
|
+
for (const t of rawTargets) {
|
|
1139
|
+
if (t === 'antigravity' || t === 'claude' || t === 'cursor' || t === 'project') {
|
|
1140
|
+
validTargets.push(t);
|
|
1141
|
+
} else if (t) {
|
|
1142
|
+
console.warn(`[WARN] Unknown target '${t}' ignored.`);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
options.targets = validTargets;
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
return options;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
function printUsage(): void {
|
|
1156
|
+
console.log(`
|
|
1157
|
+
Usage: npm run install-agent -- [options]
|
|
1158
|
+
|
|
1159
|
+
Configures coding agents (Antigravity, Claude Code, Cursor, Workspace Projects)
|
|
1160
|
+
to use neuralbrain persistent memory.
|
|
1161
|
+
|
|
1162
|
+
Modes of Operation:
|
|
1163
|
+
1. Global Install (default when --project-dir is omitted):
|
|
1164
|
+
Installs globally to base agent configurations:
|
|
1165
|
+
- Antigravity plugin: ~/.gemini/config/plugins/neuralbrain/
|
|
1166
|
+
- Global Rules: ~/.gemini/GEMINI.md
|
|
1167
|
+
- Claude Code: ~/.claude.json, ~/.claude/settings.json, ~/.claude/CLAUDE.md
|
|
1168
|
+
- Cursor: ~/.cursor/mcp.json
|
|
1169
|
+
|
|
1170
|
+
2. Project-Level Install (when --project-dir <path> is provided):
|
|
1171
|
+
Installs ONLY to the specific project workspace, touching ZERO global files:
|
|
1172
|
+
- Project ID: <projectDir>/.brainrc
|
|
1173
|
+
- Project Claude MCP: <projectDir>/.mcp.json
|
|
1174
|
+
- Project Claude: <projectDir>/.claude/settings.json
|
|
1175
|
+
- Project Gemini: <projectDir>/.gemini/hooks.json, .gemini/skills/brain-memory/
|
|
1176
|
+
- Project Cursor: <projectDir>/.cursor/mcp.json
|
|
1177
|
+
- Project Rules: <projectDir>/CLAUDE.md / AGENTS.md
|
|
1178
|
+
|
|
1179
|
+
3. Dual Install (--global with --project-dir <path>):
|
|
1180
|
+
Installs both global agent configurations and project-level workspace files.
|
|
1181
|
+
|
|
1182
|
+
Security Recommendation:
|
|
1183
|
+
Set BRAIN_API_KEY and BRAIN_API_URL in your .env file instead of passing keys
|
|
1184
|
+
via command-line arguments to avoid leaking credentials into shell history
|
|
1185
|
+
(~/.bash_history) or process listings (ps aux).
|
|
1186
|
+
Then simply run:
|
|
1187
|
+
npm run install-agent
|
|
1188
|
+
or:
|
|
1189
|
+
npm run install-agent -- --project-dir /path/to/project
|
|
1190
|
+
|
|
1191
|
+
Options:
|
|
1192
|
+
--project-dir <path> Target project workspace to initialize .brainrc & rules
|
|
1193
|
+
--project-id <slug> Explicit canonical project slug (defaults to folder name)
|
|
1194
|
+
--global Force global installation alongside --project-dir
|
|
1195
|
+
--api-key <key> API key (Warning: Prefer setting BRAIN_API_KEY in .env)
|
|
1196
|
+
--api-url <url> Brain API service URL (defaults to .env or http://127.0.0.1:3737)
|
|
1197
|
+
--target <list> Explicit targets: antigravity, claude, cursor, project
|
|
1198
|
+
--no-hooks Do not configure lifecycle hooks in plugin / settings
|
|
1199
|
+
--replace-agentmemory Replace legacy agentmemory MCP configs and rule blocks
|
|
1200
|
+
--keep-agentmemory Preserve legacy agentmemory MCP configs and rule blocks (default)
|
|
1201
|
+
--dry-run Simulate actions without writing files to disk
|
|
1202
|
+
-h, --help Show this help message
|
|
1203
|
+
`);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* Prints a human-readable summary of an installAgentIntegration run.
|
|
1208
|
+
*/
|
|
1209
|
+
export function printInstallAgentReport(report: InstallAgentReport): void {
|
|
1210
|
+
console.log('\n===================================================================');
|
|
1211
|
+
console.log(' neuralbrain Multi-Agent Installer');
|
|
1212
|
+
console.log('===================================================================');
|
|
1213
|
+
console.log(`Dry Run: ${report.dryRun ? 'YES (No files modified)' : 'NO'}`);
|
|
1214
|
+
console.log(`Configured Targets: ${report.configuredTargets.join(', ') || 'none'}`);
|
|
1215
|
+
if (report.projectId) {
|
|
1216
|
+
console.log(`Project ID: ${report.projectId}`);
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
if (report.createdFiles.length > 0) {
|
|
1220
|
+
console.log('\nCreated Files:');
|
|
1221
|
+
for (const file of report.createdFiles) {
|
|
1222
|
+
console.log(` + ${file}`);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
if (report.modifiedFiles.length > 0) {
|
|
1227
|
+
console.log('\nModified Files:');
|
|
1228
|
+
for (const file of report.modifiedFiles) {
|
|
1229
|
+
console.log(` * ${file}`);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
if (report.skippedFiles.length > 0) {
|
|
1234
|
+
console.log(`\nUnchanged Files (${report.skippedFiles.length}):`);
|
|
1235
|
+
for (const file of report.skippedFiles) {
|
|
1236
|
+
console.log(` = ${file}`);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
if (report.warnings.length > 0) {
|
|
1241
|
+
console.log('\nWarnings:');
|
|
1242
|
+
for (const w of report.warnings) {
|
|
1243
|
+
console.log(` ! ${w}`);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
console.log('\nNext Steps:');
|
|
1248
|
+
console.log(' 1. Ensure the brain service is running: neuralbrain start (check with neuralbrain status)');
|
|
1249
|
+
if (report.configuredTargets.includes('antigravity')) {
|
|
1250
|
+
console.log(' 2. For Antigravity: The neuralbrain plugin is ready under ~/.gemini/config/plugins/');
|
|
1251
|
+
}
|
|
1252
|
+
if (report.configuredTargets.includes('claude')) {
|
|
1253
|
+
console.log(' 3. For Claude Code: MCP server and hooks configured in ~/.claude.json & ~/.claude/');
|
|
1254
|
+
}
|
|
1255
|
+
if (report.configuredTargets.includes('cursor')) {
|
|
1256
|
+
console.log(' 4. For Cursor: MCP server registered in ~/.cursor/mcp.json');
|
|
1257
|
+
}
|
|
1258
|
+
if (report.configuredTargets.includes('project')) {
|
|
1259
|
+
console.log(' 5. Project Workspace: Fully initialized with hooks, skills, and .brainrc');
|
|
1260
|
+
}
|
|
1261
|
+
console.log('===================================================================\n');
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function main(): void {
|
|
1265
|
+
try {
|
|
1266
|
+
const options = parseCliArgs(process.argv.slice(2));
|
|
1267
|
+
const report = installAgentIntegration(options);
|
|
1268
|
+
printInstallAgentReport(report);
|
|
1269
|
+
} catch (error: any) {
|
|
1270
|
+
console.error('\n[ERROR] Multi-Agent Installation failed:');
|
|
1271
|
+
console.error(error?.message || error);
|
|
1272
|
+
process.exit(1);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
if (require.main === module) {
|
|
1277
|
+
main();
|
|
1278
|
+
}
|