devworkspace 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +105 -26
  3. package/dist/cli/args.d.ts +10 -0
  4. package/dist/cli/args.js +3 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/help.js +15 -5
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli/render.d.ts +2 -1
  9. package/dist/cli/render.js +71 -4
  10. package/dist/cli/render.js.map +1 -1
  11. package/dist/cli/run.js +54 -36
  12. package/dist/cli/run.js.map +1 -1
  13. package/dist/core/artifacts.d.ts +32 -0
  14. package/dist/core/artifacts.js +46 -0
  15. package/dist/core/artifacts.js.map +1 -0
  16. package/dist/core/version.js +3 -0
  17. package/dist/core/version.js.map +1 -1
  18. package/dist/core/workspace.js +1 -0
  19. package/dist/core/workspace.js.map +1 -1
  20. package/dist/integrations/adapters/graphify.js +2 -1
  21. package/dist/integrations/adapters/graphify.js.map +1 -1
  22. package/dist/integrations/adapters/pluginSkill.js +15 -1
  23. package/dist/integrations/adapters/pluginSkill.js.map +1 -1
  24. package/dist/mcp/setup.d.ts +98 -5
  25. package/dist/mcp/setup.js +332 -82
  26. package/dist/mcp/setup.js.map +1 -1
  27. package/dist/mcp/tools.d.ts +6 -0
  28. package/dist/mcp/tools.js +67 -13
  29. package/dist/mcp/tools.js.map +1 -1
  30. package/dist/mcp/verify.d.ts +41 -0
  31. package/dist/mcp/verify.js +264 -0
  32. package/dist/mcp/verify.js.map +1 -0
  33. package/dist/services/doctor.js +64 -1
  34. package/dist/services/doctor.js.map +1 -1
  35. package/dist/services/graph.d.ts +92 -4
  36. package/dist/services/graph.js +552 -191
  37. package/dist/services/graph.js.map +1 -1
  38. package/dist/services/setup.js +3 -0
  39. package/dist/services/setup.js.map +1 -1
  40. package/dist/services/taskContext.d.ts +20 -2
  41. package/dist/services/taskContext.js +29 -15
  42. package/dist/services/taskContext.js.map +1 -1
  43. package/dist/utils/proc.js +19 -3
  44. package/dist/utils/proc.js.map +1 -1
  45. package/docs/agents.md +2 -2
  46. package/docs/claude.md +13 -0
  47. package/docs/getting-started.md +40 -1
  48. package/docs/integrations.md +16 -1
  49. package/docs/mcp.md +46 -10
  50. package/docs/troubleshooting.md +5 -0
  51. package/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
- import { pathExists, readTextBounded } from '../utils/fs.js';
3
+ import { atomicWriteFile, pathExists, readTextBounded } from '../utils/fs.js';
4
4
  import { findSymbolInText } from '../features/validate.js';
5
5
  import { requireWorkspace } from '../core/workspace.js';
6
+ import { resolveGraphifyGraph } from '../core/artifacts.js';
6
7
  import { DevWorkspaceError } from '../errors/index.js';
7
8
  /**
8
9
  * Resolves the location of Graphify's output graph in the repository.
@@ -14,9 +15,10 @@ export function getGraphPath(root) {
14
15
  * Loads and validates Graphify graph JSON data safely.
15
16
  */
16
17
  export async function loadGraphData(root) {
17
- const gPath = getGraphPath(root);
18
- if (!(await pathExists(gPath))) {
19
- return { exists: false, path: gPath };
18
+ const resolved = await resolveGraphifyGraph(root);
19
+ const gPath = resolved.file;
20
+ if (!resolved.exists) {
21
+ return { exists: false, path: gPath, location: resolved.location };
20
22
  }
21
23
  let raw;
22
24
  try {
@@ -47,6 +49,8 @@ export async function loadGraphData(root) {
47
49
  return {
48
50
  exists: true,
49
51
  path: gPath,
52
+ location: resolved.location,
53
+ ...(resolved.conflict ? { conflict: resolved.conflict } : {}),
50
54
  data: { nodes, edges },
51
55
  };
52
56
  }
@@ -64,7 +68,7 @@ export async function getGraphStatusService(o) {
64
68
  edgesCount: 0,
65
69
  nodeTypes: {},
66
70
  message: 'No Graphify knowledge graph found at graphify-out/graph.json.',
67
- hint: 'In Claude Code run "/graphify ." to build the graph, or run "graphify update ." if already initialized.',
71
+ hint: 'Run "devworkspace graph generate" for an offline graph, or in Claude Code run "/graphify ." / "graphify update ." to build with Graphify.',
68
72
  };
69
73
  }
70
74
  const { nodes, edges } = loaded.data;
@@ -82,65 +86,308 @@ export async function getGraphStatusService(o) {
82
86
  message: `Graphify graph loaded: ${nodes.length} nodes, ${edges.length} edges.`,
83
87
  };
84
88
  }
89
+ const SUPPORTED_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py']);
90
+ const IGNORED_SCAN_DIRS = new Set([
91
+ 'node_modules',
92
+ '.git',
93
+ '.devworkspace',
94
+ 'dist',
95
+ 'build',
96
+ 'out',
97
+ 'coverage',
98
+ '.claude',
99
+ '.cursor',
100
+ 'graphify-out',
101
+ '.venv',
102
+ 'venv',
103
+ '__pycache__',
104
+ ]);
85
105
  /**
86
- * Extracts a candidate file path and symbol from a node definition.
106
+ * Generates an offline knowledge graph directly by scanning project source files.
107
+ * Extracts functions, classes, interfaces, types and dependencies without requiring Claude Code or network access.
87
108
  */
88
- export function extractPathAndSymbol(node) {
89
- // If explicitly declared:
90
- const rawPath = typeof node.path === 'string' ? node.path : typeof node.file === 'string' ? node.file : null;
91
- let relPath = rawPath ? rawPath.replace(/\\/g, '/').replace(/^\/+/, '') : null;
109
+ export async function generateOfflineGraphService(o, options = {}) {
110
+ const ws = await requireWorkspace(o.cwd);
111
+ const dest = options.out ? path.resolve(ws.root, options.out) : path.join(ws.root, 'graphify-out', 'graph.json');
112
+ let alreadyExists = false;
113
+ if (await pathExists(dest)) {
114
+ alreadyExists = true;
115
+ try {
116
+ const raw = await fs.readFile(dest, 'utf8');
117
+ const parsed = JSON.parse(raw);
118
+ if (parsed?.generator !== 'devworkspace-offline-fallback' && !options.force) {
119
+ throw new DevWorkspaceError('CONFLICT', `A native Graphify graph already exists at "${path.relative(ws.root, dest).replace(/\\/g, '/')}". Pass --force to overwrite.`, {
120
+ hint: 'Pass --force to replace the existing graph with the offline fallback graph.',
121
+ });
122
+ }
123
+ }
124
+ catch (e) {
125
+ if (e instanceof DevWorkspaceError)
126
+ throw e;
127
+ }
128
+ }
129
+ const files = [];
130
+ async function scan(dir) {
131
+ let entries;
132
+ try {
133
+ entries = await fs.readdir(dir, { withFileTypes: true });
134
+ }
135
+ catch {
136
+ return;
137
+ }
138
+ for (const ent of entries) {
139
+ if (ent.isDirectory()) {
140
+ if (!IGNORED_SCAN_DIRS.has(ent.name) && !ent.name.startsWith('.')) {
141
+ await scan(path.join(dir, ent.name));
142
+ }
143
+ }
144
+ else if (ent.isFile()) {
145
+ const ext = path.extname(ent.name).toLowerCase();
146
+ if (SUPPORTED_EXTS.has(ext)) {
147
+ files.push(path.join(dir, ent.name));
148
+ }
149
+ }
150
+ }
151
+ }
152
+ await scan(ws.root);
153
+ files.sort();
154
+ const nodesMap = new Map();
155
+ const edges = [];
156
+ const nodeTypes = {};
157
+ const addNode = (node) => {
158
+ if (!nodesMap.has(node.id)) {
159
+ nodesMap.set(node.id, node);
160
+ const t = node.type || 'unknown';
161
+ nodeTypes[t] = (nodeTypes[t] || 0) + 1;
162
+ }
163
+ };
164
+ for (const f of files) {
165
+ const rel = path.relative(ws.root, f).replace(/\\/g, '/');
166
+ let text;
167
+ try {
168
+ text = await fs.readFile(f, 'utf8');
169
+ }
170
+ catch {
171
+ continue;
172
+ }
173
+ // Add file node
174
+ addNode({
175
+ id: rel,
176
+ name: path.basename(rel),
177
+ label: path.basename(rel),
178
+ type: 'file',
179
+ path: rel,
180
+ source_file: rel,
181
+ source_location: 'L1',
182
+ });
183
+ const lines = text.split(/\r?\n/);
184
+ const isPy = /\.py$/i.test(rel);
185
+ for (let i = 0; i < lines.length; i++) {
186
+ const line = lines[i];
187
+ const lineNum = i + 1;
188
+ const loc = `L${lineNum}`;
189
+ if (isPy) {
190
+ const trimmed = line.replace(/#.*$/, '').trim();
191
+ if (!trimmed)
192
+ continue;
193
+ // Python function
194
+ const fnMatch = /^(?:async\s+)?def\s+([A-Za-z0-9_]+)\s*\(/.exec(trimmed);
195
+ if (fnMatch) {
196
+ const name = fnMatch[1];
197
+ const id = `${rel}:${name}`;
198
+ addNode({ id, name, label: name, type: 'function', path: rel, source_file: rel, source_location: loc });
199
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
200
+ continue;
201
+ }
202
+ // Python class
203
+ const classMatch = /^class\s+([A-Za-z0-9_]+)(?:\(([^)]*)\))?:/.exec(trimmed);
204
+ if (classMatch) {
205
+ const name = classMatch[1];
206
+ const id = `${rel}:${name}`;
207
+ addNode({ id, name, label: name, type: 'class', path: rel, source_file: rel, source_location: loc });
208
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
209
+ if (classMatch[2]) {
210
+ const bases = classMatch[2].split(',').map((s) => s.trim()).filter(Boolean);
211
+ for (const base of bases) {
212
+ edges.push({ source: id, target: base, relation: 'extends', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
213
+ }
214
+ }
215
+ continue;
216
+ }
217
+ // Python import
218
+ const impMatch = /^(?:from\s+([A-Za-z0-9_.]+)\s+import|import\s+([A-Za-z0-9_.,\s]+))/.exec(trimmed);
219
+ if (impMatch) {
220
+ const target = (impMatch[1] ?? impMatch[2]).split(',')[0].trim();
221
+ edges.push({ source: rel, target, relation: 'imports', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
222
+ }
223
+ }
224
+ else {
225
+ const trimmed = line.replace(/\/\/.*$/, '').trim();
226
+ if (!trimmed)
227
+ continue;
228
+ // TS/JS function
229
+ const fnMatch = /(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)/.exec(trimmed);
230
+ const arrowMatch = !fnMatch ? /(?:export\s+)?const\s+([A-Za-z0-9_$]+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z0-9_$]+)\s*=>/.exec(trimmed) : null;
231
+ if (fnMatch || arrowMatch) {
232
+ const name = fnMatch ? fnMatch[1] : arrowMatch[1];
233
+ const id = `${rel}:${name}`;
234
+ addNode({ id, name, label: name, type: 'function', path: rel, source_file: rel, source_location: loc });
235
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
236
+ continue;
237
+ }
238
+ // TS/JS class
239
+ const classMatch = /(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)(?:\s+extends\s+([A-Za-z0-9_$]+))?(?:\s+implements\s+([A-Za-z0-9_$,\s]+))?/.exec(trimmed);
240
+ if (classMatch) {
241
+ const name = classMatch[1];
242
+ const id = `${rel}:${name}`;
243
+ addNode({ id, name, label: name, type: 'class', path: rel, source_file: rel, source_location: loc });
244
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
245
+ if (classMatch[2]) {
246
+ edges.push({ source: id, target: classMatch[2], relation: 'extends', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
247
+ }
248
+ if (classMatch[3]) {
249
+ for (const iface of classMatch[3].split(',').map((s) => s.trim()).filter(Boolean)) {
250
+ edges.push({ source: id, target: iface, relation: 'implements', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
251
+ }
252
+ }
253
+ continue;
254
+ }
255
+ // TS interface
256
+ const ifaceMatch = /(?:export\s+)?interface\s+([A-Za-z0-9_$]+)(?:\s+extends\s+([A-Za-z0-9_$,\s]+))?/.exec(trimmed);
257
+ if (ifaceMatch) {
258
+ const name = ifaceMatch[1];
259
+ const id = `${rel}:${name}`;
260
+ addNode({ id, name, label: name, type: 'interface', path: rel, source_file: rel, source_location: loc });
261
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
262
+ continue;
263
+ }
264
+ // TS type
265
+ const typeMatch = /(?:export\s+)?type\s+([A-Za-z0-9_$]+)\s*=/.exec(trimmed);
266
+ if (typeMatch) {
267
+ const name = typeMatch[1];
268
+ const id = `${rel}:${name}`;
269
+ addNode({ id, name, label: name, type: 'type', path: rel, source_file: rel, source_location: loc });
270
+ edges.push({ source: rel, target: id, relation: 'defines', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
271
+ continue;
272
+ }
273
+ // TS/JS import
274
+ const impMatch = /(?:import\s+(?:(?:\{[^}]*\}|[\w*\s,]+)\s+from\s+)?['"]([^'"]+)['"]|require\(['"]([^'"]+)['"]\))/.exec(trimmed);
275
+ if (impMatch) {
276
+ const target = impMatch[1] ?? impMatch[2];
277
+ edges.push({ source: rel, target, relation: 'imports', confidence: 'EXTRACTED', provenance: 'extracted', source_file: rel, source_location: loc });
278
+ }
279
+ }
280
+ }
281
+ }
282
+ const nodes = Array.from(nodesMap.values());
283
+ const graphData = {
284
+ generator: 'devworkspace-offline-fallback',
285
+ generatedAt: new Date().toISOString(),
286
+ version: '1.0.0',
287
+ nodes,
288
+ edges,
289
+ };
290
+ if (!options.dryRun) {
291
+ await fs.mkdir(path.dirname(dest), { recursive: true });
292
+ await atomicWriteFile(dest, JSON.stringify(graphData, null, 2) + '\n');
293
+ }
294
+ return {
295
+ ok: true,
296
+ graphPath: dest,
297
+ nodesCount: nodes.length,
298
+ edgesCount: edges.length,
299
+ filesScanned: files.length,
300
+ nodeTypes,
301
+ dryRun: Boolean(options.dryRun),
302
+ overwritten: alreadyExists,
303
+ message: options.dryRun
304
+ ? `Dry run: would generate offline graph with ${nodes.length} nodes and ${edges.length} edges from ${files.length} files.`
305
+ : `Generated offline knowledge graph at "${path.relative(ws.root, dest).replace(/\\/g, '/')}": ${nodes.length} nodes, ${edges.length} edges from ${files.length} source files.`,
306
+ };
307
+ }
308
+ /** Parses "L4", "L4-L9", "4" or "4:2" into a 1-based line; null for anything else. */
309
+ export function parseSourceLocation(loc) {
310
+ if (typeof loc === 'number')
311
+ return Number.isInteger(loc) && loc >= 1 ? loc : null;
312
+ if (typeof loc !== 'string')
313
+ return null;
314
+ const m = /^L?(\d{1,9})(?:[-:]L?\d{1,9})?$/i.exec(loc.trim());
315
+ if (!m)
316
+ return null;
317
+ const n = Number(m[1]);
318
+ return n >= 1 ? n : null;
319
+ }
320
+ /** Normalizes a declared path to a safe workspace-relative POSIX path, or null when unsafe. */
321
+ function safeRelPath(raw) {
322
+ const p = raw.replace(/\\/g, '/').trim();
323
+ if (p === '' || p.includes('\0') || /^[a-zA-Z]:/.test(p) || p.startsWith('/'))
324
+ return null;
325
+ const parts = p.split('/').filter((x) => x !== '' && x !== '.');
326
+ if (parts.length === 0 || parts.includes('..'))
327
+ return null;
328
+ return parts.join('/');
329
+ }
330
+ /**
331
+ * Normalizes any supported node shape (Graphify `source_file`/`label`/`source_location`,
332
+ * or older `path`/`file`/`name` and `file::symbol` ids) into one representation.
333
+ */
334
+ export function normalizeNode(node) {
335
+ const declared = typeof node.source_file === 'string' ? node.source_file
336
+ : typeof node.path === 'string' ? node.path
337
+ : typeof node.file === 'string' ? node.file
338
+ : null;
339
+ let relPath = null;
340
+ let invalidPath;
341
+ if (declared !== null) {
342
+ relPath = safeRelPath(declared);
343
+ if (relPath === null)
344
+ invalidPath = declared;
345
+ }
92
346
  let symbol = null;
93
347
  if (node.id.includes('::')) {
94
348
  const parts = node.id.split('::');
95
- if (!relPath && parts[0] && (parts[0].includes('/') || parts[0].includes('.'))) {
96
- relPath = parts[0].replace(/\\/g, '/').replace(/^\/+/, '');
349
+ if (relPath === null && declared === null && parts[0] && (parts[0].includes('/') || parts[0].includes('.'))) {
350
+ relPath = safeRelPath(parts[0]);
97
351
  }
98
352
  symbol = parts[1] || null;
99
353
  }
100
- else if (!relPath && (node.id.includes('/') || node.id.includes('.'))) {
101
- relPath = node.id.replace(/\\/g, '/').replace(/^\/+/, '');
354
+ else if (relPath === null && declared === null && (node.id.includes('/') || node.id.includes('.'))) {
355
+ relPath = safeRelPath(node.id);
102
356
  }
103
- if (!symbol && typeof node.name === 'string' && node.name !== relPath) {
104
- symbol = node.name;
357
+ if (!symbol) {
358
+ const base = relPath ? relPath.split('/').pop() : null;
359
+ const cand = typeof node.name === 'string' ? node.name : typeof node.label === 'string' ? node.label : null;
360
+ // Graphify labels methods as ".name()" and functions as "name()"; file nodes are labelled with the file name.
361
+ const clean = cand?.trim().replace(/^\./, '').replace(/\(\)$/, '') ?? null;
362
+ if (clean && clean !== relPath && clean !== base)
363
+ symbol = clean;
105
364
  }
365
+ const sourceLocation = typeof node.source_location === 'string' ? node.source_location : null;
366
+ return { relPath, symbol, sourceLocation, line: parseSourceLocation(node.source_location), ...(invalidPath ? { invalidPath } : {}) };
367
+ }
368
+ /** Extracts a candidate file path and symbol from a node definition. */
369
+ export function extractPathAndSymbol(node) {
370
+ const { relPath, symbol } = normalizeNode(node);
106
371
  return { relPath, symbol };
107
372
  }
108
- /**
109
- * Verifies whether a node's physical path and symbol exist on disk.
110
- */
111
- async function verifyNode(root, node, depth) {
112
- const { relPath, symbol } = extractPathAndSymbol(node);
113
- const name = typeof node.name === 'string' ? node.name : typeof node.label === 'string' ? node.label : node.id;
114
- const type = typeof node.type === 'string' ? node.type : 'symbol';
373
+ function nodeName(node) {
374
+ return typeof node.name === 'string' ? node.name : typeof node.label === 'string' ? node.label : node.id;
375
+ }
376
+ /** Verifies whether a node's physical path and symbol exist on disk. */
377
+ export async function verifyNode(root, node, depth) {
378
+ const { relPath, symbol, sourceLocation, line, invalidPath } = normalizeNode(node);
379
+ const name = nodeName(node);
380
+ const type = typeof node.type === 'string' ? node.type : typeof node.file_type === 'string' ? node.file_type : 'symbol';
381
+ const base = { id: node.id, name, type, symbol, sourceLocation, line, depth };
115
382
  if (!relPath) {
116
383
  return {
117
- id: node.id,
118
- name,
119
- type,
120
- path: null,
121
- symbol,
122
- depth,
123
- status: 'hypothesis',
124
- fileExists: false,
125
- symbolFound: null,
126
- reason: 'No source file associated with node',
384
+ ...base, path: null, status: 'hypothesis', fileExists: false, symbolFound: null,
385
+ reason: invalidPath ? `Rejected unsafe source path "${invalidPath}"` : 'No source file associated with node',
127
386
  };
128
387
  }
129
388
  const fullPath = path.join(root, ...relPath.split('/'));
130
- const exists = await pathExists(fullPath);
131
- if (!exists) {
132
- return {
133
- id: node.id,
134
- name,
135
- type,
136
- path: relPath,
137
- symbol,
138
- depth,
139
- status: 'hypothesis',
140
- fileExists: false,
141
- symbolFound: null,
142
- reason: `File "${relPath}" not found on disk`,
143
- };
389
+ if (!(await pathExists(fullPath))) {
390
+ return { ...base, path: relPath, status: 'hypothesis', fileExists: false, symbolFound: null, reason: `File "${relPath}" not found on disk` };
144
391
  }
145
392
  let symbolFound = null;
146
393
  let status = 'verified';
@@ -152,7 +399,7 @@ async function verifyNode(root, node, depth) {
152
399
  symbolFound = findSymbolInText(text, symbol);
153
400
  if (!symbolFound) {
154
401
  status = 'hypothesis';
155
- reason = `Symbol "${symbol}" not found in "${relPath}"`;
402
+ reason = `Symbol "${symbol}" not found in existing file "${relPath}"`;
156
403
  }
157
404
  }
158
405
  }
@@ -161,191 +408,305 @@ async function verifyNode(root, node, depth) {
161
408
  reason = `Could not inspect symbols in "${relPath}"`;
162
409
  }
163
410
  }
164
- return {
165
- id: node.id,
166
- name,
167
- type,
168
- path: relPath,
169
- symbol,
170
- depth,
171
- status,
172
- fileExists: true,
173
- symbolFound,
174
- ...(reason ? { reason } : {}),
175
- };
411
+ return { ...base, path: relPath, status, fileExists: true, symbolFound, ...(reason ? { reason } : {}) };
176
412
  }
177
413
  const GRAPH_STOP_WORDS = new Set([
178
414
  'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'does', 'how',
179
415
  'what', 'where', 'why', 'when', 'which', 'to', 'in', 'of', 'at', 'by', 'on',
180
- 'as', 'an', 'a', 'or', 'is', 'it', 'be', 'so', 'db'
416
+ 'as', 'an', 'a', 'or', 'is', 'it', 'be', 'so', 'db',
417
+ ]);
418
+ /** Tokens too generic to identify a domain concept on their own; they count for little. */
419
+ const GENERIC_TOKENS = new Set([
420
+ 'service', 'services', 'controller', 'controllers', 'module', 'modules', 'handler', 'util', 'utils',
421
+ 'index', 'props', 'type', 'types', 'test', 'tests', 'spec', 'src', 'app', 'backend', 'frontend',
422
+ 'ts', 'tsx', 'js', 'jsx', 'dto', 'dtos', 'component', 'components', 'page', 'pages', 'infrastructure',
181
423
  ]);
424
+ /** Splits identifiers, paths and prose into lower-case tokens (camelCase, snake_case, kebab-case, dots, slashes). */
425
+ export function tokenize(text) {
426
+ return text
427
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
428
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
429
+ .toLowerCase()
430
+ .split(/[^a-z0-9]+/)
431
+ .filter(Boolean);
432
+ }
433
+ const stem = (t) => (t.length > 3 && t.endsWith('s') && !t.endsWith('ss') ? t.slice(0, -1) : t);
434
+ const STRONG = 10;
435
+ const MIN_SCORE = 5;
182
436
  /**
183
- * Finds the starting node in a graph that matches the user's query.
437
+ * Deterministic relevance ranking. Whole-token matches on labels and paths score; arbitrary substrings do not,
438
+ * so "erp" cannot select "PageHeaderProps". Ties break on score, shorter label, then id.
184
439
  */
185
- export function findMatchingStartNode(nodes, query) {
186
- const q = query.trim().toLowerCase();
187
- const qNorm = q.replace(/\\/g, '/');
188
- if (q.length === 0 || GRAPH_STOP_WORDS.has(q))
189
- return null;
190
- // 1. Exact match on ID
191
- const exactId = nodes.find((n) => n.id.toLowerCase() === q || n.id.toLowerCase().replace(/\\/g, '/') === qNorm);
192
- if (exactId)
193
- return exactId;
194
- // 2. Exact match on path or file
195
- const exactPath = nodes.find((n) => {
196
- const p = (n.path || n.file || '').toLowerCase().replace(/\\/g, '/');
197
- return p === qNorm;
198
- });
199
- if (exactPath)
200
- return exactPath;
201
- // 3. Exact match on name or symbol
202
- const exactName = nodes.find((n) => {
203
- const name = (n.name || n.label || '').toLowerCase();
204
- return name === q;
440
+ export function rankGraphNodes(nodes, query, opts = {}) {
441
+ const q = query.trim();
442
+ const qLower = q.toLowerCase();
443
+ const qPath = qLower.replace(/\\/g, '/');
444
+ if (qLower.length === 0 || GRAPH_STOP_WORDS.has(qLower))
445
+ return [];
446
+ const ignore = new Set((opts.ignoreTerms ?? []).flatMap((t) => tokenize(t)));
447
+ const mainTerms = new Map();
448
+ const addTerm = (t, w) => {
449
+ if (t.length < 3 || GRAPH_STOP_WORDS.has(t) || ignore.has(t))
450
+ return;
451
+ mainTerms.set(t, Math.max(mainTerms.get(t) ?? 0, w));
452
+ };
453
+ for (const t of tokenize(q))
454
+ addTerm(t, 1);
455
+ for (const x of opts.extraTerms ?? [])
456
+ for (const t of tokenize(x))
457
+ addTerm(t, 0.5);
458
+ const ranked = [];
459
+ for (const node of nodes) {
460
+ const label = nodeName(node);
461
+ const { relPath, symbol } = normalizeNode(node);
462
+ const idL = node.id.toLowerCase().replace(/\\/g, '/');
463
+ const pathL = (relPath ?? '').toLowerCase();
464
+ const labelL = label.toLowerCase();
465
+ const reasons = [];
466
+ let score = 0;
467
+ if (idL === qPath) {
468
+ score = 100;
469
+ reasons.push('exact node id');
470
+ }
471
+ else if (pathL !== '' && pathL === qPath) {
472
+ score = 90;
473
+ reasons.push('exact source path');
474
+ }
475
+ else if (symbol !== null && symbol.toLowerCase() === qLower) {
476
+ score = 80;
477
+ reasons.push('exact symbol');
478
+ }
479
+ else if (labelL === qLower || labelL.replace(/\(\)$/, '') === qLower || (typeof node.norm_label === 'string' && node.norm_label === qLower)) {
480
+ score = 80;
481
+ reasons.push('exact label');
482
+ }
483
+ else {
484
+ const labelTokens = tokenize(label).map(stem);
485
+ const pathTokens = tokenize(relPath ?? '').map(stem);
486
+ let matched = 0; // query-term matches only; synonym expansions must not earn the coverage bonus
487
+ for (const [term, w] of mainTerms) {
488
+ const ts = stem(term);
489
+ const g = GENERIC_TOKENS.has(ts) ? 0.3 : 1;
490
+ let best = 0;
491
+ let why = '';
492
+ const consider = (pts, r) => { if (pts > best) {
493
+ best = pts;
494
+ why = r;
495
+ } };
496
+ for (const t of labelTokens) {
497
+ if (t === ts)
498
+ consider(10, `label token "${term}"`);
499
+ else if (ts.length >= 4 && t.length >= 4 && (t.startsWith(ts) || ts.startsWith(t)))
500
+ consider(5, `label token "${t}" ~ "${term}"`);
501
+ }
502
+ for (const t of pathTokens) {
503
+ if (t === ts)
504
+ consider(4, `path token "${term}"`);
505
+ else if (ts.length >= 4 && t.length >= 4 && (t.startsWith(ts) || ts.startsWith(t)))
506
+ consider(2, `path token "${t}" ~ "${term}"`);
507
+ }
508
+ if (best > 0) {
509
+ score += best * w * g;
510
+ if (w === 1)
511
+ matched++;
512
+ reasons.push(why);
513
+ }
514
+ }
515
+ if (matched > 1)
516
+ score += matched * 2;
517
+ }
518
+ if (score >= MIN_SCORE) {
519
+ if (relPath)
520
+ score += 0.5;
521
+ if (typeof node.file_type === 'string' && node.file_type !== 'code')
522
+ score -= 0.25; // docs/rationale nodes rank below code at equal relevance
523
+ ranked.push({ node, score, strength: score >= 80 ? 'exact' : score >= STRONG ? 'strong' : 'weak', reasons });
524
+ }
525
+ }
526
+ ranked.sort((a, b) => b.score - a.score ||
527
+ nodeName(a.node).length - nodeName(b.node).length ||
528
+ (a.node.id < b.node.id ? -1 : a.node.id > b.node.id ? 1 : 0));
529
+ // The same symbol can appear under several ids (re-exports, duplicate extraction): keep the best-scored one.
530
+ const seen = new Set();
531
+ const unique = ranked.filter((r) => {
532
+ const n = normalizeNode(r.node);
533
+ const key = `${n.relPath ?? ''}|${(n.symbol ?? nodeName(r.node)).toLowerCase()}`;
534
+ if (seen.has(key))
535
+ return false;
536
+ seen.add(key);
537
+ return true;
205
538
  });
206
- if (exactName)
207
- return exactName;
208
- // 4. Substring match on ID or path only for meaningful terms of at least 3 characters
209
- if (q.length >= 3 && !GRAPH_STOP_WORDS.has(qNorm)) {
210
- const subMatch = nodes.find((n) => {
211
- const id = n.id.toLowerCase().replace(/\\/g, '/');
212
- const p = (n.path || n.file || '').toLowerCase().replace(/\\/g, '/');
213
- return id.includes(qNorm) || p.includes(qNorm);
214
- });
215
- if (subMatch)
216
- return subMatch;
539
+ return unique.slice(0, opts.limit ?? 10);
540
+ }
541
+ /** Finds the best starting node for a query, or null when nothing relevant matches. */
542
+ export function findMatchingStartNode(nodes, query) {
543
+ return rankGraphNodes(nodes, query, { limit: 1 })[0]?.node ?? null;
544
+ }
545
+ const provenanceOf = (e) => {
546
+ const c = typeof e.confidence === 'string' ? e.confidence.toUpperCase() : '';
547
+ if (c === 'EXTRACTED')
548
+ return { confidence: 'EXTRACTED', provenance: 'extracted' };
549
+ if (c === 'INFERRED')
550
+ return { confidence: 'INFERRED', provenance: 'inferred' };
551
+ return { confidence: null, provenance: 'unknown' };
552
+ };
553
+ const PROV_RANK = { extracted: 0, inferred: 1, unknown: 2 };
554
+ const relationOf = (e) => (typeof e.relation === 'string' ? e.relation : typeof e.type === 'string' ? e.type : 'relates_to');
555
+ /**
556
+ * Direct edges touching the matched nodes. `relevance` maps matched node id -> match score. Order: stronger evidence
557
+ * (EXTRACTED first), then edges whose endpoints are more relevant to the task, then a deterministic id tie-break.
558
+ */
559
+ export function topEdgesFor(relevance, edges, limit) {
560
+ const rel = (e) => (relevance.get(e.source) ?? 0) + (relevance.get(e.target) ?? 0);
561
+ return edges
562
+ .filter((e) => relevance.has(e.source) || relevance.has(e.target))
563
+ .map((e) => ({ source: e.source, target: e.target, relation: relationOf(e), status: 'hypothesis', ...provenanceOf(e), depth: 0, sourceCheck: 'unavailable' }))
564
+ .sort((a, b) => PROV_RANK[a.provenance] - PROV_RANK[b.provenance] || rel(b) - rel(a) ||
565
+ a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation))
566
+ .slice(0, limit);
567
+ }
568
+ const MAX_EDGE_CHECKS = 200;
569
+ /** Check an edge's own source line against the endpoint symbols. Bounded: files are read once, up to 500 KB. */
570
+ async function checkEdgeSource(root, e, symbols, cache) {
571
+ const rel = typeof e.source_file === 'string' ? safeRelPath(e.source_file) : null;
572
+ const line = parseSourceLocation(e.source_location);
573
+ if (!rel || !line)
574
+ return 'unavailable';
575
+ if (!cache.has(rel)) {
576
+ const text = await readTextBounded(path.join(root, ...rel.split('/')), 500_000).catch(() => null);
577
+ cache.set(rel, text ? text.split(/\r?\n/) : null);
217
578
  }
218
- return null;
579
+ const lines = cache.get(rel);
580
+ if (!lines || line > lines.length)
581
+ return 'unavailable';
582
+ // +-1 line tolerates small drift and decorators; a hit on either endpoint's symbol confirms the edge's location.
583
+ const window = lines.slice(Math.max(0, line - 2), line + 1).join('\n');
584
+ return symbols.some((s) => s.length > 0 && window.includes(s)) ? 'confirmed' : 'unconfirmed';
219
585
  }
220
586
  /**
221
587
  * Performs a bounded graph trace starting from a specified file or symbol node up to maxDepth.
222
- * Verifies every traversed node against the repository filesystem, marking unverified nodes
223
- * and edges as hypotheses.
588
+ * Breadth-first; the node cap is enforced during neighbour expansion, so a high-degree hub cannot overshoot it.
589
+ * Within a node, neighbours are admitted by evidence strength (EXTRACTED before INFERRED), then id.
224
590
  */
225
591
  export async function traceGraphService(o, query, options = {}) {
226
592
  const ws = await requireWorkspace(o.cwd);
227
593
  const loaded = await loadGraphData(ws.root);
228
594
  const depthLimit = Math.min(Math.max(options.depth ?? 2, 1), 10);
229
- const maxNodes = Math.min(options.maxNodes ?? 150, 500);
595
+ const maxNodes = Math.max(1, Math.min(options.maxNodes ?? 150, 500));
596
+ const empty = { depth: depthLimit, maxNodes, matchedNode: null, totalNodes: 0, verifiedNodes: 0, hypothesisNodes: 0, truncated: false, nodes: [], edges: [] };
230
597
  if (!loaded.exists || !loaded.data) {
231
- return {
232
- available: false,
233
- query,
234
- depth: depthLimit,
235
- matchedNode: null,
236
- totalNodes: 0,
237
- verifiedNodes: 0,
238
- hypothesisNodes: 0,
239
- nodes: [],
240
- edges: [],
241
- warnings: ['No Graphify graph found at graphify-out/graph.json. Run "/graphify ." in Claude Code.'],
242
- };
598
+ return { available: false, query, ...empty, warnings: ['No Graphify graph found at graphify-out/graph.json. Run "devworkspace graph generate" for an offline graph, or "/graphify ." in Claude Code.'] };
243
599
  }
244
600
  const { nodes, edges } = loaded.data;
245
- const startNode = findMatchingStartNode(nodes, query);
246
- if (!startNode) {
247
- return {
248
- available: true,
249
- query,
250
- depth: depthLimit,
251
- matchedNode: null,
252
- totalNodes: 0,
253
- verifiedNodes: 0,
254
- hypothesisNodes: 0,
255
- nodes: [],
256
- edges: [],
257
- warnings: [`No graph node found matching "${query}". Check node IDs with "devworkspace graph status".`],
258
- };
601
+ const top = rankGraphNodes(nodes, query, { limit: 1 })[0];
602
+ if (!top) {
603
+ return { available: true, query, ...empty, warnings: [`No graph node found matching "${query}". Check node IDs with "devworkspace graph status".`] };
259
604
  }
260
- // Build adjacency index
261
- const outgoing = new Map();
262
- const incoming = new Map();
605
+ const startNode = top.node;
606
+ // Adjacency (both directions) holding the neighbour id and the edge.
607
+ const adj = new Map();
608
+ const link = (from, other, edge) => {
609
+ let l = adj.get(from);
610
+ if (!l)
611
+ adj.set(from, (l = []));
612
+ l.push({ other, edge });
613
+ };
263
614
  for (const e of edges) {
264
- if (!outgoing.has(e.source))
265
- outgoing.set(e.source, []);
266
- outgoing.get(e.source).push(e);
267
- if (!incoming.has(e.target))
268
- incoming.set(e.target, []);
269
- incoming.get(e.target).push(e);
615
+ link(e.source, e.target, e);
616
+ link(e.target, e.source, e);
270
617
  }
271
618
  const nodeMap = new Map(nodes.map((n) => [n.id, n]));
272
- // Breadth-first search bounded by depthLimit
273
- const visitedDepths = new Map();
619
+ const visitedDepths = new Map([[startNode.id, 0]]);
274
620
  const queue = [{ id: startNode.id, depth: 0 }];
275
- visitedDepths.set(startNode.id, 0);
276
- const collectedEdges = [];
277
- while (queue.length > 0 && visitedDepths.size < maxNodes) {
278
- const current = queue.shift();
621
+ let truncated = false;
622
+ for (let qi = 0; qi < queue.length; qi++) {
623
+ const current = queue[qi];
279
624
  if (current.depth >= depthLimit)
280
625
  continue;
281
- // Explore outgoing edges
282
- const outEdges = outgoing.get(current.id) || [];
283
- for (const edge of outEdges) {
284
- collectedEdges.push(edge);
285
- if (!visitedDepths.has(edge.target)) {
286
- visitedDepths.set(edge.target, current.depth + 1);
287
- queue.push({ id: edge.target, depth: current.depth + 1 });
288
- }
289
- }
290
- // Explore incoming edges
291
- const inEdges = incoming.get(current.id) || [];
292
- for (const edge of inEdges) {
293
- collectedEdges.push(edge);
294
- if (!visitedDepths.has(edge.source)) {
295
- visitedDepths.set(edge.source, current.depth + 1);
296
- queue.push({ id: edge.source, depth: current.depth + 1 });
626
+ const neighbours = (adj.get(current.id) ?? [])
627
+ .filter((x) => x.other !== current.id)
628
+ .sort((a, b) => PROV_RANK[provenanceOf(a.edge).provenance] - PROV_RANK[provenanceOf(b.edge).provenance] ||
629
+ (a.other < b.other ? -1 : a.other > b.other ? 1 : 0));
630
+ for (const { other } of neighbours) {
631
+ if (visitedDepths.has(other))
632
+ continue;
633
+ if (visitedDepths.size >= maxNodes) {
634
+ truncated = true;
635
+ continue;
297
636
  }
637
+ visitedDepths.set(other, current.depth + 1);
638
+ queue.push({ id: other, depth: current.depth + 1 });
298
639
  }
299
640
  }
300
- // Verify all traversed nodes against disk
301
641
  const tracedNodes = [];
302
- const nodeStatusMap = new Map();
303
- for (const [nodeId, depth] of visitedDepths.entries()) {
304
- const rawNode = nodeMap.get(nodeId) || { id: nodeId };
305
- const verified = await verifyNode(ws.root, rawNode, depth);
306
- tracedNodes.push(verified);
307
- nodeStatusMap.set(nodeId, verified.status);
642
+ const nodeStatus = new Map();
643
+ for (const [nodeId, depth] of visitedDepths) {
644
+ const v = await verifyNode(ws.root, nodeMap.get(nodeId) ?? { id: nodeId }, depth);
645
+ tracedNodes.push(v);
646
+ nodeStatus.set(nodeId, v.status);
308
647
  }
309
- // Deduplicate and verify collected edges
310
- const edgeKeys = new Set();
648
+ // Edges among traversed nodes. An existing file proves the endpoint, not the relationship, so only
649
+ // AST-extracted edges between verified endpoints are 'verified'.
650
+ const seen = new Set();
651
+ const fileLines = new Map();
652
+ let checked = 0;
311
653
  const tracedEdges = [];
312
- for (const e of collectedEdges) {
313
- if (!visitedDepths.has(e.source) || !visitedDepths.has(e.target))
654
+ for (const e of edges) {
655
+ const sd = visitedDepths.get(e.source);
656
+ const td = visitedDepths.get(e.target);
657
+ if (sd === undefined || td === undefined)
314
658
  continue;
315
- const key = `${e.source}->${e.target}::${e.relation || e.type || ''}`;
316
- if (edgeKeys.has(key))
659
+ const relation = relationOf(e);
660
+ const key = `${e.source}->${e.target}::${relation}`;
661
+ if (seen.has(key))
317
662
  continue;
318
- edgeKeys.add(key);
319
- const srcStatus = nodeStatusMap.get(e.source);
320
- const tgtStatus = nodeStatusMap.get(e.target);
321
- const edgeStatus = srcStatus === 'verified' && tgtStatus === 'verified' ? 'verified' : 'hypothesis';
663
+ seen.add(key);
664
+ const prov = provenanceOf(e);
665
+ const endpointsOk = nodeStatus.get(e.source) === 'verified' && nodeStatus.get(e.target) === 'verified';
666
+ let sourceCheck = 'unavailable';
667
+ if (endpointsOk && prov.provenance === 'extracted' && checked < MAX_EDGE_CHECKS) {
668
+ checked++;
669
+ // Symbol names for symbol nodes; for file nodes (imports_from) the module path in the line ends with the file's base name.
670
+ const syms = [e.source, e.target].flatMap((id) => {
671
+ const n = normalizeNode(nodeMap.get(id) ?? { id });
672
+ const base = n.relPath?.split('/').pop()?.replace(/\.[^.]+$/, '');
673
+ return [n.symbol, base].filter((x) => !!x);
674
+ });
675
+ sourceCheck = await checkEdgeSource(ws.root, e, syms, fileLines);
676
+ }
322
677
  tracedEdges.push({
323
- source: e.source,
324
- target: e.target,
325
- relation: typeof e.relation === 'string' ? e.relation : typeof e.type === 'string' ? e.type : 'relates_to',
326
- status: edgeStatus,
678
+ source: e.source, target: e.target, relation, ...prov, depth: Math.min(sd, td), sourceCheck,
679
+ status: endpointsOk && prov.provenance === 'extracted' && sourceCheck !== 'unconfirmed' ? 'verified' : 'hypothesis',
327
680
  });
328
681
  }
329
- // Sort nodes by depth, then by path/name
330
- tracedNodes.sort((a, b) => a.depth - b.depth || (a.path || a.id).localeCompare(b.path || b.id));
682
+ tracedNodes.sort((a, b) => a.depth - b.depth || (a.path || a.id).localeCompare(b.path || b.id) || a.id.localeCompare(b.id));
683
+ tracedEdges.sort((a, b) => a.depth - b.depth || PROV_RANK[a.provenance] - PROV_RANK[b.provenance] ||
684
+ a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));
331
685
  const matched = tracedNodes.find((n) => n.id === startNode.id) || null;
332
686
  const verifiedCount = tracedNodes.filter((n) => n.status === 'verified').length;
333
- const hypothesisCount = tracedNodes.filter((n) => n.status === 'hypothesis').length;
687
+ const hypothesisCount = tracedNodes.length - verifiedCount;
334
688
  const warnings = [];
335
- if (hypothesisCount > 0) {
336
- warnings.push(`${hypothesisCount} node(s) or connected dependencies are unverified hypotheses (files or symbols missing on disk).`);
337
- }
689
+ if (top.strength === 'weak')
690
+ warnings.push(`Weak match for "${query}" (${top.reasons.join('; ')}); confirm this is the intended symbol.`);
691
+ if (hypothesisCount > 0)
692
+ warnings.push(`${hypothesisCount} node(s) are unverified hypotheses (file or symbol missing on disk).`);
693
+ const unconfirmed = tracedEdges.filter((e) => e.sourceCheck === 'unconfirmed').length;
694
+ if (unconfirmed > 0)
695
+ warnings.push(`${unconfirmed} extracted relationship(s) point at a source line that no longer mentions their symbols (graph may be stale; run "graphify update .").`);
696
+ if (loaded.conflict)
697
+ warnings.push(`Graphs exist in both layouts; reading ${loaded.path}. ${loaded.conflict.reason}.`);
698
+ const inferred = tracedEdges.filter((e) => e.provenance === 'inferred').length;
699
+ const unknown = tracedEdges.filter((e) => e.provenance === 'unknown').length;
700
+ if (inferred > 0)
701
+ warnings.push(`${inferred} relationship(s) are Graphify inferences, not AST-extracted; confirm in source.`);
702
+ if (unknown > 0)
703
+ warnings.push(`${unknown} relationship(s) carry no confidence metadata (older graph); treated as unverified.`);
704
+ if (truncated)
705
+ warnings.push(`Traversal stopped at the ${maxNodes}-node cap; more nodes are reachable within depth ${depthLimit}.`);
338
706
  return {
339
- available: true,
340
- query,
341
- depth: depthLimit,
342
- matchedNode: matched,
343
- totalNodes: tracedNodes.length,
344
- verifiedNodes: verifiedCount,
345
- hypothesisNodes: hypothesisCount,
346
- nodes: tracedNodes,
347
- edges: tracedEdges,
348
- warnings,
707
+ available: true, query, depth: depthLimit, maxNodes, matchedNode: matched, matchStrength: top.strength,
708
+ totalNodes: tracedNodes.length, verifiedNodes: verifiedCount, hypothesisNodes: hypothesisCount,
709
+ truncated, nodes: tracedNodes, edges: tracedEdges, warnings,
349
710
  };
350
711
  }
351
712
  //# sourceMappingURL=graph.js.map