weavatrix 0.1.1 → 0.1.3

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 (42) hide show
  1. package/README.md +117 -21
  2. package/SECURITY.md +31 -0
  3. package/package.json +16 -4
  4. package/skill/SKILL.md +69 -12
  5. package/src/analysis/coverage-reports.js +14 -11
  6. package/src/analysis/dead-check.js +87 -6
  7. package/src/analysis/dep-check.js +84 -8
  8. package/src/analysis/dep-rules.js +74 -8
  9. package/src/analysis/duplicates.compute.js +215 -215
  10. package/src/analysis/duplicates.js +15 -15
  11. package/src/analysis/duplicates.run.js +52 -51
  12. package/src/analysis/duplicates.tokenize.js +182 -182
  13. package/src/analysis/endpoints.js +50 -5
  14. package/src/analysis/graph-analysis.aggregate.js +16 -4
  15. package/src/analysis/internal-audit.collect.js +154 -31
  16. package/src/analysis/internal-audit.reach.js +52 -11
  17. package/src/analysis/internal-audit.run.js +72 -21
  18. package/src/build-graph.js +2 -1
  19. package/src/child-env.js +7 -0
  20. package/src/graph/builder/lang-js.js +66 -23
  21. package/src/graph/internal-builder.build.js +48 -10
  22. package/src/graph/internal-builder.langs.js +49 -3
  23. package/src/graph/internal-builder.resolvers.js +96 -20
  24. package/src/mcp/catalog.mjs +10 -8
  25. package/src/mcp/graph-context.mjs +107 -17
  26. package/src/mcp/sync-payload.mjs +110 -0
  27. package/src/mcp/tools-actions.mjs +42 -18
  28. package/src/mcp/tools-graph.mjs +46 -12
  29. package/src/mcp/tools-health.mjs +42 -18
  30. package/src/mcp/tools-impact.mjs +55 -43
  31. package/src/mcp-rg.mjs +2 -1
  32. package/src/mcp-server.mjs +25 -16
  33. package/src/mcp-source-tools.mjs +16 -5
  34. package/src/process.js +4 -3
  35. package/src/repo-path.js +53 -0
  36. package/src/security/advisory-store.js +51 -7
  37. package/src/security/installed.js +44 -31
  38. package/src/security/malware-heuristics.exclusions.js +134 -134
  39. package/src/security/malware-heuristics.js +15 -15
  40. package/src/security/malware-heuristics.roots.js +142 -142
  41. package/src/security/malware-heuristics.scan.js +85 -85
  42. package/src/security/malware-heuristics.sweep.js +122 -122
@@ -38,19 +38,38 @@ export function tFindDuplicates(g, args, ctx) {
38
38
  if (args.mode === 'semantic') {
39
39
  const data = computeDuplicates(ctx.repoRoot, ctx.graphPath, {nameTwins: true})
40
40
  const frags = data.frags
41
- const groups = (data.nameTwins || [])
42
- .map((t) => ({...t, members: t.members.filter((i) => (!skipTests || !frags[i].test) && frags[i].n >= tokMin)}))
43
- .map((t) => ({...t, fileCount: new Set(t.members.map((i) => frags[i].file)).size}))
44
- .filter((t) => t.members.length >= 2 && t.fileCount >= 2)
45
- if (!groups.length) return 'No same-name symbol groups across files (semantic mode).'
46
- const top = groups.slice(0, Math.min(30, Math.max(1, Number(args.top_n) || 15)))
47
- const lines = top.map((t, k) => {
48
- const verdict = t.simMax < 60 ? ' ⚠ DIVERGENT — same name, different bodies (drift hazard)' : t.simMin >= 90 ? ' near-identical — extract a shared module' : ''
49
- const head = `${k + 1}. "${t.label}" ${t.members.length} definitions in ${t.fileCount} files, similarity ${t.simMin}–${t.simMax}%${verdict}`
50
- const sites = t.members.slice(0, 8).map((i) => ` ${frags[i].file}:${frags[i].start}-${frags[i].end} (${frags[i].n} tok)`)
51
- return [head, ...sites].join('\n')
41
+ const candidates = []
42
+ for (const twin of data.nameTwins || []) {
43
+ const allowed = new Set(twin.members.filter((i) => (!skipTests || !frags[i].test) && frags[i].n >= tokMin))
44
+ const pairs = (twin.pairs || []).filter((p) => allowed.has(p.a) && allowed.has(p.b))
45
+ if (!pairs.length) continue
46
+ const closest = pairs.slice().sort((a, b) => b.similarity - a.similarity)[0]
47
+ const farthest = pairs.slice().sort((a, b) => a.similarity - b.similarity)[0]
48
+ if (closest.similarity >= 85) candidates.push({kind: 'clone', label: twin.label, pair: closest})
49
+ if (farthest.similarity <= 45) candidates.push({kind: 'collision', label: twin.label, pair: farthest})
50
+ }
51
+ for (const item of candidates) item.tokens = frags[item.pair.a].n + frags[item.pair.b].n
52
+ candidates.sort((a, b) => {
53
+ if (a.kind !== b.kind) return a.kind === 'clone' ? -1 : 1
54
+ return a.kind === 'clone'
55
+ ? b.pair.similarity - a.pair.similarity || b.tokens - a.tokens
56
+ : b.tokens - a.tokens || a.pair.similarity - b.pair.similarity
52
57
  })
53
- return `Found ${groups.length} same-name symbol group(s) across files (semantic mode; similarity = renamed-token jaccard, LOW = divergent copies). Top ${top.length}:\n\n${lines.join('\n\n')}\n\nLow-similarity groups are the risky ones — same name, drifted behavior. read_source both sites to compare.`
58
+ if (!candidates.length) return 'No actionable same-name pairs across files (semantic mode; ambiguous middle-similarity pairs are suppressed).'
59
+ const top = candidates.slice(0, Math.min(30, Math.max(1, Number(args.top_n) || 15)))
60
+ const lines = top.map((item, k) => {
61
+ const a = frags[item.pair.a]
62
+ const b = frags[item.pair.b]
63
+ const verdict = item.kind === 'clone'
64
+ ? 'near-identical duplicate candidate — review, then extract shared logic if the contract is truly shared'
65
+ : 'name collision, not a duplicate — inspect only if these definitions should share a contract'
66
+ return [
67
+ `${k + 1}. "${item.label}" — ${item.pair.similarity}% similar; ${verdict}`,
68
+ ` ${a.file}:${a.start}-${a.end} (${a.n} tok)`,
69
+ ` ${b.file}:${b.start}-${b.end} (${b.n} tok)`,
70
+ ].join('\n')
71
+ })
72
+ return `Found ${candidates.length} actionable same-name pair(s) across files (semantic mode; one closest clone and/or farthest collision per name). Top ${top.length}:\n\n${lines.join('\n\n')}\n\nThese are review candidates, not automatic refactors. Use read_source on both sites before changing code.`
54
73
  }
55
74
  const data = computeDuplicates(ctx.repoRoot, ctx.graphPath, {includeStrings})
56
75
  const groups = groupClones(data, {simMin, tokMin, mode, skipTests})
@@ -87,14 +106,15 @@ export async function tRunAudit(g, args, ctx) {
87
106
  const sev = audit.summary.bySeverity
88
107
  const bycat = audit.summary.byCategory
89
108
  const line = (f) => {
90
- const where = f.file ? ` (${f.file}${f.symbol ? ` ${f.symbol}` : ''})` : f.package ? ` (pkg ${f.package}${f.version ? `@${f.version}` : ''})` : ''
109
+ const where = f.file ? ` (${f.file}${f.symbol ? ` ${f.symbol}` : ''})` : f.package ? ` (pkg ${f.package}${f.version ? `@${f.version}` : ''}${f.manifest ? `; ${f.manifest}` : ''})` : ''
91
110
  return ` [${f.severity}/${f.confidence || '?'}] ${f.rule}: ${f.title}${where}${f.fixHint ? `\n fix: ${f.fixHint}` : ''}`
92
111
  }
112
+ const check = (name, state) => `${name} ${state?.status || 'ERROR'}${state?.detail ? ` — ${state.detail}` : ''}`
93
113
  return [
94
114
  `Internal audit of ${audit.repo} (${audit.scanned.files} files, ${audit.scanned.symbols} symbols, ${audit.scanned.externalImports} external imports; malware scan: ${audit.scanned.malwareScanMode}).`,
95
115
  `Severity: critical ${sev.critical}, high ${sev.high}, medium ${sev.medium}, low ${sev.low}, info ${sev.info}. Categories: unused ${bycat.unused}, structure ${bycat.structure}, vulnerability ${bycat.vulnerability}, malware ${bycat.malware}.`,
96
- `Structure: ${audit.structureReport?.cycles ?? 0} cycle(s), ${audit.structureReport?.orphans ?? 0} orphan(s). Dead: ${audit.deadReport.deadFiles} file(s), ${audit.deadReport.unusedExports} unused export(s).`,
97
- audit.scanned.advisoryDbDate ? `Advisory DB: ${audit.scanned.advisoryDbDate}.` : 'Advisory DB: never refreshed for this repo known-vuln matching skipped (see refresh_advisories).',
116
+ `Structure: ${audit.structureReport?.runtimeCycles ?? audit.structureReport?.cycles ?? 0} runtime cycle(s), ${audit.structureReport?.typeCouplings ?? 0} type-induced coupling group(s), ${audit.structureReport?.orphans ?? 0} orphan(s); import edges: ${audit.structureReport?.runtimeImportEdges ?? audit.structureReport?.importEdges ?? 0} runtime + ${audit.structureReport?.typeOnlyImportEdges ?? 0} type-only. Dead: ${audit.deadReport.deadFiles} file(s), ${audit.deadReport.unusedExports} unused export(s).`,
117
+ `Checks: ${check('OSV', audit.checks?.osv)}; ${check('malware', audit.checks?.malware)}. A NOT_CHECKED/PARTIAL/ERROR check is incomplete or unknown, never a clean zero.`,
98
118
  ``,
99
119
  `Showing ${shown.length} of ${filtered.length} finding(s)${cat ? ` in category "${cat}"` : ''}${args.min_severity ? ` at ≥${args.min_severity}` : ''}:`,
100
120
  ...shown.map(line),
@@ -120,13 +140,17 @@ export function tModuleMap(g, args, ctx) {
120
140
  const topN = Math.max(1, Math.min(60, Number(args.top_n) || 25))
121
141
  const mods = agg.modules.slice(0, topN)
122
142
  const edges = agg.moduleEdges.slice(0, Math.min(50, topN * 2))
143
+ const typeEdges = (agg.typeOnlyModuleEdges || []).slice(0, Math.min(50, topN * 2))
123
144
  return [
124
- `Module map: ${agg.totals.files} files in ${agg.modules.length} folder-modules, ${agg.totals.moduleEdges} module edges. Top ${mods.length}:`,
145
+ `Module map: ${agg.totals.files} files in ${agg.modules.length} folder-modules, ${agg.totals.moduleEdges} runtime module dependencies and ${agg.totals.typeOnlyModuleEdges || 0} type-only dependencies. Top ${mods.length}:`,
125
146
  ...mods.map((m) => ` ${m.name} — ${m.fileCount} files, ${m.symbolCount} symbols`),
126
147
  ``,
127
- `Strongest module dependencies:`,
148
+ `Strongest runtime module dependencies:`,
128
149
  ...edges.map((e) => ` ${e.from} → ${e.to} (${e.count})`),
129
- ].join('\n')
150
+ typeEdges.length ? `` : null,
151
+ typeEdges.length ? `Type-only module dependencies (compile-time contracts, not runtime coupling):` : null,
152
+ ...typeEdges.map((e) => ` ${e.from} → ${e.to} (${e.count})`),
153
+ ].filter((line) => line != null).join('\n')
130
154
  }
131
155
 
132
156
  // Coverage × graph: map an EXISTING coverage report (istanbul/lcov/coverage.py/Go — read offline,
@@ -3,12 +3,53 @@
3
3
  // Hot-reloadable (re-imported by catalog.mjs on change).
4
4
  import {readFileSync} from 'node:fs'
5
5
  import {spawnSync} from 'node:child_process'
6
+ import {childProcessEnv} from '../child-env.js'
6
7
  import {
7
8
  isSymbol, degreeOf, labelOf, resolveNodeInfo, ambiguityNote,
8
9
  rawGraph, prevGraphPathFor, edgeEndpoint, diffGraphs, formatGraphDiff,
9
10
  } from './graph-context.mjs'
10
11
  import {readCoverageForRepo} from '../analysis/coverage-reports.js'
11
12
 
13
+ function reverseReach(g, seeds, maxDepth) {
14
+ const states = new Map([...seeds].map((id) => [String(id), {
15
+ runtimeDepth: 0, runtimeRelation: null, compileDepth: null, compileRelation: null,
16
+ }]))
17
+ const frontier = [...seeds].map((id) => ({id: String(id), depth: 0, compileOnly: false}))
18
+ for (let cursor = 0; cursor < frontier.length; cursor++) {
19
+ const current = frontier[cursor]
20
+ if (current.depth >= maxDepth) continue
21
+ for (const e of g.inn.get(current.id) || []) {
22
+ if (e.relation === 'contains') continue
23
+ const id = String(e.id)
24
+ const compileOnly = current.compileOnly || e.typeOnly === true
25
+ const depth = current.depth + 1
26
+ const entry = states.get(id) || {
27
+ runtimeDepth: null, runtimeRelation: null, compileDepth: null, compileRelation: null,
28
+ }
29
+ const depthKey = compileOnly ? 'compileDepth' : 'runtimeDepth'
30
+ const relationKey = compileOnly ? 'compileRelation' : 'runtimeRelation'
31
+ if (entry[depthKey] != null && entry[depthKey] <= depth) continue
32
+ entry[depthKey] = depth
33
+ entry[relationKey] = e.relation || 'rel'
34
+ states.set(id, entry)
35
+ frontier.push({id, depth, compileOnly})
36
+ }
37
+ }
38
+ return new Map([...states].map(([id, entry]) => [id, {
39
+ ...entry,
40
+ depth: entry.runtimeDepth ?? entry.compileDepth ?? 0,
41
+ compileOnly: entry.runtimeDepth == null,
42
+ relation: entry.runtimeDepth != null ? entry.runtimeRelation : entry.compileRelation,
43
+ }]))
44
+ }
45
+
46
+ const impactKind = (entry) => {
47
+ if (entry?.runtimeDepth != null) {
48
+ return entry.compileDepth != null ? `runtime + compile-time(d${entry.compileDepth})` : 'runtime'
49
+ }
50
+ return 'compile-time'
51
+ }
52
+
12
53
  // Transitive blast-radius: who is affected if this node changes. Walks REVERSE dependency edges
13
54
  // (calls/imports/inherits — not structural `contains`) out to `depth`. For a symbol, also seeds its
14
55
  // containing file, because importers depend on the file rather than the individual symbol.
@@ -29,26 +70,10 @@ export function tGetDependents(g, {label, depth = 3, max_nodes = 40} = {}) {
29
70
  seeds.add(containingFile)
30
71
  }
31
72
  }
32
- const depthOf = new Map([...seeds].map((s) => [s, 0]))
33
- const relOf = new Map()
34
- let frontier = [...seeds]
35
- for (let d = 0; d < maxDepth && frontier.length; d++) {
36
- const next = []
37
- for (const cur of frontier) {
38
- for (const e of g.inn.get(cur) || []) {
39
- if (e.relation === 'contains') continue // structural nesting is not a dependency
40
- const nid = String(e.id)
41
- if (depthOf.has(nid)) continue
42
- depthOf.set(nid, d + 1)
43
- relOf.set(nid, e.relation || 'rel')
44
- next.push(nid)
45
- }
46
- }
47
- frontier = next
48
- }
49
- const ranked = [...depthOf.entries()]
73
+ const reached = reverseReach(g, seeds, maxDepth)
74
+ const ranked = [...reached.entries()]
50
75
  .filter(([nid]) => !seeds.has(nid))
51
- .map(([nid, d]) => ({id: nid, d, deg: degreeOf(g, nid)}))
76
+ .map(([nid, entry]) => ({id: nid, d: entry.depth, entry, deg: degreeOf(g, nid)}))
52
77
  .sort((a, b) => a.d - b.d || b.deg - a.deg)
53
78
  if (!ranked.length) return [note, `No dependents found for ${n.label ?? id} within depth ${maxDepth} — nothing in the graph calls, imports, or inherits it.`].filter(Boolean).join('\n')
54
79
  const shown = ranked.slice(0, cap)
@@ -56,7 +81,7 @@ export function tGetDependents(g, {label, depth = 3, max_nodes = 40} = {}) {
56
81
  note,
57
82
  `Dependents of ${n.label ?? id} (reverse calls/imports/inherits, depth ≤${maxDepth}): ${ranked.length} found, showing ${shown.length} by proximity + connectivity.`,
58
83
  containingFile ? `Includes importers of its containing file ${labelOf(g, containingFile)}.` : null,
59
- ...shown.map((r) => ` [d${r.d}] ${relOf.get(r.id) || 'rel'} ${labelOf(g, r.id)} (deg ${r.deg}) [${r.id}]`),
84
+ ...shown.map((r) => ` [d${r.d} ${impactKind(r.entry)}] ${r.entry.relation || 'rel'} ${labelOf(g, r.id)} (deg ${r.deg}) [${r.id}]`),
60
85
  ].filter(Boolean).join('\n')
61
86
  }
62
87
 
@@ -71,7 +96,8 @@ export function tGraphDiff(g, args, ctx) {
71
96
  const filter = args.path ? String(args.path).replace(/\\/g, '/') : null
72
97
  const scope = (graph) => filter ? {
73
98
  nodes: (graph.nodes || []).filter((n) => String(n.id).startsWith(filter)),
74
- links: (graph.links || []).filter((l) => String(edgeEndpoint(l.source)).startsWith(filter) || String(edgeEndpoint(l.target)).startsWith(filter))
99
+ links: (graph.links || []).filter((l) => String(edgeEndpoint(l.source)).startsWith(filter) || String(edgeEndpoint(l.target)).startsWith(filter)),
100
+ edgeTypesV: graph.edgeTypesV || 0,
75
101
  } : graph
76
102
  return [
77
103
  `Graph diff (previous rebuild state → current)${filter ? `, scoped to ${filter}` : ''}:`,
@@ -81,7 +107,7 @@ export function tGraphDiff(g, args, ctx) {
81
107
 
82
108
  // ---- change impact -------------------------------------------------------------------------------
83
109
  function gitLines(repoRoot, args) {
84
- const res = spawnSync('git', ['-C', repoRoot, ...args], {encoding: 'utf8', timeout: 8000})
110
+ const res = spawnSync('git', ['-C', repoRoot, ...args], {encoding: 'utf8', timeout: 8000, env: childProcessEnv()})
85
111
  if (res.status !== 0) return null
86
112
  return String(res.stdout || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
87
113
  }
@@ -89,7 +115,7 @@ function gitLines(repoRoot, args) {
89
115
  function resolveImpactBase(repoRoot, requested) {
90
116
  const candidates = requested ? [requested] : ['origin/HEAD', 'origin/main', 'origin/master', 'main', 'master']
91
117
  for (const ref of candidates) {
92
- const ok = spawnSync('git', ['-C', repoRoot, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`], {encoding: 'utf8', timeout: 8000})
118
+ const ok = spawnSync('git', ['-C', repoRoot, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`], {encoding: 'utf8', timeout: 8000, env: childProcessEnv()})
93
119
  if (ok.status === 0) return ref
94
120
  }
95
121
  return null
@@ -143,27 +169,11 @@ export function tChangeImpact(g, args, ctx) {
143
169
 
144
170
  const maxDepth = Math.max(1, Math.min(4, Number(args.depth) || 2))
145
171
  const cap = Math.max(5, Math.min(120, Number(args.max_nodes) || 40))
146
- const depthOf = new Map([...seeds].map((s) => [s, 0]))
147
- const relOf = new Map()
148
- let frontier = [...seeds]
149
- for (let d = 0; d < maxDepth && frontier.length; d++) {
150
- const next = []
151
- for (const cur of frontier) {
152
- for (const e of g.inn.get(cur) || []) {
153
- if (e.relation === 'contains') continue
154
- const nid = String(e.id)
155
- if (depthOf.has(nid)) continue
156
- depthOf.set(nid, d + 1)
157
- relOf.set(nid, e.relation || 'rel')
158
- next.push(nid)
159
- }
160
- }
161
- frontier = next
162
- }
172
+ const reached = reverseReach(g, seeds, maxDepth)
163
173
  const fileOfNode = (id) => { const s = String(id); const h = s.indexOf('#'); return h < 0 ? s : s.slice(0, h) }
164
- const impacted = [...depthOf.entries()]
174
+ const impacted = [...reached.entries()]
165
175
  .filter(([nid]) => !seeds.has(nid) && !changedSet.has(fileOfNode(nid)))
166
- .map(([nid, d]) => ({id: nid, d, deg: degreeOf(g, nid), file: fileOfNode(nid)}))
176
+ .map(([nid, entry]) => ({id: nid, d: entry.depth, entry, deg: degreeOf(g, nid), file: fileOfNode(nid)}))
167
177
  .sort((a, b) => a.d - b.d || b.deg - a.deg)
168
178
 
169
179
  // coverage overlay from EXISTING reports (fractions 0..1) — see coverage_map for details
@@ -171,6 +181,7 @@ export function tChangeImpact(g, args, ctx) {
171
181
  const coverage = readCoverageForRepo(ctx.repoRoot, knownFiles)
172
182
  const covOf = (file) => coverage.get(String(file).replace(/\\/g, '/'))?.pct ?? null
173
183
  const pctStr = (v) => (v == null ? 'cov n/a' : `cov ${Math.round(v * 100)}%`)
184
+ const hasCoverage = coverage.size > 0
174
185
 
175
186
  const shown = impacted.slice(0, cap)
176
187
  const untestedHotspots = shown.filter((n) => { const c = covOf(n.file); return c != null && c < 0.5 && n.deg >= 5 })
@@ -179,7 +190,8 @@ export function tChangeImpact(g, args, ctx) {
179
190
  impacted.length
180
191
  ? `${impacted.length} impacted node(s) within ${maxDepth} reverse hop(s), showing ${shown.length}:`
181
192
  : `Nothing else in the graph depends on the changed code within ${maxDepth} hop(s).`,
182
- ...shown.map((n) => ` [d${n.d}] ${relOf.get(n.id) || 'rel'} ${labelOf(g, n.id)} (deg ${n.deg}, ${pctStr(covOf(n.file))}) [${n.id}]`),
193
+ hasCoverage ? `Coverage: existing report mapped where available.` : `Coverage: unavailable (no supported report found); per-node coverage labels omitted.`,
194
+ ...shown.map((n) => ` [d${n.d} ${impactKind(n.entry)}] ${n.entry.relation || 'rel'} ${labelOf(g, n.id)} (deg ${n.deg}${hasCoverage ? `, ${pctStr(covOf(n.file))}` : ''}) [${n.id}]`),
183
195
  untestedHotspots.length ? `` : null,
184
196
  untestedHotspots.length ? `Untested hotspots in the blast radius (<50% coverage, deg ≥5) — cover these before shipping:` : null,
185
197
  ...untestedHotspots.slice(0, 10).map((n) => ` ${labelOf(g, n.id)} (${pctStr(covOf(n.file))}, deg ${n.deg}) ${n.file}`),
package/src/mcp-rg.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readdirSync, existsSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { spawnSync } from 'node:child_process'
4
+ import { childProcessEnv } from './child-env.js'
4
5
  import { createRequire } from 'node:module'
5
6
  import process from 'node:process'
6
7
 
@@ -42,7 +43,7 @@ export function createRgResolver(selfDir) {
42
43
  } catch { /* optional packaged ripgrep path */ }
43
44
  for (const c of editorRgCandidates()) if (existsSync(c)) return (rgPath = c)
44
45
  try {
45
- const probe = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['rg'], {encoding: 'utf8'})
46
+ const probe = spawnSync(process.platform === 'win32' ? 'where' : 'which', ['rg'], {encoding: 'utf8', env: childProcessEnv()})
46
47
  const p = probe.status === 0 ? probe.stdout.split(/\r?\n/)[0].trim() : ''
47
48
  if (p && existsSync(p)) return (rgPath = p)
48
49
  } catch { /* optional PATH probe */ }
@@ -15,12 +15,11 @@
15
15
  // go to stderr. Two argv forms:
16
16
  // weavatrix-mcp <repoRoot> [caps] — graph path derived from the standard layout
17
17
  // weavatrix-mcp <graph.json> <repoRoot> [caps] — explicit graph file (classic form)
18
- import {existsSync, statSync} from 'node:fs'
18
+ import {existsSync, statSync, realpathSync} from 'node:fs'
19
19
  import {join, dirname} from 'node:path'
20
20
  import {fileURLToPath} from 'node:url'
21
21
  import process from 'node:process'
22
22
  import {loadGraph} from './mcp/graph-context.mjs'
23
- import {loadHotApi, HOT_FILES} from './mcp/catalog.mjs'
24
23
  import {graphOutDirForRepo} from './graph/layout.js'
25
24
  import {createRequire} from 'node:module'
26
25
 
@@ -34,19 +33,20 @@ const log = (...a) => process.stderr.write(`[weavatrix] ${a.join(' ')}\n`)
34
33
  // otherwise it is the graph.json path and the repo root follows it.
35
34
  let GRAPH_PATH = process.argv[2]
36
35
  let repoArg = process.argv[3]
37
- // caps ABSENT (undefined) = no per-repo config → ALL tools. PRESENT (even the empty string, which a
38
- // registration may pass for a zero-capability selection) = explicit set — see catalog.loadHotApi.
36
+ // caps ABSENT (undefined) = offline defaults (including explicit-call repo retargeting, no network).
37
+ // PRESENT (even the empty string) = explicit set — see catalog.loadHotApi.
39
38
  let CAPS_ARG = process.argv[4]
40
39
  try {
41
40
  if (GRAPH_PATH && statSync(GRAPH_PATH).isDirectory()) {
42
- repoArg = GRAPH_PATH.replace(/[\\/]+$/, '')
41
+ repoArg = realpathSync.native(GRAPH_PATH)
43
42
  CAPS_ARG = process.argv[3]
44
43
  GRAPH_PATH = join(graphOutDirForRepo(repoArg), 'graph.json')
45
- if (!existsSync(GRAPH_PATH)) log(`no graph built yet for ${repoArg} — ask the agent to call rebuild_graph (or open_repo) once; it builds into the standard weavatrix-graphs layout`)
44
+ if (!existsSync(GRAPH_PATH)) log(`no graph built yet for ${repoArg} — ask the agent to call rebuild_graph; it builds into the standard weavatrix-graphs layout`)
46
45
  }
47
46
  } catch { /* argv[2] is not a directory → classic <graph.json> <repoRoot> form */ }
48
47
  // repo source root for search_code / read_source; null → those tools degrade.
49
- const REPO_ROOT = repoArg && existsSync(repoArg) ? repoArg : null
48
+ let REPO_ROOT = null
49
+ try { if (repoArg && statSync(repoArg).isDirectory()) REPO_ROOT = realpathSync.native(repoArg) } catch { /* invalid repo root */ }
50
50
 
51
51
  // ---- hot reload of tool implementations -----------------------------------------------------------
52
52
  // Node caches modules at spawn, so edits to the tool code would otherwise be invisible until the MCP
@@ -55,16 +55,19 @@ const REPO_ROOT = repoArg && existsSync(repoArg) ? repoArg : null
55
55
  // swap the tool table, then notify the client. The stdio shell, graph-context (its caches), and the
56
56
  // analysis engines are NOT swapped — changing those still needs a reconnect.
57
57
  const MCP_DIR = join(dirname(fileURLToPath(import.meta.url)), 'mcp')
58
- function hotVersion() {
58
+ const CATALOG_URL = new URL('./mcp/catalog.mjs', import.meta.url)
59
+ const loadCatalog = (version = 0) => import(version ? `${CATALOG_URL.href}?v=${version}` : CATALOG_URL.href)
60
+ function hotVersion(hotFiles) {
59
61
  let v = 0
60
- for (const f of HOT_FILES) {
62
+ for (const f of hotFiles) {
61
63
  try { const t = statSync(join(MCP_DIR, f)).mtimeMs; if (t > v) v = t } catch { /* missing file just doesn't bump the version */ }
62
64
  }
63
65
  return v
64
66
  }
65
67
 
66
68
  async function main() {
67
- let api = await loadHotApi(0, CAPS_ARG)
69
+ let catalog = await loadCatalog()
70
+ let api = await catalog.loadHotApi(0, CAPS_ARG)
68
71
  let graph = null
69
72
  let graphError = null
70
73
  // ctx owns the CURRENT target: rebuild_graph reloads it, open_repo retargets graphPath/repoRoot
@@ -81,20 +84,23 @@ async function main() {
81
84
  log(`failed to load graph: ${e.message}`)
82
85
  }
83
86
  log(`repo root: ${REPO_ROOT || '(none — source/action tools disabled)'}`)
84
- log(`capabilities: ${api.caps ? [...api.caps].join(',') : 'all'} (${api.tools.length} tools)`)
87
+ log(`capabilities: ${[...api.caps].join(',') || '(none)'} (${api.tools.length} tools)`)
85
88
 
86
89
  let protocolVersion = DEFAULT_PROTOCOL
87
90
  const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n')
88
91
  const reply = (id, result) => send({jsonrpc: '2.0', id, result})
89
92
  const fail = (id, code, message) => send({jsonrpc: '2.0', id, error: {code, message}})
90
93
 
91
- let loadedVersion = hotVersion()
94
+ let loadedVersion = hotVersion(catalog.HOT_FILES)
92
95
  let lastFailedVersion = 0
93
96
  const maybeHotReload = async () => {
94
- const v = hotVersion()
97
+ const v = hotVersion(catalog.HOT_FILES)
95
98
  if (v <= loadedVersion || v === lastFailedVersion) return
96
99
  try {
97
- api = await loadHotApi(v, CAPS_ARG)
100
+ const nextCatalog = await loadCatalog(v)
101
+ const nextApi = await nextCatalog.loadHotApi(v, CAPS_ARG)
102
+ catalog = nextCatalog
103
+ api = nextApi
98
104
  loadedVersion = v
99
105
  log(`hot-reloaded tool implementations from changed source (${api.tools.length} tools)`)
100
106
  send({jsonrpc: '2.0', method: 'notifications/tools/list_changed'})
@@ -121,10 +127,13 @@ async function main() {
121
127
  await maybeHotReload()
122
128
  const tool = api.byName.get(params?.name)
123
129
  if (!tool) return reply(id, {content: [{type: 'text', text: `Unknown tool: ${params?.name}`}], isError: true})
124
- // action tools (rebuild_graph) don't need a currently-loaded graph; read tools do
125
- if (!graph && tool.cap !== 'build') return reply(id, {content: [{type: 'text', text: `Graph unavailable: ${graphError}`}], isError: true})
130
+ // action tools can establish/retarget a graph; read tools need one already loaded
131
+ if (!graph && tool.cap !== 'build' && tool.cap !== 'retarget') return reply(id, {content: [{type: 'text', text: `Graph unavailable: ${graphError}`}], isError: true})
126
132
  try {
127
133
  let text = String(await tool.run(graph, params?.arguments || {}, ctx))
134
+ if (graph && graph.edgeTypesV < 1 && (tool.cap === 'graph' || tool.cap === 'health')) {
135
+ text += '\n\nWarning: this saved graph predates typed import edges, so type-only imports cannot be separated from runtime dependencies. Call rebuild_graph once before acting on cycle, boundary, dependency, or blast-radius findings.'
136
+ }
128
137
  // Graph answers silently reflect a point-in-time build — surface staleness on every graph tool.
129
138
  if (tool.cap === 'graph') {
130
139
  const warn = api.stalenessLine(ctx)
@@ -1,10 +1,14 @@
1
1
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
2
2
  import { spawnSync } from 'node:child_process'
3
3
  import { extname, join, relative } from 'node:path'
4
+ import { resolveRepoPath } from './repo-path.js'
5
+ import { childProcessEnv } from './child-env.js'
4
6
 
5
7
  const SEARCH_SKIP = new Set(['.git', 'node_modules', 'dist', 'build', 'out', '.next', 'coverage', 'vendor', '.venv', 'venv', 'env', 'target', '__pycache__', '.idea', '.vscode', '.cache', 'bin', 'obj', 'weavatrix-graphs'])
6
8
  const BINARY_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.tar', '.exe', '.dll', '.so', '.dylib', '.woff', '.woff2', '.ttf', '.eot', '.mp4', '.mp3', '.wasm', '.class', '.jar', '.node', '.bin'])
7
9
  const MAX_SEARCH_FILE_BYTES = 1024 * 1024
10
+ const MAX_SOURCE_FILE_BYTES = 2 * 1024 * 1024
11
+ const MAX_SOURCE_CONTEXT_LINES = 1000
8
12
 
9
13
  function rgSearch(repoRoot, resolveRg, query, { isRegex, glob, maxResults }) {
10
14
  const rg = resolveRg()
@@ -13,7 +17,7 @@ function rgSearch(repoRoot, resolveRg, query, { isRegex, glob, maxResults }) {
13
17
  if (!isRegex) args.push('--fixed-strings')
14
18
  if (glob) args.push('-g', glob)
15
19
  args.push('--', query, repoRoot)
16
- const res = spawnSync(rg, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: 15000 })
20
+ const res = spawnSync(rg, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: 15000, env: childProcessEnv() })
17
21
  if (res.status !== 0 && res.status !== 1) return null
18
22
  const out = []
19
23
  for (const line of (res.stdout || '').split(/\r?\n/)) {
@@ -122,14 +126,21 @@ export function readSource({ repoRoot, resolveNode, isSymbol }, g, { label, path
122
126
  }
123
127
  // explicit anchor wins: window = start_line-before .. start_line+after (how a path read escapes the file head)
124
128
  if (start_line != null && Number(start_line) > 0) focusLine = Math.floor(Number(start_line))
125
- const abs = join(repoRoot, file)
126
- if (!existsSync(abs)) return `File not found: ${file}`
129
+ const resolved = resolveRepoPath(repoRoot, file)
130
+ if (resolved.reason === 'escape') return `Refusing to read "${file}": path escapes the repository root.`
131
+ if (resolved.reason === 'not-found') return `File not found: ${file}`
132
+ if (!resolved.ok) return `Could not resolve ${file} inside the repository root.`
133
+ const abs = resolved.path
134
+ let st
135
+ try { st = statSync(abs) } catch (e) { return `Could not inspect ${file}: ${e.message}` }
136
+ if (!st.isFile()) return `Could not read ${file}: not a regular file.`
137
+ if (st.size > MAX_SOURCE_FILE_BYTES) return `Could not read ${file}: file exceeds the ${MAX_SOURCE_FILE_BYTES / 1024 / 1024} MB source-read limit.`
127
138
  let text
128
139
  try { text = readFileSync(abs, 'utf8') } catch (e) { return `Could not read ${file}: ${e.message}` }
129
140
  const lines = text.split(/\r?\n/)
130
141
  if (focusLine) focusLine = Math.min(focusLine, lines.length) // an anchor past EOF shows the tail, not nothing
131
- const b = Math.max(0, Number(before) || 0)
132
- const a = Math.max(1, Number(after) || 40)
142
+ const b = Math.min(MAX_SOURCE_CONTEXT_LINES, Math.max(0, Number(before) || 0))
143
+ const a = Math.min(MAX_SOURCE_CONTEXT_LINES, Math.max(1, Number(after) || 40))
133
144
  const start = focusLine ? Math.max(1, focusLine - b) : 1
134
145
  const end = focusLine ? Math.min(lines.length, focusLine + a) : Math.min(lines.length, 1 + b + a)
135
146
  const width = String(end).length
package/src/process.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Subprocess runner shared by the search engines and security sweeps.
2
2
  import { spawn } from "node:child_process";
3
+ import { childProcessEnv } from "./child-env.js";
3
4
 
4
5
  // Windows: .cmd/.ps1 shims (npx, etc.) can't be spawned directly by Node — they need a
5
6
  // shell. With shell:true Node does NOT quote args, so we build a quoted command line ourselves
@@ -18,13 +19,13 @@ export function runCommand(command, args = [], options = {}) {
18
19
  const child = needsShell
19
20
  ? spawn([command, ...args].map(winQuote).join(" "), [], {
20
21
  cwd: options.cwd || undefined,
21
- env: { ...process.env, ...(options.env || {}) },
22
+ env: childProcessEnv(options.env || {}),
22
23
  shell: true,
23
24
  windowsHide: true
24
25
  })
25
26
  : spawn(command, args, {
26
27
  cwd: options.cwd || undefined,
27
- env: { ...process.env, ...(options.env || {}) },
28
+ env: childProcessEnv(options.env || {}),
28
29
  windowsHide: true
29
30
  });
30
31
 
@@ -46,7 +47,7 @@ export function runCommand(command, args = [], options = {}) {
46
47
  const killTree = () => {
47
48
  if (process.platform === "win32" && child.pid) {
48
49
  try {
49
- spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true });
50
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, env: childProcessEnv() });
50
51
  } catch {
51
52
  try { child.kill(); } catch { /* process may already be gone */ }
52
53
  }
@@ -0,0 +1,53 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+
4
+ export function isPathInside(root, target) {
5
+ const rel = relative(root, target);
6
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
7
+ }
8
+
9
+ // Cache the canonical root for callers that resolve many graph-derived paths.
10
+ export function createRepoBoundary(repoRoot) {
11
+ let root;
12
+ let rootError;
13
+ try {
14
+ root = realpathSync.native(repoRoot);
15
+ } catch (error) {
16
+ rootError = error;
17
+ }
18
+
19
+ return {
20
+ root,
21
+ resolve(candidate) {
22
+ if (!root) return { ok: false, reason: "invalid-root", error: rootError };
23
+ const input = String(candidate ?? "");
24
+ if (!input || input.includes("\0")) return { ok: false, reason: "invalid-path" };
25
+ if (isAbsolute(input)) return { ok: false, reason: "escape" };
26
+
27
+ let lexical;
28
+ try {
29
+ lexical = resolve(root, input);
30
+ } catch (error) {
31
+ return { ok: false, reason: "invalid-path", error };
32
+ }
33
+ if (!isPathInside(root, lexical)) return { ok: false, reason: "escape" };
34
+
35
+ let target;
36
+ try {
37
+ target = realpathSync.native(lexical);
38
+ } catch (error) {
39
+ return { ok: false, reason: error?.code === "ENOENT" ? "not-found" : "unreadable", error };
40
+ }
41
+ if (!isPathInside(root, target)) return { ok: false, reason: "escape" };
42
+
43
+ return { ok: true, path: target };
44
+ },
45
+ };
46
+ }
47
+
48
+ // Resolve one existing repo-relative path without allowing lexical traversal or
49
+ // symlink/junction escapes. Callers get a reason instead of an exception so MCP
50
+ // tools can refuse the read without exposing host filesystem details.
51
+ export function resolveRepoPath(repoRoot, candidate) {
52
+ return createRepoBoundary(repoRoot).resolve(candidate);
53
+ }