devworkspace 0.4.3 → 0.4.4

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 (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +100 -22
  3. package/dist/cli/args.d.ts +3 -0
  4. package/dist/cli/args.js +1 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/help.js +8 -4
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli/render.js +53 -4
  9. package/dist/cli/render.js.map +1 -1
  10. package/dist/cli/run.js +41 -33
  11. package/dist/cli/run.js.map +1 -1
  12. package/dist/core/artifacts.d.ts +32 -0
  13. package/dist/core/artifacts.js +46 -0
  14. package/dist/core/artifacts.js.map +1 -0
  15. package/dist/core/version.js +3 -0
  16. package/dist/core/version.js.map +1 -1
  17. package/dist/core/workspace.js +1 -0
  18. package/dist/core/workspace.js.map +1 -1
  19. package/dist/integrations/adapters/graphify.js +2 -1
  20. package/dist/integrations/adapters/graphify.js.map +1 -1
  21. package/dist/mcp/setup.d.ts +77 -5
  22. package/dist/mcp/setup.js +247 -82
  23. package/dist/mcp/setup.js.map +1 -1
  24. package/dist/mcp/tools.d.ts +6 -0
  25. package/dist/mcp/tools.js +67 -13
  26. package/dist/mcp/tools.js.map +1 -1
  27. package/dist/mcp/verify.d.ts +41 -0
  28. package/dist/mcp/verify.js +229 -0
  29. package/dist/mcp/verify.js.map +1 -0
  30. package/dist/services/doctor.js +64 -1
  31. package/dist/services/doctor.js.map +1 -1
  32. package/dist/services/graph.d.ts +71 -4
  33. package/dist/services/graph.js +331 -189
  34. package/dist/services/graph.js.map +1 -1
  35. package/dist/services/setup.js +3 -0
  36. package/dist/services/setup.js.map +1 -1
  37. package/dist/services/taskContext.d.ts +20 -2
  38. package/dist/services/taskContext.js +29 -15
  39. package/dist/services/taskContext.js.map +1 -1
  40. package/docs/agents.md +2 -2
  41. package/docs/claude.md +13 -0
  42. package/docs/getting-started.md +40 -1
  43. package/docs/integrations.md +16 -1
  44. package/docs/mcp.md +42 -11
  45. package/docs/troubleshooting.md +5 -0
  46. package/package.json +1 -1
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { 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
  }
@@ -82,65 +86,89 @@ export async function getGraphStatusService(o) {
82
86
  message: `Graphify graph loaded: ${nodes.length} nodes, ${edges.length} edges.`,
83
87
  };
84
88
  }
89
+ /** Parses "L4", "L4-L9", "4" or "4:2" into a 1-based line; null for anything else. */
90
+ export function parseSourceLocation(loc) {
91
+ if (typeof loc === 'number')
92
+ return Number.isInteger(loc) && loc >= 1 ? loc : null;
93
+ if (typeof loc !== 'string')
94
+ return null;
95
+ const m = /^L?(\d{1,9})(?:[-:]L?\d{1,9})?$/i.exec(loc.trim());
96
+ if (!m)
97
+ return null;
98
+ const n = Number(m[1]);
99
+ return n >= 1 ? n : null;
100
+ }
101
+ /** Normalizes a declared path to a safe workspace-relative POSIX path, or null when unsafe. */
102
+ function safeRelPath(raw) {
103
+ const p = raw.replace(/\\/g, '/').trim();
104
+ if (p === '' || p.includes('\0') || /^[a-zA-Z]:/.test(p) || p.startsWith('/'))
105
+ return null;
106
+ const parts = p.split('/').filter((x) => x !== '' && x !== '.');
107
+ if (parts.length === 0 || parts.includes('..'))
108
+ return null;
109
+ return parts.join('/');
110
+ }
85
111
  /**
86
- * Extracts a candidate file path and symbol from a node definition.
112
+ * Normalizes any supported node shape (Graphify `source_file`/`label`/`source_location`,
113
+ * or older `path`/`file`/`name` and `file::symbol` ids) into one representation.
87
114
  */
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;
115
+ export function normalizeNode(node) {
116
+ const declared = typeof node.source_file === 'string' ? node.source_file
117
+ : typeof node.path === 'string' ? node.path
118
+ : typeof node.file === 'string' ? node.file
119
+ : null;
120
+ let relPath = null;
121
+ let invalidPath;
122
+ if (declared !== null) {
123
+ relPath = safeRelPath(declared);
124
+ if (relPath === null)
125
+ invalidPath = declared;
126
+ }
92
127
  let symbol = null;
93
128
  if (node.id.includes('::')) {
94
129
  const parts = node.id.split('::');
95
- if (!relPath && parts[0] && (parts[0].includes('/') || parts[0].includes('.'))) {
96
- relPath = parts[0].replace(/\\/g, '/').replace(/^\/+/, '');
130
+ if (relPath === null && declared === null && parts[0] && (parts[0].includes('/') || parts[0].includes('.'))) {
131
+ relPath = safeRelPath(parts[0]);
97
132
  }
98
133
  symbol = parts[1] || null;
99
134
  }
100
- else if (!relPath && (node.id.includes('/') || node.id.includes('.'))) {
101
- relPath = node.id.replace(/\\/g, '/').replace(/^\/+/, '');
135
+ else if (relPath === null && declared === null && (node.id.includes('/') || node.id.includes('.'))) {
136
+ relPath = safeRelPath(node.id);
102
137
  }
103
- if (!symbol && typeof node.name === 'string' && node.name !== relPath) {
104
- symbol = node.name;
138
+ if (!symbol) {
139
+ const base = relPath ? relPath.split('/').pop() : null;
140
+ const cand = typeof node.name === 'string' ? node.name : typeof node.label === 'string' ? node.label : null;
141
+ // Graphify labels methods as ".name()" and functions as "name()"; file nodes are labelled with the file name.
142
+ const clean = cand?.trim().replace(/^\./, '').replace(/\(\)$/, '') ?? null;
143
+ if (clean && clean !== relPath && clean !== base)
144
+ symbol = clean;
105
145
  }
146
+ const sourceLocation = typeof node.source_location === 'string' ? node.source_location : null;
147
+ return { relPath, symbol, sourceLocation, line: parseSourceLocation(node.source_location), ...(invalidPath ? { invalidPath } : {}) };
148
+ }
149
+ /** Extracts a candidate file path and symbol from a node definition. */
150
+ export function extractPathAndSymbol(node) {
151
+ const { relPath, symbol } = normalizeNode(node);
106
152
  return { relPath, symbol };
107
153
  }
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';
154
+ function nodeName(node) {
155
+ return typeof node.name === 'string' ? node.name : typeof node.label === 'string' ? node.label : node.id;
156
+ }
157
+ /** Verifies whether a node's physical path and symbol exist on disk. */
158
+ export async function verifyNode(root, node, depth) {
159
+ const { relPath, symbol, sourceLocation, line, invalidPath } = normalizeNode(node);
160
+ const name = nodeName(node);
161
+ const type = typeof node.type === 'string' ? node.type : typeof node.file_type === 'string' ? node.file_type : 'symbol';
162
+ const base = { id: node.id, name, type, symbol, sourceLocation, line, depth };
115
163
  if (!relPath) {
116
164
  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',
165
+ ...base, path: null, status: 'hypothesis', fileExists: false, symbolFound: null,
166
+ reason: invalidPath ? `Rejected unsafe source path "${invalidPath}"` : 'No source file associated with node',
127
167
  };
128
168
  }
129
169
  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
- };
170
+ if (!(await pathExists(fullPath))) {
171
+ return { ...base, path: relPath, status: 'hypothesis', fileExists: false, symbolFound: null, reason: `File "${relPath}" not found on disk` };
144
172
  }
145
173
  let symbolFound = null;
146
174
  let status = 'verified';
@@ -152,7 +180,7 @@ async function verifyNode(root, node, depth) {
152
180
  symbolFound = findSymbolInText(text, symbol);
153
181
  if (!symbolFound) {
154
182
  status = 'hypothesis';
155
- reason = `Symbol "${symbol}" not found in "${relPath}"`;
183
+ reason = `Symbol "${symbol}" not found in existing file "${relPath}"`;
156
184
  }
157
185
  }
158
186
  }
@@ -161,191 +189,305 @@ async function verifyNode(root, node, depth) {
161
189
  reason = `Could not inspect symbols in "${relPath}"`;
162
190
  }
163
191
  }
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
- };
192
+ return { ...base, path: relPath, status, fileExists: true, symbolFound, ...(reason ? { reason } : {}) };
176
193
  }
177
194
  const GRAPH_STOP_WORDS = new Set([
178
195
  'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'does', 'how',
179
196
  'what', 'where', 'why', 'when', 'which', 'to', 'in', 'of', 'at', 'by', 'on',
180
- 'as', 'an', 'a', 'or', 'is', 'it', 'be', 'so', 'db'
197
+ 'as', 'an', 'a', 'or', 'is', 'it', 'be', 'so', 'db',
198
+ ]);
199
+ /** Tokens too generic to identify a domain concept on their own; they count for little. */
200
+ const GENERIC_TOKENS = new Set([
201
+ 'service', 'services', 'controller', 'controllers', 'module', 'modules', 'handler', 'util', 'utils',
202
+ 'index', 'props', 'type', 'types', 'test', 'tests', 'spec', 'src', 'app', 'backend', 'frontend',
203
+ 'ts', 'tsx', 'js', 'jsx', 'dto', 'dtos', 'component', 'components', 'page', 'pages', 'infrastructure',
181
204
  ]);
205
+ /** Splits identifiers, paths and prose into lower-case tokens (camelCase, snake_case, kebab-case, dots, slashes). */
206
+ export function tokenize(text) {
207
+ return text
208
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
209
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
210
+ .toLowerCase()
211
+ .split(/[^a-z0-9]+/)
212
+ .filter(Boolean);
213
+ }
214
+ const stem = (t) => (t.length > 3 && t.endsWith('s') && !t.endsWith('ss') ? t.slice(0, -1) : t);
215
+ const STRONG = 10;
216
+ const MIN_SCORE = 5;
182
217
  /**
183
- * Finds the starting node in a graph that matches the user's query.
218
+ * Deterministic relevance ranking. Whole-token matches on labels and paths score; arbitrary substrings do not,
219
+ * so "erp" cannot select "PageHeaderProps". Ties break on score, shorter label, then id.
184
220
  */
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;
221
+ export function rankGraphNodes(nodes, query, opts = {}) {
222
+ const q = query.trim();
223
+ const qLower = q.toLowerCase();
224
+ const qPath = qLower.replace(/\\/g, '/');
225
+ if (qLower.length === 0 || GRAPH_STOP_WORDS.has(qLower))
226
+ return [];
227
+ const ignore = new Set((opts.ignoreTerms ?? []).flatMap((t) => tokenize(t)));
228
+ const mainTerms = new Map();
229
+ const addTerm = (t, w) => {
230
+ if (t.length < 3 || GRAPH_STOP_WORDS.has(t) || ignore.has(t))
231
+ return;
232
+ mainTerms.set(t, Math.max(mainTerms.get(t) ?? 0, w));
233
+ };
234
+ for (const t of tokenize(q))
235
+ addTerm(t, 1);
236
+ for (const x of opts.extraTerms ?? [])
237
+ for (const t of tokenize(x))
238
+ addTerm(t, 0.5);
239
+ const ranked = [];
240
+ for (const node of nodes) {
241
+ const label = nodeName(node);
242
+ const { relPath, symbol } = normalizeNode(node);
243
+ const idL = node.id.toLowerCase().replace(/\\/g, '/');
244
+ const pathL = (relPath ?? '').toLowerCase();
245
+ const labelL = label.toLowerCase();
246
+ const reasons = [];
247
+ let score = 0;
248
+ if (idL === qPath) {
249
+ score = 100;
250
+ reasons.push('exact node id');
251
+ }
252
+ else if (pathL !== '' && pathL === qPath) {
253
+ score = 90;
254
+ reasons.push('exact source path');
255
+ }
256
+ else if (symbol !== null && symbol.toLowerCase() === qLower) {
257
+ score = 80;
258
+ reasons.push('exact symbol');
259
+ }
260
+ else if (labelL === qLower || labelL.replace(/\(\)$/, '') === qLower || (typeof node.norm_label === 'string' && node.norm_label === qLower)) {
261
+ score = 80;
262
+ reasons.push('exact label');
263
+ }
264
+ else {
265
+ const labelTokens = tokenize(label).map(stem);
266
+ const pathTokens = tokenize(relPath ?? '').map(stem);
267
+ let matched = 0; // query-term matches only; synonym expansions must not earn the coverage bonus
268
+ for (const [term, w] of mainTerms) {
269
+ const ts = stem(term);
270
+ const g = GENERIC_TOKENS.has(ts) ? 0.3 : 1;
271
+ let best = 0;
272
+ let why = '';
273
+ const consider = (pts, r) => { if (pts > best) {
274
+ best = pts;
275
+ why = r;
276
+ } };
277
+ for (const t of labelTokens) {
278
+ if (t === ts)
279
+ consider(10, `label token "${term}"`);
280
+ else if (ts.length >= 4 && t.length >= 4 && (t.startsWith(ts) || ts.startsWith(t)))
281
+ consider(5, `label token "${t}" ~ "${term}"`);
282
+ }
283
+ for (const t of pathTokens) {
284
+ if (t === ts)
285
+ consider(4, `path token "${term}"`);
286
+ else if (ts.length >= 4 && t.length >= 4 && (t.startsWith(ts) || ts.startsWith(t)))
287
+ consider(2, `path token "${t}" ~ "${term}"`);
288
+ }
289
+ if (best > 0) {
290
+ score += best * w * g;
291
+ if (w === 1)
292
+ matched++;
293
+ reasons.push(why);
294
+ }
295
+ }
296
+ if (matched > 1)
297
+ score += matched * 2;
298
+ }
299
+ if (score >= MIN_SCORE) {
300
+ if (relPath)
301
+ score += 0.5;
302
+ if (typeof node.file_type === 'string' && node.file_type !== 'code')
303
+ score -= 0.25; // docs/rationale nodes rank below code at equal relevance
304
+ ranked.push({ node, score, strength: score >= 80 ? 'exact' : score >= STRONG ? 'strong' : 'weak', reasons });
305
+ }
306
+ }
307
+ ranked.sort((a, b) => b.score - a.score ||
308
+ nodeName(a.node).length - nodeName(b.node).length ||
309
+ (a.node.id < b.node.id ? -1 : a.node.id > b.node.id ? 1 : 0));
310
+ // The same symbol can appear under several ids (re-exports, duplicate extraction): keep the best-scored one.
311
+ const seen = new Set();
312
+ const unique = ranked.filter((r) => {
313
+ const n = normalizeNode(r.node);
314
+ const key = `${n.relPath ?? ''}|${(n.symbol ?? nodeName(r.node)).toLowerCase()}`;
315
+ if (seen.has(key))
316
+ return false;
317
+ seen.add(key);
318
+ return true;
205
319
  });
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;
320
+ return unique.slice(0, opts.limit ?? 10);
321
+ }
322
+ /** Finds the best starting node for a query, or null when nothing relevant matches. */
323
+ export function findMatchingStartNode(nodes, query) {
324
+ return rankGraphNodes(nodes, query, { limit: 1 })[0]?.node ?? null;
325
+ }
326
+ const provenanceOf = (e) => {
327
+ const c = typeof e.confidence === 'string' ? e.confidence.toUpperCase() : '';
328
+ if (c === 'EXTRACTED')
329
+ return { confidence: 'EXTRACTED', provenance: 'extracted' };
330
+ if (c === 'INFERRED')
331
+ return { confidence: 'INFERRED', provenance: 'inferred' };
332
+ return { confidence: null, provenance: 'unknown' };
333
+ };
334
+ const PROV_RANK = { extracted: 0, inferred: 1, unknown: 2 };
335
+ const relationOf = (e) => (typeof e.relation === 'string' ? e.relation : typeof e.type === 'string' ? e.type : 'relates_to');
336
+ /**
337
+ * Direct edges touching the matched nodes. `relevance` maps matched node id -> match score. Order: stronger evidence
338
+ * (EXTRACTED first), then edges whose endpoints are more relevant to the task, then a deterministic id tie-break.
339
+ */
340
+ export function topEdgesFor(relevance, edges, limit) {
341
+ const rel = (e) => (relevance.get(e.source) ?? 0) + (relevance.get(e.target) ?? 0);
342
+ return edges
343
+ .filter((e) => relevance.has(e.source) || relevance.has(e.target))
344
+ .map((e) => ({ source: e.source, target: e.target, relation: relationOf(e), status: 'hypothesis', ...provenanceOf(e), depth: 0, sourceCheck: 'unavailable' }))
345
+ .sort((a, b) => PROV_RANK[a.provenance] - PROV_RANK[b.provenance] || rel(b) - rel(a) ||
346
+ a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation))
347
+ .slice(0, limit);
348
+ }
349
+ const MAX_EDGE_CHECKS = 200;
350
+ /** Check an edge's own source line against the endpoint symbols. Bounded: files are read once, up to 500 KB. */
351
+ async function checkEdgeSource(root, e, symbols, cache) {
352
+ const rel = typeof e.source_file === 'string' ? safeRelPath(e.source_file) : null;
353
+ const line = parseSourceLocation(e.source_location);
354
+ if (!rel || !line)
355
+ return 'unavailable';
356
+ if (!cache.has(rel)) {
357
+ const text = await readTextBounded(path.join(root, ...rel.split('/')), 500_000).catch(() => null);
358
+ cache.set(rel, text ? text.split(/\r?\n/) : null);
217
359
  }
218
- return null;
360
+ const lines = cache.get(rel);
361
+ if (!lines || line > lines.length)
362
+ return 'unavailable';
363
+ // +-1 line tolerates small drift and decorators; a hit on either endpoint's symbol confirms the edge's location.
364
+ const window = lines.slice(Math.max(0, line - 2), line + 1).join('\n');
365
+ return symbols.some((s) => s.length > 0 && window.includes(s)) ? 'confirmed' : 'unconfirmed';
219
366
  }
220
367
  /**
221
368
  * 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.
369
+ * Breadth-first; the node cap is enforced during neighbour expansion, so a high-degree hub cannot overshoot it.
370
+ * Within a node, neighbours are admitted by evidence strength (EXTRACTED before INFERRED), then id.
224
371
  */
225
372
  export async function traceGraphService(o, query, options = {}) {
226
373
  const ws = await requireWorkspace(o.cwd);
227
374
  const loaded = await loadGraphData(ws.root);
228
375
  const depthLimit = Math.min(Math.max(options.depth ?? 2, 1), 10);
229
- const maxNodes = Math.min(options.maxNodes ?? 150, 500);
376
+ const maxNodes = Math.max(1, Math.min(options.maxNodes ?? 150, 500));
377
+ const empty = { depth: depthLimit, maxNodes, matchedNode: null, totalNodes: 0, verifiedNodes: 0, hypothesisNodes: 0, truncated: false, nodes: [], edges: [] };
230
378
  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
- };
379
+ return { available: false, query, ...empty, warnings: ['No Graphify graph found at graphify-out/graph.json. Run "/graphify ." in Claude Code.'] };
243
380
  }
244
381
  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
- };
382
+ const top = rankGraphNodes(nodes, query, { limit: 1 })[0];
383
+ if (!top) {
384
+ return { available: true, query, ...empty, warnings: [`No graph node found matching "${query}". Check node IDs with "devworkspace graph status".`] };
259
385
  }
260
- // Build adjacency index
261
- const outgoing = new Map();
262
- const incoming = new Map();
386
+ const startNode = top.node;
387
+ // Adjacency (both directions) holding the neighbour id and the edge.
388
+ const adj = new Map();
389
+ const link = (from, other, edge) => {
390
+ let l = adj.get(from);
391
+ if (!l)
392
+ adj.set(from, (l = []));
393
+ l.push({ other, edge });
394
+ };
263
395
  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);
396
+ link(e.source, e.target, e);
397
+ link(e.target, e.source, e);
270
398
  }
271
399
  const nodeMap = new Map(nodes.map((n) => [n.id, n]));
272
- // Breadth-first search bounded by depthLimit
273
- const visitedDepths = new Map();
400
+ const visitedDepths = new Map([[startNode.id, 0]]);
274
401
  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();
402
+ let truncated = false;
403
+ for (let qi = 0; qi < queue.length; qi++) {
404
+ const current = queue[qi];
279
405
  if (current.depth >= depthLimit)
280
406
  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 });
407
+ const neighbours = (adj.get(current.id) ?? [])
408
+ .filter((x) => x.other !== current.id)
409
+ .sort((a, b) => PROV_RANK[provenanceOf(a.edge).provenance] - PROV_RANK[provenanceOf(b.edge).provenance] ||
410
+ (a.other < b.other ? -1 : a.other > b.other ? 1 : 0));
411
+ for (const { other } of neighbours) {
412
+ if (visitedDepths.has(other))
413
+ continue;
414
+ if (visitedDepths.size >= maxNodes) {
415
+ truncated = true;
416
+ continue;
297
417
  }
418
+ visitedDepths.set(other, current.depth + 1);
419
+ queue.push({ id: other, depth: current.depth + 1 });
298
420
  }
299
421
  }
300
- // Verify all traversed nodes against disk
301
422
  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);
423
+ const nodeStatus = new Map();
424
+ for (const [nodeId, depth] of visitedDepths) {
425
+ const v = await verifyNode(ws.root, nodeMap.get(nodeId) ?? { id: nodeId }, depth);
426
+ tracedNodes.push(v);
427
+ nodeStatus.set(nodeId, v.status);
308
428
  }
309
- // Deduplicate and verify collected edges
310
- const edgeKeys = new Set();
429
+ // Edges among traversed nodes. An existing file proves the endpoint, not the relationship, so only
430
+ // AST-extracted edges between verified endpoints are 'verified'.
431
+ const seen = new Set();
432
+ const fileLines = new Map();
433
+ let checked = 0;
311
434
  const tracedEdges = [];
312
- for (const e of collectedEdges) {
313
- if (!visitedDepths.has(e.source) || !visitedDepths.has(e.target))
435
+ for (const e of edges) {
436
+ const sd = visitedDepths.get(e.source);
437
+ const td = visitedDepths.get(e.target);
438
+ if (sd === undefined || td === undefined)
314
439
  continue;
315
- const key = `${e.source}->${e.target}::${e.relation || e.type || ''}`;
316
- if (edgeKeys.has(key))
440
+ const relation = relationOf(e);
441
+ const key = `${e.source}->${e.target}::${relation}`;
442
+ if (seen.has(key))
317
443
  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';
444
+ seen.add(key);
445
+ const prov = provenanceOf(e);
446
+ const endpointsOk = nodeStatus.get(e.source) === 'verified' && nodeStatus.get(e.target) === 'verified';
447
+ let sourceCheck = 'unavailable';
448
+ if (endpointsOk && prov.provenance === 'extracted' && checked < MAX_EDGE_CHECKS) {
449
+ checked++;
450
+ // Symbol names for symbol nodes; for file nodes (imports_from) the module path in the line ends with the file's base name.
451
+ const syms = [e.source, e.target].flatMap((id) => {
452
+ const n = normalizeNode(nodeMap.get(id) ?? { id });
453
+ const base = n.relPath?.split('/').pop()?.replace(/\.[^.]+$/, '');
454
+ return [n.symbol, base].filter((x) => !!x);
455
+ });
456
+ sourceCheck = await checkEdgeSource(ws.root, e, syms, fileLines);
457
+ }
322
458
  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,
459
+ source: e.source, target: e.target, relation, ...prov, depth: Math.min(sd, td), sourceCheck,
460
+ status: endpointsOk && prov.provenance === 'extracted' && sourceCheck !== 'unconfirmed' ? 'verified' : 'hypothesis',
327
461
  });
328
462
  }
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));
463
+ tracedNodes.sort((a, b) => a.depth - b.depth || (a.path || a.id).localeCompare(b.path || b.id) || a.id.localeCompare(b.id));
464
+ tracedEdges.sort((a, b) => a.depth - b.depth || PROV_RANK[a.provenance] - PROV_RANK[b.provenance] ||
465
+ a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));
331
466
  const matched = tracedNodes.find((n) => n.id === startNode.id) || null;
332
467
  const verifiedCount = tracedNodes.filter((n) => n.status === 'verified').length;
333
- const hypothesisCount = tracedNodes.filter((n) => n.status === 'hypothesis').length;
468
+ const hypothesisCount = tracedNodes.length - verifiedCount;
334
469
  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
- }
470
+ if (top.strength === 'weak')
471
+ warnings.push(`Weak match for "${query}" (${top.reasons.join('; ')}); confirm this is the intended symbol.`);
472
+ if (hypothesisCount > 0)
473
+ warnings.push(`${hypothesisCount} node(s) are unverified hypotheses (file or symbol missing on disk).`);
474
+ const unconfirmed = tracedEdges.filter((e) => e.sourceCheck === 'unconfirmed').length;
475
+ if (unconfirmed > 0)
476
+ warnings.push(`${unconfirmed} extracted relationship(s) point at a source line that no longer mentions their symbols (graph may be stale; run "graphify update .").`);
477
+ if (loaded.conflict)
478
+ warnings.push(`Graphs exist in both layouts; reading ${loaded.path}. ${loaded.conflict.reason}.`);
479
+ const inferred = tracedEdges.filter((e) => e.provenance === 'inferred').length;
480
+ const unknown = tracedEdges.filter((e) => e.provenance === 'unknown').length;
481
+ if (inferred > 0)
482
+ warnings.push(`${inferred} relationship(s) are Graphify inferences, not AST-extracted; confirm in source.`);
483
+ if (unknown > 0)
484
+ warnings.push(`${unknown} relationship(s) carry no confidence metadata (older graph); treated as unverified.`);
485
+ if (truncated)
486
+ warnings.push(`Traversal stopped at the ${maxNodes}-node cap; more nodes are reachable within depth ${depthLimit}.`);
338
487
  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,
488
+ available: true, query, depth: depthLimit, maxNodes, matchedNode: matched, matchStrength: top.strength,
489
+ totalNodes: tracedNodes.length, verifiedNodes: verifiedCount, hypothesisNodes: hypothesisCount,
490
+ truncated, nodes: tracedNodes, edges: tracedEdges, warnings,
349
491
  };
350
492
  }
351
493
  //# sourceMappingURL=graph.js.map