nervapack 0.1.0__py3-none-any.whl
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.
- nervapack/__init__.py +1 -0
- nervapack/cli.py +278 -0
- nervapack/git/__init__.py +0 -0
- nervapack/git/tracker.py +46 -0
- nervapack/graph/__init__.py +0 -0
- nervapack/graph/builder.py +58 -0
- nervapack/graph/retrieval.py +75 -0
- nervapack/graph/vector_store.py +63 -0
- nervapack/llm/__init__.py +0 -0
- nervapack/llm/summarizer.py +45 -0
- nervapack/parser/__init__.py +0 -0
- nervapack/parser/ast_parser.py +91 -0
- nervapack/parser/md_chunker.py +64 -0
- nervapack-0.1.0.dist-info/METADATA +251 -0
- nervapack-0.1.0.dist-info/RECORD +19 -0
- nervapack-0.1.0.dist-info/WHEEL +5 -0
- nervapack-0.1.0.dist-info/entry_points.txt +2 -0
- nervapack-0.1.0.dist-info/licenses/LICENSE +21 -0
- nervapack-0.1.0.dist-info/top_level.txt +1 -0
nervapack/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# NervaPack module
|
nervapack/cli.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
from rich.console import Console
|
|
3
|
+
|
|
4
|
+
app = typer.Typer(help="NervaPack: Privacy-first, offline knowledge graph for developers.")
|
|
5
|
+
console = Console()
|
|
6
|
+
|
|
7
|
+
@app.command()
|
|
8
|
+
def init():
|
|
9
|
+
"""
|
|
10
|
+
Initialize a NervaPack graph in the current directory.
|
|
11
|
+
"""
|
|
12
|
+
console.print("[bold green]Initializing NervaPack graph...[/bold green]")
|
|
13
|
+
# TODO: Implement initialization logic
|
|
14
|
+
console.print("Initialization complete.")
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def ingest(path: str = typer.Argument(".", help="Path to the repository to ingest")):
|
|
18
|
+
"""
|
|
19
|
+
Ingest a repository, building the AST and Vector graph.
|
|
20
|
+
"""
|
|
21
|
+
from nervapack.parser.ast_parser import scan_directory
|
|
22
|
+
from nervapack.graph.builder import GraphBuilder
|
|
23
|
+
|
|
24
|
+
console.print(f"[bold blue]Ingesting repository at {path}...[/bold blue]")
|
|
25
|
+
|
|
26
|
+
console.print("Scanning directory for code entities...")
|
|
27
|
+
entities = scan_directory(path)
|
|
28
|
+
console.print(f"Found {len(entities)} AST entities.")
|
|
29
|
+
|
|
30
|
+
console.print("Building deterministic Structural Graph...")
|
|
31
|
+
builder = GraphBuilder()
|
|
32
|
+
graph = builder.build_from_entities(entities)
|
|
33
|
+
builder.save_graph()
|
|
34
|
+
console.print(f"Graph saved with {graph.number_of_nodes()} nodes and {graph.number_of_edges()} edges.")
|
|
35
|
+
|
|
36
|
+
console.print("Ingesting AST nodes into Vector Store...")
|
|
37
|
+
try:
|
|
38
|
+
from nervapack.graph.vector_store import VectorStore
|
|
39
|
+
vstore = VectorStore()
|
|
40
|
+
|
|
41
|
+
# We'll just ingest them with basic code text for now (in production, LLMSummarizer would summarize them first)
|
|
42
|
+
ast_docs = []
|
|
43
|
+
for e in entities:
|
|
44
|
+
# We construct a mock 'summary' that just describes the node to avoid calling local Ollama during tests
|
|
45
|
+
node_id = f"{e.type}:{e.file_path}:{e.name}:{e.start_line}"
|
|
46
|
+
ast_docs.append({
|
|
47
|
+
"node_id": node_id,
|
|
48
|
+
"summary": f"This is a {e.type} named {e.name} in {e.file_path}. Code:\n{e.content}",
|
|
49
|
+
"file_path": e.file_path
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
vstore.ingest_ast_entities(ast_docs)
|
|
53
|
+
console.print("AST Vector ingestion complete.")
|
|
54
|
+
|
|
55
|
+
from nervapack.parser.md_chunker import scan_markdown_directory
|
|
56
|
+
console.print("Scanning directory for Markdown docs...")
|
|
57
|
+
md_chunks = scan_markdown_directory(path)
|
|
58
|
+
console.print(f"Found {len(md_chunks)} Markdown chunks.")
|
|
59
|
+
|
|
60
|
+
if md_chunks:
|
|
61
|
+
# Ingest to vector store
|
|
62
|
+
vstore.ingest_chunks(md_chunks)
|
|
63
|
+
|
|
64
|
+
# Add to graph and Bind with LLM
|
|
65
|
+
from nervapack.llm.summarizer import LLMSummarizer
|
|
66
|
+
llm = LLMSummarizer()
|
|
67
|
+
|
|
68
|
+
console.print("Binding documentation to AST (this may take a while)...")
|
|
69
|
+
for i, chunk in enumerate(md_chunks):
|
|
70
|
+
md_node_id = f"md_{chunk['file_path']}_{i}"
|
|
71
|
+
if not graph.has_node(md_node_id):
|
|
72
|
+
graph.add_node(md_node_id, type="markdown", header=chunk['header'], content=chunk['content'], file_path=chunk['file_path'])
|
|
73
|
+
|
|
74
|
+
# Try to bind
|
|
75
|
+
matched_ids = llm.bind_docs_to_ast(chunk['content'], ast_docs)
|
|
76
|
+
for matched_id in matched_ids:
|
|
77
|
+
if graph.has_node(matched_id):
|
|
78
|
+
graph.add_edge(md_node_id, matched_id, relation="EXPLAINS")
|
|
79
|
+
|
|
80
|
+
builder.save_graph()
|
|
81
|
+
console.print("Semantic binding complete.")
|
|
82
|
+
|
|
83
|
+
except Exception as e:
|
|
84
|
+
console.print(f"[bold red]Error during ingestion:[/bold red] {e}")
|
|
85
|
+
|
|
86
|
+
console.print("[bold green]Ingestion complete.[/bold green]")
|
|
87
|
+
|
|
88
|
+
@app.command()
|
|
89
|
+
def sync(path: str = typer.Argument(".", help="Path to the repository to sync")):
|
|
90
|
+
"""
|
|
91
|
+
Sync graph with modified git files.
|
|
92
|
+
"""
|
|
93
|
+
from nervapack.git.tracker import GitTracker
|
|
94
|
+
from nervapack.graph.builder import GraphBuilder
|
|
95
|
+
from nervapack.graph.vector_store import VectorStore
|
|
96
|
+
from nervapack.parser.ast_parser import ASTParser
|
|
97
|
+
from nervapack.parser.md_chunker import MarkdownChunker
|
|
98
|
+
import os
|
|
99
|
+
|
|
100
|
+
console.print("[bold blue]Syncing changed files with NervaPack graph...[/bold blue]")
|
|
101
|
+
|
|
102
|
+
tracker = GitTracker(path)
|
|
103
|
+
if not tracker.repo:
|
|
104
|
+
console.print("[bold red]Not a git repository. Cannot sync.[/bold red]")
|
|
105
|
+
raise typer.Exit(1)
|
|
106
|
+
|
|
107
|
+
changed_files = tracker.get_changed_files()
|
|
108
|
+
if not changed_files:
|
|
109
|
+
console.print("[bold green]No files changed. Graph is up to date.[/bold green]")
|
|
110
|
+
raise typer.Exit(0)
|
|
111
|
+
|
|
112
|
+
console.print(f"Found {len(changed_files)} changed files.")
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
builder = GraphBuilder()
|
|
116
|
+
graph = builder.load_graph()
|
|
117
|
+
vstore = VectorStore()
|
|
118
|
+
except Exception as e:
|
|
119
|
+
console.print(f"[bold red]Failed to load graph or vector store. Run 'nervapack ingest' first.[/bold red]")
|
|
120
|
+
raise typer.Exit(1)
|
|
121
|
+
|
|
122
|
+
ast_parser = ASTParser()
|
|
123
|
+
md_chunker = MarkdownChunker()
|
|
124
|
+
|
|
125
|
+
ast_docs = []
|
|
126
|
+
|
|
127
|
+
# Pre-gather all existing ast_docs for LLM binding
|
|
128
|
+
# We reconstruct a simple mock summary for existing nodes just for binding if needed.
|
|
129
|
+
# In a real app, we'd pull these from the graph directly.
|
|
130
|
+
for node, data in graph.nodes(data=True):
|
|
131
|
+
if data.get("type") in ["class", "function", "import"]:
|
|
132
|
+
ast_docs.append({
|
|
133
|
+
"node_id": node,
|
|
134
|
+
"summary": f"This is a {data.get('type')} named {data.get('name')} in {data.get('file_path')}. Code:\n{data.get('content')}"
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
for f in changed_files:
|
|
138
|
+
file_path = os.path.join(path, f)
|
|
139
|
+
|
|
140
|
+
# 1. Prune old nodes and vectors
|
|
141
|
+
builder.remove_nodes_for_file(file_path)
|
|
142
|
+
vstore.delete_by_file(file_path)
|
|
143
|
+
|
|
144
|
+
if not os.path.exists(file_path):
|
|
145
|
+
console.print(f"Removed [red]{f}[/red]")
|
|
146
|
+
continue
|
|
147
|
+
|
|
148
|
+
# 2. Re-parse and insert
|
|
149
|
+
if file_path.endswith(('.py', '.js', '.jsx', '.ts', '.tsx')):
|
|
150
|
+
entities = ast_parser.parse_file(file_path)
|
|
151
|
+
|
|
152
|
+
# Add to graph
|
|
153
|
+
file_node_id = f"file:{file_path}"
|
|
154
|
+
if not graph.has_node(file_node_id):
|
|
155
|
+
graph.add_node(file_node_id, type="file", path=file_path)
|
|
156
|
+
|
|
157
|
+
for entity in entities:
|
|
158
|
+
entity_node_id = f"{entity.type}:{entity.file_path}:{entity.name}:{entity.start_line}"
|
|
159
|
+
graph.add_node(
|
|
160
|
+
entity_node_id,
|
|
161
|
+
type=entity.type,
|
|
162
|
+
name=entity.name,
|
|
163
|
+
file_path=entity.file_path,
|
|
164
|
+
start_line=entity.start_line,
|
|
165
|
+
end_line=entity.end_line,
|
|
166
|
+
content=entity.content
|
|
167
|
+
)
|
|
168
|
+
graph.add_edge(file_node_id, entity_node_id, relation="DEFINES")
|
|
169
|
+
|
|
170
|
+
# Add to vector store
|
|
171
|
+
node_summary = {"node_id": entity_node_id, "summary": f"This is a {entity.type} named {entity.name} in {entity.file_path}. Code:\n{entity.content}", "file_path": entity.file_path}
|
|
172
|
+
vstore.ingest_ast_entities([node_summary])
|
|
173
|
+
ast_docs.append(node_summary)
|
|
174
|
+
|
|
175
|
+
console.print(f"Updated AST for [green]{f}[/green]")
|
|
176
|
+
|
|
177
|
+
elif file_path.endswith('.md'):
|
|
178
|
+
chunks = md_chunker.chunk_file(file_path)
|
|
179
|
+
if chunks:
|
|
180
|
+
vstore.ingest_chunks(chunks)
|
|
181
|
+
|
|
182
|
+
from nervapack.llm.summarizer import LLMSummarizer
|
|
183
|
+
llm = LLMSummarizer()
|
|
184
|
+
for i, chunk in enumerate(chunks):
|
|
185
|
+
md_node_id = f"md_{chunk['file_path']}_{i}"
|
|
186
|
+
graph.add_node(md_node_id, type="markdown", header=chunk['header'], content=chunk['content'], file_path=chunk['file_path'])
|
|
187
|
+
matched_ids = llm.bind_docs_to_ast(chunk['content'], ast_docs)
|
|
188
|
+
for matched_id in matched_ids:
|
|
189
|
+
if graph.has_node(matched_id):
|
|
190
|
+
graph.add_edge(md_node_id, matched_id, relation="EXPLAINS")
|
|
191
|
+
|
|
192
|
+
console.print(f"Updated Markdown for [cyan]{f}[/cyan]")
|
|
193
|
+
|
|
194
|
+
builder.save_graph()
|
|
195
|
+
console.print("[bold green]Sync complete.[/bold green]")
|
|
196
|
+
|
|
197
|
+
@app.command()
|
|
198
|
+
def query(prompt: str = typer.Argument(..., help="Query to run against the knowledge graph")):
|
|
199
|
+
"""
|
|
200
|
+
Query the knowledge graph for context.
|
|
201
|
+
"""
|
|
202
|
+
from nervapack.graph.builder import GraphBuilder
|
|
203
|
+
from nervapack.graph.vector_store import VectorStore
|
|
204
|
+
from nervapack.graph.retrieval import GraphRetriever
|
|
205
|
+
|
|
206
|
+
console.print(f"[bold magenta]Running query:[/bold magenta] {prompt}")
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
builder = GraphBuilder()
|
|
210
|
+
graph = builder.load_graph()
|
|
211
|
+
except Exception as e:
|
|
212
|
+
console.print(f"[bold red]Failed to load graph:[/bold red] {e}. Run 'nervapack ingest' first.")
|
|
213
|
+
raise typer.Exit(1)
|
|
214
|
+
|
|
215
|
+
try:
|
|
216
|
+
vstore = VectorStore()
|
|
217
|
+
results = vstore.search(prompt, n_results=3)
|
|
218
|
+
except Exception as e:
|
|
219
|
+
console.print(f"[bold red]Failed to query vector store:[/bold red] {e}")
|
|
220
|
+
raise typer.Exit(1)
|
|
221
|
+
|
|
222
|
+
start_nodes = []
|
|
223
|
+
if results and results['ids'] and len(results['ids']) > 0:
|
|
224
|
+
start_nodes = results['ids'][0]
|
|
225
|
+
|
|
226
|
+
if not start_nodes:
|
|
227
|
+
console.print("No relevant nodes found in vector search.")
|
|
228
|
+
raise typer.Exit(0)
|
|
229
|
+
|
|
230
|
+
console.print(f"Found {len(start_nodes)} seed nodes. Traversing graph...")
|
|
231
|
+
retriever = GraphRetriever(graph)
|
|
232
|
+
subgraph = retriever.retrieve_context(start_nodes, max_hops=1)
|
|
233
|
+
|
|
234
|
+
markdown_context = retriever.format_as_markdown(subgraph)
|
|
235
|
+
|
|
236
|
+
console.print("\n[bold cyan]--- Retrieved Context ---[/bold cyan]\n")
|
|
237
|
+
console.print(markdown_context)
|
|
238
|
+
console.print("\n[bold cyan]--- End Context ---[/bold cyan]\n")
|
|
239
|
+
console.print("Query complete.")
|
|
240
|
+
|
|
241
|
+
@app.command()
|
|
242
|
+
def status():
|
|
243
|
+
"""
|
|
244
|
+
Show the status of the local NervaPack graph.
|
|
245
|
+
"""
|
|
246
|
+
from nervapack.graph.builder import GraphBuilder
|
|
247
|
+
from nervapack.git.tracker import GitTracker
|
|
248
|
+
|
|
249
|
+
console.print("[bold cyan]NervaPack Status:[/bold cyan]")
|
|
250
|
+
|
|
251
|
+
try:
|
|
252
|
+
builder = GraphBuilder()
|
|
253
|
+
graph = builder.load_graph()
|
|
254
|
+
console.print(f"- Graph loaded: [green]Yes[/green]")
|
|
255
|
+
console.print(f"- Nodes: [cyan]{graph.number_of_nodes()}[/cyan]")
|
|
256
|
+
console.print(f"- Edges: [cyan]{graph.number_of_edges()}[/cyan]")
|
|
257
|
+
except Exception:
|
|
258
|
+
console.print("- Graph loaded: [red]No (Run 'nervapack ingest')[/red]")
|
|
259
|
+
|
|
260
|
+
gitsync = GitTracker()
|
|
261
|
+
if gitsync.repo:
|
|
262
|
+
changed = gitsync.get_changed_files()
|
|
263
|
+
console.print(f"- Git repo detected: [green]Yes[/green]")
|
|
264
|
+
if changed:
|
|
265
|
+
console.print(f"- Unsynced changes: [yellow]{len(changed)} file(s)[/yellow]")
|
|
266
|
+
for f in changed[:5]:
|
|
267
|
+
console.print(f" - {f}")
|
|
268
|
+
if len(changed) > 5:
|
|
269
|
+
console.print(" - ...")
|
|
270
|
+
else:
|
|
271
|
+
console.print("- Unsynced changes: [green]None[/green]")
|
|
272
|
+
else:
|
|
273
|
+
console.print("- Git repo detected: [yellow]No[/yellow]")
|
|
274
|
+
|
|
275
|
+
console.print("Status: OK")
|
|
276
|
+
|
|
277
|
+
if __name__ == "__main__":
|
|
278
|
+
app()
|
|
File without changes
|
nervapack/git/tracker.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import git
|
|
2
|
+
from typing import List
|
|
3
|
+
|
|
4
|
+
class GitTracker:
|
|
5
|
+
def __init__(self, repo_path: str = "."):
|
|
6
|
+
self.repo_path = repo_path
|
|
7
|
+
try:
|
|
8
|
+
self.repo = git.Repo(self.repo_path)
|
|
9
|
+
except git.InvalidGitRepositoryError:
|
|
10
|
+
self.repo = None
|
|
11
|
+
|
|
12
|
+
def get_changed_files(self, commit_sha: str = None) -> List[str]:
|
|
13
|
+
"""
|
|
14
|
+
Gets a list of modified files.
|
|
15
|
+
If commit_sha is provided, diffs against that.
|
|
16
|
+
Otherwise diffs the working tree against HEAD.
|
|
17
|
+
"""
|
|
18
|
+
if not self.repo:
|
|
19
|
+
return []
|
|
20
|
+
|
|
21
|
+
changed_files = []
|
|
22
|
+
|
|
23
|
+
if commit_sha:
|
|
24
|
+
try:
|
|
25
|
+
commit = self.repo.commit(commit_sha)
|
|
26
|
+
diffs = commit.diff(commit.parents[0] if commit.parents else None)
|
|
27
|
+
for diff in diffs:
|
|
28
|
+
changed_files.append(diff.b_path or diff.a_path)
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
else:
|
|
32
|
+
# Diff working tree against HEAD
|
|
33
|
+
diffs = self.repo.index.diff(None)
|
|
34
|
+
for diff in diffs:
|
|
35
|
+
changed_files.append(diff.b_path or diff.a_path)
|
|
36
|
+
|
|
37
|
+
# Staged diffs
|
|
38
|
+
staged_diffs = self.repo.index.diff("HEAD")
|
|
39
|
+
for diff in staged_diffs:
|
|
40
|
+
changed_files.append(diff.b_path or diff.a_path)
|
|
41
|
+
|
|
42
|
+
# Untracked files
|
|
43
|
+
changed_files.extend(self.repo.untracked_files)
|
|
44
|
+
|
|
45
|
+
# Remove duplicates
|
|
46
|
+
return list(set(changed_files))
|
|
File without changes
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import networkx as nx
|
|
2
|
+
from typing import List
|
|
3
|
+
from nervapack.parser.ast_parser import ParsedEntity
|
|
4
|
+
|
|
5
|
+
class GraphBuilder:
|
|
6
|
+
def __init__(self):
|
|
7
|
+
self.graph = nx.DiGraph()
|
|
8
|
+
|
|
9
|
+
def build_from_entities(self, entities: List[ParsedEntity]) -> nx.DiGraph:
|
|
10
|
+
"""
|
|
11
|
+
Takes a list of ParsedEntity and constructs a directed graph.
|
|
12
|
+
Files are nodes, entities are nodes. Contains/Defines edges connect them.
|
|
13
|
+
"""
|
|
14
|
+
for entity in entities:
|
|
15
|
+
# File Node
|
|
16
|
+
file_node_id = f"file:{entity.file_path}"
|
|
17
|
+
if not self.graph.has_node(file_node_id):
|
|
18
|
+
self.graph.add_node(file_node_id, type="file", path=entity.file_path)
|
|
19
|
+
|
|
20
|
+
# Entity Node
|
|
21
|
+
# Unique ID for the entity
|
|
22
|
+
entity_node_id = f"{entity.type}:{entity.file_path}:{entity.name}:{entity.start_line}"
|
|
23
|
+
self.graph.add_node(
|
|
24
|
+
entity_node_id,
|
|
25
|
+
type=entity.type,
|
|
26
|
+
name=entity.name,
|
|
27
|
+
file_path=entity.file_path,
|
|
28
|
+
start_line=entity.start_line,
|
|
29
|
+
end_line=entity.end_line,
|
|
30
|
+
content=entity.content
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Edge from File -> Entity
|
|
34
|
+
self.graph.add_edge(file_node_id, entity_node_id, relation="DEFINES")
|
|
35
|
+
|
|
36
|
+
return self.graph
|
|
37
|
+
|
|
38
|
+
def save_graph(self, path: str = ".nervapack/graph.graphml"):
|
|
39
|
+
import os
|
|
40
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
41
|
+
nx.write_graphml(self.graph, path)
|
|
42
|
+
|
|
43
|
+
def load_graph(self, path: str = ".nervapack/graph.graphml"):
|
|
44
|
+
self.graph = nx.read_graphml(path)
|
|
45
|
+
return self.graph
|
|
46
|
+
|
|
47
|
+
def remove_nodes_for_file(self, file_path: str):
|
|
48
|
+
"""Removes the file node and all entities associated with it."""
|
|
49
|
+
nodes_to_remove = []
|
|
50
|
+
file_node_id = f"file:{file_path}"
|
|
51
|
+
if self.graph.has_node(file_node_id):
|
|
52
|
+
nodes_to_remove.append(file_node_id)
|
|
53
|
+
|
|
54
|
+
for node, data in self.graph.nodes(data=True):
|
|
55
|
+
if data.get("file_path") == file_path:
|
|
56
|
+
nodes_to_remove.append(node)
|
|
57
|
+
|
|
58
|
+
self.graph.remove_nodes_from(nodes_to_remove)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import networkx as nx
|
|
2
|
+
from typing import List, Set, Dict
|
|
3
|
+
|
|
4
|
+
class GraphRetriever:
|
|
5
|
+
def __init__(self, graph: nx.DiGraph):
|
|
6
|
+
self.graph = graph
|
|
7
|
+
|
|
8
|
+
def retrieve_context(self, start_node_ids: List[str], max_hops: int = 2) -> nx.DiGraph:
|
|
9
|
+
"""
|
|
10
|
+
Retrieves a sub-graph using K-Hop BFS from the given start nodes.
|
|
11
|
+
Uses Betweenness Centrality to prune high-degree "hub" nodes if necessary.
|
|
12
|
+
"""
|
|
13
|
+
visited = set()
|
|
14
|
+
queue = [(node_id, 0) for node_id in start_node_ids if self.graph.has_node(node_id)]
|
|
15
|
+
|
|
16
|
+
subgraph_nodes = set()
|
|
17
|
+
|
|
18
|
+
while queue:
|
|
19
|
+
current_node, hops = queue.pop(0)
|
|
20
|
+
|
|
21
|
+
if current_node in visited:
|
|
22
|
+
continue
|
|
23
|
+
|
|
24
|
+
visited.add(current_node)
|
|
25
|
+
subgraph_nodes.add(current_node)
|
|
26
|
+
|
|
27
|
+
if hops < max_hops:
|
|
28
|
+
for neighbor in self.graph.neighbors(current_node):
|
|
29
|
+
if neighbor not in visited:
|
|
30
|
+
# Pruning logic: If degree is extremely high, it might be a utility file/hub.
|
|
31
|
+
# For now, we skip pruning if it's within hops, but this is where betweenness centrality could be applied.
|
|
32
|
+
queue.append((neighbor, hops + 1))
|
|
33
|
+
|
|
34
|
+
# Also traverse incoming edges
|
|
35
|
+
for predecessor in self.graph.predecessors(current_node):
|
|
36
|
+
if predecessor not in visited:
|
|
37
|
+
queue.append((predecessor, hops + 1))
|
|
38
|
+
|
|
39
|
+
return self.graph.subgraph(subgraph_nodes).copy()
|
|
40
|
+
|
|
41
|
+
def format_as_markdown(self, subgraph: nx.DiGraph) -> str:
|
|
42
|
+
"""
|
|
43
|
+
Formats the retrieved sub-graph into a minimized, clean Markdown block.
|
|
44
|
+
"""
|
|
45
|
+
markdown_lines = []
|
|
46
|
+
markdown_lines.append("# NervaPack Context Retrieval\n")
|
|
47
|
+
|
|
48
|
+
# Group by file
|
|
49
|
+
files = {}
|
|
50
|
+
for node, data in subgraph.nodes(data=True):
|
|
51
|
+
if data.get('type') == 'file':
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
file_path = data.get('file_path', 'Unknown')
|
|
55
|
+
if file_path not in files:
|
|
56
|
+
files[file_path] = []
|
|
57
|
+
files[file_path].append(data)
|
|
58
|
+
|
|
59
|
+
for file_path, nodes in files.items():
|
|
60
|
+
markdown_lines.append(f"## File: `{file_path}`\n")
|
|
61
|
+
# Sort by start line
|
|
62
|
+
nodes = sorted(nodes, key=lambda x: x.get('start_line', 0))
|
|
63
|
+
for node_data in nodes:
|
|
64
|
+
node_type = node_data.get('type', 'entity').upper()
|
|
65
|
+
name = node_data.get('name', 'Unknown')
|
|
66
|
+
lines = f"(L{node_data.get('start_line', '?')}-L{node_data.get('end_line', '?')})"
|
|
67
|
+
markdown_lines.append(f"### {node_type}: {name} {lines}")
|
|
68
|
+
|
|
69
|
+
content = node_data.get('content', '')
|
|
70
|
+
if content:
|
|
71
|
+
markdown_lines.append("```")
|
|
72
|
+
markdown_lines.append(content)
|
|
73
|
+
markdown_lines.append("```\n")
|
|
74
|
+
|
|
75
|
+
return "\n".join(markdown_lines)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import chromadb
|
|
2
|
+
from typing import List, Dict
|
|
3
|
+
|
|
4
|
+
class VectorStore:
|
|
5
|
+
def __init__(self, db_path: str = ".nervapack/chroma_db"):
|
|
6
|
+
self.client = chromadb.PersistentClient(path=db_path)
|
|
7
|
+
# We use a single collection for both AST node summaries and Markdown chunks
|
|
8
|
+
self.collection = self.client.get_or_create_collection(name="nervapack_nodes")
|
|
9
|
+
|
|
10
|
+
def ingest_chunks(self, chunks: List[Dict[str, str]]):
|
|
11
|
+
"""
|
|
12
|
+
Ingest a list of Markdown chunks into the vector store.
|
|
13
|
+
"""
|
|
14
|
+
if not chunks:
|
|
15
|
+
return
|
|
16
|
+
|
|
17
|
+
documents = []
|
|
18
|
+
metadatas = []
|
|
19
|
+
ids = []
|
|
20
|
+
|
|
21
|
+
for i, chunk in enumerate(chunks):
|
|
22
|
+
documents.append(chunk["content"])
|
|
23
|
+
metadatas.append({"header": chunk["header"], "file_path": chunk["file_path"], "type": "markdown"})
|
|
24
|
+
ids.append(f"md_{chunk['file_path']}_{i}")
|
|
25
|
+
|
|
26
|
+
self.collection.add(
|
|
27
|
+
documents=documents,
|
|
28
|
+
metadatas=metadatas,
|
|
29
|
+
ids=ids
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
def ingest_ast_entities(self, entities: List[Dict[str, str]]):
|
|
33
|
+
"""
|
|
34
|
+
Ingest AST summaries into the vector store.
|
|
35
|
+
"""
|
|
36
|
+
if not entities:
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
documents = []
|
|
40
|
+
metadatas = []
|
|
41
|
+
ids = []
|
|
42
|
+
|
|
43
|
+
for entity in entities:
|
|
44
|
+
documents.append(entity["summary"])
|
|
45
|
+
# Assuming 'file_path' is added to the entity dict in cli.py
|
|
46
|
+
metadatas.append({"node_id": entity["node_id"], "type": "ast", "file_path": entity.get("file_path", "")})
|
|
47
|
+
ids.append(entity["node_id"])
|
|
48
|
+
|
|
49
|
+
self.collection.add(
|
|
50
|
+
documents=documents,
|
|
51
|
+
metadatas=metadatas,
|
|
52
|
+
ids=ids
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def search(self, query: str, n_results: int = 5):
|
|
56
|
+
return self.collection.query(
|
|
57
|
+
query_texts=[query],
|
|
58
|
+
n_results=n_results
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def delete_by_file(self, file_path: str):
|
|
62
|
+
"""Delete all vectors associated with a specific file."""
|
|
63
|
+
self.collection.delete(where={"file_path": file_path})
|
|
File without changes
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import ollama
|
|
2
|
+
from typing import List, Dict
|
|
3
|
+
from nervapack.parser.ast_parser import ParsedEntity
|
|
4
|
+
|
|
5
|
+
class LLMSummarizer:
|
|
6
|
+
def __init__(self, model_name: str = "llama3"):
|
|
7
|
+
self.model_name = model_name
|
|
8
|
+
|
|
9
|
+
def summarize_entity(self, entity: ParsedEntity) -> str:
|
|
10
|
+
"""
|
|
11
|
+
Generate a quick summary for an AST node using Ollama.
|
|
12
|
+
"""
|
|
13
|
+
prompt = f"Summarize the following code block (Type: {entity.type}, Name: {entity.name}):\n\n```\n{entity.content}\n```\n\nSummary:"
|
|
14
|
+
try:
|
|
15
|
+
response = ollama.chat(model=self.model_name, messages=[
|
|
16
|
+
{"role": "system", "content": "You are a concise code summarizer. Output only a 1-3 sentence summary of what the code does."},
|
|
17
|
+
{"role": "user", "content": prompt}
|
|
18
|
+
])
|
|
19
|
+
return response['message']['content']
|
|
20
|
+
except Exception as e:
|
|
21
|
+
return f"Summary unavailable: {str(e)}"
|
|
22
|
+
|
|
23
|
+
def bind_docs_to_ast(self, doc_chunk: str, ast_nodes: List[Dict[str, str]]) -> List[str]:
|
|
24
|
+
"""
|
|
25
|
+
Takes a documentation chunk and a list of candidate AST nodes.
|
|
26
|
+
Returns a list of node_ids that the documentation EXPLAINS or IMPLEMENTS.
|
|
27
|
+
"""
|
|
28
|
+
candidates_str = "\n".join([f"ID: {n['node_id']} | Summary: {n['summary']}" for n in ast_nodes])
|
|
29
|
+
prompt = (
|
|
30
|
+
f"Given the following documentation chunk:\n\n{doc_chunk}\n\n"
|
|
31
|
+
f"Which of the following code entities does it explain or implement? "
|
|
32
|
+
f"Return a comma-separated list of IDs only, or 'None' if none match.\n\n"
|
|
33
|
+
f"Candidates:\n{candidates_str}\n\nMatched IDs:"
|
|
34
|
+
)
|
|
35
|
+
try:
|
|
36
|
+
response = ollama.chat(model=self.model_name, messages=[
|
|
37
|
+
{"role": "system", "content": "You are an AI binding engine. Output ONLY a comma-separated list of IDs."},
|
|
38
|
+
{"role": "user", "content": prompt}
|
|
39
|
+
])
|
|
40
|
+
content = response['message']['content'].strip()
|
|
41
|
+
if content.lower() == "none" or not content:
|
|
42
|
+
return []
|
|
43
|
+
return [i.strip() for i in content.split(",") if i.strip()]
|
|
44
|
+
except Exception:
|
|
45
|
+
return []
|
|
File without changes
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import List, Dict, Any, Optional
|
|
5
|
+
|
|
6
|
+
import tree_sitter_python
|
|
7
|
+
import tree_sitter_javascript
|
|
8
|
+
import tree_sitter_typescript
|
|
9
|
+
from tree_sitter import Language, Parser, Node
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class ParsedEntity:
|
|
13
|
+
name: str
|
|
14
|
+
type: str # 'class', 'function', 'import', 'export'
|
|
15
|
+
file_path: str
|
|
16
|
+
start_line: int
|
|
17
|
+
end_line: int
|
|
18
|
+
content: str
|
|
19
|
+
metadata: Dict[str, Any]
|
|
20
|
+
|
|
21
|
+
class ASTParser:
|
|
22
|
+
def __init__(self):
|
|
23
|
+
self.languages = {
|
|
24
|
+
".py": Language(tree_sitter_python.language()),
|
|
25
|
+
".js": Language(tree_sitter_javascript.language()),
|
|
26
|
+
".jsx": Language(tree_sitter_javascript.language()),
|
|
27
|
+
".ts": Language(tree_sitter_typescript.language_typescript()),
|
|
28
|
+
".tsx": Language(tree_sitter_typescript.language_tsx())
|
|
29
|
+
}
|
|
30
|
+
self.parsers = {}
|
|
31
|
+
for ext, lang in self.languages.items():
|
|
32
|
+
parser = Parser(lang)
|
|
33
|
+
self.parsers[ext] = parser
|
|
34
|
+
|
|
35
|
+
def parse_file(self, file_path: str) -> List[ParsedEntity]:
|
|
36
|
+
ext = Path(file_path).suffix
|
|
37
|
+
if ext not in self.parsers:
|
|
38
|
+
return []
|
|
39
|
+
|
|
40
|
+
with open(file_path, "rb") as f:
|
|
41
|
+
content_bytes = f.read()
|
|
42
|
+
|
|
43
|
+
tree = self.parsers[ext].parse(content_bytes)
|
|
44
|
+
entities = []
|
|
45
|
+
self._traverse_tree(tree.root_node, content_bytes, file_path, ext, entities)
|
|
46
|
+
return entities
|
|
47
|
+
|
|
48
|
+
def _traverse_tree(self, node: Node, content_bytes: bytes, file_path: str, ext: str, entities: List[ParsedEntity]):
|
|
49
|
+
# Simple extraction logic for Python and JS/TS
|
|
50
|
+
if node.type in ["class_definition", "class_declaration"]:
|
|
51
|
+
name_node = node.child_by_field_name("name")
|
|
52
|
+
if name_node:
|
|
53
|
+
name = name_node.text.decode("utf8")
|
|
54
|
+
entities.append(self._create_entity(name, "class", node, content_bytes, file_path))
|
|
55
|
+
|
|
56
|
+
elif node.type in ["function_definition", "function_declaration", "method_definition"]:
|
|
57
|
+
name_node = node.child_by_field_name("name")
|
|
58
|
+
if name_node:
|
|
59
|
+
name = name_node.text.decode("utf8")
|
|
60
|
+
entities.append(self._create_entity(name, "function", node, content_bytes, file_path))
|
|
61
|
+
|
|
62
|
+
elif node.type in ["import_statement", "import_from_statement", "import_declaration"]:
|
|
63
|
+
# For simplicity, extract the entire import block as an entity for the graph
|
|
64
|
+
name = f"import_{node.start_point[0]}"
|
|
65
|
+
entities.append(self._create_entity(name, "import", node, content_bytes, file_path))
|
|
66
|
+
|
|
67
|
+
for child in node.children:
|
|
68
|
+
self._traverse_tree(child, content_bytes, file_path, ext, entities)
|
|
69
|
+
|
|
70
|
+
def _create_entity(self, name: str, entity_type: str, node: Node, content_bytes: bytes, file_path: str) -> ParsedEntity:
|
|
71
|
+
return ParsedEntity(
|
|
72
|
+
name=name,
|
|
73
|
+
type=entity_type,
|
|
74
|
+
file_path=file_path,
|
|
75
|
+
start_line=node.start_point[0] + 1,
|
|
76
|
+
end_line=node.end_point[0] + 1,
|
|
77
|
+
content=node.text.decode("utf8"),
|
|
78
|
+
metadata={}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def scan_directory(directory: str) -> List[ParsedEntity]:
|
|
82
|
+
parser = ASTParser()
|
|
83
|
+
all_entities = []
|
|
84
|
+
for root, _, files in os.walk(directory):
|
|
85
|
+
# Ignore common bad directories
|
|
86
|
+
if any(ignored in root for ignored in [".git", "node_modules", "venv", "__pycache__"]):
|
|
87
|
+
continue
|
|
88
|
+
for file in files:
|
|
89
|
+
file_path = os.path.join(root, file)
|
|
90
|
+
all_entities.extend(parser.parse_file(file_path))
|
|
91
|
+
return all_entities
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import List, Dict
|
|
3
|
+
|
|
4
|
+
class MarkdownChunker:
|
|
5
|
+
def __init__(self):
|
|
6
|
+
# A simple regex for matching markdown headers
|
|
7
|
+
self.header_regex = re.compile(r'^(#{1,6})\s+(.*)')
|
|
8
|
+
|
|
9
|
+
def chunk_file(self, file_path: str) -> List[Dict[str, str]]:
|
|
10
|
+
"""
|
|
11
|
+
Parses a Markdown file and returns chunks separated by headers.
|
|
12
|
+
"""
|
|
13
|
+
try:
|
|
14
|
+
with open(file_path, 'r', encoding='utf-8') as f:
|
|
15
|
+
lines = f.readlines()
|
|
16
|
+
except Exception:
|
|
17
|
+
return []
|
|
18
|
+
|
|
19
|
+
chunks = []
|
|
20
|
+
current_chunk = []
|
|
21
|
+
current_header = "Document Root"
|
|
22
|
+
|
|
23
|
+
for line in lines:
|
|
24
|
+
match = self.header_regex.match(line)
|
|
25
|
+
if match:
|
|
26
|
+
# Save previous chunk
|
|
27
|
+
if current_chunk:
|
|
28
|
+
content = "".join(current_chunk).strip()
|
|
29
|
+
if content:
|
|
30
|
+
chunks.append({
|
|
31
|
+
"header": current_header,
|
|
32
|
+
"content": content,
|
|
33
|
+
"file_path": file_path
|
|
34
|
+
})
|
|
35
|
+
current_header = match.group(2).strip()
|
|
36
|
+
current_chunk = [line]
|
|
37
|
+
else:
|
|
38
|
+
current_chunk.append(line)
|
|
39
|
+
|
|
40
|
+
# Add the last chunk
|
|
41
|
+
if current_chunk:
|
|
42
|
+
content = "".join(current_chunk).strip()
|
|
43
|
+
if content:
|
|
44
|
+
chunks.append({
|
|
45
|
+
"header": current_header,
|
|
46
|
+
"content": content,
|
|
47
|
+
"file_path": file_path
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
return chunks
|
|
51
|
+
|
|
52
|
+
def scan_markdown_directory(directory: str) -> List[Dict[str, str]]:
|
|
53
|
+
import os
|
|
54
|
+
chunker = MarkdownChunker()
|
|
55
|
+
all_chunks = []
|
|
56
|
+
for root, _, files in os.walk(directory):
|
|
57
|
+
# Ignore common bad directories
|
|
58
|
+
if any(ignored in root for ignored in [".git", "node_modules", "venv", "__pycache__"]):
|
|
59
|
+
continue
|
|
60
|
+
for file in files:
|
|
61
|
+
if file.endswith(".md"):
|
|
62
|
+
file_path = os.path.join(root, file)
|
|
63
|
+
all_chunks.extend(chunker.chunk_file(file_path))
|
|
64
|
+
return all_chunks
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nervapack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Privacy-first, offline knowledge graph for developers
|
|
5
|
+
Author-email: Preetam Ramdhave <ramdhavepreetam@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ramdhavepreetam/NervaPack
|
|
8
|
+
Project-URL: Repository, https://github.com/ramdhavepreetam/NervaPack
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/ramdhavepreetam/NervaPack/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/ramdhavepreetam/NervaPack#readme
|
|
11
|
+
Keywords: knowledge-graph,rag,ast,code-search,offline,llm,developer-tools
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Operating System :: OS Independent
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: typer>=0.9.0
|
|
26
|
+
Requires-Dist: rich>=13.0.0
|
|
27
|
+
Requires-Dist: tree-sitter>=0.22.3
|
|
28
|
+
Requires-Dist: tree-sitter-python>=0.21.0
|
|
29
|
+
Requires-Dist: tree-sitter-javascript>=0.21.2
|
|
30
|
+
Requires-Dist: tree-sitter-typescript>=0.21.2
|
|
31
|
+
Requires-Dist: networkx>=3.1
|
|
32
|
+
Requires-Dist: ollama>=0.2.0
|
|
33
|
+
Requires-Dist: gitpython>=3.1.30
|
|
34
|
+
Requires-Dist: chromadb>=0.4.24
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# NervaPack
|
|
38
|
+
|
|
39
|
+
[](https://pypi.org/project/nervapack/)
|
|
40
|
+
[](https://pypi.org/project/nervapack/)
|
|
41
|
+
[](https://opensource.org/licenses/MIT)
|
|
42
|
+
|
|
43
|
+
**NervaPack** is a privacy-first, offline knowledge graph for your codebase. It solves two fundamental problems with standard Vector RAG:
|
|
44
|
+
|
|
45
|
+
- **Token waste** — chunk-based RAG retrieves blobs of text that may only tangentially relate to your query, bloating your context window.
|
|
46
|
+
- **Privacy risk** — sending code to cloud embedding APIs leaks your proprietary logic.
|
|
47
|
+
|
|
48
|
+
NervaPack runs 100% on your machine. It uses `tree-sitter` to parse your codebase into a deterministic Abstract Syntax Tree graph, then uses a local Ollama model to draw hard semantic edges between your documentation and your code. Queries traverse this graph with a K-Hop BFS, returning a hyper-targeted, token-efficient context window — no cloud required.
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Why NervaPack vs. standard Vector RAG
|
|
53
|
+
|
|
54
|
+
| | Standard Vector RAG | NervaPack |
|
|
55
|
+
|---|---|---|
|
|
56
|
+
| **Parsing** | Arbitrary text chunks | Deterministic AST nodes (class, function, import) |
|
|
57
|
+
| **Retrieval** | Nearest-neighbor blob | K-Hop BFS on a structural graph |
|
|
58
|
+
| **Doc ↔ Code links** | None | Hard `EXPLAINS` edges drawn by local LLM |
|
|
59
|
+
| **Privacy** | Cloud embeddings | 100% local (ChromaDB + Ollama) |
|
|
60
|
+
| **Incremental sync** | Re-index everything | Surgical per-file update via GitPython diff |
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Prerequisites
|
|
65
|
+
|
|
66
|
+
- **Python 3.10+**
|
|
67
|
+
- **Ollama** — install from [ollama.com](https://ollama.com/), then pull a model:
|
|
68
|
+
```bash
|
|
69
|
+
ollama pull llama3
|
|
70
|
+
```
|
|
71
|
+
NervaPack defaults to `llama3`. Any model that can follow instructions works.
|
|
72
|
+
- **Git** — your project must be a git repository (`git init` if not).
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## Installation
|
|
77
|
+
|
|
78
|
+
**Option A — Homebrew (Mac/Linux, recommended)**
|
|
79
|
+
```bash
|
|
80
|
+
brew tap ramdhavepreetam/nervapack
|
|
81
|
+
brew install nervapack
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**Option B — pipx (any platform, cleanest Python install)**
|
|
85
|
+
```bash
|
|
86
|
+
pipx install nervapack
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**Option C — pip**
|
|
90
|
+
```bash
|
|
91
|
+
pip install nervapack
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
> On first run, `chromadb` downloads `onnxruntime` embedding models to your cache and `tree-sitter` compiles its language bindings. This is a one-time setup (~1–2 min).
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Quick Start
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
cd your-project/
|
|
102
|
+
|
|
103
|
+
# 1. Build the knowledge graph (run once)
|
|
104
|
+
nervapack ingest .
|
|
105
|
+
|
|
106
|
+
# 2. Query for context
|
|
107
|
+
nervapack query "How does authentication work?"
|
|
108
|
+
|
|
109
|
+
# 3. After modifying files, sync the graph incrementally
|
|
110
|
+
nervapack sync .
|
|
111
|
+
|
|
112
|
+
# 4. Check graph health
|
|
113
|
+
nervapack status
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Command Reference
|
|
119
|
+
|
|
120
|
+
### `nervapack ingest [PATH]`
|
|
121
|
+
|
|
122
|
+
Scans `PATH` (default: `.`) and builds the full knowledge graph.
|
|
123
|
+
|
|
124
|
+
What happens:
|
|
125
|
+
1. `tree-sitter` parses all `.py`, `.js`, `.jsx`, `.ts`, `.tsx` files into Classes, Functions, and Imports — exact AST nodes, not text chunks.
|
|
126
|
+
2. All `.md` files are chunked by header hierarchy.
|
|
127
|
+
3. Each Markdown chunk is sent to your local Ollama model. If the model identifies a code entity the prose explains, a hard `EXPLAINS` edge is written into the graph.
|
|
128
|
+
4. All nodes are embedded and stored in a local ChromaDB instance (`.nervapack/chroma_db`).
|
|
129
|
+
|
|
130
|
+
> The initial LLM binding pass is the slowest step. On a large repo with many docs, budget several minutes.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
### `nervapack query PROMPT`
|
|
135
|
+
|
|
136
|
+
Retrieves context from the graph for a natural-language prompt.
|
|
137
|
+
|
|
138
|
+
What happens:
|
|
139
|
+
1. The prompt is embedded and ChromaDB returns the top-3 most semantically similar nodes.
|
|
140
|
+
2. Those nodes seed a K-Hop Breadth-First Search (default `max_hops=1`) through the NetworkX graph.
|
|
141
|
+
3. Adjacent nodes — including any Markdown docs linked via `EXPLAINS` edges — are collected into a compressed Markdown snippet and printed to your terminal.
|
|
142
|
+
|
|
143
|
+
The output is designed to be pasted directly into an LLM prompt as context.
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
### `nervapack sync [PATH]`
|
|
148
|
+
|
|
149
|
+
Incrementally updates the graph for files changed since the last ingest.
|
|
150
|
+
|
|
151
|
+
What happens:
|
|
152
|
+
1. `GitPython` diffs your working tree to find modified and deleted files.
|
|
153
|
+
2. For each changed file, old graph nodes and ChromaDB vectors are pruned.
|
|
154
|
+
3. Only the changed files are re-parsed and re-ingested.
|
|
155
|
+
|
|
156
|
+
A full `ingest` on a large codebase can take minutes. `sync` turns that into a 2–5 second surgical update.
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
### `nervapack status`
|
|
161
|
+
|
|
162
|
+
Prints the current state of the graph: node count, edge count, and any files that are out of sync with the graph.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Configuration
|
|
167
|
+
|
|
168
|
+
NervaPack reads the Ollama model from the `LLMSummarizer` class (`src/nervapack/llm/summarizer.py`). To use a different model, set `model` to any model you have pulled locally:
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
# src/nervapack/llm/summarizer.py
|
|
172
|
+
self.model = "phi3" # or "mistral", "codellama", etc.
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Ollama is expected at `http://localhost:11434` (its default). To use a remote Ollama instance, set `OLLAMA_HOST`:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
OLLAMA_HOST=http://my-server:11434 nervapack ingest .
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## Architecture
|
|
184
|
+
|
|
185
|
+
```
|
|
186
|
+
nervapack ingest .
|
|
187
|
+
│
|
|
188
|
+
├─ ASTParser (tree-sitter)
|
|
189
|
+
│ └─ ParsedEntity[]: class, function, import
|
|
190
|
+
│
|
|
191
|
+
├─ GraphBuilder (NetworkX DiGraph)
|
|
192
|
+
│ ├─ Nodes: file, class, function, import, markdown
|
|
193
|
+
│ └─ Edges: DEFINES, EXPLAINS
|
|
194
|
+
│
|
|
195
|
+
├─ LLMSummarizer (Ollama)
|
|
196
|
+
│ └─ Draws EXPLAINS edges: markdown → code entity
|
|
197
|
+
│
|
|
198
|
+
└─ VectorStore (ChromaDB)
|
|
199
|
+
└─ Embeds node summaries for semantic search
|
|
200
|
+
|
|
201
|
+
nervapack query "..."
|
|
202
|
+
│
|
|
203
|
+
├─ VectorStore.search() → seed node IDs
|
|
204
|
+
└─ GraphRetriever.retrieve_context() → BFS subgraph → Markdown
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
**Storage layout** (inside your project root):
|
|
208
|
+
```
|
|
209
|
+
.nervapack/
|
|
210
|
+
├── graph.graphml # NetworkX graph (deterministic structure)
|
|
211
|
+
└── chroma_db/ # ChromaDB (semantic embeddings)
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
**Source modules:**
|
|
215
|
+
| Module | Responsibility |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `nervapack.parser.ast_parser` | Tree-sitter parsing → `ParsedEntity` objects |
|
|
218
|
+
| `nervapack.parser.md_chunker` | Markdown → header-delimited chunks |
|
|
219
|
+
| `nervapack.graph.builder` | Build and persist the NetworkX DiGraph |
|
|
220
|
+
| `nervapack.graph.vector_store` | ChromaDB ingest and semantic search |
|
|
221
|
+
| `nervapack.graph.retrieval` | K-Hop BFS context extraction |
|
|
222
|
+
| `nervapack.llm.summarizer` | Local Ollama interface for LLM binding |
|
|
223
|
+
| `nervapack.git.tracker` | GitPython diff for incremental sync |
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Privacy
|
|
228
|
+
|
|
229
|
+
NervaPack is 100% offline. No code, documentation, or query ever leaves your machine:
|
|
230
|
+
|
|
231
|
+
- Embeddings are generated by ChromaDB's built-in local model.
|
|
232
|
+
- LLM calls go exclusively to `localhost:11434` (your Ollama instance).
|
|
233
|
+
- All graph and vector data is stored in `.nervapack/` inside your project.
|
|
234
|
+
|
|
235
|
+
Add `.nervapack/` to your `.gitignore` to keep it out of version control.
|
|
236
|
+
|
|
237
|
+
---
|
|
238
|
+
|
|
239
|
+
## Contributing
|
|
240
|
+
|
|
241
|
+
1. Fork the repo and create a branch.
|
|
242
|
+
2. Make your changes with tests where applicable.
|
|
243
|
+
3. Open a pull request against `master`.
|
|
244
|
+
|
|
245
|
+
Bug reports and feature requests go to the [issue tracker](https://github.com/ramdhavepreetam/NervaPack/issues).
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## License
|
|
250
|
+
|
|
251
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
nervapack/__init__.py,sha256=40vPG8PV_0KBbr_bW_RQIJCfrazA01s1-u5gPWzPFjs,19
|
|
2
|
+
nervapack/cli.py,sha256=joW4W8WcrXW2aQ4SiBwonvF0JD9YMbAgtVPJec705Tw,11193
|
|
3
|
+
nervapack/git/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
nervapack/git/tracker.py,sha256=vpk0UJxBEfxZ1lyVqcRbHxHoW2cA81zpsHhAGErLTkw,1498
|
|
5
|
+
nervapack/graph/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
nervapack/graph/builder.py,sha256=HN0NM3-KjNLem4-QIw_dRYirgVbWQVwTyfvgCPRXiUE,2166
|
|
7
|
+
nervapack/graph/retrieval.py,sha256=SCvbkzty5d6zA_10yMj7GJVwxyRPLy4TLBPK5SN7DVQ,3043
|
|
8
|
+
nervapack/graph/vector_store.py,sha256=5-rBqgwb5RMZvHrEuDtv6kzwV1-XmDrpOE9gLiHBbjQ,2036
|
|
9
|
+
nervapack/llm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
nervapack/llm/summarizer.py,sha256=NCmY_8K0TaSDFglyq1JyOMOvDOxXxQf0vCtMxPNf5x4,2171
|
|
11
|
+
nervapack/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
nervapack/parser/ast_parser.py,sha256=N-x1Hk1sDRNgOWftB54le7FBix7Tn_FjSo6DBZhJBXA,3603
|
|
13
|
+
nervapack/parser/md_chunker.py,sha256=o3mKfWDaQLdtezo-AUHxO45Ii53d386fJnAwZJnMzL8,2176
|
|
14
|
+
nervapack-0.1.0.dist-info/licenses/LICENSE,sha256=FWEWrQ3gFAwZTFoPP1mSI1RpPc1Qbzpp2X1zuW_jiyk,1073
|
|
15
|
+
nervapack-0.1.0.dist-info/METADATA,sha256=BJMk64mYzV4bzBH9pgszBtm6Mgoag3ZloTNKEUPNjr8,8695
|
|
16
|
+
nervapack-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
17
|
+
nervapack-0.1.0.dist-info/entry_points.txt,sha256=Ke1CpbU-LPw7I26PCAnpm_n7E0GKtDn8FG0ITWnAgZQ,48
|
|
18
|
+
nervapack-0.1.0.dist-info/top_level.txt,sha256=PKpoqpD5E4FU4pXFYs8qUt7dSQnM_UYGNqF7djWbF04,10
|
|
19
|
+
nervapack-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Preetam Ramdhave
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nervapack
|