gitnexus 1.3.9 → 1.3.10

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 (38) hide show
  1. package/README.md +194 -194
  2. package/dist/cli/ai-context.js +87 -87
  3. package/dist/cli/index.js +15 -25
  4. package/dist/cli/lazy-action.d.ts +6 -0
  5. package/dist/cli/lazy-action.js +18 -0
  6. package/dist/core/augmentation/engine.js +20 -20
  7. package/dist/core/embeddings/embedding-pipeline.js +26 -26
  8. package/dist/core/ingestion/ast-cache.js +3 -2
  9. package/dist/core/ingestion/cluster-enricher.js +16 -16
  10. package/dist/core/ingestion/pipeline.js +8 -0
  11. package/dist/core/ingestion/tree-sitter-queries.js +484 -484
  12. package/dist/core/kuzu/kuzu-adapter.js +9 -9
  13. package/dist/core/kuzu/schema.js +287 -287
  14. package/dist/core/search/bm25-index.js +5 -5
  15. package/dist/core/search/hybrid-search.js +3 -3
  16. package/dist/core/wiki/graph-queries.js +52 -52
  17. package/dist/core/wiki/html-viewer.js +192 -192
  18. package/dist/core/wiki/prompts.js +82 -82
  19. package/dist/mcp/compatible-stdio-transport.d.ts +25 -0
  20. package/dist/mcp/compatible-stdio-transport.js +200 -0
  21. package/dist/mcp/local/local-backend.js +128 -128
  22. package/dist/mcp/resources.js +42 -42
  23. package/dist/mcp/server.js +18 -18
  24. package/dist/mcp/tools.js +86 -86
  25. package/hooks/claude/gitnexus-hook.cjs +155 -155
  26. package/hooks/claude/pre-tool-use.sh +79 -79
  27. package/hooks/claude/session-start.sh +42 -42
  28. package/package.json +96 -96
  29. package/scripts/patch-tree-sitter-swift.cjs +74 -74
  30. package/skills/gitnexus-cli.md +82 -82
  31. package/skills/gitnexus-debugging.md +89 -89
  32. package/skills/gitnexus-exploring.md +78 -78
  33. package/skills/gitnexus-guide.md +64 -64
  34. package/skills/gitnexus-impact-analysis.md +97 -97
  35. package/skills/gitnexus-pr-review.md +163 -163
  36. package/skills/gitnexus-refactoring.md +121 -121
  37. package/vendor/leiden/index.cjs +355 -355
  38. package/vendor/leiden/utils.cjs +392 -392
package/dist/mcp/tools.js CHANGED
@@ -7,14 +7,14 @@
7
7
  export const GITNEXUS_TOOLS = [
8
8
  {
9
9
  name: 'list_repos',
10
- description: `List all indexed repositories available to GitNexus.
11
-
12
- Returns each repo's name, path, indexed date, last commit, and stats.
13
-
14
- WHEN TO USE: First step when multiple repos are indexed, or to discover available repos.
15
- AFTER THIS: READ gitnexus://repo/{name}/context for the repo you want to work with.
16
-
17
- When multiple repos are indexed, you MUST specify the "repo" parameter
10
+ description: `List all indexed repositories available to GitNexus.
11
+
12
+ Returns each repo's name, path, indexed date, last commit, and stats.
13
+
14
+ WHEN TO USE: First step when multiple repos are indexed, or to discover available repos.
15
+ AFTER THIS: READ gitnexus://repo/{name}/context for the repo you want to work with.
16
+
17
+ When multiple repos are indexed, you MUST specify the "repo" parameter
18
18
  on other tools (query, context, impact, etc.) to target the correct one.`,
19
19
  inputSchema: {
20
20
  type: 'object',
@@ -24,17 +24,17 @@ on other tools (query, context, impact, etc.) to target the correct one.`,
24
24
  },
25
25
  {
26
26
  name: 'query',
27
- description: `Query the code knowledge graph for execution flows related to a concept.
28
- Returns processes (call chains) ranked by relevance, each with its symbols and file locations.
29
-
30
- WHEN TO USE: Understanding how code works together. Use this when you need execution flows and relationships, not just file matches. Complements grep/IDE search.
31
- AFTER THIS: Use context() on a specific symbol for 360-degree view (callers, callees, categorized refs).
32
-
33
- Returns results grouped by process (execution flow):
34
- - processes: ranked execution flows with relevance priority
35
- - process_symbols: all symbols in those flows with file locations and module (functional area)
36
- - definitions: standalone types/interfaces not in any process
37
-
27
+ description: `Query the code knowledge graph for execution flows related to a concept.
28
+ Returns processes (call chains) ranked by relevance, each with its symbols and file locations.
29
+
30
+ WHEN TO USE: Understanding how code works together. Use this when you need execution flows and relationships, not just file matches. Complements grep/IDE search.
31
+ AFTER THIS: Use context() on a specific symbol for 360-degree view (callers, callees, categorized refs).
32
+
33
+ Returns results grouped by process (execution flow):
34
+ - processes: ranked execution flows with relevance priority
35
+ - process_symbols: all symbols in those flows with file locations and module (functional area)
36
+ - definitions: standalone types/interfaces not in any process
37
+
38
38
  Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank Fusion.`,
39
39
  inputSchema: {
40
40
  type: 'object',
@@ -52,34 +52,34 @@ Hybrid ranking: BM25 keyword + semantic vector search, ranked by Reciprocal Rank
52
52
  },
53
53
  {
54
54
  name: 'cypher',
55
- description: `Execute Cypher query against the code knowledge graph.
56
-
57
- WHEN TO USE: Complex structural queries that search/explore can't answer. READ gitnexus://repo/{name}/schema first for the full schema.
58
- AFTER THIS: Use context() on result symbols for deeper context.
59
-
60
- SCHEMA:
61
- - Nodes: File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process
62
- - Multi-language nodes (use backticks): \`Struct\`, \`Enum\`, \`Trait\`, \`Impl\`, etc.
63
- - All edges via single CodeRelation table with 'type' property
64
- - Edge types: CONTAINS, DEFINES, CALLS, IMPORTS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS
65
- - Edge properties: type (STRING), confidence (DOUBLE), reason (STRING), step (INT32)
66
-
67
- EXAMPLES:
68
- • Find callers of a function:
69
- MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b:Function {name: "validateUser"}) RETURN a.name, a.filePath
70
-
71
- • Find community members:
72
- MATCH (f)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community) WHERE c.heuristicLabel = "Auth" RETURN f.name
73
-
74
- • Trace a process:
75
- MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process) WHERE p.heuristicLabel = "UserLogin" RETURN s.name, r.step ORDER BY r.step
76
-
77
- OUTPUT: Returns { markdown, row_count } — results formatted as a Markdown table for easy reading.
78
-
79
- TIPS:
80
- - All relationships use single CodeRelation table — filter with {type: 'CALLS'} etc.
81
- - Community = auto-detected functional area (Leiden algorithm)
82
- - Process = execution flow trace from entry point to terminal
55
+ description: `Execute Cypher query against the code knowledge graph.
56
+
57
+ WHEN TO USE: Complex structural queries that search/explore can't answer. READ gitnexus://repo/{name}/schema first for the full schema.
58
+ AFTER THIS: Use context() on result symbols for deeper context.
59
+
60
+ SCHEMA:
61
+ - Nodes: File, Folder, Function, Class, Interface, Method, CodeElement, Community, Process
62
+ - Multi-language nodes (use backticks): \`Struct\`, \`Enum\`, \`Trait\`, \`Impl\`, etc.
63
+ - All edges via single CodeRelation table with 'type' property
64
+ - Edge types: CONTAINS, DEFINES, CALLS, IMPORTS, EXTENDS, IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS
65
+ - Edge properties: type (STRING), confidence (DOUBLE), reason (STRING), step (INT32)
66
+
67
+ EXAMPLES:
68
+ • Find callers of a function:
69
+ MATCH (a)-[:CodeRelation {type: 'CALLS'}]->(b:Function {name: "validateUser"}) RETURN a.name, a.filePath
70
+
71
+ • Find community members:
72
+ MATCH (f)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community) WHERE c.heuristicLabel = "Auth" RETURN f.name
73
+
74
+ • Trace a process:
75
+ MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process) WHERE p.heuristicLabel = "UserLogin" RETURN s.name, r.step ORDER BY r.step
76
+
77
+ OUTPUT: Returns { markdown, row_count } — results formatted as a Markdown table for easy reading.
78
+
79
+ TIPS:
80
+ - All relationships use single CodeRelation table — filter with {type: 'CALLS'} etc.
81
+ - Community = auto-detected functional area (Leiden algorithm)
82
+ - Process = execution flow trace from entry point to terminal
83
83
  - Use heuristicLabel (not label) for human-readable community/process names`,
84
84
  inputSchema: {
85
85
  type: 'object',
@@ -92,12 +92,12 @@ TIPS:
92
92
  },
93
93
  {
94
94
  name: 'context',
95
- description: `360-degree view of a single code symbol.
96
- Shows categorized incoming/outgoing references (calls, imports, extends, implements), process participation, and file location.
97
-
98
- WHEN TO USE: After query() to understand a specific symbol in depth. When you need to know all callers, callees, and what execution flows a symbol participates in.
99
- AFTER THIS: Use impact() if planning changes, or READ gitnexus://repo/{name}/process/{processName} for full execution trace.
100
-
95
+ description: `360-degree view of a single code symbol.
96
+ Shows categorized incoming/outgoing references (calls, imports, extends, implements), process participation, and file location.
97
+
98
+ WHEN TO USE: After query() to understand a specific symbol in depth. When you need to know all callers, callees, and what execution flows a symbol participates in.
99
+ AFTER THIS: Use impact() if planning changes, or READ gitnexus://repo/{name}/process/{processName} for full execution trace.
100
+
101
101
  Handles disambiguation: if multiple symbols share the same name, returns candidates for you to pick from. Use uid param for zero-ambiguity lookup from prior results.`,
102
102
  inputSchema: {
103
103
  type: 'object',
@@ -113,12 +113,12 @@ Handles disambiguation: if multiple symbols share the same name, returns candida
113
113
  },
114
114
  {
115
115
  name: 'detect_changes',
116
- description: `Analyze uncommitted git changes and find affected execution flows.
117
- Maps git diff hunks to indexed symbols, then traces which processes are impacted.
118
-
119
- WHEN TO USE: Before committing — to understand what your changes affect. Pre-commit review, PR preparation.
120
- AFTER THIS: Review affected processes. Use context() on high-risk symbols. READ gitnexus://repo/{name}/process/{name} for full traces.
121
-
116
+ description: `Analyze uncommitted git changes and find affected execution flows.
117
+ Maps git diff hunks to indexed symbols, then traces which processes are impacted.
118
+
119
+ WHEN TO USE: Before committing — to understand what your changes affect. Pre-commit review, PR preparation.
120
+ AFTER THIS: Review affected processes. Use context() on high-risk symbols. READ gitnexus://repo/{name}/process/{name} for full traces.
121
+
122
122
  Returns: changed symbols, affected processes, and a risk summary.`,
123
123
  inputSchema: {
124
124
  type: 'object',
@@ -132,14 +132,14 @@ Returns: changed symbols, affected processes, and a risk summary.`,
132
132
  },
133
133
  {
134
134
  name: 'rename',
135
- description: `Multi-file coordinated rename using the knowledge graph + text search.
136
- Finds all references via graph (high confidence) and regex text search (lower confidence). Preview by default.
137
-
138
- WHEN TO USE: Renaming a function, class, method, or variable across the codebase. Safer than find-and-replace.
139
- AFTER THIS: Run detect_changes() to verify no unexpected side effects.
140
-
141
- Each edit is tagged with confidence:
142
- - "graph": found via knowledge graph relationships (high confidence, safe to accept)
135
+ description: `Multi-file coordinated rename using the knowledge graph + text search.
136
+ Finds all references via graph (high confidence) and regex text search (lower confidence). Preview by default.
137
+
138
+ WHEN TO USE: Renaming a function, class, method, or variable across the codebase. Safer than find-and-replace.
139
+ AFTER THIS: Run detect_changes() to verify no unexpected side effects.
140
+
141
+ Each edit is tagged with confidence:
142
+ - "graph": found via knowledge graph relationships (high confidence, safe to accept)
143
143
  - "text_search": found via regex text search (lower confidence, review carefully)`,
144
144
  inputSchema: {
145
145
  type: 'object',
@@ -156,25 +156,25 @@ Each edit is tagged with confidence:
156
156
  },
157
157
  {
158
158
  name: 'impact',
159
- description: `Analyze the blast radius of changing a code symbol.
160
- Returns affected symbols grouped by depth, plus risk assessment, affected execution flows, and affected modules.
161
-
162
- WHEN TO USE: Before making code changes — especially refactoring, renaming, or modifying shared code. Shows what would break.
163
- AFTER THIS: Review d=1 items (WILL BREAK). Use context() on high-risk symbols.
164
-
165
- Output includes:
166
- - risk: LOW / MEDIUM / HIGH / CRITICAL
167
- - summary: direct callers, processes affected, modules affected
168
- - affected_processes: which execution flows break and at which step
169
- - affected_modules: which functional areas are hit (direct vs indirect)
170
- - byDepth: all affected symbols grouped by traversal depth
171
-
172
- Depth groups:
173
- - d=1: WILL BREAK (direct callers/importers)
174
- - d=2: LIKELY AFFECTED (indirect)
175
- - d=3: MAY NEED TESTING (transitive)
176
-
177
- EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
159
+ description: `Analyze the blast radius of changing a code symbol.
160
+ Returns affected symbols grouped by depth, plus risk assessment, affected execution flows, and affected modules.
161
+
162
+ WHEN TO USE: Before making code changes — especially refactoring, renaming, or modifying shared code. Shows what would break.
163
+ AFTER THIS: Review d=1 items (WILL BREAK). Use context() on high-risk symbols.
164
+
165
+ Output includes:
166
+ - risk: LOW / MEDIUM / HIGH / CRITICAL
167
+ - summary: direct callers, processes affected, modules affected
168
+ - affected_processes: which execution flows break and at which step
169
+ - affected_modules: which functional areas are hit (direct vs indirect)
170
+ - byDepth: all affected symbols grouped by traversal depth
171
+
172
+ Depth groups:
173
+ - d=1: WILL BREAK (direct callers/importers)
174
+ - d=2: LIKELY AFFECTED (indirect)
175
+ - d=3: MAY NEED TESTING (transitive)
176
+
177
+ EdgeType: CALLS, IMPORTS, EXTENDS, IMPLEMENTS
178
178
  Confidence: 1.0 = certain, <0.8 = fuzzy match`,
179
179
  inputSchema: {
180
180
  type: 'object',
@@ -1,155 +1,155 @@
1
- #!/usr/bin/env node
2
- /**
3
- * GitNexus Claude Code Hook
4
- *
5
- * PreToolUse handler — intercepts Grep/Glob/Bash searches
6
- * and augments with graph context from the GitNexus index.
7
- *
8
- * NOTE: SessionStart hooks are broken on Windows (Claude Code bug).
9
- * Session context is injected via CLAUDE.md / skills instead.
10
- */
11
-
12
- const fs = require('fs');
13
- const path = require('path');
14
- const { execFileSync } = require('child_process');
15
-
16
- /**
17
- * Read JSON input from stdin synchronously.
18
- */
19
- function readInput() {
20
- try {
21
- const data = fs.readFileSync(0, 'utf-8');
22
- return JSON.parse(data);
23
- } catch {
24
- return {};
25
- }
26
- }
27
-
28
- /**
29
- * Check if a directory (or ancestor) has a .gitnexus index.
30
- */
31
- function findGitNexusIndex(startDir) {
32
- let dir = startDir || process.cwd();
33
- for (let i = 0; i < 5; i++) {
34
- if (fs.existsSync(path.join(dir, '.gitnexus'))) {
35
- return true;
36
- }
37
- const parent = path.dirname(dir);
38
- if (parent === dir) break;
39
- dir = parent;
40
- }
41
- return false;
42
- }
43
-
44
- /**
45
- * Extract search pattern from tool input.
46
- */
47
- function extractPattern(toolName, toolInput) {
48
- if (toolName === 'Grep') {
49
- return toolInput.pattern || null;
50
- }
51
-
52
- if (toolName === 'Glob') {
53
- const raw = toolInput.pattern || '';
54
- const match = raw.match(/[*\/]([a-zA-Z][a-zA-Z0-9_-]{2,})/);
55
- return match ? match[1] : null;
56
- }
57
-
58
- if (toolName === 'Bash') {
59
- const cmd = toolInput.command || '';
60
- if (!/\brg\b|\bgrep\b/.test(cmd)) return null;
61
-
62
- const tokens = cmd.split(/\s+/);
63
- let foundCmd = false;
64
- let skipNext = false;
65
- const flagsWithValues = new Set(['-e', '-f', '-m', '-A', '-B', '-C', '-g', '--glob', '-t', '--type', '--include', '--exclude']);
66
-
67
- for (const token of tokens) {
68
- if (skipNext) { skipNext = false; continue; }
69
- if (!foundCmd) {
70
- if (/\brg$|\bgrep$/.test(token)) foundCmd = true;
71
- continue;
72
- }
73
- if (token.startsWith('-')) {
74
- if (flagsWithValues.has(token)) skipNext = true;
75
- continue;
76
- }
77
- const cleaned = token.replace(/['"]/g, '');
78
- return cleaned.length >= 3 ? cleaned : null;
79
- }
80
- return null;
81
- }
82
-
83
- return null;
84
- }
85
-
86
- function main() {
87
- try {
88
- const input = readInput();
89
- const hookEvent = input.hook_event_name || '';
90
-
91
- if (hookEvent !== 'PreToolUse') return;
92
-
93
- const cwd = input.cwd || process.cwd();
94
- if (!findGitNexusIndex(cwd)) return;
95
-
96
- const toolName = input.tool_name || '';
97
- const toolInput = input.tool_input || {};
98
-
99
- if (toolName !== 'Grep' && toolName !== 'Glob' && toolName !== 'Bash') return;
100
-
101
- const pattern = extractPattern(toolName, toolInput);
102
- if (!pattern || pattern.length < 3) return;
103
-
104
- // Resolve CLI path — try multiple strategies:
105
- // 1. Relative path (works when script is inside npm package)
106
- // 2. require.resolve (works when gitnexus is globally installed)
107
- // 3. Fall back to npx (works when neither is available)
108
- let cliPath = path.resolve(__dirname, '..', '..', 'dist', 'cli', 'index.js');
109
- if (!fs.existsSync(cliPath)) {
110
- try {
111
- cliPath = require.resolve('gitnexus/dist/cli/index.js');
112
- } catch {
113
- cliPath = ''; // will use npx fallback
114
- }
115
- }
116
-
117
- // augment CLI writes result to stderr (KuzuDB's native module captures
118
- // stdout fd at OS level, making it unusable in subprocess contexts).
119
- const { spawnSync } = require('child_process');
120
- let result = '';
121
- try {
122
- let child;
123
- if (cliPath) {
124
- child = spawnSync(
125
- process.execPath,
126
- [cliPath, 'augment', pattern],
127
- { encoding: 'utf-8', timeout: 8000, cwd, stdio: ['pipe', 'pipe', 'pipe'] }
128
- );
129
- } else {
130
- // npx fallback
131
- const cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
132
- child = spawnSync(
133
- cmd,
134
- ['-y', 'gitnexus', 'augment', pattern],
135
- { encoding: 'utf-8', timeout: 15000, cwd, stdio: ['pipe', 'pipe', 'pipe'] }
136
- );
137
- }
138
- result = child.stderr || '';
139
- } catch { /* graceful failure */ }
140
-
141
- if (result && result.trim()) {
142
- console.log(JSON.stringify({
143
- hookSpecificOutput: {
144
- hookEventName: 'PreToolUse',
145
- additionalContext: result.trim()
146
- }
147
- }));
148
- }
149
- } catch (err) {
150
- // Graceful failure — log to stderr for debugging
151
- console.error('GitNexus hook error:', err.message);
152
- }
153
- }
154
-
155
- main();
1
+ #!/usr/bin/env node
2
+ /**
3
+ * GitNexus Claude Code Hook
4
+ *
5
+ * PreToolUse handler — intercepts Grep/Glob/Bash searches
6
+ * and augments with graph context from the GitNexus index.
7
+ *
8
+ * NOTE: SessionStart hooks are broken on Windows (Claude Code bug).
9
+ * Session context is injected via CLAUDE.md / skills instead.
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { execFileSync } = require('child_process');
15
+
16
+ /**
17
+ * Read JSON input from stdin synchronously.
18
+ */
19
+ function readInput() {
20
+ try {
21
+ const data = fs.readFileSync(0, 'utf-8');
22
+ return JSON.parse(data);
23
+ } catch {
24
+ return {};
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Check if a directory (or ancestor) has a .gitnexus index.
30
+ */
31
+ function findGitNexusIndex(startDir) {
32
+ let dir = startDir || process.cwd();
33
+ for (let i = 0; i < 5; i++) {
34
+ if (fs.existsSync(path.join(dir, '.gitnexus'))) {
35
+ return true;
36
+ }
37
+ const parent = path.dirname(dir);
38
+ if (parent === dir) break;
39
+ dir = parent;
40
+ }
41
+ return false;
42
+ }
43
+
44
+ /**
45
+ * Extract search pattern from tool input.
46
+ */
47
+ function extractPattern(toolName, toolInput) {
48
+ if (toolName === 'Grep') {
49
+ return toolInput.pattern || null;
50
+ }
51
+
52
+ if (toolName === 'Glob') {
53
+ const raw = toolInput.pattern || '';
54
+ const match = raw.match(/[*\/]([a-zA-Z][a-zA-Z0-9_-]{2,})/);
55
+ return match ? match[1] : null;
56
+ }
57
+
58
+ if (toolName === 'Bash') {
59
+ const cmd = toolInput.command || '';
60
+ if (!/\brg\b|\bgrep\b/.test(cmd)) return null;
61
+
62
+ const tokens = cmd.split(/\s+/);
63
+ let foundCmd = false;
64
+ let skipNext = false;
65
+ const flagsWithValues = new Set(['-e', '-f', '-m', '-A', '-B', '-C', '-g', '--glob', '-t', '--type', '--include', '--exclude']);
66
+
67
+ for (const token of tokens) {
68
+ if (skipNext) { skipNext = false; continue; }
69
+ if (!foundCmd) {
70
+ if (/\brg$|\bgrep$/.test(token)) foundCmd = true;
71
+ continue;
72
+ }
73
+ if (token.startsWith('-')) {
74
+ if (flagsWithValues.has(token)) skipNext = true;
75
+ continue;
76
+ }
77
+ const cleaned = token.replace(/['"]/g, '');
78
+ return cleaned.length >= 3 ? cleaned : null;
79
+ }
80
+ return null;
81
+ }
82
+
83
+ return null;
84
+ }
85
+
86
+ function main() {
87
+ try {
88
+ const input = readInput();
89
+ const hookEvent = input.hook_event_name || '';
90
+
91
+ if (hookEvent !== 'PreToolUse') return;
92
+
93
+ const cwd = input.cwd || process.cwd();
94
+ if (!findGitNexusIndex(cwd)) return;
95
+
96
+ const toolName = input.tool_name || '';
97
+ const toolInput = input.tool_input || {};
98
+
99
+ if (toolName !== 'Grep' && toolName !== 'Glob' && toolName !== 'Bash') return;
100
+
101
+ const pattern = extractPattern(toolName, toolInput);
102
+ if (!pattern || pattern.length < 3) return;
103
+
104
+ // Resolve CLI path — try multiple strategies:
105
+ // 1. Relative path (works when script is inside npm package)
106
+ // 2. require.resolve (works when gitnexus is globally installed)
107
+ // 3. Fall back to npx (works when neither is available)
108
+ let cliPath = path.resolve(__dirname, '..', '..', 'dist', 'cli', 'index.js');
109
+ if (!fs.existsSync(cliPath)) {
110
+ try {
111
+ cliPath = require.resolve('gitnexus/dist/cli/index.js');
112
+ } catch {
113
+ cliPath = ''; // will use npx fallback
114
+ }
115
+ }
116
+
117
+ // augment CLI writes result to stderr (KuzuDB's native module captures
118
+ // stdout fd at OS level, making it unusable in subprocess contexts).
119
+ const { spawnSync } = require('child_process');
120
+ let result = '';
121
+ try {
122
+ let child;
123
+ if (cliPath) {
124
+ child = spawnSync(
125
+ process.execPath,
126
+ [cliPath, 'augment', pattern],
127
+ { encoding: 'utf-8', timeout: 8000, cwd, stdio: ['pipe', 'pipe', 'pipe'] }
128
+ );
129
+ } else {
130
+ // npx fallback
131
+ const cmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
132
+ child = spawnSync(
133
+ cmd,
134
+ ['-y', 'gitnexus', 'augment', pattern],
135
+ { encoding: 'utf-8', timeout: 15000, cwd, stdio: ['pipe', 'pipe', 'pipe'] }
136
+ );
137
+ }
138
+ result = child.stderr || '';
139
+ } catch { /* graceful failure */ }
140
+
141
+ if (result && result.trim()) {
142
+ console.log(JSON.stringify({
143
+ hookSpecificOutput: {
144
+ hookEventName: 'PreToolUse',
145
+ additionalContext: result.trim()
146
+ }
147
+ }));
148
+ }
149
+ } catch (err) {
150
+ // Graceful failure — log to stderr for debugging
151
+ console.error('GitNexus hook error:', err.message);
152
+ }
153
+ }
154
+
155
+ main();