weavatrix 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -0
  3. package/bin/weavatrix-mcp.mjs +6 -0
  4. package/package.json +50 -0
  5. package/skill/SKILL.md +56 -0
  6. package/src/analysis/coverage-reports.js +232 -0
  7. package/src/analysis/dead-check.js +136 -0
  8. package/src/analysis/dep-check.js +310 -0
  9. package/src/analysis/dep-rules.js +221 -0
  10. package/src/analysis/duplicates-worker.js +11 -0
  11. package/src/analysis/duplicates.compute.js +215 -0
  12. package/src/analysis/duplicates.js +15 -0
  13. package/src/analysis/duplicates.run.js +51 -0
  14. package/src/analysis/duplicates.tokenize.js +182 -0
  15. package/src/analysis/endpoints.js +156 -0
  16. package/src/analysis/findings.js +52 -0
  17. package/src/analysis/graph-analysis.aggregate.js +280 -0
  18. package/src/analysis/graph-analysis.js +7 -0
  19. package/src/analysis/graph-analysis.refs.js +146 -0
  20. package/src/analysis/graph-analysis.summaries.js +62 -0
  21. package/src/analysis/internal-audit.collect.js +117 -0
  22. package/src/analysis/internal-audit.js +9 -0
  23. package/src/analysis/internal-audit.reach.js +47 -0
  24. package/src/analysis/internal-audit.run.js +189 -0
  25. package/src/analysis/manifests.js +169 -0
  26. package/src/analysis/source-complexity.ast.js +97 -0
  27. package/src/analysis/source-complexity.constants.js +55 -0
  28. package/src/analysis/source-complexity.js +14 -0
  29. package/src/analysis/source-complexity.report.js +76 -0
  30. package/src/analysis/source-complexity.walk.js +174 -0
  31. package/src/build-graph.js +102 -0
  32. package/src/config.js +5 -0
  33. package/src/graph/build-worker.js +30 -0
  34. package/src/graph/builder/lang-csharp.js +40 -0
  35. package/src/graph/builder/lang-css.js +29 -0
  36. package/src/graph/builder/lang-go.js +53 -0
  37. package/src/graph/builder/lang-html.js +29 -0
  38. package/src/graph/builder/lang-java.js +29 -0
  39. package/src/graph/builder/lang-js.js +168 -0
  40. package/src/graph/builder/lang-python.js +78 -0
  41. package/src/graph/builder/lang-rust.js +45 -0
  42. package/src/graph/builder/spec-pkg.js +87 -0
  43. package/src/graph/graph-filter.js +44 -0
  44. package/src/graph/internal-builder.build.js +217 -0
  45. package/src/graph/internal-builder.js +12 -0
  46. package/src/graph/internal-builder.langs.js +86 -0
  47. package/src/graph/internal-builder.resolvers.js +116 -0
  48. package/src/graph/layout.js +35 -0
  49. package/src/infra/infra-items.js +255 -0
  50. package/src/infra/infra-registry.js +184 -0
  51. package/src/infra/infra.detect.js +119 -0
  52. package/src/infra/infra.js +38 -0
  53. package/src/infra/infra.match.js +102 -0
  54. package/src/infra/infra.scan.js +93 -0
  55. package/src/mcp/catalog.mjs +68 -0
  56. package/src/mcp/graph-context.mjs +276 -0
  57. package/src/mcp/tools-actions.mjs +132 -0
  58. package/src/mcp/tools-graph.mjs +274 -0
  59. package/src/mcp/tools-health.mjs +209 -0
  60. package/src/mcp/tools-impact.mjs +189 -0
  61. package/src/mcp-rg.mjs +51 -0
  62. package/src/mcp-server.mjs +171 -0
  63. package/src/mcp-source-tools.mjs +139 -0
  64. package/src/process.js +77 -0
  65. package/src/scan/discover.inventory.js +78 -0
  66. package/src/scan/discover.js +5 -0
  67. package/src/scan/discover.list.js +79 -0
  68. package/src/scan/discover.stack.js +227 -0
  69. package/src/scan/search.core.js +24 -0
  70. package/src/scan/search.git.js +102 -0
  71. package/src/scan/search.js +9 -0
  72. package/src/scan/search.node.js +83 -0
  73. package/src/scan/search.preview.js +49 -0
  74. package/src/scan/search.rg.js +145 -0
  75. package/src/security/advisory-store.js +177 -0
  76. package/src/security/installed.js +247 -0
  77. package/src/security/malware-file-heuristics.js +121 -0
  78. package/src/security/malware-heuristics.exclusions.js +134 -0
  79. package/src/security/malware-heuristics.js +15 -0
  80. package/src/security/malware-heuristics.roots.js +142 -0
  81. package/src/security/malware-heuristics.scan.js +87 -0
  82. package/src/security/malware-heuristics.sweep.js +122 -0
  83. package/src/security/malware-scoring.js +84 -0
  84. package/src/security/match.js +85 -0
  85. package/src/security/registry-sig.classify.js +136 -0
  86. package/src/security/registry-sig.js +18 -0
  87. package/src/security/registry-sig.rules.js +188 -0
  88. package/src/security/typosquat.js +72 -0
  89. package/src/util.js +27 -0
@@ -0,0 +1,78 @@
1
+ // Filesystem inventory helpers for repo discovery: size proxy, file/extension census, last commit.
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ // Directories never worth walking when sizing a repo (vendored deps, build output, caches).
6
+ const SIZE_SKIP_DIRS = new Set([
7
+ ".git", "node_modules", "dist", "build", "out", ".next", "coverage", "vendor",
8
+ ".venv", "venv", "env", "target", "__pycache__", ".idea", ".vscode", ".cache", "bin", "obj"
9
+ ]);
10
+
11
+ // Cheap "size" proxy: count source files in the working tree (skipping the heavy dirs above).
12
+ // Bounded so a pathological tree can't stall the scan.
13
+ export function repoFileCount(dir) {
14
+ let count = 0;
15
+ const stack = [dir];
16
+ while (stack.length) {
17
+ const cur = stack.pop();
18
+ let entries;
19
+ try {
20
+ entries = readdirSync(cur, { withFileTypes: true });
21
+ } catch {
22
+ continue;
23
+ }
24
+ for (const entry of entries) {
25
+ if (entry.isDirectory()) {
26
+ if (!SIZE_SKIP_DIRS.has(entry.name)) stack.push(join(cur, entry.name));
27
+ } else if (entry.isFile()) {
28
+ if (++count >= 100000) return count;
29
+ }
30
+ }
31
+ }
32
+ return count;
33
+ }
34
+
35
+ export function repoInventory(dir) {
36
+ let count = 0;
37
+ const ext = {};
38
+ const files = new Set();
39
+ const stack = [dir];
40
+ while (stack.length) {
41
+ const cur = stack.pop();
42
+ let entries;
43
+ try {
44
+ entries = readdirSync(cur, { withFileTypes: true });
45
+ } catch {
46
+ continue;
47
+ }
48
+ for (const entry of entries) {
49
+ if (entry.isDirectory()) {
50
+ if (!SIZE_SKIP_DIRS.has(entry.name)) stack.push(join(cur, entry.name));
51
+ continue;
52
+ }
53
+ if (!entry.isFile()) continue;
54
+ if (++count >= 100000) return { count, ext, files };
55
+ const full = join(cur, entry.name);
56
+ const rel = full.slice(dir.length).replace(/^[\\/]/, "").replace(/\\/g, "/").toLowerCase();
57
+ files.add(rel);
58
+ const m = entry.name.toLowerCase().match(/(\.[a-z0-9]+)$/);
59
+ if (m) ext[m[1]] = (ext[m[1]] || 0) + 1;
60
+ }
61
+ }
62
+ return { count, ext, files };
63
+ }
64
+
65
+ // Last commit time (ms) read straight from .git/logs/HEAD — no `git` spawn. Each reflog line is
66
+ // "<old> <new> <Name> <email> <unixtime> <tz>\t<message>"; the unixtime is the token before the tz.
67
+ export function repoLastCommit(dir) {
68
+ try {
69
+ const log = readFileSync(join(dir, ".git", "logs", "HEAD"), "utf8").trimEnd();
70
+ if (!log) return 0;
71
+ const lastLine = log.slice(log.lastIndexOf("\n") + 1).split("\t")[0];
72
+ const tokens = lastLine.trim().split(/\s+/);
73
+ const unixTime = Number(tokens[tokens.length - 2]);
74
+ return Number.isFinite(unixTime) ? unixTime * 1000 : 0;
75
+ } catch {
76
+ return 0;
77
+ }
78
+ }
@@ -0,0 +1,5 @@
1
+ // Discover local git repos under a folder, browse child folders, and persist per-repo run results.
2
+ // Facade: implementation lives in discover.inventory.js (fs walking / git metadata),
3
+ // discover.stack.js (framework + badge detection) and discover.list.js (repo/folder listing).
4
+ export { cleanVersion, detectFramework, detectRepoStack } from "./discover.stack.js";
5
+ export { listGitRepos, repoBaseName, listChildFolders } from "./discover.list.js";
@@ -0,0 +1,79 @@
1
+ // Repo listing: describe direct child git repos of a folder and browse child folders.
2
+ import { existsSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { ROOT_DIR } from "../config.js";
5
+ import { repoFileCount, repoInventory, repoLastCommit } from "./discover.inventory.js";
6
+ import { detectFramework, detectRepoStack } from "./discover.stack.js";
7
+
8
+ function reposDefaultFolder() {
9
+ return join(ROOT_DIR, "..", "..");
10
+ }
11
+
12
+ function describeRepo(dir, name) {
13
+ const has = (file) => existsSync(join(dir, file));
14
+ // RUNTIME first — a Bun/Deno project also has a package.json, so check its markers before falling
15
+ // back to "node". (Fixes Bun repos like edge-analytics being mislabelled "node".)
16
+ let language = "other";
17
+ if (has("bun.lock") || has("bun.lockb") || has("bunfig.toml")) language = "bun";
18
+ else if (has("deno.json") || has("deno.jsonc") || has("deno.lock")) language = "deno";
19
+ else if (has("package.json")) language = "node";
20
+ else if (has("go.mod")) language = "go";
21
+ else if (has("pom.xml") || has("build.gradle")) language = "java";
22
+ else if (has("requirements.txt") || has("pyproject.toml") || has("setup.py") || has("Pipfile")) language = "python";
23
+ else if (has("Cargo.toml")) language = "rust";
24
+ else if (has("composer.json")) language = "php";
25
+ else if (has("Gemfile")) language = "ruby";
26
+ // framework detection uses the JS-ecosystem table for bun/deno too (they run npm packages)
27
+ const fwRuntime = language === "bun" || language === "deno" ? "node" : language;
28
+ const inventory = repoInventory(dir);
29
+ const stack = detectRepoStack(dir, inventory);
30
+ language = stack.languages[0]?.id || stack.runtimes[0]?.id || language;
31
+ const stackRunsJs = stack.runtimes.some((badge) => ["node", "bun", "deno"].includes(badge.id)) || ["javascript", "typescript"].includes(language);
32
+ const stackFwRuntime = stackRunsJs ? "node" : language;
33
+ return {
34
+ name,
35
+ path: dir,
36
+ language,
37
+ stack,
38
+ framework: detectFramework(dir, stackFwRuntime || fwRuntime),
39
+ knipEligible: has("package.json"),
40
+ size: inventory.count || repoFileCount(dir),
41
+ lastCommit: repoLastCommit(dir)
42
+ };
43
+ }
44
+
45
+ // Only DIRECT child git repos of the opened folder. We do not descend into folders or into
46
+ // repos, so nested/sub-repos are not listed.
47
+ export function listGitRepos(folder) {
48
+ const root = folder && String(folder).trim() ? String(folder).trim() : reposDefaultFolder();
49
+ if (!existsSync(root)) throw new Error(`Folder not found: ${root}`);
50
+ let entries;
51
+ try {
52
+ entries = readdirSync(root, { withFileTypes: true });
53
+ } catch (error) {
54
+ throw new Error(`Cannot read folder: ${error.message}`);
55
+ }
56
+ const repos = entries
57
+ .filter((entry) => entry.isDirectory() && existsSync(join(root, entry.name, ".git")))
58
+ .map((entry) => describeRepo(join(root, entry.name), entry.name))
59
+ .sort((left, right) => left.name.localeCompare(right.name));
60
+ return { root, repos };
61
+ }
62
+
63
+ export function repoBaseName(repoPath) {
64
+ return String(repoPath).split(/[\\/]/).filter(Boolean).pop() || repoPath;
65
+ }
66
+
67
+ export function listChildFolders(folder) {
68
+ const root = folder && existsSync(folder) ? folder : reposDefaultFolder();
69
+ const entries = readdirSync(root, { withFileTypes: true })
70
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")
71
+ .map((entry) => ({
72
+ name: entry.name,
73
+ path: join(root, entry.name),
74
+ isRepo: existsSync(join(root, entry.name, ".git"))
75
+ }))
76
+ .sort((left, right) => left.name.localeCompare(right.name));
77
+ const parent = join(root, "..");
78
+ return { path: root, parent: parent !== root ? parent : null, entries };
79
+ }
@@ -0,0 +1,227 @@
1
+ // Stack detection for repo cards: frameworks, languages/runtimes, test/infra/deploy badges.
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { INFRA_SERVICES } from "../infra/infra-registry.js";
5
+ import { depMatches, depsFromManifest } from "../infra/infra.js";
6
+ import { repoInventory } from "./discover.inventory.js";
7
+
8
+ // Web/app frameworks worth surfacing on the repo card, per ecosystem. token → display name; first
9
+ // match (in array order) wins, so list server frameworks before generic UI libs. Versions come from
10
+ // the manifest's declared range (not the installed lockfile — close enough for "which version").
11
+ const FRAMEWORKS = {
12
+ node: [
13
+ ["@nestjs/core", "NestJS"], ["express", "Express"], ["fastify", "Fastify"], ["koa", "Koa"],
14
+ ["@hapi/hapi", "Hapi"], ["hapi", "Hapi"], ["restify", "Restify"], ["hono", "Hono"],
15
+ ["@adonisjs/core", "AdonisJS"], ["@feathersjs/feathers", "Feathers"], ["sails", "Sails"],
16
+ ["next", "Next.js"], ["nuxt", "Nuxt"], ["@sveltejs/kit", "SvelteKit"], ["@remix-run/server-runtime", "Remix"],
17
+ ["@angular/core", "Angular"], ["react", "React"], ["vue", "Vue"], ["svelte", "Svelte"],
18
+ ],
19
+ python: [
20
+ ["django", "Django"], ["fastapi", "FastAPI"], ["flask", "Flask"], ["sanic", "Sanic"],
21
+ ["tornado", "Tornado"], ["aiohttp", "aiohttp"], ["falcon", "Falcon"], ["bottle", "Bottle"],
22
+ ],
23
+ go: [
24
+ ["github.com/gin-gonic/gin", "Gin"], ["github.com/labstack/echo", "Echo"], ["github.com/gofiber/fiber", "Fiber"],
25
+ ["github.com/go-chi/chi", "Chi"], ["github.com/gorilla/mux", "Gorilla"], ["github.com/beego/beego", "Beego"],
26
+ ],
27
+ };
28
+
29
+ // "^5.2.0" / "~4.18" / "v1.9.1" / ">=2,<3" / "==4.2" → "5.2" (major.minor, range operators stripped).
30
+ export function cleanVersion(raw) {
31
+ const m = String(raw || "").match(/(\d+)(?:\.(\d+))?/);
32
+ return m ? (m[2] != null ? `${m[1]}.${m[2]}` : m[1]) : "";
33
+ }
34
+
35
+ // Read a manifest and return the first framework {name, version} it declares. Cheap: one file read.
36
+ export function detectFramework(dir, runtime) {
37
+ const read = (file) => { try { return readFileSync(join(dir, file), "utf8"); } catch { return ""; } };
38
+ const list = FRAMEWORKS[runtime];
39
+ if (!list) return null;
40
+ if (runtime === "node") {
41
+ let pkg;
42
+ try { pkg = JSON.parse(read("package.json")); } catch { return null; }
43
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
44
+ for (const [tok, label] of list) if (deps[tok] != null) return { name: label, version: cleanVersion(deps[tok]) };
45
+ } else if (runtime === "python") {
46
+ const text = (read("requirements.txt") + "\n" + read("pyproject.toml") + "\n" + read("Pipfile")).toLowerCase();
47
+ for (const [tok, label] of list) {
48
+ const m = text.match(new RegExp(`(?:^|[\\s"'\\[])${tok}\\s*[~^>=<! ]*\\s*([0-9][0-9.]*)`, "m"));
49
+ if (m || new RegExp(`(?:^|[\\s"'\\[])${tok}(?:$|[\\s"'\\],~^>=<])`, "m").test(text)) return { name: label, version: m ? cleanVersion(m[1]) : "" };
50
+ }
51
+ } else if (runtime === "go") {
52
+ const text = read("go.mod");
53
+ for (const [tok, label] of list) {
54
+ const m = text.match(new RegExp(`${tok.replace(/[.\\]/g, "\\$&")}(?:/v\\d+)?\\s+v([0-9][0-9.]*)`));
55
+ if (m) return { name: label, version: cleanVersion(m[1]) };
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function readRootFile(dir, file) {
62
+ try {
63
+ return readFileSync(join(dir, file), "utf8");
64
+ } catch {
65
+ return "";
66
+ }
67
+ }
68
+
69
+ function readPackage(dir) {
70
+ try {
71
+ return JSON.parse(readRootFile(dir, "package.json"));
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ function packageDeps(pkg, includeDev = true) {
78
+ if (!pkg || typeof pkg !== "object") return {};
79
+ return {
80
+ ...(pkg.dependencies || {}),
81
+ ...(pkg.optionalDependencies || {}),
82
+ ...(pkg.peerDependencies || {}),
83
+ ...(includeDev ? pkg.devDependencies || {} : {})
84
+ };
85
+ }
86
+
87
+ function manifestDeps(dir) {
88
+ const out = new Set();
89
+ for (const file of [
90
+ "package.json", "go.mod", "go.sum", "requirements.txt", "constraints.txt", "pyproject.toml",
91
+ "Pipfile", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts", "composer.json", "Gemfile"
92
+ ]) {
93
+ if (!existsSync(join(dir, file))) continue;
94
+ for (const dep of depsFromManifest(file, readRootFile(dir, file))) out.add(dep);
95
+ }
96
+ return out;
97
+ }
98
+
99
+ function addBadge(list, seen, id, label, extra = {}) {
100
+ if (!id || seen.has(id)) return;
101
+ seen.add(id);
102
+ list.push({ id, label, ...extra });
103
+ }
104
+
105
+ function infraDisplayName(service) {
106
+ const names = {
107
+ postgres: "Postgres",
108
+ mysql: "MySQL",
109
+ mariadb: "MariaDB",
110
+ sqlserver: "SQL Server",
111
+ sqlite: "SQLite",
112
+ mongodb: "MongoDB",
113
+ dynamodb: "DynamoDB",
114
+ elasticsearch: "Elastic",
115
+ clickhouse: "ClickHouse",
116
+ influxdb: "InfluxDB",
117
+ timescaledb: "Timescale",
118
+ redis: "Redis",
119
+ valkey: "Valkey",
120
+ memcached: "Memcached",
121
+ kafka: "Kafka",
122
+ rabbitmq: "RabbitMQ",
123
+ "gcp-pubsub": "Pub/Sub",
124
+ "azure-servicebus": "Service Bus",
125
+ keycloak: "Keycloak",
126
+ "firebase-auth": "Firebase Auth",
127
+ "oidc-generic": "OIDC",
128
+ "azure-blob": "Azure Blob"
129
+ };
130
+ return names[service.id] || String(service.name || service.id || "").replace(/_/g, " ").replace(/\b\w/g, (m) => m.toUpperCase());
131
+ }
132
+
133
+ function detectInfraBadges(prodDeps) {
134
+ const badges = [];
135
+ const seen = new Set();
136
+ const visibleKinds = new Set(["db", "ts", "cache", "queue", "cloud"]);
137
+ for (const service of INFRA_SERVICES) {
138
+ if (!visibleKinds.has(service.kind)) continue;
139
+ const hit = (service.deps || []).some((token) => [...prodDeps].some((dep) => depMatches(dep, token)));
140
+ if (hit) addBadge(badges, seen, service.id, infraDisplayName(service), { kind: service.kind });
141
+ }
142
+ return badges;
143
+ }
144
+
145
+ function detectTestBadges({ dir, pkg, inventory, allDeps }) {
146
+ const badges = [];
147
+ const seen = new Set();
148
+ const deps = new Set(Object.keys(allDeps || {}).map((x) => x.toLowerCase()));
149
+ const scripts = Object.values(pkg?.scripts || {}).join("\n").toLowerCase();
150
+ const hasDep = (...names) => names.some((name) => deps.has(name.toLowerCase()));
151
+ const hasFile = (re) => [...(inventory.files || [])].some((file) => re.test(file));
152
+ const hasScript = (re) => re.test(scripts);
153
+
154
+ if (hasDep("@playwright/test", "playwright") || hasFile(/(^|\/)playwright\.config\.[cm]?[jt]s$/) || hasScript(/\bplaywright\b/)) {
155
+ addBadge(badges, seen, "playwright", "Playwright", { kind: "e2e" });
156
+ }
157
+ if (hasDep("vitest") || hasFile(/(^|\/)vitest\.config\.[cm]?[jt]s$/) || hasScript(/\bvitest\b/)) {
158
+ addBadge(badges, seen, "vitest", "Vitest", { kind: "unit" });
159
+ }
160
+ if (hasDep("jest", "@jest/globals", "ts-jest") || hasFile(/(^|\/)jest\.config\.[cm]?[jt]s$/) || hasScript(/\bjest\b/)) {
161
+ addBadge(badges, seen, "jest", "Jest", { kind: "unit" });
162
+ }
163
+ if (hasDep("cypress") || hasFile(/(^|\/)cypress\.config\.[cm]?[jt]s$/) || hasScript(/\bcypress\b/)) {
164
+ addBadge(badges, seen, "cypress", "Cypress", { kind: "e2e" });
165
+ }
166
+ if (hasDep("mocha") || hasScript(/\bmocha\b/)) addBadge(badges, seen, "mocha", "Mocha", { kind: "unit" });
167
+ if (hasDep("ava") || hasScript(/\bava\b/)) addBadge(badges, seen, "ava", "AVA", { kind: "unit" });
168
+ if (hasDep("pytest") || existsSync(join(dir, "pytest.ini")) || hasFile(/(^|\/)test_.*\.py$/)) {
169
+ addBadge(badges, seen, "pytest", "pytest", { kind: "unit" });
170
+ }
171
+ if (existsSync(join(dir, "go.mod")) && hasFile(/_test\.go$/)) addBadge(badges, seen, "go-test", "go test", { kind: "unit" });
172
+ if (existsSync(join(dir, "Cargo.toml")) && hasFile(/(^|\/)tests\/.*\.rs$/)) addBadge(badges, seen, "cargo-test", "cargo test", { kind: "unit" });
173
+ return badges;
174
+ }
175
+
176
+ // Deployment / infra-as-code tooling, detected by file presence. inventory.files is a lowercased,
177
+ // "/"-joined recursive path list (vendored/build dirs already skipped), so a repo's Dockerfile,
178
+ // skaffold.yaml, k8s manifests, helm chart or *.tf light up even when nested.
179
+ function detectDeployBadges(inventory) {
180
+ const badges = [];
181
+ const seen = new Set();
182
+ const files = [...(inventory.files || [])];
183
+ const hasFile = (re) => files.some((file) => re.test(file));
184
+ if (hasFile(/(^|\/)(dockerfile|containerfile)(\.[\w.-]+)?$/) || hasFile(/\.dockerfile$/)) addBadge(badges, seen, "docker", "Docker", { kind: "container" });
185
+ if (hasFile(/(^|\/)(docker-)?compose(\.[\w.-]+)?\.ya?ml$/)) addBadge(badges, seen, "compose", "Compose", { kind: "container" });
186
+ if (hasFile(/(^|\/)skaffold(\.[\w.-]+)?\.ya?ml$/)) addBadge(badges, seen, "skaffold", "Skaffold", { kind: "deploy" });
187
+ if (hasFile(/(^|\/)chart\.ya?ml$/) || hasFile(/(^|\/)helm\//)) addBadge(badges, seen, "helm", "Helm", { kind: "orchestration" });
188
+ if (hasFile(/(^|\/)kustomization\.ya?ml$/) || hasFile(/(^|\/)(k8s|kubernetes|manifests)\/.*\.ya?ml$/)) addBadge(badges, seen, "kubernetes", "K8s", { kind: "orchestration" });
189
+ if (hasFile(/(^|\/)[^/]+\.tf$/)) addBadge(badges, seen, "terraform", "Terraform", { kind: "iac" });
190
+ return badges;
191
+ }
192
+
193
+ export function detectRepoStack(dir, inventory = repoInventory(dir)) {
194
+ const has = (file) => existsSync(join(dir, file));
195
+ const pkg = readPackage(dir);
196
+ const allDeps = packageDeps(pkg, true);
197
+ const prodDeps = manifestDeps(dir);
198
+ const ext = inventory.ext || {};
199
+ const languages = [];
200
+ const runtimes = [];
201
+ const seenLang = new Set();
202
+ const seenRuntime = new Set();
203
+ const depNames = new Set(Object.keys(allDeps).map((x) => x.toLowerCase()));
204
+
205
+ const hasTs = !!(ext[".ts"] || ext[".tsx"] || has("tsconfig.json") || depNames.has("typescript"));
206
+ const hasJs = !!(ext[".js"] || ext[".jsx"] || ext[".mjs"] || ext[".cjs"] || pkg);
207
+ if (hasTs) addBadge(languages, seenLang, "typescript", "TS", { title: "TypeScript" });
208
+ if (hasJs) addBadge(languages, seenLang, "javascript", "JS", { title: "JavaScript" });
209
+ if (ext[".go"] || has("go.mod")) addBadge(languages, seenLang, "go", "Go", { title: "Go" });
210
+ if (ext[".py"] || has("requirements.txt") || has("pyproject.toml") || has("setup.py") || has("Pipfile")) addBadge(languages, seenLang, "python", "Python");
211
+ if (ext[".java"] || has("pom.xml") || has("build.gradle")) addBadge(languages, seenLang, "java", "Java");
212
+ if (ext[".rs"] || has("Cargo.toml")) addBadge(languages, seenLang, "rust", "Rust");
213
+ if (ext[".php"] || has("composer.json")) addBadge(languages, seenLang, "php", "PHP");
214
+ if (ext[".rb"] || has("Gemfile")) addBadge(languages, seenLang, "ruby", "Ruby");
215
+
216
+ if (has("bun.lock") || has("bun.lockb") || has("bunfig.toml")) addBadge(runtimes, seenRuntime, "bun", "Bun");
217
+ if (has("deno.json") || has("deno.jsonc") || has("deno.lock")) addBadge(runtimes, seenRuntime, "deno", "Deno");
218
+ if (pkg && !seenRuntime.has("bun") && !seenRuntime.has("deno")) addBadge(runtimes, seenRuntime, "node", "Node");
219
+
220
+ return {
221
+ languages,
222
+ runtimes,
223
+ tests: detectTestBadges({ dir, pkg, inventory, allDeps }),
224
+ infra: detectInfraBadges(prodDeps),
225
+ deploy: detectDeployBadges(inventory)
226
+ };
227
+ }
@@ -0,0 +1,24 @@
1
+ // Orchestrator for the cross-repo search: picks ripgrep → git grep → pure-Node engine per the
2
+ // configured engine and delegates to the matching module. Split out of search.js.
3
+ import { existsSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { resolveRg, rgSearch } from "./search.rg.js";
6
+ import { gitSearch } from "./search.git.js";
7
+ import { nodeSearch } from "./search.node.js";
8
+
9
+ // repos: array of absolute repo paths; mode: "content" | "filename"; engine/rgPath: see resolveRg.
10
+ // Returns { ok, engine, truncated, results:[{repo, path, line, column, preview}] }.
11
+ export async function searchAcrossRepos({ repos, query, mode = "content", cap = 300, engine = "auto", rgPath = "", gitPath = "" } = {}) {
12
+ const roots = [...new Set((Array.isArray(repos) ? repos : []).filter((p) => p && existsSync(p)).map((p) => resolve(p)))].sort((a, b) => b.length - a.length);
13
+ const q = String(query || "");
14
+ if (!roots.length || q.trim().length < 2) return { ok: true, engine: "none", truncated: false, results: [] };
15
+ const rg = await resolveRg(engine, rgPath);
16
+ const git = (engine === "auto" || engine === "git") ? String(gitPath || "").trim() || "git" : "";
17
+ try {
18
+ if (rg) return await rgSearch(rg, roots, q, mode, cap);
19
+ if (git) return await gitSearch(git, roots, q, mode, cap);
20
+ return await nodeSearch(roots, q, mode, cap);
21
+ } catch (error) {
22
+ return { ok: false, error: error.message, engine: rg ? "ripgrep" : git ? "git-grep" : "node-fallback", results: [] };
23
+ }
24
+ }
@@ -0,0 +1,102 @@
1
+ // git grep / git ls-files engine for the cross-repo search — the fast native fallback when no
2
+ // ripgrep can be resolved (falls back to the pure-Node scanner per repo). Split out of search.js.
3
+ import { join } from "node:path";
4
+ import { runCommand } from "../process.js";
5
+ import { repoBaseName } from "./discover.js";
6
+ import { SKIP_DIRS, nodeSearch } from "./search.node.js";
7
+
8
+ // ---- git grep native fallback ------------------------------------------------------------------
9
+ const GIT_PATHSPECS = [
10
+ ".",
11
+ ...[...SKIP_DIRS].map((dir) => `:(exclude)${dir}/**`)
12
+ ];
13
+
14
+ function gitArgs(root, subcommand, args) {
15
+ return ["-C", root, "-c", "core.quotePath=false", subcommand, ...args];
16
+ }
17
+
18
+ function parseGitGrepLine(line) {
19
+ const m = /^(.+?):(\d+):(\d+):(.*)$/.exec(line);
20
+ if (!m) return null;
21
+ return {
22
+ relPath: m[1],
23
+ line: Number(m[2]) || 0,
24
+ column: Math.max(0, (Number(m[3]) || 1) - 1),
25
+ preview: m[4]
26
+ };
27
+ }
28
+
29
+ function pathHasSkippedDir(relPath) {
30
+ return String(relPath || "")
31
+ .split(/[\\/]+/)
32
+ .some((part) => SKIP_DIRS.has(part));
33
+ }
34
+
35
+ async function gitSearchRoot(git, root, query, mode, cap) {
36
+ if (mode === "filename") {
37
+ const r = await runCommand(git, gitArgs(root, "ls-files", ["-z", "--cached", "--others", "--exclude-standard", "--", ...GIT_PATHSPECS]), { timeoutMs: 15000 });
38
+ if (r.exitCode !== 0) return { ok: false, error: (r.stderr || r.stdout || "git ls-files failed").slice(0, 300) };
39
+ const lower = query.toLowerCase();
40
+ const ci = query === lower;
41
+ const hitIdx = (s) => (ci ? s.toLowerCase().indexOf(lower) : s.indexOf(query));
42
+ const files = String(r.stdout || "").split("\0").filter(Boolean);
43
+ const results = [];
44
+ for (const relPath of files) {
45
+ if (results.length >= cap) break;
46
+ if (pathHasSkippedDir(relPath)) continue;
47
+ const idx = hitIdx(relPath);
48
+ if (idx >= 0) results.push({ repo: repoBaseName(root), path: join(root, relPath), line: 0, column: idx, preview: relPath.replace(/\\/g, "/") });
49
+ }
50
+ return { ok: true, truncated: files.length > results.length && results.length >= cap, results };
51
+ }
52
+
53
+ const r = await runCommand(
54
+ git,
55
+ gitArgs(root, "grep", ["-n", "--column", "-I", "--untracked", "-F", "-e", query, "--", ...GIT_PATHSPECS]),
56
+ { timeoutMs: 20000 }
57
+ );
58
+ if (r.exitCode !== 0 && r.exitCode !== 1) return { ok: false, error: (r.stderr || r.stdout || "git grep failed").slice(0, 300) };
59
+ const lines = String(r.stdout || "").split(/\r?\n/).filter(Boolean);
60
+ const results = [];
61
+ for (const line of lines) {
62
+ if (results.length >= cap) break;
63
+ const parsed = parseGitGrepLine(line);
64
+ if (!parsed || pathHasSkippedDir(parsed.relPath)) continue;
65
+ results.push({
66
+ repo: repoBaseName(root),
67
+ path: join(root, parsed.relPath),
68
+ line: parsed.line,
69
+ column: parsed.column,
70
+ preview: parsed.preview.slice(0, 400)
71
+ });
72
+ }
73
+ return { ok: true, truncated: lines.length > results.length && results.length >= cap, results };
74
+ }
75
+
76
+ export async function gitSearch(git, roots, query, mode, cap) {
77
+ const results = [];
78
+ let truncated = false;
79
+ let usedNodeFallback = false;
80
+ for (const root of roots) {
81
+ if (results.length >= cap) {
82
+ truncated = true;
83
+ break;
84
+ }
85
+ let r;
86
+ try {
87
+ r = await gitSearchRoot(git, root, query, mode, cap - results.length);
88
+ } catch {
89
+ r = { ok: false };
90
+ }
91
+ if (!r.ok) {
92
+ usedNodeFallback = true;
93
+ const fallback = await nodeSearch([root], query, mode, cap - results.length);
94
+ results.push(...fallback.results);
95
+ truncated ||= fallback.truncated;
96
+ continue;
97
+ }
98
+ results.push(...r.results);
99
+ truncated ||= r.truncated;
100
+ }
101
+ return { ok: true, engine: usedNodeFallback ? "git-grep+node-fallback" : "git-grep", truncated, results };
102
+ }
@@ -0,0 +1,9 @@
1
+ // Fast cross-repo search: file NAMES + TEXT inside files, across every open repo at once. Backed by
2
+ // ripgrep when one can be resolved (bundled / VS Code / Cursor / PATH), git grep as a fast native
3
+ // fallback, and finally a dependency-free Node fs-walk fallback. One reusable searchAcrossRepos() so
4
+ // a future MCP server can call the same code.
5
+ // Facade: the implementation lives in search.rg.js (ripgrep), search.git.js (git grep),
6
+ // search.node.js (pure-Node walker), search.core.js (orchestrator) and search.preview.js.
7
+ export { resolveRgInfo, resolveRg } from "./search.rg.js";
8
+ export { searchAcrossRepos } from "./search.core.js";
9
+ export { readFileForPreview, writeFileForPreview } from "./search.preview.js";
@@ -0,0 +1,83 @@
1
+ // Dependency-free Node fs-walk search engine for the cross-repo search, plus the shared SKIP_DIRS
2
+ // list. Split out of search.js.
3
+ import { statSync } from "node:fs";
4
+ import { readFile, opendir } from "node:fs/promises";
5
+ import { join, relative } from "node:path";
6
+ import { repoBaseName } from "./discover.js";
7
+
8
+ export const SKIP_DIRS = new Set([".git", "node_modules", "dist", "build", "out", "coverage", ".next", ".cache", ".turbo", "vendor", "__pycache__", ".venv"]);
9
+
10
+ // ---- Node fs-walk fallback (no ripgrep) ---------------------------------------------------------
11
+ export async function nodeSearch(roots, query, mode, cap) {
12
+ const isContent = mode !== "filename";
13
+ const lower = query.toLowerCase();
14
+ const ci = query === lower; // smart-case: case-insensitive unless the query has an uppercase letter
15
+ const hit = (s) => (ci ? s.toLowerCase().includes(lower) : s.includes(query));
16
+ const hitIdx = (s) => (ci ? s.toLowerCase().indexOf(lower) : s.indexOf(query));
17
+ const results = [];
18
+ let truncated = false;
19
+ async function walk(dir, root) {
20
+ if (results.length >= cap) {
21
+ truncated = true;
22
+ return;
23
+ }
24
+ let dh;
25
+ try {
26
+ dh = await opendir(dir);
27
+ } catch {
28
+ return;
29
+ }
30
+ for await (const ent of dh) {
31
+ if (results.length >= cap) {
32
+ truncated = true;
33
+ break;
34
+ }
35
+ const full = join(dir, ent.name);
36
+ if (ent.isDirectory()) {
37
+ if (!SKIP_DIRS.has(ent.name)) await walk(full, root);
38
+ continue;
39
+ }
40
+ if (!ent.isFile()) continue;
41
+ const relPath = relative(root, full).replace(/\\/g, "/");
42
+ if (!isContent) {
43
+ const nameIdx = hitIdx(ent.name);
44
+ const relIdx = hitIdx(relPath);
45
+ if (nameIdx >= 0 || relIdx >= 0) results.push({ repo: repoBaseName(root), path: full, line: 0, column: Math.max(0, relIdx >= 0 ? relIdx : nameIdx), preview: relPath });
46
+ continue;
47
+ }
48
+ let st;
49
+ try {
50
+ st = statSync(full);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (st.size > 1500000) continue;
55
+ let buf;
56
+ try {
57
+ buf = await readFile(full);
58
+ } catch {
59
+ continue;
60
+ }
61
+ if (buf.includes(0)) continue; // binary
62
+ const linesArr = buf.toString("utf8").split(/\r?\n/);
63
+ let fileHits = 0;
64
+ for (let i = 0; i < linesArr.length; i++) {
65
+ if (results.length >= cap) {
66
+ truncated = true;
67
+ break;
68
+ }
69
+ const idx = hitIdx(linesArr[i]);
70
+ if (idx >= 0) {
71
+ results.push({ repo: repoBaseName(root), path: full, line: i + 1, column: idx, preview: linesArr[i].slice(0, 400) });
72
+ fileHits++;
73
+ if (fileHits >= 40) break; // match rgSearch's --max-count 40 per file
74
+ }
75
+ }
76
+ }
77
+ }
78
+ for (const root of roots) {
79
+ if (results.length >= cap) break;
80
+ await walk(root, root);
81
+ }
82
+ return { ok: true, engine: "node-fallback", truncated, results };
83
+ }
@@ -0,0 +1,49 @@
1
+ // In-app search preview file access: read/write a file's text ONLY if it sits under one of the
2
+ // known repo roots. Split out of search.js.
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { readFile, writeFile } from "node:fs/promises";
5
+ import { resolve, sep } from "node:path";
6
+
7
+ // Resolve a preview/edit target ONLY if it sits UNDER one of the known repo roots — the shared guard
8
+ // for files:read and files:write. Returns { ok:true, path } or { ok:false, error }.
9
+ function resolveRepoFilePath(filePath, repos) {
10
+ const roots = (Array.isArray(repos) ? repos : []).filter(Boolean).map((p) => resolve(p));
11
+ const abs = resolve(String(filePath || ""));
12
+ if (!abs || !roots.some((r) => abs === r || abs.startsWith(r + sep))) return { ok: false, error: "Path is outside the known repos" };
13
+ if (!existsSync(abs)) return { ok: false, error: "File not found" };
14
+ return { ok: true, path: abs };
15
+ }
16
+
17
+ // Read a file's text for the in-app preview — only if it sits UNDER one of the known repo roots.
18
+ export async function readFileForPreview(filePath, repos) {
19
+ const resolved = resolveRepoFilePath(filePath, repos);
20
+ if (resolved.ok === false) return resolved;
21
+ const abs = resolved.path;
22
+ let st;
23
+ try {
24
+ st = statSync(abs);
25
+ } catch {
26
+ return { ok: false, error: "Cannot stat file" };
27
+ }
28
+ if (st.size > 2000000) return { ok: false, error: "File too large to preview (>2 MB) — open it in VS Code." };
29
+ try {
30
+ return { ok: true, path: abs, content: await readFile(abs, "utf8") };
31
+ } catch (error) {
32
+ return { ok: false, error: error.message };
33
+ }
34
+ }
35
+
36
+ // Write edited text back from the Search preview's Edit mode — same repo-root guard as the read, and
37
+ // only over files that already exist (the in-app editor touches up files, it never creates them).
38
+ export async function writeFileForPreview(filePath, repos, content) {
39
+ const resolved = resolveRepoFilePath(filePath, repos);
40
+ if (resolved.ok === false) return resolved;
41
+ const text = String(content ?? "");
42
+ if (text.length > 2000000) return { ok: false, error: "Edited text too large to save (>2 MB) — use VS Code." };
43
+ try {
44
+ await writeFile(resolved.path, text, "utf8");
45
+ return { ok: true, path: resolved.path };
46
+ } catch (error) {
47
+ return { ok: false, error: error.message };
48
+ }
49
+ }