promptgraph-mcp 1.0.3 → 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 CHANGED
@@ -128,7 +128,8 @@ promptgraph-mcp reindex # Re-index all skills
128
128
  |---|---|---|
129
129
  | Skills in context | All 40+ | 1 (router) |
130
130
  | Tokens per session | ~20,000–50,000 | ~150 + 1 skill |
131
- | Scales to | ~50 skills | 5,000+ skills |
131
+
132
+ > **Note:** Search is currently linear O(N) over all chunks. Works well up to ~1,000 skills. ANN index (HNSW/LanceDB) planned for larger collections.
132
133
 
133
134
  ## File Structure
134
135
 
package/chunker.js ADDED
@@ -0,0 +1,17 @@
1
+ const CHUNK_SIZE = 400;
2
+ const CHUNK_OVERLAP = 80;
3
+
4
+ export function chunkText(text) {
5
+ const words = text.split(/\s+/);
6
+ const chunks = [];
7
+ let i = 0;
8
+
9
+ while (i < words.length) {
10
+ const chunk = words.slice(i, i + CHUNK_SIZE).join(' ');
11
+ chunks.push(chunk);
12
+ if (i + CHUNK_SIZE >= words.length) break;
13
+ i += CHUNK_SIZE - CHUNK_OVERLAP;
14
+ }
15
+
16
+ return chunks.length > 0 ? chunks : [text];
17
+ }
package/db.js CHANGED
@@ -1,32 +1,44 @@
1
- import Database from 'better-sqlite3';
2
- import path from 'path';
3
- import os from 'os';
4
- import fs from 'fs';
5
-
6
- const DB_PATH = path.join(os.homedir(), '.claude', '.promptgraph', 'promptgraph.db');
7
-
8
- export function getDb() {
9
- fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
10
- const db = new Database(DB_PATH);
11
- db.pragma('journal_mode = WAL');
12
-
13
- db.exec(`
14
- CREATE TABLE IF NOT EXISTS skills (
15
- id INTEGER PRIMARY KEY AUTOINCREMENT,
16
- name TEXT UNIQUE NOT NULL,
17
- description TEXT,
18
- path TEXT NOT NULL,
19
- source TEXT NOT NULL,
20
- content TEXT NOT NULL,
21
- embedding TEXT
22
- );
23
-
24
- CREATE TABLE IF NOT EXISTS edges (
25
- from_skill TEXT NOT NULL,
26
- to_skill TEXT NOT NULL,
27
- PRIMARY KEY (from_skill, to_skill)
28
- );
29
- `);
30
-
31
- return db;
32
- }
1
+ import Database from 'better-sqlite3';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import fs from 'fs';
5
+
6
+ const DB_PATH = path.join(os.homedir(), '.claude', '.promptgraph', 'promptgraph.db');
7
+
8
+ export function getDb() {
9
+ fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
10
+ const db = new Database(DB_PATH);
11
+ db.pragma('journal_mode = WAL');
12
+
13
+ db.exec(`
14
+ CREATE TABLE IF NOT EXISTS skills (
15
+ id TEXT PRIMARY KEY,
16
+ name TEXT NOT NULL,
17
+ description TEXT,
18
+ path TEXT NOT NULL,
19
+ source TEXT NOT NULL,
20
+ content TEXT NOT NULL
21
+ );
22
+
23
+ CREATE TABLE IF NOT EXISTS chunks (
24
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
25
+ skill_id TEXT NOT NULL,
26
+ chunk_index INTEGER NOT NULL,
27
+ text TEXT NOT NULL,
28
+ embedding TEXT NOT NULL,
29
+ UNIQUE(skill_id, chunk_index)
30
+ );
31
+
32
+ CREATE TABLE IF NOT EXISTS edges (
33
+ from_skill TEXT NOT NULL,
34
+ to_skill TEXT NOT NULL,
35
+ PRIMARY KEY (from_skill, to_skill)
36
+ );
37
+ `);
38
+
39
+ return db;
40
+ }
41
+
42
+ export function skillId(source, name) {
43
+ return `${source}::${name}`;
44
+ }
@@ -0,0 +1,49 @@
1
+ import { execSync } from 'child_process';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import fs from 'fs';
5
+ import { globSync } from 'glob';
6
+ import { indexAll } from './indexer.js';
7
+ import { loadConfig, saveConfig } from './config.js';
8
+
9
+ const SKILLS_DIR = path.join(os.homedir(), '.claude', 'skills-store');
10
+
11
+ export async function importFromGitHub(repoUrl) {
12
+ if (!repoUrl) {
13
+ console.error('Usage: promptgraph-mcp import <github-url-or-owner/repo>');
14
+ process.exit(1);
15
+ }
16
+
17
+ const url = repoUrl.startsWith('http') ? repoUrl : `https://github.com/${repoUrl}`;
18
+ const repoName = url.split('/').slice(-2).join('-').replace('.git', '');
19
+ const dest = path.join(SKILLS_DIR, 'github', repoName);
20
+
21
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
22
+
23
+ if (fs.existsSync(dest)) {
24
+ console.log(`Updating ${repoName}...`);
25
+ execSync(`git -C "${dest}" pull --depth=1`, { stdio: 'inherit' });
26
+ } else {
27
+ console.log(`Cloning ${url}...`);
28
+ execSync(`git clone --depth=1 ${url} "${dest}"`, { stdio: 'inherit' });
29
+ }
30
+
31
+ const mdFiles = globSync(`${dest}/**/*.md`);
32
+ console.log(`Found ${mdFiles.length} .md files`);
33
+
34
+ if (mdFiles.length < 2) {
35
+ console.warn('Warning: repo has fewer than 2 .md files — may be empty');
36
+ }
37
+
38
+ const config = loadConfig();
39
+ const githubDir = path.join(SKILLS_DIR, 'github');
40
+ if (!config.sources.find(s => s.dir === githubDir)) {
41
+ config.sources.push({ dir: githubDir, source: 'github' });
42
+ saveConfig(config);
43
+ console.log('Added github dir to config');
44
+ }
45
+
46
+ console.log('\nReindexing...');
47
+ await indexAll();
48
+ console.log(`Done! Imported ${mdFiles.length} files from ${repoName}`);
49
+ }
package/index.js CHANGED
@@ -6,6 +6,8 @@ import { search, getContext, getCallers, getCallees, getImpact, listAll } from '
6
6
  import { indexAll } from './indexer.js';
7
7
  import { startWatcher } from './watcher.js';
8
8
  import { promptConfig } from './config.js';
9
+ import { importFromGitHub } from './github-import.js';
10
+ import { detectPlatforms, PLATFORMS } from './platform.js';
9
11
 
10
12
  const args = process.argv.slice(2);
11
13
 
@@ -14,10 +16,14 @@ if (args[0] === 'help' || args[0] === '--help' || args[0] === '-h') {
14
16
  PromptGraph — semantic skill router for Claude Code
15
17
 
16
18
  Usage:
17
- promptgraph-mcp init First-time setup + index all skills
18
- promptgraph-mcp reindex Re-index all skills
19
- promptgraph-mcp Start MCP server (used by Claude)
20
- promptgraph-mcp help Show this help
19
+ promptgraph-mcp init First-time setup + index all skills
20
+ promptgraph-mcp reindex Re-index all skills
21
+ promptgraph-mcp import <owner/repo> Import skills from GitHub repo
22
+ promptgraph-mcp setup <platform> Register MCP in platform config
23
+ promptgraph-mcp Start MCP server (used by Claude)
24
+ promptgraph-mcp help Show this help
25
+
26
+ Platforms: claude-code, claude-desktop, cline, codex, cursor, windsurf
21
27
 
22
28
  GitHub: https://github.com/NeiP4n/promptgraph
23
29
  npm: https://npmjs.com/package/promptgraph-mcp
@@ -25,6 +31,27 @@ npm: https://npmjs.com/package/promptgraph-mcp
25
31
  process.exit(0);
26
32
  }
27
33
 
34
+ if (args[0] === 'import') {
35
+ await importFromGitHub(args[1]);
36
+ process.exit(0);
37
+ }
38
+
39
+ if (args[0] === 'setup') {
40
+ const platformId = args[1];
41
+ if (!platformId) {
42
+ const detected = detectPlatforms();
43
+ console.log('Detected platforms:');
44
+ detected.forEach(p => console.log(` - ${p.id}: ${p.name}`));
45
+ console.log('\nUsage: promptgraph-mcp setup <platform-id>');
46
+ } else {
47
+ const platform = PLATFORMS[platformId];
48
+ if (!platform) { console.error(`Unknown platform: ${platformId}`); process.exit(1); }
49
+ platform.addMcp(platform);
50
+ console.log(`✓ Registered promptgraph MCP in ${platform.name} (${platform.configPath})`);
51
+ }
52
+ process.exit(0);
53
+ }
54
+
28
55
  if (args[0] === 'init') {
29
56
  const config = await promptConfig();
30
57
  console.log('\nIndexing skills...');
package/indexer.js CHANGED
@@ -1,65 +1,63 @@
1
- import { globSync } from 'glob';
2
- import { parseSkillFile } from './parser.js';
3
- import { embed } from './embedder.js';
4
- import { getDb } from './db.js';
5
- import { loadConfig } from './config.js';
6
-
7
- export async function indexAll() {
8
- const config = loadConfig();
9
- const db = getDb();
10
-
11
- const upsert = db.prepare(`
12
- INSERT INTO skills (name, description, path, source, content, embedding)
13
- VALUES (@name, @description, @path, @source, @content, @embedding)
14
- ON CONFLICT(name) DO UPDATE SET
15
- description = excluded.description,
16
- path = excluded.path,
17
- source = excluded.source,
18
- content = excluded.content,
19
- embedding = excluded.embedding
20
- `);
21
- const upsertEdge = db.prepare(`INSERT OR IGNORE INTO edges (from_skill, to_skill) VALUES (?, ?)`);
22
- db.prepare('DELETE FROM edges').run();
23
-
24
- let count = 0;
25
- for (const { dir, source } of config.sources) {
26
- const files = globSync(`${dir}/**/*.md`);
27
- for (const file of files) {
28
- try {
29
- const skill = parseSkillFile(file, source);
30
- const embedding = await embed(skill.name + ' ' + skill.description + ' ' + skill.content.slice(0, 500));
31
- upsert.run({ ...skill, embedding: JSON.stringify(embedding) });
32
- for (const called of skill.calls) {
33
- upsertEdge.run(skill.name, called);
34
- }
35
- count++;
36
- process.stdout.write(`\r Indexed: ${count} skills`);
37
- } catch (e) {
38
- console.error(`\n Error indexing ${file}: ${e.message}`);
39
- }
40
- }
41
- }
42
- console.log(`\n Done. ${count} skills indexed.`);
43
- }
44
-
45
- export async function indexFile(filePath, source) {
46
- const db = getDb();
47
- const skill = parseSkillFile(filePath, source);
48
- const embedding = await embed(skill.name + ' ' + skill.description + ' ' + skill.content.slice(0, 500));
49
- db.prepare(`
50
- INSERT INTO skills (name, description, path, source, content, embedding)
51
- VALUES (@name, @description, @path, @source, @content, @embedding)
52
- ON CONFLICT(name) DO UPDATE SET
53
- description = excluded.description,
54
- path = excluded.path,
55
- source = excluded.source,
56
- content = excluded.content,
57
- embedding = excluded.embedding
58
- `).run({ ...skill, embedding: JSON.stringify(embedding) });
59
-
60
- db.prepare('DELETE FROM edges WHERE from_skill = ?').run(skill.name);
61
- const upsertEdge = db.prepare('INSERT OR IGNORE INTO edges (from_skill, to_skill) VALUES (?, ?)');
62
- for (const called of skill.calls) {
63
- upsertEdge.run(skill.name, called);
64
- }
65
- }
1
+ import { globSync } from 'glob';
2
+ import { parseSkillFile } from './parser.js';
3
+ import { embed } from './embedder.js';
4
+ import { getDb, skillId } from './db.js';
5
+ import { loadConfig } from './config.js';
6
+ import { chunkText } from './chunker.js';
7
+
8
+ async function indexSkill(db, skill) {
9
+ const id = skillId(skill.source, skill.name);
10
+
11
+ db.prepare(`
12
+ INSERT INTO skills (id, name, description, path, source, content)
13
+ VALUES (@id, @name, @description, @path, @source, @content)
14
+ ON CONFLICT(id) DO UPDATE SET
15
+ name = excluded.name,
16
+ description = excluded.description,
17
+ path = excluded.path,
18
+ content = excluded.content
19
+ `).run({ id, name: skill.name, description: skill.description, path: skill.path, source: skill.source, content: skill.content });
20
+
21
+ db.prepare('DELETE FROM chunks WHERE skill_id = ?').run(id);
22
+
23
+ const chunks = chunkText(skill.name + ' ' + skill.description + '\n' + skill.content);
24
+ const upsertChunk = db.prepare(`INSERT OR REPLACE INTO chunks (skill_id, chunk_index, text, embedding) VALUES (?, ?, ?, ?)`);
25
+ for (let i = 0; i < chunks.length; i++) {
26
+ const vec = await embed(chunks[i]);
27
+ upsertChunk.run(id, i, chunks[i], JSON.stringify(vec));
28
+ }
29
+
30
+ db.prepare('DELETE FROM edges WHERE from_skill = ?').run(id);
31
+ const upsertEdge = db.prepare('INSERT OR IGNORE INTO edges (from_skill, to_skill) VALUES (?, ?)');
32
+ for (const called of skill.calls) {
33
+ upsertEdge.run(id, called);
34
+ }
35
+ }
36
+
37
+ export async function indexAll() {
38
+ const config = loadConfig();
39
+ const db = getDb();
40
+ db.prepare('DELETE FROM edges').run();
41
+
42
+ let count = 0;
43
+ for (const { dir, source } of config.sources) {
44
+ const files = globSync(`${dir}/**/*.md`);
45
+ for (const file of files) {
46
+ try {
47
+ const skill = parseSkillFile(file, source);
48
+ await indexSkill(db, skill);
49
+ count++;
50
+ process.stdout.write(`\r Indexed: ${count} skills`);
51
+ } catch (e) {
52
+ console.error(`\n Error indexing ${file}: ${e.message}`);
53
+ }
54
+ }
55
+ }
56
+ console.log(`\n Done. ${count} skills indexed.`);
57
+ }
58
+
59
+ export async function indexFile(filePath, source) {
60
+ const db = getDb();
61
+ const skill = parseSkillFile(filePath, source);
62
+ await indexSkill(db, skill);
63
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptgraph-mcp",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "main": "index.js",
5
5
  "type": "module",
6
6
  "bin": {
package/parser.js CHANGED
@@ -1,47 +1,36 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- const SKILL_REF_RE = /\/([a-z0-9][a-z0-9-]+)/g;
5
- const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---/;
6
-
7
- export function parseSkillFile(filePath, source) {
8
- const raw = fs.readFileSync(filePath, 'utf8');
9
-
10
- let name = null;
11
- let description = null;
12
- let content = raw;
13
-
14
- const fm = raw.match(FRONTMATTER_RE);
15
- if (fm) {
16
- try {
17
- const nameMatch = fm[1].match(/^name:\s*(.+)$/m);
18
- const descMatch = fm[1].match(/^description:\s*(.+)$/m);
19
- if (nameMatch) name = nameMatch[1].trim().replace(/^["']|["']$/g, '');
20
- if (descMatch) description = descMatch[1].trim().replace(/^["']|["']$/g, '');
21
- } catch {}
22
- }
23
-
24
- name = name || path.basename(filePath, '.md');
25
- description = description || extractFirstParagraph(raw);
26
-
27
- const calls = new Set();
28
- for (const match of raw.matchAll(SKILL_REF_RE)) {
29
- const ref = match[1];
30
- if (ref !== name && ref.length > 2) calls.add(ref);
31
- }
32
-
33
- return {
34
- name,
35
- description,
36
- path: filePath,
37
- source,
38
- content: raw,
39
- calls: [...calls],
40
- };
41
- }
42
-
43
- function extractFirstParagraph(content) {
44
- const lines = content.replace(FRONTMATTER_RE, '').split('\n')
45
- .filter(l => l.trim() && !l.startsWith('#') && !l.startsWith('---'));
46
- return lines[0]?.trim().slice(0, 200) || '';
47
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import matter from 'gray-matter';
4
+
5
+ const SKILL_REF_RE = /\/([a-z0-9][a-z0-9-]+)/g;
6
+
7
+ export function parseSkillFile(filePath, source) {
8
+ const raw = fs.readFileSync(filePath, 'utf8');
9
+
10
+ let name, description, content;
11
+
12
+ try {
13
+ const { data, content: body } = matter(raw);
14
+ name = data.name;
15
+ description = data.description;
16
+ content = body;
17
+ } catch {
18
+ content = raw;
19
+ }
20
+
21
+ name = (name && String(name).trim()) || path.basename(filePath, '.md');
22
+ description = (description && String(description).trim()) || extractFirstParagraph(content || raw);
23
+
24
+ const calls = new Set();
25
+ for (const match of raw.matchAll(SKILL_REF_RE)) {
26
+ const ref = match[1];
27
+ if (ref !== name && ref.length > 2) calls.add(ref);
28
+ }
29
+
30
+ return { name, description, path: filePath, source, content: raw, calls: [...calls] };
31
+ }
32
+
33
+ function extractFirstParagraph(content) {
34
+ const lines = content.split('\n').filter(l => l.trim() && !l.startsWith('#') && !l.startsWith('---'));
35
+ return lines[0]?.trim().slice(0, 200) || '';
36
+ }
package/platform.js ADDED
@@ -0,0 +1,98 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+
5
+ const HOME = os.homedir();
6
+
7
+ export const PLATFORMS = {
8
+ 'claude-code': {
9
+ name: 'Claude Code',
10
+ configPath: path.join(HOME, '.claude', 'settings.json'),
11
+ addMcp: (config, serverPath) => {
12
+ const json = readJson(config.configPath);
13
+ json.mcpServers = json.mcpServers || {};
14
+ json.mcpServers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
15
+ writeJson(config.configPath, json);
16
+ },
17
+ },
18
+ 'claude-desktop': {
19
+ name: 'Claude Desktop',
20
+ configPath: getClaudeDesktopConfig(),
21
+ addMcp: (config, serverPath) => {
22
+ const json = readJson(config.configPath);
23
+ json.mcpServers = json.mcpServers || {};
24
+ json.mcpServers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
25
+ writeJson(config.configPath, json);
26
+ },
27
+ },
28
+ 'cline': {
29
+ name: 'Cline (VS Code)',
30
+ configPath: path.join(HOME, '.vscode', 'mcp.json'),
31
+ addMcp: (config, serverPath) => {
32
+ const json = readJson(config.configPath) || { servers: {} };
33
+ json.servers = json.servers || {};
34
+ json.servers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
35
+ fs.mkdirSync(path.dirname(config.configPath), { recursive: true });
36
+ writeJson(config.configPath, json);
37
+ },
38
+ },
39
+ 'codex': {
40
+ name: 'OpenAI Codex CLI',
41
+ configPath: path.join(HOME, '.codex', 'config.json'),
42
+ addMcp: (config, serverPath) => {
43
+ const json = readJson(config.configPath) || {};
44
+ json.mcpServers = json.mcpServers || {};
45
+ json.mcpServers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
46
+ fs.mkdirSync(path.dirname(config.configPath), { recursive: true });
47
+ writeJson(config.configPath, json);
48
+ },
49
+ },
50
+ 'cursor': {
51
+ name: 'Cursor',
52
+ configPath: path.join(HOME, '.cursor', 'mcp.json'),
53
+ addMcp: (config, serverPath) => {
54
+ const json = readJson(config.configPath) || { mcpServers: {} };
55
+ json.mcpServers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
56
+ fs.mkdirSync(path.dirname(config.configPath), { recursive: true });
57
+ writeJson(config.configPath, json);
58
+ },
59
+ },
60
+ 'windsurf': {
61
+ name: 'Windsurf',
62
+ configPath: path.join(HOME, '.codeium', 'windsurf', 'mcp_config.json'),
63
+ addMcp: (config, serverPath) => {
64
+ const json = readJson(config.configPath) || { mcpServers: {} };
65
+ json.mcpServers.promptgraph = { command: 'npx', args: ['promptgraph-mcp'] };
66
+ fs.mkdirSync(path.dirname(config.configPath), { recursive: true });
67
+ writeJson(config.configPath, json);
68
+ },
69
+ },
70
+ };
71
+
72
+ export function detectPlatforms() {
73
+ return Object.entries(PLATFORMS)
74
+ .filter(([, p]) => p.configPath && fs.existsSync(path.dirname(p.configPath)))
75
+ .map(([id, p]) => ({ id, ...p }));
76
+ }
77
+
78
+ function getClaudeDesktopConfig() {
79
+ if (process.platform === 'win32') {
80
+ const base = process.env.LOCALAPPDATA || '';
81
+ const packages = path.join(base, 'Packages');
82
+ if (fs.existsSync(packages)) {
83
+ const claudeDir = fs.readdirSync(packages).find(d => d.startsWith('Claude_'));
84
+ if (claudeDir) return path.join(packages, claudeDir, 'LocalCache', 'Roaming', 'Claude', 'claude_desktop_config.json');
85
+ }
86
+ }
87
+ if (process.platform === 'darwin') return path.join(HOME, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
88
+ return path.join(HOME, '.config', 'Claude', 'claude_desktop_config.json');
89
+ }
90
+
91
+ function readJson(filePath) {
92
+ try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); } catch { return {}; }
93
+ }
94
+
95
+ function writeJson(filePath, data) {
96
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
97
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
98
+ }
package/search.js CHANGED
@@ -1,58 +1,66 @@
1
- import { embed, cosineSimilarity } from './embedder.js';
2
- import { getDb } from './db.js';
3
-
4
- export async function search(query, topK = 5) {
5
- const db = getDb();
6
- const queryVec = await embed(query);
7
- const skills = db.prepare('SELECT name, description, path, source, embedding FROM skills').all();
8
-
9
- return skills
10
- .map(skill => ({
11
- name: skill.name,
12
- description: skill.description,
13
- path: skill.path,
14
- source: skill.source,
15
- score: cosineSimilarity(queryVec, JSON.parse(skill.embedding)),
16
- }))
17
- .sort((a, b) => b.score - a.score)
18
- .slice(0, topK);
19
- }
20
-
21
- export function getContext(name) {
22
- const db = getDb();
23
- const skill = db.prepare('SELECT * FROM skills WHERE name = ?').get(name);
24
- if (!skill) return null;
25
- const callees = db.prepare('SELECT to_skill FROM edges WHERE from_skill = ?').all(name).map(r => r.to_skill);
26
- const callers = db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(name).map(r => r.from_skill);
27
- return { ...skill, embedding: undefined, callees, callers };
28
- }
29
-
30
- export function getCallers(name) {
31
- const db = getDb();
32
- return db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(name).map(r => r.from_skill);
33
- }
34
-
35
- export function getCallees(name) {
36
- const db = getDb();
37
- return db.prepare('SELECT to_skill FROM edges WHERE from_skill = ?').all(name).map(r => r.to_skill);
38
- }
39
-
40
- export function getImpact(name) {
41
- const db = getDb();
42
- const visited = new Set();
43
- const queue = [name];
44
- while (queue.length) {
45
- const cur = queue.shift();
46
- if (visited.has(cur)) continue;
47
- visited.add(cur);
48
- const callers = db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(cur).map(r => r.from_skill);
49
- queue.push(...callers);
50
- }
51
- visited.delete(name);
52
- return [...visited];
53
- }
54
-
55
- export function listAll() {
56
- const db = getDb();
57
- return db.prepare('SELECT name, description, source FROM skills ORDER BY name').all();
58
- }
1
+ import { embed, cosineSimilarity } from './embedder.js';
2
+ import { getDb } from './db.js';
3
+
4
+ export async function search(query, topK = 5) {
5
+ const db = getDb();
6
+ const queryVec = await embed(query);
7
+
8
+ const chunks = db.prepare('SELECT skill_id, embedding FROM chunks').all();
9
+
10
+ const bestBySkill = new Map();
11
+ for (const chunk of chunks) {
12
+ const score = cosineSimilarity(queryVec, JSON.parse(chunk.embedding));
13
+ const prev = bestBySkill.get(chunk.skill_id);
14
+ if (!prev || score > prev) bestBySkill.set(chunk.skill_id, score);
15
+ }
16
+
17
+ const topIds = [...bestBySkill.entries()]
18
+ .sort((a, b) => b[1] - a[1])
19
+ .slice(0, topK)
20
+ .map(([id]) => id);
21
+
22
+ return topIds.map(id => {
23
+ const skill = db.prepare('SELECT id, name, description, path, source FROM skills WHERE id = ?').get(id);
24
+ return { ...skill, score: bestBySkill.get(id) };
25
+ });
26
+ }
27
+
28
+ export function getContext(id) {
29
+ const db = getDb();
30
+ const skill = db.prepare('SELECT * FROM skills WHERE id = ?').get(id)
31
+ || db.prepare("SELECT * FROM skills WHERE name = ? ORDER BY id LIMIT 1").get(id);
32
+ if (!skill) return null;
33
+ const callees = db.prepare('SELECT to_skill FROM edges WHERE from_skill = ?').all(skill.id).map(r => r.to_skill);
34
+ const callers = db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(skill.id).map(r => r.from_skill);
35
+ return { ...skill, callees, callers };
36
+ }
37
+
38
+ export function getCallers(id) {
39
+ const db = getDb();
40
+ return db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(id).map(r => r.from_skill);
41
+ }
42
+
43
+ export function getCallees(id) {
44
+ const db = getDb();
45
+ return db.prepare('SELECT to_skill FROM edges WHERE from_skill = ?').all(id).map(r => r.to_skill);
46
+ }
47
+
48
+ export function getImpact(id) {
49
+ const db = getDb();
50
+ const visited = new Set();
51
+ const queue = [id];
52
+ while (queue.length) {
53
+ const cur = queue.shift();
54
+ if (visited.has(cur)) continue;
55
+ visited.add(cur);
56
+ const callers = db.prepare('SELECT from_skill FROM edges WHERE to_skill = ?').all(cur).map(r => r.from_skill);
57
+ queue.push(...callers);
58
+ }
59
+ visited.delete(id);
60
+ return [...visited];
61
+ }
62
+
63
+ export function listAll() {
64
+ const db = getDb();
65
+ return db.prepare('SELECT id, name, description, source FROM skills ORDER BY source, name').all();
66
+ }