lakonai 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -11
- package/bin/lakonai.js +7 -1
- package/package.json +1 -1
- package/src/graph/annotate.js +195 -0
- package/src/graph/embed.js +25 -3
- package/src/graph/index.js +32 -3
- package/src/graph/parser.js +81 -16
- package/src/hooks/session-start.js +46 -0
package/README.md
CHANGED
|
@@ -31,15 +31,29 @@
|
|
|
31
31
|
|
|
32
32
|
## Real savings, measured
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
All numbers from live projects using `lakonai@1.1.1`.
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
|
39
|
-
|
|
40
|
-
| `
|
|
41
|
-
| `git diff HEAD~
|
|
42
|
-
| `
|
|
36
|
+
**CLI filters** — output compressed before it reaches the model (React + TipTap + Yjs microfrontend, 2,185 files):
|
|
37
|
+
|
|
38
|
+
| Command | Raw | Filtered | Saved |
|
|
39
|
+
|---|---:|---:|---:|
|
|
40
|
+
| `git log -20` | 17,097 tok | 450 tok | **−97%** |
|
|
41
|
+
| `git diff HEAD~3` | 10,780 tok | 1,952 tok | **−82%** |
|
|
42
|
+
| `git diff main…HEAD` ¹ | 1,513,910 tok | 2,331 tok | **−99.8%** |
|
|
43
|
+
| `find src -type f` | 28,392 tok | 707 tok | **−97%** |
|
|
44
|
+
| `ls -la` | 913 tok | 212 tok | **−77%** |
|
|
45
|
+
|
|
46
|
+
¹ 182k-line diff — previously crashed with `ENOBUFS`. Fixed in 1.1.1.
|
|
47
|
+
|
|
48
|
+
**Read-guard** — compact AST subgraph served instead of the raw file (WhatsApp client SDK, 300 files, 816 nodes):
|
|
49
|
+
|
|
50
|
+
| File | Raw | Subgraph | Saved |
|
|
51
|
+
|---|---:|---:|---:|
|
|
52
|
+
| `WAProto/index.js` | 293,256 tok | 13 tok | **−100%** |
|
|
53
|
+
| `src/index.js` | 1,849 tok | 69 tok | **−96%** |
|
|
54
|
+
| `src/index.d.ts` | 1,470 tok | 37 tok | **−97%** |
|
|
55
|
+
| `ProviderPanel.tsx` | 1,400 tok | 33 tok | **−98%** |
|
|
56
|
+
| `server/wa-client.js` | 1,134 tok | 9 tok | **−99%** |
|
|
43
57
|
|
|
44
58
|
**Proxy compression** — what actually reaches the Anthropic API (real session, 49 requests):
|
|
45
59
|
|
|
@@ -49,7 +63,6 @@
|
|
|
49
63
|
| Build log (80 lines)| 1,298 tok | 8 tok | **-99%** |
|
|
50
64
|
| JSON API (120 users)| 2,386 tok | 104 tok | **-96%** |
|
|
51
65
|
| Git diff | ~3,000 tok | ~2,880 tok | **-4%**|
|
|
52
|
-
| Source file read | via graph read-guard → **-87%** | |
|
|
53
66
|
|
|
54
67
|
**Typical coding session:** ~53% savings from proxy alone, ~75% with graph read-guard.
|
|
55
68
|
|
|
@@ -99,7 +112,7 @@ lakonai ls -la # → files without noise
|
|
|
99
112
|
|
|
100
113
|
### Layer 2 — Graph read-guard (Claude Code)
|
|
101
114
|
|
|
102
|
-
`lakonai graph build` parses your codebase into an AST knowledge graph — pure AST, works in under a second for most projects. When Claude Code reads a source file, the read-guard intercepts and returns a compact subgraph (symbols, edges, community) instead of the full text.
|
|
115
|
+
`lakonai graph build` parses your codebase into an AST knowledge graph — zero LLM, pure AST, works in under a second for most projects. When Claude Code reads a source file, the read-guard intercepts and returns a compact subgraph (symbols, edges, community) instead of the full text.
|
|
103
116
|
|
|
104
117
|
```
|
|
105
118
|
102 files → 512 nodes → 573 edges built in <0.1s
|
|
@@ -107,16 +120,33 @@ file read: 2,835 tok raw → 300 tok subgraph (-89%)
|
|
|
107
120
|
```
|
|
108
121
|
|
|
109
122
|
```bash
|
|
110
|
-
lakonai graph build # build / rebuild
|
|
123
|
+
lakonai graph build # build / rebuild (auto-annotates + embeds)
|
|
111
124
|
lakonai graph query "what calls parseFile?"
|
|
112
125
|
lakonai graph explain src/foo.js
|
|
113
126
|
lakonai graph path src/a.js src/b.js
|
|
114
127
|
lakonai graph html # open interactive viz
|
|
115
128
|
lakonai graph watch # rebuild on file change
|
|
129
|
+
lakonai graph annotate # regenerate LLM docblocks only
|
|
116
130
|
```
|
|
117
131
|
|
|
118
132
|
The graph JSON is auto-added to `.gitignore`. Set `LAKON_GRAPH_CAT=0` to bypass.
|
|
119
133
|
|
|
134
|
+
**Semantic search** — install `@xenova/transformers` to unlock hybrid BM25 + vector search (BGE-small-en-v1.5, ~23 MB, runs fully local):
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
npm install @xenova/transformers
|
|
138
|
+
lakonai graph build # first run downloads the model, subsequent runs are instant
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
On build, lakonai auto-annotates undocumented files via `claude --print` (Haiku, zero config for Claude Code users) and stores one-line search-optimised docblocks in `lakonai-graph/annotations.json` — source files are never modified. Only new or modified files are re-annotated (mtime-based cache).
|
|
142
|
+
|
|
143
|
+
Benchmark on the lakonai codebase itself (30 queries, 15 literal + 15 semantic):
|
|
144
|
+
|
|
145
|
+
| Method | Score | Literal | Semantic |
|
|
146
|
+
|--------|------:|--------:|---------:|
|
|
147
|
+
| BM25 only | 19/30 | 15/15 | 4/15 |
|
|
148
|
+
| Hybrid (BM25 + semantic) | **29/30** | 15/15 | 14/15 |
|
|
149
|
+
|
|
120
150
|
### Layer 3 — Proxy compression (Claude Code)
|
|
121
151
|
|
|
122
152
|
A local HTTP proxy on port 7474 sits between Claude Code and `api.anthropic.com`. It compresses request bodies before they're sent — the model sees fewer tokens, you pay less.
|
package/bin/lakonai.js
CHANGED
|
@@ -140,8 +140,14 @@ function runAndFilter(cmd, args) {
|
|
|
140
140
|
// binary, not the lakonai shim that may have invoked us (prevents recursion).
|
|
141
141
|
const { pathWithoutShim } = require('../src/install/shim');
|
|
142
142
|
const env = { ...process.env, PATH: pathWithoutShim(process.env) };
|
|
143
|
-
const child = spawnSync(cmd, args, { encoding: 'utf8', stdio, env });
|
|
143
|
+
const child = spawnSync(cmd, args, { encoding: 'utf8', stdio, env, maxBuffer: 200 * 1024 * 1024 });
|
|
144
144
|
if (child.error) {
|
|
145
|
+
/* istanbul ignore next -- requires >200 MB output to trigger; not unit-testable */
|
|
146
|
+
if (child.error.code === 'ENOBUFS') {
|
|
147
|
+
// Output exceeded maxBuffer — pass through raw so nothing is lost.
|
|
148
|
+
const fallback = spawnSync(cmd, args, { stdio: 'inherit', env });
|
|
149
|
+
process.exit(fallback.status ?? 0);
|
|
150
|
+
}
|
|
145
151
|
process.stderr.write(`lakonai: ${child.error.message}\n`);
|
|
146
152
|
process.exit(127);
|
|
147
153
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lakonai",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "lakonai — save AI context tokens. Filters & compresses CLI output (git, ls, grep, find, test runners, lint/build, docker/kubectl/aws) before it reaches Claude Code, Codex, Cursor, Windsurf, Cline or Gemini — and learns to filter new commands automatically the more you use it.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude",
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Generates one-line docblocks for file nodes that lack comments.
|
|
4
|
+
// Stores results in lakonai-graph/annotations.json — never modifies source files.
|
|
5
|
+
// On build, annotations are merged into nodes before embedding generation.
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const https = require('https');
|
|
9
|
+
const http = require('http');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const { execFileSync } = require('child_process');
|
|
12
|
+
|
|
13
|
+
const ANNOTATIONS_FILE = 'annotations.json';
|
|
14
|
+
const PROMPT = (src) =>
|
|
15
|
+
`Write a ONE-line search index entry (max 120 chars) for this source file. Lead with the primary action verb and main concept a developer would search for. Include key synonyms inline (e.g. "Rate-limits / throttles requests", "Blocks / intercepts dangerous commands", "Compresses / strips / shrinks output"). No preamble, no quotes — just the description.\n\n${src}`;
|
|
16
|
+
|
|
17
|
+
// --- LLM backends ---
|
|
18
|
+
|
|
19
|
+
function callClaudeCLI(src) {
|
|
20
|
+
try {
|
|
21
|
+
const result = execFileSync('claude', [
|
|
22
|
+
'--print',
|
|
23
|
+
'--model', 'claude-haiku-4-5-20251001',
|
|
24
|
+
PROMPT(src),
|
|
25
|
+
], { encoding: 'utf8', timeout: 30000 });
|
|
26
|
+
return result.trim();
|
|
27
|
+
} catch (err) {
|
|
28
|
+
throw new Error('claude CLI failed: ' + (err.stderr || err.message).slice(0, 100));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function callAnthropic(src) {
|
|
33
|
+
const key = process.env.ANTHROPIC_API_KEY;
|
|
34
|
+
if (!key) throw new Error('ANTHROPIC_API_KEY not set');
|
|
35
|
+
const body = JSON.stringify({
|
|
36
|
+
model: 'claude-haiku-4-5-20251001',
|
|
37
|
+
max_tokens: 128,
|
|
38
|
+
messages: [{ role: 'user', content: PROMPT(src) }],
|
|
39
|
+
});
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const req = https.request({
|
|
42
|
+
hostname: 'api.anthropic.com',
|
|
43
|
+
path: '/v1/messages',
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: {
|
|
46
|
+
'Content-Type': 'application/json',
|
|
47
|
+
'x-api-key': key,
|
|
48
|
+
'anthropic-version': '2023-06-01',
|
|
49
|
+
'Content-Length': Buffer.byteLength(body),
|
|
50
|
+
},
|
|
51
|
+
}, (res) => {
|
|
52
|
+
let data = '';
|
|
53
|
+
res.on('data', (c) => { data += c; });
|
|
54
|
+
res.on('end', () => {
|
|
55
|
+
try { resolve(JSON.parse(data).content[0].text.trim()); }
|
|
56
|
+
catch { reject(new Error('Anthropic parse error: ' + data.slice(0, 200))); }
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
req.on('error', reject);
|
|
60
|
+
req.write(body);
|
|
61
|
+
req.end();
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function callOllama(src, model = 'llama3.2') {
|
|
66
|
+
const body = JSON.stringify({ model, prompt: PROMPT(src), stream: false });
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
const req = http.request({
|
|
69
|
+
hostname: '127.0.0.1',
|
|
70
|
+
port: 11434,
|
|
71
|
+
path: '/api/generate',
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
|
|
74
|
+
}, (res) => {
|
|
75
|
+
let data = '';
|
|
76
|
+
res.on('data', (c) => { data += c; });
|
|
77
|
+
res.on('end', () => {
|
|
78
|
+
try { resolve(JSON.parse(data).response.trim()); }
|
|
79
|
+
catch { reject(new Error('Ollama parse error: ' + data.slice(0, 200))); }
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
req.on('error', reject);
|
|
83
|
+
req.write(body);
|
|
84
|
+
req.end();
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function detectBackend() {
|
|
89
|
+
// Prefer claude CLI (zero config for Claude Code users)
|
|
90
|
+
try { execFileSync('claude', ['--version'], { encoding: 'utf8', timeout: 3000 }); return 'claude-cli'; } catch { /* not available */ }
|
|
91
|
+
if (process.env.ANTHROPIC_API_KEY) return 'anthropic';
|
|
92
|
+
// Probe Ollama
|
|
93
|
+
try {
|
|
94
|
+
await new Promise((res, rej) => {
|
|
95
|
+
const r = http.get('http://127.0.0.1:11434/', (resp) => { resp.resume(); res(resp.statusCode); });
|
|
96
|
+
r.on('error', rej);
|
|
97
|
+
r.setTimeout(1000, () => { r.destroy(); rej(new Error('timeout')); });
|
|
98
|
+
});
|
|
99
|
+
return 'ollama';
|
|
100
|
+
} catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function callLLM(src, backend) {
|
|
106
|
+
if (backend === 'claude-cli') return callClaudeCLI(src);
|
|
107
|
+
if (backend === 'anthropic') return callAnthropic(src);
|
|
108
|
+
if (backend === 'ollama') return callOllama(src);
|
|
109
|
+
throw new Error('no LLM backend — install claude CLI, set ANTHROPIC_API_KEY, or start Ollama');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// --- Annotation store helpers ---
|
|
113
|
+
|
|
114
|
+
// annotations.json format: { "src/foo.js": { docblock: "...", mtime: 1234567890 } }
|
|
115
|
+
// Supports plain string values from older versions for backwards compat.
|
|
116
|
+
|
|
117
|
+
function readAnnotations(annotPath) {
|
|
118
|
+
if (!fs.existsSync(annotPath)) return {};
|
|
119
|
+
return JSON.parse(fs.readFileSync(annotPath, 'utf8'));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function getDocblock(entry) {
|
|
123
|
+
if (!entry) return null;
|
|
124
|
+
return typeof entry === 'string' ? entry : entry.docblock;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function needsAnnotation(filePath, entry) {
|
|
128
|
+
if (!entry) return true; // never annotated
|
|
129
|
+
try {
|
|
130
|
+
const mtime = fs.statSync(filePath).mtimeMs;
|
|
131
|
+
const stored = typeof entry === 'string' ? 0 : (entry.mtime || 0);
|
|
132
|
+
return mtime > stored; // file modified since last annotation
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// --- Main annotate logic ---
|
|
139
|
+
|
|
140
|
+
async function annotateGraph(rootDir, graphDir, graph, { silent = false } = {}) {
|
|
141
|
+
const annotPath = path.join(graphDir, ANNOTATIONS_FILE);
|
|
142
|
+
const annotations = readAnnotations(annotPath);
|
|
143
|
+
|
|
144
|
+
const pending = graph.nodes.filter((n) => {
|
|
145
|
+
if (n.kind !== 'file' || n.docblock) return false;
|
|
146
|
+
const filePath = path.join(rootDir, n.file);
|
|
147
|
+
return needsAnnotation(filePath, annotations[n.file]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
if (!pending.length) return annotations;
|
|
151
|
+
|
|
152
|
+
const backend = await detectBackend();
|
|
153
|
+
if (!backend) {
|
|
154
|
+
if (!silent) process.stderr.write(' annotate: no LLM backend — install claude CLI, set ANTHROPIC_API_KEY, or start Ollama\n');
|
|
155
|
+
return annotations;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (!silent) process.stdout.write(` annotate: ${pending.length} file(s) → ${backend}\n`);
|
|
159
|
+
|
|
160
|
+
for (const node of pending) {
|
|
161
|
+
const filePath = path.join(rootDir, node.file);
|
|
162
|
+
let src = '';
|
|
163
|
+
try { src = fs.readFileSync(filePath, 'utf8').split('\n').slice(0, 40).join('\n'); }
|
|
164
|
+
catch { continue; }
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
const raw = await callLLM(src, backend);
|
|
168
|
+
const docblock = raw.split('\n')[0].replace(/^["']|["']$/g, '').slice(0, 120);
|
|
169
|
+
const mtime = fs.statSync(filePath).mtimeMs;
|
|
170
|
+
annotations[node.file] = { docblock, mtime };
|
|
171
|
+
if (!silent) process.stdout.write(` ${node.file}: ${docblock}\n`);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (!silent) process.stdout.write(` ${node.file}: skipped (${err.message})\n`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
fs.writeFileSync(annotPath, JSON.stringify(annotations, null, 2));
|
|
178
|
+
return annotations;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Merge stored annotations into graph nodes (called during build before embedding).
|
|
182
|
+
function mergeAnnotations(nodes, graphDir) {
|
|
183
|
+
const annotPath = path.join(graphDir, ANNOTATIONS_FILE);
|
|
184
|
+
if (!fs.existsSync(annotPath)) return nodes;
|
|
185
|
+
const annotations = readAnnotations(annotPath);
|
|
186
|
+
return nodes.map((n) => {
|
|
187
|
+
if (n.kind === 'file' && !n.docblock) {
|
|
188
|
+
const doc = getDocblock(annotations[n.file]);
|
|
189
|
+
if (doc) return { ...n, docblock: doc };
|
|
190
|
+
}
|
|
191
|
+
return n;
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
module.exports = { annotateGraph, mergeAnnotations, ANNOTATIONS_FILE };
|
package/src/graph/embed.js
CHANGED
|
@@ -35,8 +35,18 @@ function dot(a, b) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
// Build the text to embed for a node.
|
|
38
|
+
// Including param names dramatically improves semantic queries:
|
|
39
|
+
// "writeStats(stats, filePath)" → model connects "save ... to disk" correctly.
|
|
40
|
+
// Nomic requires "search_document: " prefix on corpus text; BGE needs none.
|
|
41
|
+
const DOC_PREFIX = MODEL.includes('nomic') ? 'search_document: ' : '';
|
|
42
|
+
|
|
38
43
|
function nodeText(n) {
|
|
39
|
-
|
|
44
|
+
const base = `${n.label} ${n.kind} ${n.file}`;
|
|
45
|
+
const params = Array.isArray(n.params) && n.params.length
|
|
46
|
+
? ` params ${n.params.join(' ')}`
|
|
47
|
+
: '';
|
|
48
|
+
const doc = n.docblock ? ` ${n.docblock}` : '';
|
|
49
|
+
return DOC_PREFIX + base + params + doc;
|
|
40
50
|
}
|
|
41
51
|
|
|
42
52
|
// Generate embeddings for all nodes. Returns [{id, embedding: number[]}].
|
|
@@ -71,13 +81,20 @@ async function generateEmbeddings(nodes) {
|
|
|
71
81
|
}
|
|
72
82
|
|
|
73
83
|
// Embed a single query string. Returns number[].
|
|
84
|
+
// BGE retrieval instruction — prepended to queries only (not to corpus).
|
|
85
|
+
// Documented to improve asymmetric retrieval quality on BGE models.
|
|
86
|
+
// Model-specific query prefix for asymmetric retrieval.
|
|
87
|
+
const QUERY_PREFIX = MODEL.includes('nomic')
|
|
88
|
+
? 'search_query: '
|
|
89
|
+
: 'Represent this sentence for searching relevant passages: ';
|
|
90
|
+
|
|
74
91
|
async function embedQuery(question) {
|
|
75
92
|
const xeno = await tryXenova();
|
|
76
93
|
if (!xeno) throw new Error('@xenova/transformers not installed');
|
|
77
94
|
|
|
78
95
|
const { pipeline } = xeno;
|
|
79
96
|
const embedder = await pipeline('feature-extraction', MODEL, { quantized: true });
|
|
80
|
-
const out = await embedder([question], { pooling: 'mean', normalize: true });
|
|
97
|
+
const out = await embedder([QUERY_PREFIX + question], { pooling: 'mean', normalize: true });
|
|
81
98
|
embedder.dispose();
|
|
82
99
|
return Array.from(out.data);
|
|
83
100
|
}
|
|
@@ -85,11 +102,16 @@ async function embedQuery(question) {
|
|
|
85
102
|
// Score nodes by cosine similarity to a query embedding.
|
|
86
103
|
// embeddingMap: Map<nodeId, number[]>
|
|
87
104
|
// Returns [{node, score}] sorted desc, limited to topK.
|
|
105
|
+
// Paths outside src/ are secondary artifacts — penalise so source files win ties.
|
|
106
|
+
const NON_SOURCE_RE = /^(tests?|scripts?|bin|coverage|benchmark)\//;
|
|
107
|
+
|
|
88
108
|
function scoreByEmbedding(nodes, embeddingMap, queryVec, topK) {
|
|
89
109
|
return nodes
|
|
90
110
|
.map((n) => {
|
|
91
111
|
const vec = embeddingMap.get(n.id);
|
|
92
|
-
|
|
112
|
+
const raw = vec ? dot(vec, queryVec) : 0;
|
|
113
|
+
const score = raw * (NON_SOURCE_RE.test(n.file || '') ? 0.5 : 1);
|
|
114
|
+
return { node: n, score };
|
|
93
115
|
})
|
|
94
116
|
.filter((x) => x.score > 0.2) // cosine threshold — avoids returning noise
|
|
95
117
|
.sort((a, b) => b.score - a.score)
|
package/src/graph/index.js
CHANGED
|
@@ -9,6 +9,7 @@ const { buildReport } = require('./report');
|
|
|
9
9
|
const { buildHtml } = require('./html');
|
|
10
10
|
const { explain, shortestPath, nlQuery, nlQuerySemantic, nlQueryHybrid, formatExplain, formatPath, formatNlQuery } = require('./query');
|
|
11
11
|
const { hasXenova, generateEmbeddings, embedQuery } = require('./embed');
|
|
12
|
+
const { annotateGraph, mergeAnnotations } = require('./annotate');
|
|
12
13
|
const { watchDir } = require('./watch');
|
|
13
14
|
|
|
14
15
|
const REPORT_FILE = 'GRAPH_REPORT.md';
|
|
@@ -45,7 +46,10 @@ async function build(rootDir) {
|
|
|
45
46
|
|
|
46
47
|
if (hasXenova()) {
|
|
47
48
|
try {
|
|
48
|
-
|
|
49
|
+
// Auto-annotate files without docblocks (new + modified), then embed.
|
|
50
|
+
await annotateGraph(absRoot, dir, graph, { silent: true });
|
|
51
|
+
const enrichedNodes = mergeAnnotations(graph.nodes, dir);
|
|
52
|
+
const embeddings = await generateEmbeddings(enrichedNodes);
|
|
49
53
|
fs.writeFileSync(path.join(dir, EMBEDDINGS_FILE), JSON.stringify(embeddings));
|
|
50
54
|
graph._embeddingsGenerated = true;
|
|
51
55
|
} catch {
|
|
@@ -91,12 +95,17 @@ function runGraph(args) {
|
|
|
91
95
|
` ${REPORT_FILE} — highlights\n` +
|
|
92
96
|
` ${HTML_FILE} — interactive viz\n`
|
|
93
97
|
);
|
|
94
|
-
// Fire-and-forget
|
|
98
|
+
// Fire-and-forget: auto-annotate undocumented files, then generate embeddings.
|
|
95
99
|
if (hasXenova()) {
|
|
96
100
|
process.stdout.write(' embeddings: generating (first run downloads ~23MB model)…\n');
|
|
97
101
|
const absRoot = path.resolve(rootDir);
|
|
98
102
|
const dir = graphDir(absRoot);
|
|
99
|
-
|
|
103
|
+
annotateGraph(absRoot, dir, graph).then((annotations) => {
|
|
104
|
+
const annotCount = Object.keys(annotations).length;
|
|
105
|
+
if (annotCount) process.stdout.write(` annotate: ${annotCount} docblock(s) cached\n`);
|
|
106
|
+
const enriched = mergeAnnotations(graph.nodes, dir);
|
|
107
|
+
return generateEmbeddings(enriched);
|
|
108
|
+
}).then((embeddings) => {
|
|
100
109
|
fs.writeFileSync(path.join(dir, EMBEDDINGS_FILE), JSON.stringify(embeddings));
|
|
101
110
|
process.stdout.write(` embeddings: ${graph.meta.nodeCount} vectors written (semantic query enabled)\n ${EMBEDDINGS_FILE} — semantic embeddings\n`);
|
|
102
111
|
}).catch(() => { /* best-effort */ });
|
|
@@ -104,6 +113,26 @@ function runGraph(args) {
|
|
|
104
113
|
return;
|
|
105
114
|
}
|
|
106
115
|
|
|
116
|
+
if (sub === 'annotate') {
|
|
117
|
+
const rootDir = rest[0] || '.';
|
|
118
|
+
const absRoot = path.resolve(rootDir);
|
|
119
|
+
const graph = readGraph(rootDir);
|
|
120
|
+
if (!graph) { process.stderr.write('no graph.json found — run: lakonai graph build\n'); process.exitCode = 1; return; }
|
|
121
|
+
const dir = graphDir(absRoot);
|
|
122
|
+
annotateGraph(absRoot, dir, graph).then((annotations) => {
|
|
123
|
+
const count = Object.keys(annotations).length;
|
|
124
|
+
process.stdout.write(` annotate: ${count} docblocks stored → ${path.join(dir, 'annotations.json')}\n`);
|
|
125
|
+
if (!hasXenova()) return;
|
|
126
|
+
process.stdout.write(' embeddings: regenerating with annotations…\n');
|
|
127
|
+
const enriched = mergeAnnotations(graph.nodes, dir);
|
|
128
|
+
return generateEmbeddings(enriched).then((embs) => {
|
|
129
|
+
fs.writeFileSync(path.join(dir, EMBEDDINGS_FILE), JSON.stringify(embs));
|
|
130
|
+
process.stdout.write(` embeddings: ${embs.length} vectors updated\n`);
|
|
131
|
+
});
|
|
132
|
+
}).catch((err) => { process.stderr.write(`annotate error: ${err.message}\n`); process.exitCode = 1; });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
107
136
|
if (sub === 'explain') {
|
|
108
137
|
const [nodeId] = rest;
|
|
109
138
|
if (!nodeId) { process.stderr.write('usage: lakonai graph explain <nodeId>\n'); process.exitCode = 1; return; }
|
package/src/graph/parser.js
CHANGED
|
@@ -56,6 +56,63 @@ function resolveImport(specifier, fromFile, rootDir) {
|
|
|
56
56
|
return path.relative(rootDir, resolved);
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// Extract the leading docblock from source — consecutive // lines or /* */ block at top.
|
|
60
|
+
// Skips shebang, 'use strict', and blank lines. Returns plain text, max 250 chars, or ''.
|
|
61
|
+
function extractDocblock(src) {
|
|
62
|
+
const lines = src.split('\n');
|
|
63
|
+
const fragments = [];
|
|
64
|
+
let inBlock = false;
|
|
65
|
+
|
|
66
|
+
for (const raw of lines) {
|
|
67
|
+
const line = raw.trim();
|
|
68
|
+
if (!line) continue;
|
|
69
|
+
if (line.startsWith('#!') || line === "'use strict';" || line === '"use strict";') continue;
|
|
70
|
+
|
|
71
|
+
if (!inBlock && line.startsWith('/*')) {
|
|
72
|
+
inBlock = true;
|
|
73
|
+
const inner = line.replace(/^\/\*+/, '').replace(/\*+\/$/, '').trim();
|
|
74
|
+
if (inner) fragments.push(inner);
|
|
75
|
+
if (line.includes('*/')) break; // single-line block
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (inBlock) {
|
|
79
|
+
if (line.includes('*/')) break;
|
|
80
|
+
fragments.push(line.replace(/^\*\s?/, '').trim());
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (line.startsWith('//')) {
|
|
84
|
+
fragments.push(line.replace(/^\/\/\s?/, '').trim());
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (line.startsWith('#')) {
|
|
88
|
+
fragments.push(line.replace(/^#\s?/, '').trim());
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
break; // non-comment line — stop
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const text = fragments.filter(Boolean).join(' ').trim();
|
|
95
|
+
return text.length > 250 ? text.slice(0, 247) + '…' : text;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Extract parameter names from a raw param string, stripping types/defaults/destructuring.
|
|
99
|
+
// "stats, filePath" → ["stats", "filePath"]
|
|
100
|
+
// "{ topK = 10 } = {}" → ["topK"]
|
|
101
|
+
// "a: number, b = 0" → ["a", "b"]
|
|
102
|
+
function parseParams(raw) {
|
|
103
|
+
if (!raw || !raw.trim()) return [];
|
|
104
|
+
return raw
|
|
105
|
+
.split(',')
|
|
106
|
+
.map((p) => p.trim()
|
|
107
|
+
.replace(/[{}\[\]]/g, '') // strip destructure brackets
|
|
108
|
+
.replace(/\s*=.*$/, '') // strip default values
|
|
109
|
+
.replace(/\s*:\s*\S+/, '') // strip TypeScript type annotations
|
|
110
|
+
.replace(/\.\.\./g, '') // strip rest operator
|
|
111
|
+
.trim()
|
|
112
|
+
)
|
|
113
|
+
.filter((p) => p && /^[A-Za-z_$]/.test(p));
|
|
114
|
+
}
|
|
115
|
+
|
|
59
116
|
// --- JS/TS parser ---
|
|
60
117
|
function parseJS(src, relPath, rootDir) {
|
|
61
118
|
const stripped = stripStrings(src);
|
|
@@ -65,7 +122,8 @@ function parseJS(src, relPath, rootDir) {
|
|
|
65
122
|
const fileId = relPath;
|
|
66
123
|
|
|
67
124
|
// File node
|
|
68
|
-
|
|
125
|
+
const docblock = extractDocblock(src);
|
|
126
|
+
nodes.push({ id: fileId, label: path.basename(relPath), kind: 'file', file: relPath, line: 0, docblock });
|
|
69
127
|
|
|
70
128
|
// ES imports: import X from 'y' / import { X } from 'y' / import 'y'
|
|
71
129
|
// Run on original src — import paths are not inside strings/comments
|
|
@@ -83,24 +141,26 @@ function parseJS(src, relPath, rootDir) {
|
|
|
83
141
|
if (target) edges.push({ from: fileId, to: target, rel: 'imports', tag: 'EXTRACTED' });
|
|
84
142
|
}
|
|
85
143
|
|
|
86
|
-
// Function declarations: function name( / async function name(
|
|
87
|
-
const funcRe = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/gm;
|
|
144
|
+
// Function declarations: function name(params) / async function name(params)
|
|
145
|
+
const funcRe = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/gm;
|
|
88
146
|
while ((m = funcRe.exec(src)) !== null) {
|
|
89
147
|
const name = m[1];
|
|
148
|
+
const params = parseParams(m[2]);
|
|
90
149
|
const line = src.slice(0, m.index).split('\n').length;
|
|
91
150
|
const id = nodeId(name);
|
|
92
|
-
nodes.push({ id, label: name, kind: 'function', file: relPath, line });
|
|
151
|
+
nodes.push({ id, label: name, kind: 'function', file: relPath, line, params });
|
|
93
152
|
edges.push({ from: fileId, to: id, rel: 'contains', tag: 'EXTRACTED' });
|
|
94
153
|
}
|
|
95
154
|
|
|
96
|
-
// Arrow
|
|
97
|
-
const arrowRe = /^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s+)?(?:\([^)]
|
|
155
|
+
// Arrow / const assignments: const name = (params) => / const name = function(
|
|
156
|
+
const arrowRe = /^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s+)?(?:\(([^)]*)\)\s*=>|function\s*\(([^)]*)\))/gm;
|
|
98
157
|
while ((m = arrowRe.exec(src)) !== null) {
|
|
99
158
|
const name = m[1];
|
|
159
|
+
const params = parseParams(m[2] || m[3] || '');
|
|
100
160
|
const line = src.slice(0, m.index).split('\n').length;
|
|
101
161
|
const id = nodeId(name);
|
|
102
162
|
if (!nodes.find((n) => n.id === id)) {
|
|
103
|
-
nodes.push({ id, label: name, kind: 'function', file: relPath, line });
|
|
163
|
+
nodes.push({ id, label: name, kind: 'function', file: relPath, line, params });
|
|
104
164
|
edges.push({ from: fileId, to: id, rel: 'contains', tag: 'EXTRACTED' });
|
|
105
165
|
}
|
|
106
166
|
}
|
|
@@ -127,7 +187,8 @@ function parsePython(src, relPath, rootDir) {
|
|
|
127
187
|
const fileId = relPath;
|
|
128
188
|
const nodeId = (sym) => `${relPath}#${sym}`;
|
|
129
189
|
|
|
130
|
-
|
|
190
|
+
const docblock = extractDocblock(src);
|
|
191
|
+
nodes.push({ id: fileId, label: path.basename(relPath), kind: 'file', file: relPath, line: 0, docblock });
|
|
131
192
|
|
|
132
193
|
// from x import y / import x
|
|
133
194
|
const fromImportRe = /^from\s+([\w.]+)\s+import/gm;
|
|
@@ -146,13 +207,14 @@ function parsePython(src, relPath, rootDir) {
|
|
|
146
207
|
}
|
|
147
208
|
}
|
|
148
209
|
|
|
149
|
-
// def name(
|
|
150
|
-
const defRe = /^(?: )*def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/gm;
|
|
210
|
+
// def name(params):
|
|
211
|
+
const defRe = /^(?: )*def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)/gm;
|
|
151
212
|
while ((m = defRe.exec(src)) !== null) {
|
|
152
213
|
const name = m[1];
|
|
214
|
+
const params = parseParams(m[2]);
|
|
153
215
|
const line = src.slice(0, m.index).split('\n').length;
|
|
154
216
|
const id = nodeId(name);
|
|
155
|
-
nodes.push({ id, label: name, kind: 'function', file: relPath, line });
|
|
217
|
+
nodes.push({ id, label: name, kind: 'function', file: relPath, line, params });
|
|
156
218
|
edges.push({ from: fileId, to: id, rel: 'contains', tag: 'EXTRACTED' });
|
|
157
219
|
}
|
|
158
220
|
|
|
@@ -180,16 +242,18 @@ function parseGo(src, relPath, _rootDir) {
|
|
|
180
242
|
const fileId = relPath;
|
|
181
243
|
const nodeId = (sym) => `${relPath}#${sym}`;
|
|
182
244
|
|
|
183
|
-
|
|
245
|
+
const docblock = extractDocblock(src);
|
|
246
|
+
nodes.push({ id: fileId, label: path.basename(relPath), kind: 'file', file: relPath, line: 0, docblock });
|
|
184
247
|
|
|
185
|
-
// func Name( / func (r *Type) Name(
|
|
186
|
-
const funcRe = /^func\s+(?:\([^)]+\)\s+)?([A-Z][A-Za-z0-9_]*)\s*\(/gm;
|
|
248
|
+
// func Name(params) / func (r *Type) Name(params)
|
|
249
|
+
const funcRe = /^func\s+(?:\([^)]+\)\s+)?([A-Z][A-Za-z0-9_]*)\s*\(([^)]*)\)/gm;
|
|
187
250
|
let m;
|
|
188
251
|
while ((m = funcRe.exec(src)) !== null) {
|
|
189
252
|
const name = m[1];
|
|
253
|
+
const params = parseParams(m[2]);
|
|
190
254
|
const line = src.slice(0, m.index).split('\n').length;
|
|
191
255
|
const id = nodeId(name);
|
|
192
|
-
nodes.push({ id, label: name, kind: 'function', file: relPath, line });
|
|
256
|
+
nodes.push({ id, label: name, kind: 'function', file: relPath, line, params });
|
|
193
257
|
edges.push({ from: fileId, to: id, rel: 'contains', tag: 'EXTRACTED' });
|
|
194
258
|
}
|
|
195
259
|
|
|
@@ -213,7 +277,8 @@ function parseRust(src, relPath, _rootDir) {
|
|
|
213
277
|
const fileId = relPath;
|
|
214
278
|
const nodeId = (sym) => `${relPath}#${sym}`;
|
|
215
279
|
|
|
216
|
-
|
|
280
|
+
const docblock = extractDocblock(src);
|
|
281
|
+
nodes.push({ id: fileId, label: path.basename(relPath), kind: 'file', file: relPath, line: 0, docblock });
|
|
217
282
|
|
|
218
283
|
// pub fn name / fn name / async fn name
|
|
219
284
|
const fnRe = /^(?:pub\s+)?(?:async\s+)?fn\s+([a-z_][a-z0-9_]*)\s*[<(]/gm;
|
|
@@ -2,8 +2,40 @@
|
|
|
2
2
|
/* istanbul ignore file -- thin SessionStart I/O shell: stdin + version check */
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { execFileSync, spawn } = require('child_process');
|
|
5
8
|
const { checkForUpdate, formatNotice } = require('./version-check');
|
|
6
9
|
|
|
10
|
+
// Walk up from cwd to find the git root. Returns null if not in a git repo.
|
|
11
|
+
function findGitRoot(dir) {
|
|
12
|
+
let cur = dir;
|
|
13
|
+
while (true) {
|
|
14
|
+
if (fs.existsSync(path.join(cur, '.git'))) return cur;
|
|
15
|
+
const parent = path.dirname(cur);
|
|
16
|
+
if (parent === cur) return null;
|
|
17
|
+
cur = parent;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Trigger a background graph build and return a notice string.
|
|
22
|
+
// Fire-and-forget — never blocks the session start.
|
|
23
|
+
function triggerGraphBuild(gitRoot) {
|
|
24
|
+
try {
|
|
25
|
+
const lakonai = process.execPath === process.argv[0]
|
|
26
|
+
? 'lakonai'
|
|
27
|
+
: process.execPath;
|
|
28
|
+
spawn('lakonai', ['graph', 'build', gitRoot], {
|
|
29
|
+
detached: true,
|
|
30
|
+
stdio: 'ignore',
|
|
31
|
+
env: { ...process.env },
|
|
32
|
+
}).unref();
|
|
33
|
+
return `lakonai graph: new project detected — building graph for ${gitRoot} in background.\nRun \`lakonai graph query\` once done.`;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
7
39
|
/* istanbul ignore next */
|
|
8
40
|
async function readStdin() {
|
|
9
41
|
let raw = '';
|
|
@@ -28,6 +60,20 @@ async function main() {
|
|
|
28
60
|
if (summary) parts.push(`lakonai learn: ${summary}`);
|
|
29
61
|
} catch { /* best-effort */ }
|
|
30
62
|
|
|
63
|
+
// Auto-build graph for new git projects that don't have one yet.
|
|
64
|
+
if (!process.env.LAKON_NO_AUTO_GRAPH) {
|
|
65
|
+
try {
|
|
66
|
+
const gitRoot = findGitRoot(process.cwd());
|
|
67
|
+
if (gitRoot) {
|
|
68
|
+
const graphJson = path.join(gitRoot, 'lakonai-graph', 'graph.json');
|
|
69
|
+
if (!fs.existsSync(graphJson)) {
|
|
70
|
+
const notice = triggerGraphBuild(gitRoot);
|
|
71
|
+
if (notice) parts.push(notice);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} catch { /* best-effort */ }
|
|
75
|
+
}
|
|
76
|
+
|
|
31
77
|
if (!parts.length) process.exit(0);
|
|
32
78
|
|
|
33
79
|
const response = {
|