vibecode-anything 0.3.0 → 0.4.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 (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,2017 @@
1
+ /**
2
+ * Zero-dependency Project Intelligence & Auto-Discovery engine for `vibecode-anything`.
3
+ *
4
+ * Safely inspects a project workspace (with strict depth/file/size bounds, symlink
5
+ * traversal protection, and zero-secret guarantees) to detect ecosystems, manifests,
6
+ * frameworks, entrypoints, HTTP/web routes, API spec artifacts, inferred ports,
7
+ * suggested domains/slices, and ready-to-run `lock` / `ingest` commands.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { VibecodeError, errorMessage } from "../core/errors.js";
12
+ import { ANSI, FORBIDDEN_OBJECT_KEYS, clampInt, hasCrossPlatformPathEscape, hasVaultOrHoldoutSegment, isEnvExampleFileName, isInsideVaultDirectory, isPathWithinDir, isRecordSafe, isSecretRelativePath, redactSensitiveText, safeOwnProp, sanitizeSingleLine, styleAnsi } from "../core/security.js";
13
+ import { MAX_ROUTE_FILE_BYTES, extractFileSystemRoutes, extractRoutesFromSource, safeReadTextFile } from "./routes.js";
14
+ export const DEFAULT_MAX_DEPTH = 6;
15
+ export const MAX_ALLOWED_DEPTH = 12;
16
+ export const DEFAULT_MAX_FILES = 500;
17
+ export const MAX_ALLOWED_FILES = 2000;
18
+ export const MAX_ALLOWED_FILE_BYTES = 1024 * 1024;
19
+ export const IGNORED_DISCOVERY_DIRS = new Set([
20
+ "node_modules",
21
+ ".git",
22
+ ".vibecode",
23
+ "dist",
24
+ "build",
25
+ "out",
26
+ ".next",
27
+ "target",
28
+ ".venv",
29
+ "venv",
30
+ "__pycache__",
31
+ "coverage",
32
+ ".turbo",
33
+ ".cache"
34
+ ]);
35
+ const FRAMEWORK_CATALOG = {
36
+ express: { id: "express", name: "Express", ecosystem: "node", category: "api" },
37
+ fastify: { id: "fastify", name: "Fastify", ecosystem: "node", category: "api" },
38
+ hono: { id: "hono", name: "Hono", ecosystem: "node", category: "api" },
39
+ koa: { id: "koa", name: "Koa", ecosystem: "node", category: "api" },
40
+ nextjs: { id: "nextjs", name: "Next.js", ecosystem: "node", category: "fullstack" },
41
+ vite: { id: "vite", name: "Vite", ecosystem: "node", category: "web" },
42
+ react: { id: "react", name: "React", ecosystem: "node", category: "web" },
43
+ vue: { id: "vue", name: "Vue", ecosystem: "node", category: "web" },
44
+ svelte: { id: "svelte", name: "Svelte", ecosystem: "node", category: "web" },
45
+ nestjs: { id: "nestjs", name: "NestJS", ecosystem: "node", category: "api" },
46
+ commander: { id: "commander", name: "Commander", ecosystem: "node", category: "cli" },
47
+ yargs: { id: "yargs", name: "Yargs", ecosystem: "node", category: "cli" },
48
+ cac: { id: "cac", name: "CAC", ecosystem: "node", category: "cli" },
49
+ fastapi: { id: "fastapi", name: "FastAPI", ecosystem: "python", category: "api" },
50
+ flask: { id: "flask", name: "Flask", ecosystem: "python", category: "api" },
51
+ django: { id: "django", name: "Django", ecosystem: "python", category: "fullstack" },
52
+ typer: { id: "typer", name: "Typer", ecosystem: "python", category: "cli" },
53
+ click: { id: "click", name: "Click", ecosystem: "python", category: "cli" },
54
+ axum: { id: "axum", name: "Axum", ecosystem: "rust", category: "api" },
55
+ actix: { id: "actix", name: "Actix", ecosystem: "rust", category: "api" },
56
+ clap: { id: "clap", name: "Clap", ecosystem: "rust", category: "cli" },
57
+ gin: { id: "gin", name: "Gin", ecosystem: "go", category: "api" },
58
+ fiber: { id: "fiber", name: "Fiber", ecosystem: "go", category: "api" },
59
+ cobra: { id: "cobra", name: "Cobra", ecosystem: "go", category: "cli" }
60
+ };
61
+ const NODE_DEP_TO_FRAMEWORK = {
62
+ express: "express",
63
+ fastify: "fastify",
64
+ hono: "hono",
65
+ koa: "koa",
66
+ "@koa/router": "koa",
67
+ "koa-router": "koa",
68
+ next: "nextjs",
69
+ vite: "vite",
70
+ react: "react",
71
+ "react-dom": "react",
72
+ vue: "vue",
73
+ nuxt: "vue",
74
+ svelte: "svelte",
75
+ "@sveltejs/kit": "svelte",
76
+ "@nestjs/core": "nestjs",
77
+ "@nestjs/common": "nestjs",
78
+ commander: "commander",
79
+ yargs: "yargs",
80
+ cac: "cac"
81
+ };
82
+ const PYTHON_DEP_TO_FRAMEWORK = {
83
+ fastapi: "fastapi",
84
+ flask: "flask",
85
+ django: "django",
86
+ typer: "typer",
87
+ click: "click"
88
+ };
89
+ const RUST_DEP_TO_FRAMEWORK = {
90
+ axum: "axum",
91
+ "actix-web": "actix",
92
+ actix: "actix",
93
+ clap: "clap"
94
+ };
95
+ const DANGEROUS_OBJECT_KEYS = FORBIDDEN_OBJECT_KEYS;
96
+ const EXCLUDED_MANIFEST_SEGMENTS = new Set([".git", ".vibecode", ".vibecode-vault", "node_modules"]);
97
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
98
+ const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f]+/g;
99
+ const WINDOWS_DRIVE_PREFIX_RE = /^[A-Za-z]:/;
100
+ const UNC_PREFIX_RE = /^(?:\\\\|\/\/)/;
101
+ const SHELL_UNSAFE_PATH_RE = /[\x00-\x1f\x7f$`;&|<>()'"\\!%^*?~#{}[\]]/;
102
+ const SHELL_UNSAFE_COMMAND_ARG_RE = /[\x00-\x1f\x7f$`;&|<>()'"\\!%]/;
103
+ const SAFE_BIN_NAME_RE = /^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/;
104
+ const SAFE_CARGO_BIN_NAME_RE = /^[A-Za-z0-9_-]+$/;
105
+ const SAFE_PY_SCRIPT_NAME_RE = /^[A-Za-z0-9._-]+$/;
106
+ const SAFE_PY_ENTRY_TARGET_RE = /^[A-Za-z0-9_.:-]+$/;
107
+ const MAX_DISPLAY_NAME_LENGTH = 256;
108
+ const SOURCE_SCAN_EXTS = new Set([
109
+ ".js",
110
+ ".mjs",
111
+ ".cjs",
112
+ ".ts",
113
+ ".mts",
114
+ ".cts",
115
+ ".jsx",
116
+ ".tsx",
117
+ ".py",
118
+ ".go",
119
+ ".rs"
120
+ ]);
121
+ const ROUTE_SOURCE_EXTS = new Set([
122
+ ".js",
123
+ ".mjs",
124
+ ".cjs",
125
+ ".ts",
126
+ ".mts",
127
+ ".cts",
128
+ ".jsx",
129
+ ".tsx",
130
+ ".py"
131
+ ]);
132
+ const SKIP_JSON_SPEC_NAMES = new Set([
133
+ "package.json",
134
+ "package-lock.json",
135
+ "tsconfig.json",
136
+ "tsconfig.check.json",
137
+ "tsconfig.build.json",
138
+ "jsconfig.json",
139
+ "composer.json",
140
+ "deno.json",
141
+ "deno.jsonc"
142
+ ]);
143
+ const NOTABLE_SCRIPT_NAMES = new Set([
144
+ "dev",
145
+ "start",
146
+ "serve",
147
+ "server",
148
+ "preview",
149
+ "api",
150
+ "web",
151
+ "cli",
152
+ "run"
153
+ ]);
154
+ const COMMON_REPO_ENTRY_FILES = new Set([
155
+ "src/index.ts",
156
+ "src/index.js",
157
+ "src/index.mts",
158
+ "src/index.mjs",
159
+ "index.ts",
160
+ "index.js",
161
+ "src/lib.rs"
162
+ ]);
163
+ const TEST_OR_FIXTURE_PATH_RE = /(?:^|\/)(?:test|tests|__tests__|__mocks__|fixtures)\//i;
164
+ const TEST_FILENAME_RE = /\.(?:test|spec|stories|d)\.[a-z0-9]+$/i;
165
+ const IMPORTABLE_TEST_FILENAME_RE = /(?:\.(?:test|spec)\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)|^test_.*\.py$|_test\.py$)$/i;
166
+ const EXAMPLE_PATH_RE = /(?:^|\/)(?:examples?|demos?|samples?|benchmarks?)\//i;
167
+ const NON_APP_PORT_PATH_RE = /(?:^|\/)(?:examples?|demos?|samples?|benchmarks?|docs?|site|website)\//i;
168
+ const MAKEFILE_NAMES = new Set(["makefile", "gnumakefile"]);
169
+ const REQUIREMENTS_FILE_RE = /^requirements(?:-[a-z0-9._-]+)?\.txt$/i;
170
+ const OPENAPI_YAML_HEADER_RE = /^\s*(?:openapi|swagger)\s*:/m;
171
+ const ASYNCAPI_YAML_HEADER_RE = /^\s*asyncapi\s*:/m;
172
+ const OPENRPC_YAML_HEADER_RE = /^\s*openrpc\s*:/m;
173
+ const INSOMNIA_YAML_TYPE_RE = /^\s*_type\s*:\s*["']?export["']?\s*$/m;
174
+ const INSOMNIA_YAML_FORMAT_RE = /^\s*__export_format\s*:\s*\d+/m;
175
+ const ENV_PORT_LINE_RE = /^\s*(?:export\s+)?(?:[A-Z0-9_]*_)?PORT\s*=\s*["']?(\d{1,5})["']?\s*(?:#.*)?$/;
176
+ // Bounded, linear-time (ReDoS-safe) port extraction patterns.
177
+ const PORT_LISTEN_RE = /\.listen\(\s*(?:process\.env\.[A-Z0-9_]{1,64}\s*(?:\|\||\?\?)\s*)?(\d{1,5})\b/g;
178
+ const PORT_LISTEN_OBJ_RE = /\.listen\(\s*\{[^{}]{0,120}\bport\s*:\s*(?:Number\()?\s*(\d{1,5})\b/g;
179
+ const PORT_ENV_ASSIGN_RE = /\b(?:[A-Z0-9_]{0,64}_)?PORT\s*=\s*["']?(\d{1,5})["']?/g;
180
+ const PORT_FALLBACK_RE = /\bPORT\s*(?:\|\||\?\?)\s*["']?(\d{1,5})["']?/g;
181
+ const PORT_KV_RE = /\bport\s*[:=]\s*["']?(\d{1,5})["']?/gi;
182
+ const PORT_FLAG_RE = /--port(?:=|\s+)(\d{1,5})\b/g;
183
+ const PORT_SHORT_FLAG_RE = /\b(?:uvicorn|gunicorn|flask|next|vite|fastapi|serve|http-server)\b[^\r\n;]{0,120}\s-p\s+(\d{1,5})\b/g;
184
+ const PORT_LOCALHOST_RE = /\b(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d{1,5})\b/g;
185
+ const PORT_GO_LISTEN_RE = /ListenAndServe\(\s*"[^":\r\n]{0,40}:(\d{1,5})"/g;
186
+ const PORT_PY_ENV_RE = /os\.(?:getenv|environ\.get)\(\s*["']PORT["']\s*,\s*["']?(\d{1,5})["']?\s*\)/g;
187
+ const SERVER_LISTEN_HINT_RE = /(?:\.listen\(|createServer\(|uvicorn\.run\(|app\.run\(|Bun\.serve\(|Deno\.serve\(|ListenAndServe\(|axum::serve\(|HttpServer::new\()/;
188
+ const isRecord = isRecordSafe;
189
+ function ownLookup(map, key) {
190
+ return safeOwnProp(map, key);
191
+ }
192
+ function sanitizeDisplayName(value) {
193
+ return sanitizeSingleLine(value, MAX_DISPLAY_NAME_LENGTH);
194
+ }
195
+ function canonicalFsKey(absPath) {
196
+ return process.platform === "win32" ? absPath.toLowerCase() : absPath;
197
+ }
198
+ function toPosixRel(rootDir, absPath) {
199
+ const rel = path.relative(rootDir, absPath);
200
+ return rel.split(path.sep).join("/").replace(/^\.\//, "");
201
+ }
202
+ function normalizeRelPosix(relPath) {
203
+ return relPath.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+/g, "/");
204
+ }
205
+ function hasIgnoredPathSegment(posixRel, ignored) {
206
+ for (const segment of posixRel.split("/")) {
207
+ if (segment && ignored.has(segment))
208
+ return true;
209
+ }
210
+ return false;
211
+ }
212
+ function resolveSafeWorkspaceRelPath(baseDirAbs, candidate, realRoot) {
213
+ if (typeof candidate !== "string")
214
+ return null;
215
+ const trimmed = candidate.trim();
216
+ if (!trimmed || CONTROL_CHAR_RE.test(trimmed))
217
+ return null;
218
+ if (WINDOWS_DRIVE_PREFIX_RE.test(trimmed) ||
219
+ UNC_PREFIX_RE.test(trimmed) ||
220
+ trimmed.startsWith("/") ||
221
+ trimmed.startsWith("\\")) {
222
+ return null;
223
+ }
224
+ if (baseDirAbs === realRoot && hasCrossPlatformPathEscape(trimmed))
225
+ return null;
226
+ // Normalize backslashes before resolving so `..\\..\\evil.sh` is rejected on POSIX as well as Windows.
227
+ const resolved = path.resolve(baseDirAbs, trimmed.replace(/\\/g, "/"));
228
+ if (!isPathWithinDir(resolved, realRoot))
229
+ return null;
230
+ let targetExists = false;
231
+ try {
232
+ const lstat = fs.lstatSync(resolved);
233
+ targetExists = true;
234
+ const targetReal = fs.realpathSync(resolved);
235
+ if (!isPathWithinDir(targetReal, realRoot) || isInsideVaultDirectory(resolved) || isInsideVaultDirectory(targetReal)) {
236
+ return null;
237
+ }
238
+ const targetStat = lstat.isSymbolicLink() ? fs.statSync(targetReal) : lstat;
239
+ if (!targetStat.isFile())
240
+ return null;
241
+ const realRel = toPosixRel(realRoot, targetReal);
242
+ if (!realRel ||
243
+ realRel === "." ||
244
+ isSecretRelativePath(realRel, { allowEnvExample: true, ignoredSegments: EXCLUDED_MANIFEST_SEGMENTS })) {
245
+ return null;
246
+ }
247
+ }
248
+ catch {
249
+ // Either target doesn't exist, or it's a broken symlink / unreadable target.
250
+ try {
251
+ fs.lstatSync(resolved);
252
+ return null; // Entry exists (e.g. broken symlink) -> reject.
253
+ }
254
+ catch {
255
+ targetExists = false;
256
+ }
257
+ }
258
+ if (!targetExists) {
259
+ // Walk up to nearest existing ancestor so symlinked parent directories (`escape-link/not-built.js`) cannot escape.
260
+ let ancestor = resolved;
261
+ while (true) {
262
+ const parent = path.dirname(ancestor);
263
+ if (parent === ancestor)
264
+ break;
265
+ ancestor = parent;
266
+ try {
267
+ const ancestorReal = fs.realpathSync(ancestor);
268
+ if (!isPathWithinDir(ancestorReal, realRoot) || isInsideVaultDirectory(ancestorReal))
269
+ return null;
270
+ break;
271
+ }
272
+ catch {
273
+ // Keep walking up until an existing ancestor is found.
274
+ }
275
+ }
276
+ }
277
+ const rel = toPosixRel(realRoot, resolved);
278
+ if (!rel ||
279
+ rel === "." ||
280
+ rel.split("/").includes("..") ||
281
+ isSecretRelativePath(rel, { allowEnvExample: true, ignoredSegments: EXCLUDED_MANIFEST_SEGMENTS })) {
282
+ return null;
283
+ }
284
+ return rel;
285
+ }
286
+ function isSecretFilePath(relPath) {
287
+ return isSecretRelativePath(relPath, { allowEnvExample: true });
288
+ }
289
+ function isTestOrFixturePath(relPath) {
290
+ return TEST_OR_FIXTURE_PATH_RE.test(relPath) || TEST_FILENAME_RE.test(relPath);
291
+ }
292
+ function isValidTcpPort(port) {
293
+ return Number.isInteger(port) && port >= 1 && port <= 65535;
294
+ }
295
+ function collectRegexPorts(text, regex, ports) {
296
+ regex.lastIndex = 0;
297
+ let match;
298
+ while ((match = regex.exec(text)) !== null) {
299
+ const port = Number.parseInt(match[1], 10);
300
+ if (isValidTcpPort(port))
301
+ ports.add(port);
302
+ }
303
+ }
304
+ function extractPortsFromText(text, ports, mode) {
305
+ if (!text)
306
+ return;
307
+ if (mode === "env-example") {
308
+ for (const line of text.split(/\r\n|\r|\n/)) {
309
+ const m = ENV_PORT_LINE_RE.exec(line);
310
+ if (m) {
311
+ const port = Number.parseInt(m[1], 10);
312
+ if (isValidTcpPort(port))
313
+ ports.add(port);
314
+ }
315
+ }
316
+ return;
317
+ }
318
+ collectRegexPorts(text, PORT_FLAG_RE, ports);
319
+ collectRegexPorts(text, PORT_SHORT_FLAG_RE, ports);
320
+ collectRegexPorts(text, PORT_ENV_ASSIGN_RE, ports);
321
+ collectRegexPorts(text, PORT_LOCALHOST_RE, ports);
322
+ if (mode === "source") {
323
+ collectRegexPorts(text, PORT_LISTEN_RE, ports);
324
+ collectRegexPorts(text, PORT_LISTEN_OBJ_RE, ports);
325
+ collectRegexPorts(text, PORT_FALLBACK_RE, ports);
326
+ collectRegexPorts(text, PORT_KV_RE, ports);
327
+ collectRegexPorts(text, PORT_GO_LISTEN_RE, ports);
328
+ collectRegexPorts(text, PORT_PY_ENV_RE, ports);
329
+ }
330
+ }
331
+ function isRuntimeCodePath(p) {
332
+ const lower = p.toLowerCase();
333
+ return !lower.endsWith(".d.ts") && !lower.endsWith(".d.mts") && !lower.endsWith(".d.cts");
334
+ }
335
+ function extractPackageExportsTargets(exportsField, out, depth = 0) {
336
+ if (depth > 6 || exportsField === null || exportsField === undefined)
337
+ return;
338
+ if (typeof exportsField === "string") {
339
+ if (isRuntimeCodePath(exportsField))
340
+ out.push(exportsField);
341
+ return;
342
+ }
343
+ if (Array.isArray(exportsField)) {
344
+ for (const item of exportsField)
345
+ extractPackageExportsTargets(item, out, depth + 1);
346
+ return;
347
+ }
348
+ if (!isRecord(exportsField))
349
+ return;
350
+ const keys = Object.keys(exportsField).filter((k) => !DANGEROUS_OBJECT_KEYS.has(k));
351
+ const isSubpathMap = keys.some((k) => k.startsWith("."));
352
+ if (isSubpathMap) {
353
+ // Prefer root `.` export first, then remaining subpaths in deterministic order.
354
+ const sorted = [...keys].sort((a, b) => {
355
+ if (a === ".")
356
+ return -1;
357
+ if (b === ".")
358
+ return 1;
359
+ return a.localeCompare(b);
360
+ });
361
+ for (const subpath of sorted) {
362
+ if (subpath.includes("*"))
363
+ continue;
364
+ extractPackageExportsTargets(exportsField[subpath], out, depth + 1);
365
+ }
366
+ return;
367
+ }
368
+ // Conditional exports object: prefer runtime targets before fallback, never `types`.
369
+ const priorityKeys = ["import", "node", "default", "require", "module"];
370
+ for (const key of priorityKeys) {
371
+ if (Object.prototype.hasOwnProperty.call(exportsField, key)) {
372
+ const before = out.length;
373
+ extractPackageExportsTargets(exportsField[key], out, depth + 1);
374
+ if (out.length > before)
375
+ return;
376
+ }
377
+ }
378
+ }
379
+ function buildCliCommandForFile(relPath) {
380
+ if (SHELL_UNSAFE_PATH_RE.test(relPath))
381
+ return null;
382
+ const ext = path.posix.extname(relPath).toLowerCase();
383
+ const quoted = /\s/.test(relPath) ? `"${relPath}"` : relPath;
384
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs" || ext === ".ts" || ext === ".mts") {
385
+ return `node ${quoted}`;
386
+ }
387
+ if (ext === ".py")
388
+ return `python ${quoted}`;
389
+ if (ext === ".sh")
390
+ return `sh ${quoted}`;
391
+ return `./${quoted}`;
392
+ }
393
+ function stripTomlInlineComment(line) {
394
+ let inSingle = false;
395
+ let inDouble = false;
396
+ for (let i = 0; i < line.length; i++) {
397
+ const ch = line[i];
398
+ if (ch === "\\" && inDouble) {
399
+ i++;
400
+ continue;
401
+ }
402
+ if (ch === "'" && !inDouble)
403
+ inSingle = !inSingle;
404
+ else if (ch === '"' && !inSingle)
405
+ inDouble = !inDouble;
406
+ else if (ch === "#" && !inSingle && !inDouble)
407
+ return line.slice(0, i);
408
+ }
409
+ return line;
410
+ }
411
+ function parseTomlQuotedString(raw) {
412
+ const trimmed = raw.trim();
413
+ if (trimmed.length >= 2 &&
414
+ ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
415
+ return trimmed.slice(1, -1);
416
+ }
417
+ return null;
418
+ }
419
+ function extractPythonDepName(spec) {
420
+ const trimmed = spec.trim();
421
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("-"))
422
+ return null;
423
+ const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(trimmed);
424
+ return match ? match[1].toLowerCase() : null;
425
+ }
426
+ function parsePyprojectToml(content) {
427
+ const result = { deps: new Set(), scripts: {} };
428
+ let section = "";
429
+ let inDepsArray = false;
430
+ const addQuotedDeps = (raw) => {
431
+ for (const match of raw.matchAll(/["']([^"']+)["']/g)) {
432
+ const dep = extractPythonDepName(match[1]);
433
+ if (dep && !DANGEROUS_OBJECT_KEYS.has(dep))
434
+ result.deps.add(dep);
435
+ }
436
+ };
437
+ for (const rawLine of content.split(/\r\n|\r|\n/)) {
438
+ const line = stripTomlInlineComment(rawLine).trim();
439
+ if (!line)
440
+ continue;
441
+ if (line.startsWith("[") && line.endsWith("]") && !inDepsArray) {
442
+ section = line.replace(/^\[+|\]+$/g, "").trim().toLowerCase();
443
+ continue;
444
+ }
445
+ if (inDepsArray) {
446
+ addQuotedDeps(line);
447
+ if (line.includes("]"))
448
+ inDepsArray = false;
449
+ continue;
450
+ }
451
+ const eqIdx = line.indexOf("=");
452
+ if (eqIdx <= 0)
453
+ continue;
454
+ const key = line.slice(0, eqIdx).trim().replace(/^["']|["']$/g, "");
455
+ const keyLower = key.toLowerCase();
456
+ const val = line.slice(eqIdx + 1).trim();
457
+ if (section === "project" || section === "tool.poetry") {
458
+ if (keyLower === "name" && !result.name) {
459
+ result.name = parseTomlQuotedString(val) ?? undefined;
460
+ }
461
+ else if (keyLower === "version" && !result.version) {
462
+ result.version = parseTomlQuotedString(val) ?? undefined;
463
+ }
464
+ else if (keyLower === "dependencies" && val.startsWith("[")) {
465
+ addQuotedDeps(val);
466
+ if (!val.includes("]"))
467
+ inDepsArray = true;
468
+ }
469
+ }
470
+ else if (section === "tool.poetry.dependencies" || section.startsWith("tool.poetry.group.")) {
471
+ if (keyLower !== "python" && !DANGEROUS_OBJECT_KEYS.has(keyLower))
472
+ result.deps.add(keyLower);
473
+ }
474
+ else if (section === "project.optional-dependencies") {
475
+ if (val.startsWith("[")) {
476
+ addQuotedDeps(val);
477
+ if (!val.includes("]"))
478
+ inDepsArray = true;
479
+ }
480
+ }
481
+ else if (section === "project.scripts" || section === "tool.poetry.scripts") {
482
+ const target = parseTomlQuotedString(val);
483
+ if (target && !DANGEROUS_OBJECT_KEYS.has(key) && SAFE_PY_SCRIPT_NAME_RE.test(key)) {
484
+ result.scripts[key] = redactSensitiveText(target.replace(CONTROL_CHAR_GLOBAL_RE, " ").trim());
485
+ }
486
+ }
487
+ }
488
+ return result;
489
+ }
490
+ function parseRequirementsTxt(content) {
491
+ const deps = new Set();
492
+ for (const rawLine of content.split(/\r\n|\r|\n/)) {
493
+ const clean = rawLine.split("#")[0].trim();
494
+ const dep = extractPythonDepName(clean);
495
+ if (dep && !DANGEROUS_OBJECT_KEYS.has(dep))
496
+ deps.add(dep);
497
+ }
498
+ return deps;
499
+ }
500
+ function parseCargoToml(content) {
501
+ const result = { deps: new Set(), bins: [] };
502
+ let section = "";
503
+ let currentBin = null;
504
+ const flushBin = () => {
505
+ if (currentBin && currentBin.name) {
506
+ result.bins.push({ name: currentBin.name, ...(currentBin.path ? { path: currentBin.path } : {}) });
507
+ }
508
+ currentBin = null;
509
+ };
510
+ for (const rawLine of content.split(/\r\n|\r|\n/)) {
511
+ const line = stripTomlInlineComment(rawLine).trim();
512
+ if (!line)
513
+ continue;
514
+ if (line.startsWith("[[") && line.endsWith("]]")) {
515
+ flushBin();
516
+ section = line.slice(2, -2).trim().toLowerCase();
517
+ if (section === "bin")
518
+ currentBin = {};
519
+ continue;
520
+ }
521
+ if (line.startsWith("[") && line.endsWith("]")) {
522
+ flushBin();
523
+ section = line.slice(1, -1).trim().toLowerCase();
524
+ continue;
525
+ }
526
+ const eqIdx = line.indexOf("=");
527
+ if (eqIdx <= 0)
528
+ continue;
529
+ const key = line.slice(0, eqIdx).trim().replace(/^["']|["']$/g, "");
530
+ const keyLower = key.toLowerCase();
531
+ const val = line.slice(eqIdx + 1).trim();
532
+ if (section === "package") {
533
+ if (keyLower === "name" && !result.name)
534
+ result.name = parseTomlQuotedString(val) ?? undefined;
535
+ if (keyLower === "version" && !result.version)
536
+ result.version = parseTomlQuotedString(val) ?? undefined;
537
+ }
538
+ else if (section === "dependencies" || section === "dev-dependencies" || section === "build-dependencies") {
539
+ if (!DANGEROUS_OBJECT_KEYS.has(keyLower))
540
+ result.deps.add(keyLower);
541
+ }
542
+ else if (section === "bin" && currentBin) {
543
+ if (keyLower === "name")
544
+ currentBin.name = parseTomlQuotedString(val) ?? undefined;
545
+ if (keyLower === "path")
546
+ currentBin.path = parseTomlQuotedString(val) ?? undefined;
547
+ }
548
+ }
549
+ flushBin();
550
+ return result;
551
+ }
552
+ function parseGoMod(content) {
553
+ const result = { requires: [] };
554
+ let inRequireBlock = false;
555
+ for (const rawLine of content.split(/\r\n|\r|\n/)) {
556
+ const clean = rawLine.split("//")[0].trim();
557
+ if (!clean)
558
+ continue;
559
+ if (inRequireBlock) {
560
+ if (clean === ")") {
561
+ inRequireBlock = false;
562
+ continue;
563
+ }
564
+ const mod = clean.split(/\s+/)[0];
565
+ if (mod)
566
+ result.requires.push(mod);
567
+ continue;
568
+ }
569
+ if (clean.startsWith("module ")) {
570
+ const mod = clean.slice(7).trim().replace(/^["']|["']$/g, "");
571
+ if (mod)
572
+ result.modulePath = mod;
573
+ continue;
574
+ }
575
+ if (clean === "require (" || clean.startsWith("require (")) {
576
+ inRequireBlock = true;
577
+ continue;
578
+ }
579
+ if (clean.startsWith("require ")) {
580
+ const mod = clean.slice(8).trim().split(/\s+/)[0];
581
+ if (mod)
582
+ result.requires.push(mod);
583
+ }
584
+ }
585
+ return result;
586
+ }
587
+ function parseMakefileTargets(content) {
588
+ const targets = [];
589
+ const seen = new Set();
590
+ const targetRe = /^([A-Za-z0-9][A-Za-z0-9_.-]*)\s*:(?![=:])/;
591
+ for (const rawLine of content.split(/\r\n|\r|\n/)) {
592
+ if (!rawLine || rawLine.startsWith("\t") || rawLine.startsWith(" ") || rawLine.startsWith("#")) {
593
+ continue;
594
+ }
595
+ const match = targetRe.exec(rawLine);
596
+ if (!match)
597
+ continue;
598
+ const target = match[1];
599
+ if (!seen.has(target)) {
600
+ seen.add(target);
601
+ targets.push(target);
602
+ }
603
+ }
604
+ return targets;
605
+ }
606
+ function detectSpecsFromJson(doc, relPath) {
607
+ if (!isRecord(doc))
608
+ return null;
609
+ // OpenAPI / Swagger JSON
610
+ if ((Object.prototype.hasOwnProperty.call(doc, "openapi") && typeof doc.openapi === "string") ||
611
+ (Object.prototype.hasOwnProperty.call(doc, "swagger") && typeof doc.swagger === "string")) {
612
+ return {
613
+ kind: "openapi",
614
+ path: relPath,
615
+ ingestDomain: "api",
616
+ format: "json"
617
+ };
618
+ }
619
+ // AsyncAPI JSON
620
+ if (Object.prototype.hasOwnProperty.call(doc, "asyncapi") && typeof doc.asyncapi === "string") {
621
+ return {
622
+ kind: "asyncapi",
623
+ path: relPath,
624
+ ingestDomain: "asyncapi",
625
+ format: "json"
626
+ };
627
+ }
628
+ // OpenRPC JSON
629
+ if (Object.prototype.hasOwnProperty.call(doc, "openrpc") && typeof doc.openrpc === "string") {
630
+ return {
631
+ kind: "openrpc",
632
+ path: relPath,
633
+ ingestDomain: "openrpc",
634
+ format: "json"
635
+ };
636
+ }
637
+ // Insomnia v4 export JSON
638
+ const hasInsomniaFormat = (Object.prototype.hasOwnProperty.call(doc, "__export_format") && typeof doc.__export_format === "number") ||
639
+ (Object.prototype.hasOwnProperty.call(doc, "_type") && doc._type === "export");
640
+ if (hasInsomniaFormat && Object.prototype.hasOwnProperty.call(doc, "resources") && Array.isArray(doc.resources)) {
641
+ return {
642
+ kind: "insomnia",
643
+ path: relPath,
644
+ ingestDomain: "insomnia",
645
+ format: "json"
646
+ };
647
+ }
648
+ // Bruno collection manifest (`bruno.json`)
649
+ if (path.posix.basename(relPath).toLowerCase() === "bruno.json" &&
650
+ Object.prototype.hasOwnProperty.call(doc, "name") &&
651
+ typeof doc.name === "string" &&
652
+ Object.prototype.hasOwnProperty.call(doc, "type") &&
653
+ doc.type === "collection") {
654
+ const dirRel = path.posix.dirname(relPath);
655
+ return {
656
+ kind: "bruno",
657
+ path: dirRel === "." ? relPath : dirRel,
658
+ ingestDomain: "bruno",
659
+ format: "bru"
660
+ };
661
+ }
662
+ // Postman Collection v2.x
663
+ if (Object.prototype.hasOwnProperty.call(doc, "info") && isRecord(doc.info)) {
664
+ const schemaStr = Object.prototype.hasOwnProperty.call(doc.info, "schema") && typeof doc.info.schema === "string"
665
+ ? doc.info.schema
666
+ : "";
667
+ if ((Object.prototype.hasOwnProperty.call(doc.info, "_postman_id") && typeof doc.info._postman_id === "string") ||
668
+ schemaStr.includes("schema.getpostman.com")) {
669
+ return {
670
+ kind: "postman",
671
+ path: relPath,
672
+ ingestDomain: "postman",
673
+ format: "json"
674
+ };
675
+ }
676
+ }
677
+ // GraphQL Introspection JSON
678
+ const schemaObj = Object.prototype.hasOwnProperty.call(doc, "data") &&
679
+ isRecord(doc.data) &&
680
+ Object.prototype.hasOwnProperty.call(doc.data, "__schema") &&
681
+ isRecord(doc.data.__schema)
682
+ ? doc.data.__schema
683
+ : Object.prototype.hasOwnProperty.call(doc, "__schema") && isRecord(doc.__schema)
684
+ ? doc.__schema
685
+ : null;
686
+ if (schemaObj && Object.prototype.hasOwnProperty.call(schemaObj, "types") && Array.isArray(schemaObj.types)) {
687
+ return {
688
+ kind: "graphql",
689
+ path: relPath,
690
+ ingestDomain: "graphql",
691
+ format: "introspection-json"
692
+ };
693
+ }
694
+ return null;
695
+ }
696
+ const JS_FRAMEWORK_IMPORT_CHECKS = [
697
+ ["express", "express", "express"],
698
+ ["fastify", "fastify", "fastify"],
699
+ ["hono", "hono(?:/[^\"']*)?", "hono"],
700
+ ["koa", "(?:koa|@koa/router|koa-router)", "(?:koa|@koa/router|koa-router)"],
701
+ ["nestjs", "@nestjs/(?:core|common)", null],
702
+ ["commander", "commander", "commander"],
703
+ ["yargs", "yargs(?:/[^\"']*)?", "yargs"],
704
+ ["cac", "cac", "cac"]
705
+ ].map(([id, esmPkg, cjsPkg]) => [
706
+ id,
707
+ new RegExp(cjsPkg
708
+ ? `^\\s*(?:import\\b[^\\r\\n;]{0,160}\\bfrom\\s+["']${esmPkg}["']|(?:const|let|var)\\b[^\\r\\n;]{0,80}=\\s*require\\(\\s*["']${cjsPkg}["']\\s*\\))`
709
+ : `^\\s*import\\b[^\\r\\n;]{0,160}\\bfrom\\s+["']${esmPkg}["']`, "m")
710
+ ]);
711
+ function detectFrameworksFromSourceImports(content, ext, relPath, addFramework) {
712
+ if (ext === ".py") {
713
+ for (const fw of ["fastapi", "flask", "django", "typer", "click"]) {
714
+ if (new RegExp(`^\\s*(?:from\\s+${fw}\\b|import\\s+${fw}\\b)`, "m").test(content)) {
715
+ addFramework(fw, `import in ${relPath}`);
716
+ }
717
+ }
718
+ return;
719
+ }
720
+ if (ext === ".rs") {
721
+ for (const [fw, crate] of [["axum", "axum"], ["actix", "actix_web"], ["clap", "clap"]]) {
722
+ if (new RegExp(`^\\s*use\\s+${crate}\\b`, "m").test(content))
723
+ addFramework(fw, `import in ${relPath}`);
724
+ }
725
+ return;
726
+ }
727
+ if (ext === ".go") {
728
+ for (const [fw, mod] of [
729
+ ["gin", "github\\.com\\/gin-gonic\\/gin"],
730
+ ["fiber", "github\\.com\\/gofiber\\/fiber(?:\\/[^\"]*)?"],
731
+ ["cobra", "github\\.com\\/spf13\\/cobra"]
732
+ ]) {
733
+ if (new RegExp(`^\\s*(?:import\\s+)?(?:[A-Za-z0-9_.]+\\s+)?"${mod}"`, "m").test(content)) {
734
+ addFramework(fw, `import in ${relPath}`);
735
+ }
736
+ }
737
+ return;
738
+ }
739
+ for (const [fwId, pattern] of JS_FRAMEWORK_IMPORT_CHECKS) {
740
+ if (pattern.test(content))
741
+ addFramework(fwId, `import in ${relPath}`);
742
+ }
743
+ }
744
+ function isShellSafeCommandArg(value) {
745
+ if (!value || CONTROL_CHAR_RE.test(value))
746
+ return false;
747
+ return !SHELL_UNSAFE_COMMAND_ARG_RE.test(value);
748
+ }
749
+ function isShellSafeCliSource(value) {
750
+ if (!value || CONTROL_CHAR_RE.test(value))
751
+ return false;
752
+ // Allow only clean space-wrapping double quotes like `node "dir with space/cli.js"`, never shell metacharacters.
753
+ if (/[`$;|&<>'\\!%()]/.test(value))
754
+ return false;
755
+ return ((value.match(/"/g) ?? []).length % 2) === 0;
756
+ }
757
+ function shellQuote(value) {
758
+ const clean = redactSensitiveText(value.replace(CONTROL_CHAR_GLOBAL_RE, " ").trim());
759
+ if (/^[A-Za-z0-9_./:@-]+$/.test(clean))
760
+ return clean;
761
+ return `"${clean.replace(/[\\"$`!]/g, "\\$&")}"`;
762
+ }
763
+ function slugifySliceSuffix(value) {
764
+ const s = value
765
+ .toLowerCase()
766
+ .replace(/[^a-z0-9]+/g, "-")
767
+ .replace(/^-+|-+$/g, "")
768
+ .slice(0, 32);
769
+ return s || "core";
770
+ }
771
+ function isRootOrNonSubpkgEvidence(evidence) {
772
+ const match = /\bin\s+([^\s]+)$/.exec(evidence);
773
+ const fileRef = match ? match[1] : evidence;
774
+ if (!fileRef.includes("/"))
775
+ return true;
776
+ return !/\/(?:package\.json|pyproject\.toml|Cargo\.toml|go\.mod)$/i.test(fileRef);
777
+ }
778
+ function buildDomainRanking(params) {
779
+ const scores = {
780
+ cli: 0,
781
+ api: 0,
782
+ web: 0,
783
+ repo: 0
784
+ };
785
+ const hasRootCliBin = params.entrypoints.some((e) => e.kind === "cli" && (e.source === "package.json" || e.source === "pyproject.toml" || e.source === "Cargo.toml"));
786
+ if (hasRootCliBin)
787
+ scores.cli += 12;
788
+ else if (params.entrypoints.some((e) => e.kind === "cli"))
789
+ scores.cli += 8;
790
+ if (params.frameworks.some((f) => f.category === "cli"))
791
+ scores.cli += 6;
792
+ const nonExampleApiRoutes = params.routes.filter((r) => r.kind === "api" && !EXAMPLE_PATH_RE.test(r.source));
793
+ const exampleApiRoutes = params.routes.filter((r) => r.kind === "api" && EXAMPLE_PATH_RE.test(r.source));
794
+ const nonExampleSpecs = params.specs.filter((s) => !EXAMPLE_PATH_RE.test(s.path));
795
+ const exampleSpecs = params.specs.filter((s) => EXAMPLE_PATH_RE.test(s.path));
796
+ if (nonExampleApiRoutes.length > 0)
797
+ scores.api += 11;
798
+ else if (exampleApiRoutes.length > 0)
799
+ scores.api += 3;
800
+ if (nonExampleSpecs.length > 0)
801
+ scores.api += 9;
802
+ else if (exampleSpecs.length > 0)
803
+ scores.api += 3;
804
+ if (params.frameworks.some((f) => f.category === "api"))
805
+ scores.api += 10;
806
+ if (params.frameworks.some((f) => f.category === "fullstack") && nonExampleApiRoutes.length > 0)
807
+ scores.api += 4;
808
+ const nonExampleWebRoutes = params.routes.filter((r) => r.kind === "web" && !EXAMPLE_PATH_RE.test(r.source));
809
+ const webFrameworks = params.frameworks.filter((f) => f.category === "web" || f.category === "fullstack");
810
+ const hasRootWebFramework = webFrameworks.some((f) => f.evidence.some(isRootOrNonSubpkgEvidence));
811
+ if (nonExampleWebRoutes.length > 0)
812
+ scores.web += 11;
813
+ if (hasRootWebFramework)
814
+ scores.web += 9;
815
+ else if (webFrameworks.length > 0)
816
+ scores.web += 4;
817
+ const hasRootRepoEntry = params.entrypoints.some((e) => e.kind === "repo" && (e.source === "package.json" || !e.source.includes("/")));
818
+ const hasRepoEntry = params.entrypoints.some((e) => e.kind === "repo");
819
+ if (hasRootRepoEntry)
820
+ scores.repo += 10;
821
+ else if (hasRepoEntry)
822
+ scores.repo += 8;
823
+ else if (params.manifests.length > 0 && scores.cli === 0 && scores.api === 0 && scores.web === 0) {
824
+ scores.repo += 4;
825
+ }
826
+ const tieBreakOrder = ["cli", "api", "web", "repo"];
827
+ return tieBreakOrder
828
+ .filter((d) => scores[d] > 0)
829
+ .sort((a, b) => {
830
+ if (scores[b] !== scores[a])
831
+ return scores[b] - scores[a];
832
+ return tieBreakOrder.indexOf(a) - tieBreakOrder.indexOf(b);
833
+ });
834
+ }
835
+ function buildSliceSuggestions(params) {
836
+ const slices = [];
837
+ const domainRank = (d) => {
838
+ const idx = params.suggestedDomains.indexOf(d);
839
+ return idx >= 0 ? idx : 99;
840
+ };
841
+ const cliEntries = params.entrypoints.filter((e) => e.kind === "cli");
842
+ if (cliEntries.length > 0) {
843
+ slices.push({
844
+ id: "slice-cli",
845
+ title: "CLI Entrypoints & Commands",
846
+ domain: "cli",
847
+ priority: 0,
848
+ items: cliEntries.map((e) => e.command ?? e.path ?? e.name),
849
+ reason: `Detected ${cliEntries.length} CLI entrypoint${cliEntries.length === 1 ? "" : "s"}.`
850
+ });
851
+ }
852
+ if (params.specs.length > 0) {
853
+ slices.push({
854
+ id: "slice-api-specs",
855
+ title: "API Spec Contracts",
856
+ domain: "api",
857
+ priority: 0,
858
+ items: params.specs.map((s) => `${s.kind}:${s.path}`),
859
+ reason: `Detected ${params.specs.length} machine-readable API spec artifact${params.specs.length === 1 ? "" : "s"}.`
860
+ });
861
+ }
862
+ const apiRoutes = params.routes.filter((r) => r.kind === "api");
863
+ if (apiRoutes.length > 0) {
864
+ if (apiRoutes.length <= 10) {
865
+ slices.push({
866
+ id: "slice-api-routes",
867
+ title: "HTTP API Routes",
868
+ domain: "api",
869
+ priority: 0,
870
+ items: apiRoutes.map((r) => `${r.method} ${r.path}`),
871
+ reason: `Statically extracted ${apiRoutes.length} HTTP API route${apiRoutes.length === 1 ? "" : "s"}.`
872
+ });
873
+ }
874
+ else {
875
+ const grouped = new Map();
876
+ for (const route of apiRoutes) {
877
+ const seg = route.path.split("/").filter(Boolean)[0] ?? "root";
878
+ const group = grouped.get(seg);
879
+ if (group)
880
+ group.push(route);
881
+ else
882
+ grouped.set(seg, [route]);
883
+ }
884
+ const sortedGroups = [...grouped.entries()].sort((a, b) => a[0].localeCompare(b[0])).slice(0, 6);
885
+ for (const [groupName, groupRoutes] of sortedGroups) {
886
+ slices.push({
887
+ id: `slice-api-${slugifySliceSuffix(groupName)}`,
888
+ title: `API Routes (/${groupName === "root" ? "" : groupName})`,
889
+ domain: "api",
890
+ priority: 0,
891
+ items: groupRoutes.slice(0, 20).map((r) => `${r.method} ${r.path}`),
892
+ reason: `Grouped ${groupRoutes.length} API route${groupRoutes.length === 1 ? "" : "s"} under /${groupName === "root" ? "" : groupName}.`
893
+ });
894
+ }
895
+ }
896
+ }
897
+ const webRoutes = params.routes.filter((r) => r.kind === "web");
898
+ const hasWebFramework = params.frameworks.some((f) => f.category === "web" || f.category === "fullstack");
899
+ if (webRoutes.length > 0 || hasWebFramework) {
900
+ slices.push({
901
+ id: "slice-web-pages",
902
+ title: "Web Pages & UI Routes",
903
+ domain: "web",
904
+ priority: 0,
905
+ items: webRoutes.length > 0 ? webRoutes.slice(0, 20).map((r) => `${r.method} ${r.path}`) : ["GET /"],
906
+ reason: webRoutes.length > 0
907
+ ? `Discovered ${webRoutes.length} web page route${webRoutes.length === 1 ? "" : "s"}.`
908
+ : "Detected frontend web framework."
909
+ });
910
+ }
911
+ const repoEntries = params.entrypoints.filter((e) => e.kind === "repo");
912
+ if (repoEntries.length > 0) {
913
+ slices.push({
914
+ id: "slice-repo-exports",
915
+ title: "Public Module Exports",
916
+ domain: "repo",
917
+ priority: 0,
918
+ items: repoEntries.map((e) => e.path ?? e.name),
919
+ reason: `Detected ${repoEntries.length} package/module export entrypoint${repoEntries.length === 1 ? "" : "s"}.`
920
+ });
921
+ }
922
+ slices.sort((a, b) => {
923
+ const ra = domainRank(a.domain);
924
+ const rb = domainRank(b.domain);
925
+ if (ra !== rb)
926
+ return ra - rb;
927
+ return a.id.localeCompare(b.id);
928
+ });
929
+ return slices.map((slice, idx) => ({ ...slice, priority: idx + 1 }));
930
+ }
931
+ function buildCommandSuggestions(params) {
932
+ const raw = [];
933
+ const seenCmds = new Set();
934
+ const primaryPort = params.ports[0] ?? 3000;
935
+ const baseUrl = `http://127.0.0.1:${primaryPort}`;
936
+ const hasInferredPort = params.ports.length > 0;
937
+ const pushCmd = (entry) => {
938
+ const safeEntry = {
939
+ ...entry,
940
+ label: redactSensitiveText(entry.label),
941
+ command: redactSensitiveText(entry.command),
942
+ reason: redactSensitiveText(entry.reason)
943
+ };
944
+ if (seenCmds.has(safeEntry.command))
945
+ return;
946
+ seenCmds.add(safeEntry.command);
947
+ raw.push(safeEntry);
948
+ };
949
+ // 1. CLI commands
950
+ const primaryCli = params.entrypoints.find((e) => e.kind === "cli");
951
+ if (primaryCli) {
952
+ const cliSource = primaryCli.command ?? primaryCli.path ?? primaryCli.name;
953
+ if (isShellSafeCliSource(cliSource)) {
954
+ pushCmd({
955
+ label: `Lock CLI baseline (${primaryCli.name})`,
956
+ action: "lock",
957
+ domain: "cli",
958
+ command: `vibecode-anything lock --domain cli --source ${shellQuote(cliSource)}`,
959
+ reason: `Snapshot golden CLI behavior from ${primaryCli.source}.`
960
+ });
961
+ pushCmd({
962
+ label: `Ingest CLI contract (${primaryCli.name})`,
963
+ action: "ingest",
964
+ domain: "cli",
965
+ command: `vibecode-anything ingest --domain cli --source ${shellQuote(cliSource)}`,
966
+ reason: `Capture CLI stdout/stderr/exit invariants from ${primaryCli.source}.`
967
+ });
968
+ }
969
+ }
970
+ // 2. Spec artifact commands (prefer non-example specs first, covering each distinct spec kind)
971
+ const orderedSpecs = [...params.specs].sort((a, b) => {
972
+ const aEx = EXAMPLE_PATH_RE.test(a.path) ? 1 : 0;
973
+ const bEx = EXAMPLE_PATH_RE.test(b.path) ? 1 : 0;
974
+ if (aEx !== bEx)
975
+ return aEx - bEx;
976
+ return a.path.localeCompare(b.path);
977
+ });
978
+ const selectedSpecs = [];
979
+ const seenSpecKinds = new Set();
980
+ for (const spec of orderedSpecs) {
981
+ if (!seenSpecKinds.has(spec.kind)) {
982
+ seenSpecKinds.add(spec.kind);
983
+ selectedSpecs.push(spec);
984
+ }
985
+ }
986
+ for (const spec of orderedSpecs) {
987
+ if (selectedSpecs.length >= 8)
988
+ break;
989
+ if (!selectedSpecs.includes(spec))
990
+ selectedSpecs.push(spec);
991
+ }
992
+ for (const spec of selectedSpecs) {
993
+ if (!isShellSafeCommandArg(spec.path))
994
+ continue;
995
+ const baseUrlFlag = hasInferredPort ? ` --base-url ${shellQuote(baseUrl)}` : "";
996
+ if (spec.kind === "har") {
997
+ pushCmd({
998
+ label: `Ingest HAR trace (${spec.path})`,
999
+ action: "ingest",
1000
+ domain: "api",
1001
+ command: `vibecode-anything ingest --domain api --from-har ${shellQuote(spec.path)}`,
1002
+ reason: `Convert captured HAR traffic ${spec.path} into API invariants.`
1003
+ });
1004
+ }
1005
+ else if (spec.kind === "openapi") {
1006
+ pushCmd({
1007
+ label: `Lock OpenAPI contract (${spec.path})`,
1008
+ action: "lock",
1009
+ domain: "api",
1010
+ command: `vibecode-anything lock --domain api --source ${shellQuote(spec.path)}${baseUrlFlag}`,
1011
+ reason: `Lock API contract generated from OpenAPI spec ${spec.path}.`
1012
+ });
1013
+ pushCmd({
1014
+ label: `Ingest OpenAPI spec (${spec.path})`,
1015
+ action: "ingest",
1016
+ domain: "api",
1017
+ command: `vibecode-anything ingest --domain api --source ${shellQuote(spec.path)}${baseUrlFlag}`,
1018
+ reason: `Generate HTTP invariants directly from ${spec.path}.`
1019
+ });
1020
+ }
1021
+ else {
1022
+ pushCmd({
1023
+ label: `Lock ${spec.kind} contract (${spec.path})`,
1024
+ action: "lock",
1025
+ domain: spec.ingestDomain,
1026
+ command: `vibecode-anything lock --domain ${spec.ingestDomain} --source ${shellQuote(spec.path)}${baseUrlFlag}`,
1027
+ reason: `Lock API contract generated from ${spec.kind} artifact ${spec.path}.`
1028
+ });
1029
+ pushCmd({
1030
+ label: `Ingest ${spec.kind} artifact (${spec.path})`,
1031
+ action: "ingest",
1032
+ domain: spec.ingestDomain,
1033
+ command: `vibecode-anything ingest --domain ${spec.ingestDomain} --source ${shellQuote(spec.path)}${baseUrlFlag}`,
1034
+ reason: `Generate API contract from ${spec.kind} artifact ${spec.path}.`
1035
+ });
1036
+ }
1037
+ }
1038
+ // 3. Live API server commands (when API routes detected)
1039
+ const apiRoutes = params.routes.filter((r) => r.kind === "api" && !EXAMPLE_PATH_RE.test(r.source));
1040
+ if (apiRoutes.length > 0) {
1041
+ pushCmd({
1042
+ label: `Lock live API server (${baseUrl})`,
1043
+ action: "lock",
1044
+ domain: "api",
1045
+ command: `vibecode-anything lock --domain api --source ${shellQuote(baseUrl)}`,
1046
+ reason: `Lock ${apiRoutes.length} discovered HTTP route${apiRoutes.length === 1 ? "" : "s"} against running server.`
1047
+ });
1048
+ if (orderedSpecs.length === 0) {
1049
+ pushCmd({
1050
+ label: `Ingest live API server (${baseUrl})`,
1051
+ action: "ingest",
1052
+ domain: "api",
1053
+ command: `vibecode-anything ingest --domain api --source ${shellQuote(baseUrl)}`,
1054
+ reason: `Probe running API server on port ${primaryPort}.`
1055
+ });
1056
+ }
1057
+ }
1058
+ // 4. Web page commands
1059
+ const webRoutes = params.routes.filter((r) => r.kind === "web" && !EXAMPLE_PATH_RE.test(r.source));
1060
+ const hasWebFramework = params.frameworks.some((f) => f.category === "web" || f.category === "fullstack");
1061
+ if (webRoutes.length > 0 || hasWebFramework) {
1062
+ const staticWebPaths = [
1063
+ ...new Set(webRoutes
1064
+ .map((r) => r.path)
1065
+ .filter((p) => !p.includes(":") && !p.includes("*") && isShellSafeCommandArg(p)))
1066
+ ].slice(0, 3);
1067
+ const routeFlags = staticWebPaths.map((p) => ` --route ${shellQuote(p)}`).join("");
1068
+ pushCmd({
1069
+ label: `Lock web routes (${baseUrl})`,
1070
+ action: "lock",
1071
+ domain: "web",
1072
+ command: `vibecode-anything lock --domain web --source ${shellQuote(baseUrl)}${routeFlags}`,
1073
+ reason: "Lock rendered web route landmarks and layout parity before refactoring."
1074
+ });
1075
+ pushCmd({
1076
+ label: `Ingest web routes (${baseUrl})`,
1077
+ action: "ingest",
1078
+ domain: "web",
1079
+ command: `vibecode-anything ingest --domain web --source ${shellQuote(baseUrl)}${routeFlags}`,
1080
+ reason: "Capture web route snapshots from local dev server."
1081
+ });
1082
+ }
1083
+ // 5. Repo export commands
1084
+ if (params.entrypoints.some((e) => e.kind === "repo") || params.suggestedDomains.includes("repo")) {
1085
+ pushCmd({
1086
+ label: "Lock public repo exports",
1087
+ action: "lock",
1088
+ domain: "repo",
1089
+ command: "vibecode-anything lock --domain repo --source .",
1090
+ reason: "Lock exported module symbols to catch accidental breaking API changes."
1091
+ });
1092
+ pushCmd({
1093
+ label: "Ingest public repo exports",
1094
+ action: "ingest",
1095
+ domain: "repo",
1096
+ command: "vibecode-anything ingest --domain repo --source .",
1097
+ reason: "Snapshot exported package/module API surface."
1098
+ });
1099
+ }
1100
+ // 6. Existing test suite static import suggestion
1101
+ if (params.testRootDir && (params.testFileCount ?? 0) > 0 && isShellSafeCommandArg(params.testRootDir)) {
1102
+ const testDom = params.suggestedDomains[0] === "cli" || params.suggestedDomains[0] === "api" || params.suggestedDomains[0] === "repo"
1103
+ ? params.suggestedDomains[0]
1104
+ : "api";
1105
+ pushCmd({
1106
+ label: `Import existing tests (${params.testRootDir})`,
1107
+ action: "ingest",
1108
+ domain: testDom,
1109
+ command: `vibecode-anything ingest --from-tests ${shellQuote(params.testRootDir)}`,
1110
+ reason: `Statically import ${params.testFileCount} existing test file${params.testFileCount === 1 ? "" : "s"} without executing test code.`
1111
+ });
1112
+ }
1113
+ const domainOrder = (d) => {
1114
+ const mapped = d === "graphql" ||
1115
+ d === "postman" ||
1116
+ d === "http-file" ||
1117
+ d === "curl" ||
1118
+ d === "insomnia" ||
1119
+ d === "bruno" ||
1120
+ d === "asyncapi" ||
1121
+ d === "proto" ||
1122
+ d === "openrpc"
1123
+ ? "api"
1124
+ : d === "cli" || d === "api" || d === "web" || d === "repo"
1125
+ ? d
1126
+ : "api";
1127
+ const idx = params.suggestedDomains.indexOf(mapped);
1128
+ return idx >= 0 ? idx : 99;
1129
+ };
1130
+ raw.sort((a, b) => {
1131
+ const da = domainOrder(a.domain);
1132
+ const db = domainOrder(b.domain);
1133
+ if (da !== db)
1134
+ return da - db;
1135
+ if (a.action !== b.action)
1136
+ return a.action === "lock" ? -1 : 1;
1137
+ return a.command.localeCompare(b.command);
1138
+ });
1139
+ return raw;
1140
+ }
1141
+ /**
1142
+ * Synchronously inspect a project workspace and produce a structured, zero-secret
1143
+ * discovery report with frameworks, entrypoints, static routes, spec artifacts,
1144
+ * inferred ports, suggested domains, slice plan, and ready-to-run commands.
1145
+ */
1146
+ export function discoverProject(rootDir = process.cwd(), options = {}) {
1147
+ const resolvedRoot = path.resolve(rootDir);
1148
+ let rootStat;
1149
+ try {
1150
+ rootStat = fs.statSync(resolvedRoot);
1151
+ }
1152
+ catch (err) {
1153
+ throw new VibecodeError("TARGET_MISSING", `Discovery root directory not found: ${resolvedRoot}`, {
1154
+ details: errorMessage(err)
1155
+ });
1156
+ }
1157
+ if (!rootStat.isDirectory()) {
1158
+ throw new VibecodeError("TARGET_MISSING", `Discovery root path is not a directory: ${resolvedRoot}`);
1159
+ }
1160
+ const realRoot = fs.realpathSync(resolvedRoot);
1161
+ const maxDepth = clampInt(options.maxDepth, DEFAULT_MAX_DEPTH, 0, MAX_ALLOWED_DEPTH);
1162
+ const maxFiles = clampInt(options.maxFiles, DEFAULT_MAX_FILES, 1, MAX_ALLOWED_FILES);
1163
+ const maxFileBytes = clampInt(options.maxFileBytes, MAX_ROUTE_FILE_BYTES, 1024, MAX_ALLOWED_FILE_BYTES);
1164
+ const maxDirectories = Math.max(maxFiles * 4, 2000);
1165
+ const stats = {
1166
+ filesScanned: 0,
1167
+ directoriesVisited: 0,
1168
+ truncated: false,
1169
+ symlinksSkipped: 0,
1170
+ oversizedFilesSkipped: 0
1171
+ };
1172
+ const warnings = [];
1173
+ const pushWarning = (msg) => {
1174
+ warnings.push(redactSensitiveText(msg));
1175
+ };
1176
+ // Breadth-first traversal so root manifests and top-level files are always discovered first.
1177
+ const scannedFiles = [];
1178
+ const visitedRealDirs = new Set([canonicalFsKey(realRoot)]);
1179
+ const queue = [{ absDir: realRoot, depth: 0 }];
1180
+ let queueIdx = 0;
1181
+ while (queueIdx < queue.length && !stats.truncated) {
1182
+ if (stats.directoriesVisited >= maxDirectories) {
1183
+ stats.truncated = true;
1184
+ break;
1185
+ }
1186
+ const current = queue[queueIdx++];
1187
+ stats.directoriesVisited++;
1188
+ let dirEntries;
1189
+ try {
1190
+ dirEntries = fs.readdirSync(current.absDir, { withFileTypes: true });
1191
+ }
1192
+ catch {
1193
+ continue;
1194
+ }
1195
+ dirEntries.sort((a, b) => a.name.localeCompare(b.name));
1196
+ for (const entry of dirEntries) {
1197
+ const absPath = path.join(current.absDir, entry.name);
1198
+ let lstat;
1199
+ try {
1200
+ lstat = fs.lstatSync(absPath);
1201
+ }
1202
+ catch {
1203
+ continue;
1204
+ }
1205
+ if (lstat.isSymbolicLink()) {
1206
+ if (hasVaultOrHoldoutSegment(entry.name)) {
1207
+ stats.symlinksSkipped++;
1208
+ continue;
1209
+ }
1210
+ let targetReal;
1211
+ let targetStat;
1212
+ try {
1213
+ targetReal = fs.realpathSync(absPath);
1214
+ targetStat = fs.statSync(targetReal);
1215
+ }
1216
+ catch {
1217
+ stats.symlinksSkipped++;
1218
+ continue;
1219
+ }
1220
+ if (!isPathWithinDir(targetReal, realRoot) || isInsideVaultDirectory(targetReal)) {
1221
+ stats.symlinksSkipped++;
1222
+ continue;
1223
+ }
1224
+ const targetRel = toPosixRel(realRoot, targetReal);
1225
+ if (hasIgnoredPathSegment(targetRel, IGNORED_DISCOVERY_DIRS) || hasVaultOrHoldoutSegment(targetRel)) {
1226
+ stats.symlinksSkipped++;
1227
+ continue;
1228
+ }
1229
+ if (targetStat.isDirectory()) {
1230
+ const dirKey = canonicalFsKey(targetReal);
1231
+ if (IGNORED_DISCOVERY_DIRS.has(entry.name) || visitedRealDirs.has(dirKey)) {
1232
+ stats.symlinksSkipped++;
1233
+ continue;
1234
+ }
1235
+ if (current.depth < maxDepth) {
1236
+ visitedRealDirs.add(dirKey);
1237
+ queue.push({ absDir: absPath, depth: current.depth + 1 });
1238
+ }
1239
+ continue;
1240
+ }
1241
+ if (targetStat.isFile()) {
1242
+ // Never follow an internal symlink disguised under a harmless name into a secret file (e.g. `src/a.ts -> ../.env`).
1243
+ if (isSecretFilePath(targetRel)) {
1244
+ stats.symlinksSkipped++;
1245
+ continue;
1246
+ }
1247
+ if (scannedFiles.length >= maxFiles) {
1248
+ stats.truncated = true;
1249
+ break;
1250
+ }
1251
+ scannedFiles.push({
1252
+ absPath,
1253
+ relPath: toPosixRel(realRoot, absPath),
1254
+ baseName: entry.name,
1255
+ ext: path.posix.extname(entry.name).toLowerCase(),
1256
+ size: targetStat.size
1257
+ });
1258
+ }
1259
+ continue;
1260
+ }
1261
+ if (hasVaultOrHoldoutSegment(entry.name) || isInsideVaultDirectory(absPath))
1262
+ continue;
1263
+ if (lstat.isDirectory()) {
1264
+ if (IGNORED_DISCOVERY_DIRS.has(entry.name))
1265
+ continue;
1266
+ if (current.depth < maxDepth) {
1267
+ let dirReal;
1268
+ try {
1269
+ dirReal = fs.realpathSync(absPath);
1270
+ }
1271
+ catch {
1272
+ continue;
1273
+ }
1274
+ const dirKey = canonicalFsKey(dirReal);
1275
+ if (!isPathWithinDir(dirReal, realRoot) || isInsideVaultDirectory(dirReal) || visitedRealDirs.has(dirKey)) {
1276
+ stats.symlinksSkipped++;
1277
+ continue;
1278
+ }
1279
+ visitedRealDirs.add(dirKey);
1280
+ queue.push({ absDir: absPath, depth: current.depth + 1 });
1281
+ }
1282
+ continue;
1283
+ }
1284
+ if (lstat.isFile()) {
1285
+ if (scannedFiles.length >= maxFiles) {
1286
+ stats.truncated = true;
1287
+ break;
1288
+ }
1289
+ const relPath = toPosixRel(realRoot, absPath);
1290
+ scannedFiles.push({
1291
+ absPath,
1292
+ relPath,
1293
+ baseName: entry.name,
1294
+ ext: path.posix.extname(entry.name).toLowerCase(),
1295
+ size: lstat.size
1296
+ });
1297
+ }
1298
+ }
1299
+ }
1300
+ stats.filesScanned = scannedFiles.length;
1301
+ const fileByRel = new Map();
1302
+ const textCache = new Map();
1303
+ const oversizedRecorded = new Set();
1304
+ for (const f of scannedFiles)
1305
+ fileByRel.set(f.relPath, f);
1306
+ const readScannedText = (file) => {
1307
+ if (isSecretFilePath(file.relPath))
1308
+ return null;
1309
+ if (textCache.has(file.relPath))
1310
+ return textCache.get(file.relPath) ?? null;
1311
+ if (file.size > maxFileBytes) {
1312
+ if (!oversizedRecorded.has(file.relPath)) {
1313
+ oversizedRecorded.add(file.relPath);
1314
+ stats.oversizedFilesSkipped++;
1315
+ }
1316
+ textCache.set(file.relPath, null);
1317
+ return null;
1318
+ }
1319
+ const text = safeReadTextFile(file.absPath, maxFileBytes);
1320
+ textCache.set(file.relPath, text);
1321
+ return text;
1322
+ };
1323
+ const ecosystemsSet = new Set();
1324
+ const manifests = [];
1325
+ const frameworkEvidence = new Map();
1326
+ const entrypoints = [];
1327
+ const seenEntrypoints = new Set();
1328
+ const specs = [];
1329
+ const seenSpecs = new Set();
1330
+ const portsSet = new Set();
1331
+ const rawRoutes = [];
1332
+ let detectedProjectName;
1333
+ const addFramework = (id, evidence) => {
1334
+ if (!ownLookup(FRAMEWORK_CATALOG, id))
1335
+ return;
1336
+ let set = frameworkEvidence.get(id);
1337
+ if (!set) {
1338
+ set = new Set();
1339
+ frameworkEvidence.set(id, set);
1340
+ }
1341
+ set.add(evidence);
1342
+ };
1343
+ const addEntrypoint = (entry) => {
1344
+ const key = `${entry.kind}|${entry.name}|${entry.path ?? ""}|${entry.command ?? ""}`;
1345
+ if (seenEntrypoints.has(key))
1346
+ return;
1347
+ seenEntrypoints.add(key);
1348
+ entrypoints.push(entry);
1349
+ };
1350
+ const addSpec = (spec) => {
1351
+ const key = `${spec.kind}|${spec.path}`;
1352
+ if (seenSpecs.has(key))
1353
+ return;
1354
+ seenSpecs.add(key);
1355
+ specs.push(spec);
1356
+ };
1357
+ // Pass 1: Manifests, config markers, env templates, and spec artifacts
1358
+ for (const file of scannedFiles) {
1359
+ const lowerBase = file.baseName.toLowerCase();
1360
+ if (isSecretFilePath(file.relPath))
1361
+ continue;
1362
+ // Safe PORT-only extraction from `.env.example` / `.env.sample` / `.env.template`
1363
+ if (isEnvExampleFileName(lowerBase)) {
1364
+ const content = readScannedText(file);
1365
+ if (content)
1366
+ extractPortsFromText(content, portsSet, "env-example");
1367
+ continue;
1368
+ }
1369
+ // Config-file framework hints
1370
+ const configFw = [
1371
+ [/^next\.config\.(?:js|mjs|cjs|ts|mts)$/i, "nextjs"],
1372
+ [/^vite\.config\.(?:js|mjs|cjs|ts|mts)$/i, "vite"],
1373
+ [/^svelte\.config\.(?:js|mjs|cjs|ts)$/i, "svelte"],
1374
+ [/^nuxt\.config\.(?:js|mjs|ts)$/i, "vue"]
1375
+ ];
1376
+ for (const [re, fwId] of configFw) {
1377
+ if (re.test(lowerBase)) {
1378
+ ecosystemsSet.add("node");
1379
+ addFramework(fwId, file.relPath);
1380
+ break;
1381
+ }
1382
+ }
1383
+ if (lowerBase === "manage.py") {
1384
+ ecosystemsSet.add("python");
1385
+ const content = readScannedText(file);
1386
+ if (content && content.includes("django"))
1387
+ addFramework("django", file.relPath);
1388
+ }
1389
+ // package.json
1390
+ if (lowerBase === "package.json") {
1391
+ if (isTestOrFixturePath(file.relPath) || EXAMPLE_PATH_RE.test(file.relPath))
1392
+ continue;
1393
+ ecosystemsSet.add("node");
1394
+ const content = readScannedText(file);
1395
+ if (!content)
1396
+ continue;
1397
+ let pkg;
1398
+ try {
1399
+ pkg = JSON.parse(content);
1400
+ }
1401
+ catch (err) {
1402
+ pushWarning(`Malformed JSON in ${file.relPath}: ${errorMessage(err)}`);
1403
+ continue;
1404
+ }
1405
+ if (!isRecord(pkg)) {
1406
+ pushWarning(`Expected JSON object in ${file.relPath}.`);
1407
+ continue;
1408
+ }
1409
+ const rawPkgName = Object.prototype.hasOwnProperty.call(pkg, "name") && typeof pkg.name === "string" && pkg.name.trim()
1410
+ ? sanitizeDisplayName(pkg.name)
1411
+ : undefined;
1412
+ const pkgName = rawPkgName || undefined;
1413
+ const rawPkgVersion = Object.prototype.hasOwnProperty.call(pkg, "version") && typeof pkg.version === "string" && pkg.version.trim()
1414
+ ? sanitizeDisplayName(pkg.version)
1415
+ : undefined;
1416
+ const pkgVersion = rawPkgVersion || undefined;
1417
+ if (file.relPath === "package.json" && pkgName)
1418
+ detectedProjectName = pkgName;
1419
+ const sanitizedScripts = {};
1420
+ if (Object.prototype.hasOwnProperty.call(pkg, "scripts") && isRecord(pkg.scripts)) {
1421
+ for (const [scriptName, scriptVal] of Object.entries(pkg.scripts)) {
1422
+ if (DANGEROUS_OBJECT_KEYS.has(scriptName) || typeof scriptVal !== "string")
1423
+ continue;
1424
+ const cleanCmd = redactSensitiveText(scriptVal.trim());
1425
+ sanitizedScripts[scriptName] = cleanCmd;
1426
+ if (!NON_APP_PORT_PATH_RE.test(file.relPath)) {
1427
+ extractPortsFromText(scriptVal, portsSet, "script");
1428
+ }
1429
+ if (NOTABLE_SCRIPT_NAMES.has(scriptName.toLowerCase())) {
1430
+ addEntrypoint({
1431
+ kind: "script",
1432
+ name: scriptName,
1433
+ command: cleanCmd,
1434
+ source: file.relPath
1435
+ });
1436
+ }
1437
+ }
1438
+ }
1439
+ manifests.push({
1440
+ kind: "package.json",
1441
+ path: file.relPath,
1442
+ ...(pkgName ? { name: pkgName } : {}),
1443
+ ...(pkgVersion ? { version: pkgVersion } : {}),
1444
+ ...(Object.keys(sanitizedScripts).length > 0 ? { scripts: sanitizedScripts } : {})
1445
+ });
1446
+ const pkgDirAbs = path.dirname(file.absPath);
1447
+ // CLI bins
1448
+ if (Object.prototype.hasOwnProperty.call(pkg, "bin") && typeof pkg.bin === "string" && pkg.bin.trim()) {
1449
+ const relBin = resolveSafeWorkspaceRelPath(pkgDirAbs, pkg.bin, realRoot);
1450
+ if (relBin) {
1451
+ const cmd = buildCliCommandForFile(relBin);
1452
+ const candidateName = pkgName ?? path.posix.basename(relBin, path.posix.extname(relBin));
1453
+ const safeBinName = SAFE_BIN_NAME_RE.test(candidateName)
1454
+ ? candidateName
1455
+ : path.posix.basename(relBin, path.posix.extname(relBin));
1456
+ if (cmd && SAFE_BIN_NAME_RE.test(safeBinName) && !DANGEROUS_OBJECT_KEYS.has(safeBinName)) {
1457
+ addEntrypoint({
1458
+ kind: "cli",
1459
+ name: safeBinName,
1460
+ path: relBin,
1461
+ command: cmd,
1462
+ source: file.relPath
1463
+ });
1464
+ }
1465
+ else {
1466
+ pushWarning(`Skipped unsafe CLI bin entrypoint in ${file.relPath}.`);
1467
+ }
1468
+ }
1469
+ }
1470
+ else if (Object.prototype.hasOwnProperty.call(pkg, "bin") && isRecord(pkg.bin)) {
1471
+ for (const [binName, binTarget] of Object.entries(pkg.bin)) {
1472
+ if (DANGEROUS_OBJECT_KEYS.has(binName) || typeof binTarget !== "string" || !binTarget.trim())
1473
+ continue;
1474
+ if (!SAFE_BIN_NAME_RE.test(binName)) {
1475
+ pushWarning(`Skipped unsafe CLI bin name in ${file.relPath}.`);
1476
+ continue;
1477
+ }
1478
+ const relBin = resolveSafeWorkspaceRelPath(pkgDirAbs, binTarget, realRoot);
1479
+ if (relBin) {
1480
+ const cmd = buildCliCommandForFile(relBin);
1481
+ if (cmd) {
1482
+ addEntrypoint({
1483
+ kind: "cli",
1484
+ name: binName,
1485
+ path: relBin,
1486
+ command: cmd,
1487
+ source: file.relPath
1488
+ });
1489
+ }
1490
+ else {
1491
+ pushWarning(`Skipped unsafe CLI bin path in ${file.relPath}.`);
1492
+ }
1493
+ }
1494
+ }
1495
+ }
1496
+ // Repo export entry files (`exports`, `main`, `module`)
1497
+ const exportTargets = [];
1498
+ if (Object.prototype.hasOwnProperty.call(pkg, "exports") && pkg.exports !== undefined) {
1499
+ extractPackageExportsTargets(pkg.exports, exportTargets);
1500
+ }
1501
+ for (const field of ["main", "module"]) {
1502
+ const val = Object.prototype.hasOwnProperty.call(pkg, field) ? pkg[field] : undefined;
1503
+ if (typeof val === "string" && val.trim() && isRuntimeCodePath(val)) {
1504
+ exportTargets.push(val.trim());
1505
+ }
1506
+ }
1507
+ for (const target of exportTargets) {
1508
+ const relEntry = resolveSafeWorkspaceRelPath(pkgDirAbs, target, realRoot);
1509
+ if (relEntry) {
1510
+ addEntrypoint({
1511
+ kind: "repo",
1512
+ name: pkgName ?? path.posix.basename(relEntry),
1513
+ path: relEntry,
1514
+ source: file.relPath
1515
+ });
1516
+ }
1517
+ }
1518
+ // Dependencies -> framework detection
1519
+ const depBlocks = [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies, pkg.optionalDependencies];
1520
+ for (const block of depBlocks) {
1521
+ if (!isRecord(block))
1522
+ continue;
1523
+ for (const depName of Object.keys(block)) {
1524
+ if (DANGEROUS_OBJECT_KEYS.has(depName))
1525
+ continue;
1526
+ const fwId = ownLookup(NODE_DEP_TO_FRAMEWORK, depName.toLowerCase());
1527
+ if (fwId)
1528
+ addFramework(fwId, `${depName} in ${file.relPath}`);
1529
+ }
1530
+ }
1531
+ continue;
1532
+ }
1533
+ // pyproject.toml
1534
+ if (lowerBase === "pyproject.toml") {
1535
+ ecosystemsSet.add("python");
1536
+ const content = readScannedText(file);
1537
+ if (!content)
1538
+ continue;
1539
+ const parsed = parsePyprojectToml(content);
1540
+ const pyName = parsed.name ? sanitizeDisplayName(parsed.name) : undefined;
1541
+ const pyVersion = parsed.version ? sanitizeDisplayName(parsed.version) : undefined;
1542
+ if (file.relPath === "pyproject.toml" && pyName && !detectedProjectName) {
1543
+ detectedProjectName = pyName;
1544
+ }
1545
+ manifests.push({
1546
+ kind: "pyproject.toml",
1547
+ path: file.relPath,
1548
+ ...(pyName ? { name: pyName } : {}),
1549
+ ...(pyVersion ? { version: pyVersion } : {}),
1550
+ ...(Object.keys(parsed.scripts).length > 0 ? { scripts: parsed.scripts } : {})
1551
+ });
1552
+ for (const dep of parsed.deps) {
1553
+ const fwId = ownLookup(PYTHON_DEP_TO_FRAMEWORK, dep);
1554
+ if (fwId)
1555
+ addFramework(fwId, `${dep} in ${file.relPath}`);
1556
+ }
1557
+ for (const [scriptName, target] of Object.entries(parsed.scripts)) {
1558
+ if (DANGEROUS_OBJECT_KEYS.has(scriptName) || !SAFE_PY_SCRIPT_NAME_RE.test(scriptName))
1559
+ continue;
1560
+ const safeTarget = SAFE_PY_ENTRY_TARGET_RE.test(target) && !target.includes("..") ? target : undefined;
1561
+ addEntrypoint({
1562
+ kind: "cli",
1563
+ name: scriptName,
1564
+ command: scriptName,
1565
+ ...(safeTarget ? { path: safeTarget } : {}),
1566
+ source: file.relPath
1567
+ });
1568
+ }
1569
+ continue;
1570
+ }
1571
+ // requirements*.txt
1572
+ if (REQUIREMENTS_FILE_RE.test(lowerBase)) {
1573
+ ecosystemsSet.add("python");
1574
+ const content = readScannedText(file);
1575
+ if (!content)
1576
+ continue;
1577
+ const deps = parseRequirementsTxt(content);
1578
+ manifests.push({ kind: "requirements.txt", path: file.relPath });
1579
+ for (const dep of deps) {
1580
+ const fwId = ownLookup(PYTHON_DEP_TO_FRAMEWORK, dep);
1581
+ if (fwId)
1582
+ addFramework(fwId, `${dep} in ${file.relPath}`);
1583
+ }
1584
+ continue;
1585
+ }
1586
+ // Cargo.toml
1587
+ if (lowerBase === "cargo.toml") {
1588
+ ecosystemsSet.add("rust");
1589
+ const content = readScannedText(file);
1590
+ if (!content)
1591
+ continue;
1592
+ const parsed = parseCargoToml(content);
1593
+ const cargoName = parsed.name ? sanitizeDisplayName(parsed.name) : undefined;
1594
+ const cargoVersion = parsed.version ? sanitizeDisplayName(parsed.version) : undefined;
1595
+ if (file.relPath === "Cargo.toml" && cargoName && !detectedProjectName) {
1596
+ detectedProjectName = cargoName;
1597
+ }
1598
+ manifests.push({
1599
+ kind: "Cargo.toml",
1600
+ path: file.relPath,
1601
+ ...(cargoName ? { name: cargoName } : {}),
1602
+ ...(cargoVersion ? { version: cargoVersion } : {})
1603
+ });
1604
+ for (const dep of parsed.deps) {
1605
+ const fwId = ownLookup(RUST_DEP_TO_FRAMEWORK, dep);
1606
+ if (fwId)
1607
+ addFramework(fwId, `${dep} in ${file.relPath}`);
1608
+ }
1609
+ const cargoDirAbs = path.dirname(file.absPath);
1610
+ for (const bin of parsed.bins) {
1611
+ if (!SAFE_CARGO_BIN_NAME_RE.test(bin.name) || DANGEROUS_OBJECT_KEYS.has(bin.name)) {
1612
+ pushWarning(`Skipped unsafe Cargo bin name in ${file.relPath}.`);
1613
+ continue;
1614
+ }
1615
+ const relBin = bin.path ? resolveSafeWorkspaceRelPath(cargoDirAbs, bin.path, realRoot) : undefined;
1616
+ if (bin.path && !relBin) {
1617
+ pushWarning(`Skipped unsafe Cargo bin path in ${file.relPath}.`);
1618
+ continue;
1619
+ }
1620
+ addEntrypoint({
1621
+ kind: "cli",
1622
+ name: bin.name,
1623
+ ...(relBin ? { path: relBin } : {}),
1624
+ command: `cargo run --bin ${bin.name}`,
1625
+ source: file.relPath
1626
+ });
1627
+ }
1628
+ continue;
1629
+ }
1630
+ // go.mod
1631
+ if (lowerBase === "go.mod") {
1632
+ ecosystemsSet.add("go");
1633
+ const content = readScannedText(file);
1634
+ if (!content)
1635
+ continue;
1636
+ const parsed = parseGoMod(content);
1637
+ const safeModPath = parsed.modulePath ? sanitizeDisplayName(parsed.modulePath) : undefined;
1638
+ const shortName = safeModPath ? safeModPath.split("/").filter(Boolean).pop() : undefined;
1639
+ if (file.relPath === "go.mod" && shortName && !detectedProjectName) {
1640
+ detectedProjectName = shortName;
1641
+ }
1642
+ manifests.push({
1643
+ kind: "go.mod",
1644
+ path: file.relPath,
1645
+ ...(safeModPath ? { name: safeModPath } : {})
1646
+ });
1647
+ for (const req of parsed.requires) {
1648
+ if (req.startsWith("github.com/gin-gonic/gin"))
1649
+ addFramework("gin", `${req} in ${file.relPath}`);
1650
+ if (req.startsWith("github.com/gofiber/fiber"))
1651
+ addFramework("fiber", `${req} in ${file.relPath}`);
1652
+ if (req.startsWith("github.com/spf13/cobra"))
1653
+ addFramework("cobra", `${req} in ${file.relPath}`);
1654
+ }
1655
+ continue;
1656
+ }
1657
+ // Makefile
1658
+ if (MAKEFILE_NAMES.has(lowerBase)) {
1659
+ const content = readScannedText(file);
1660
+ if (!content)
1661
+ continue;
1662
+ const targets = parseMakefileTargets(content);
1663
+ if (!NON_APP_PORT_PATH_RE.test(file.relPath)) {
1664
+ extractPortsFromText(content, portsSet, "script");
1665
+ }
1666
+ manifests.push({
1667
+ kind: "Makefile",
1668
+ path: file.relPath,
1669
+ ...(targets.length > 0 ? { targets } : {})
1670
+ });
1671
+ for (const target of targets) {
1672
+ if (NOTABLE_SCRIPT_NAMES.has(target.toLowerCase())) {
1673
+ addEntrypoint({
1674
+ kind: "script",
1675
+ name: `make:${target}`,
1676
+ command: `make ${target}`,
1677
+ source: file.relPath
1678
+ });
1679
+ }
1680
+ }
1681
+ continue;
1682
+ }
1683
+ // Spec artifacts by extension
1684
+ if (file.ext === ".graphql" || file.ext === ".gql") {
1685
+ addSpec({ kind: "graphql", path: file.relPath, ingestDomain: "graphql", format: "sdl" });
1686
+ continue;
1687
+ }
1688
+ if (file.ext === ".http" || file.ext === ".rest") {
1689
+ addSpec({ kind: "http-file", path: file.relPath, ingestDomain: "http-file", format: file.ext.slice(1) });
1690
+ continue;
1691
+ }
1692
+ if (file.ext === ".har") {
1693
+ addSpec({ kind: "har", path: file.relPath, ingestDomain: "api", format: "har" });
1694
+ continue;
1695
+ }
1696
+ if (file.ext === ".proto" && !isTestOrFixturePath(file.relPath)) {
1697
+ addSpec({ kind: "proto", path: file.relPath, ingestDomain: "proto", format: "proto" });
1698
+ continue;
1699
+ }
1700
+ if (file.ext === ".bru" && !isTestOrFixturePath(file.relPath)) {
1701
+ const dirRel = path.posix.dirname(file.relPath);
1702
+ const hasCollectionManifest = specs.some((s) => s.kind === "bruno" && (s.path === "bruno.json" || s.path === dirRel || file.relPath.startsWith(`${s.path}/`)));
1703
+ if (!hasCollectionManifest) {
1704
+ addSpec({ kind: "bruno", path: file.relPath, ingestDomain: "bruno", format: "bru" });
1705
+ }
1706
+ continue;
1707
+ }
1708
+ if (file.ext === ".yaml" || file.ext === ".yml") {
1709
+ if (isTestOrFixturePath(file.relPath))
1710
+ continue;
1711
+ const content = readScannedText(file);
1712
+ if (content) {
1713
+ if (OPENAPI_YAML_HEADER_RE.test(content)) {
1714
+ addSpec({ kind: "openapi", path: file.relPath, ingestDomain: "api", format: "yaml" });
1715
+ }
1716
+ else if (ASYNCAPI_YAML_HEADER_RE.test(content)) {
1717
+ addSpec({ kind: "asyncapi", path: file.relPath, ingestDomain: "asyncapi", format: "yaml" });
1718
+ }
1719
+ else if (OPENRPC_YAML_HEADER_RE.test(content)) {
1720
+ addSpec({ kind: "openrpc", path: file.relPath, ingestDomain: "openrpc", format: "yaml" });
1721
+ }
1722
+ else if (INSOMNIA_YAML_TYPE_RE.test(content) && INSOMNIA_YAML_FORMAT_RE.test(content)) {
1723
+ addSpec({ kind: "insomnia", path: file.relPath, ingestDomain: "insomnia", format: "yaml" });
1724
+ }
1725
+ }
1726
+ continue;
1727
+ }
1728
+ if (file.ext === ".json" && !SKIP_JSON_SPEC_NAMES.has(lowerBase) && !isTestOrFixturePath(file.relPath)) {
1729
+ const content = readScannedText(file);
1730
+ if (!content)
1731
+ continue;
1732
+ // Fast pre-filter before JSON.parse so unrelated config JSON files stay cheap.
1733
+ if (lowerBase !== "bruno.json" &&
1734
+ !content.includes('"openapi"') &&
1735
+ !content.includes('"swagger"') &&
1736
+ !content.includes('"_postman_id"') &&
1737
+ !content.includes("schema.getpostman.com") &&
1738
+ !content.includes('"__schema"') &&
1739
+ !content.includes('"asyncapi"') &&
1740
+ !content.includes('"openrpc"') &&
1741
+ !content.includes('"__export_format"') &&
1742
+ !content.includes('"_type"')) {
1743
+ continue;
1744
+ }
1745
+ try {
1746
+ const doc = JSON.parse(content);
1747
+ const spec = detectSpecsFromJson(doc, file.relPath);
1748
+ if (spec)
1749
+ addSpec(spec);
1750
+ }
1751
+ catch (err) {
1752
+ pushWarning(`Malformed JSON in ${file.relPath}: ${errorMessage(err)}`);
1753
+ }
1754
+ }
1755
+ }
1756
+ // Pass 2: Next.js filesystem routes (App Router & Pages Router)
1757
+ const fsRoutes = extractFileSystemRoutes(scannedFiles.map((f) => f.relPath), (relPath) => {
1758
+ const normalized = normalizeRelPosix(relPath);
1759
+ const file = fileByRel.get(normalized);
1760
+ return file ? readScannedText(file) : null;
1761
+ });
1762
+ if (fsRoutes.length > 0) {
1763
+ ecosystemsSet.add("node");
1764
+ addFramework("nextjs", fsRoutes[0].source);
1765
+ for (const r of fsRoutes)
1766
+ rawRoutes.push(r);
1767
+ }
1768
+ // Pass 3: Source file scanning (routes, ports, imports, repo/server entrypoints, test-suite roots)
1769
+ const testDirCounts = new Map();
1770
+ let totalTestFiles = 0;
1771
+ for (const file of scannedFiles) {
1772
+ if (isSecretFilePath(file.relPath))
1773
+ continue;
1774
+ // Infer ecosystems from source file extensions when manifests are absent
1775
+ if (file.ext === ".py")
1776
+ ecosystemsSet.add("python");
1777
+ else if (file.ext === ".rs")
1778
+ ecosystemsSet.add("rust");
1779
+ else if (file.ext === ".go")
1780
+ ecosystemsSet.add("go");
1781
+ else if (file.ext === ".ts" || file.ext === ".tsx" || file.ext === ".mts" || file.ext === ".js" || file.ext === ".mjs") {
1782
+ ecosystemsSet.add("node");
1783
+ }
1784
+ if (COMMON_REPO_ENTRY_FILES.has(file.relPath)) {
1785
+ addEntrypoint({
1786
+ kind: "repo",
1787
+ name: path.posix.basename(file.relPath),
1788
+ path: file.relPath,
1789
+ source: file.relPath
1790
+ });
1791
+ }
1792
+ if (!EXAMPLE_PATH_RE.test(file.relPath) && IMPORTABLE_TEST_FILENAME_RE.test(file.baseName)) {
1793
+ totalTestFiles++;
1794
+ const topDir = file.relPath.includes("/") ? file.relPath.split("/")[0] : ".";
1795
+ testDirCounts.set(topDir, (testDirCounts.get(topDir) ?? 0) + 1);
1796
+ }
1797
+ if (!SOURCE_SCAN_EXTS.has(file.ext))
1798
+ continue;
1799
+ if (isTestOrFixturePath(file.relPath))
1800
+ continue;
1801
+ const content = readScannedText(file);
1802
+ if (!content)
1803
+ continue;
1804
+ detectFrameworksFromSourceImports(content, file.ext, file.relPath, addFramework);
1805
+ if (!NON_APP_PORT_PATH_RE.test(file.relPath)) {
1806
+ extractPortsFromText(content, portsSet, "source");
1807
+ }
1808
+ let fileHasRoutes = false;
1809
+ if (ROUTE_SOURCE_EXTS.has(file.ext)) {
1810
+ const extracted = extractRoutesFromSource(content, file.relPath);
1811
+ if (extracted.length > 0) {
1812
+ fileHasRoutes = true;
1813
+ for (const r of extracted) {
1814
+ rawRoutes.push({ ...r, path: redactSensitiveText(r.path) });
1815
+ if (r.framework && ownLookup(FRAMEWORK_CATALOG, r.framework)) {
1816
+ addFramework(r.framework, `route in ${file.relPath}`);
1817
+ }
1818
+ }
1819
+ }
1820
+ }
1821
+ if (!EXAMPLE_PATH_RE.test(file.relPath) && (fileHasRoutes || SERVER_LISTEN_HINT_RE.test(content))) {
1822
+ addEntrypoint({
1823
+ kind: "server",
1824
+ name: path.posix.basename(file.relPath),
1825
+ path: file.relPath,
1826
+ source: file.relPath
1827
+ });
1828
+ }
1829
+ }
1830
+ let testRootDir;
1831
+ if (totalTestFiles > 0) {
1832
+ if (testDirCounts.has("test"))
1833
+ testRootDir = "test";
1834
+ else if (testDirCounts.has("tests"))
1835
+ testRootDir = "tests";
1836
+ else {
1837
+ testRootDir = [...testDirCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0];
1838
+ }
1839
+ }
1840
+ // Deduplicate & sort routes deterministically
1841
+ const routeSeen = new Set();
1842
+ const routes = [];
1843
+ for (const r of rawRoutes) {
1844
+ const key = `${r.kind}|${r.method}|${r.path}|${r.source}`;
1845
+ if (routeSeen.has(key))
1846
+ continue;
1847
+ routeSeen.add(key);
1848
+ routes.push(r);
1849
+ }
1850
+ routes.sort((a, b) => {
1851
+ if (a.kind !== b.kind)
1852
+ return a.kind.localeCompare(b.kind);
1853
+ if (a.path !== b.path)
1854
+ return a.path.localeCompare(b.path);
1855
+ if (a.method !== b.method)
1856
+ return a.method.localeCompare(b.method);
1857
+ return a.source.localeCompare(b.source);
1858
+ });
1859
+ // Finalize sorted collections
1860
+ const frameworks = [...frameworkEvidence.entries()]
1861
+ .map(([id, ev]) => ({
1862
+ ...FRAMEWORK_CATALOG[id],
1863
+ evidence: [...ev].sort((a, b) => a.localeCompare(b))
1864
+ }))
1865
+ .sort((a, b) => a.id.localeCompare(b.id));
1866
+ manifests.sort((a, b) => a.path.localeCompare(b.path));
1867
+ specs.sort((a, b) => a.path.localeCompare(b.path));
1868
+ const entrypointOrder = {
1869
+ cli: 0,
1870
+ server: 1,
1871
+ repo: 2,
1872
+ script: 3
1873
+ };
1874
+ entrypoints.sort((a, b) => {
1875
+ if (entrypointOrder[a.kind] !== entrypointOrder[b.kind]) {
1876
+ return entrypointOrder[a.kind] - entrypointOrder[b.kind];
1877
+ }
1878
+ const pa = a.path ?? a.name;
1879
+ const pb = b.path ?? b.name;
1880
+ if (pa !== pb)
1881
+ return pa.localeCompare(pb);
1882
+ return a.name.localeCompare(b.name);
1883
+ });
1884
+ const ports = [...portsSet].sort((a, b) => a - b);
1885
+ const ecosystems = [...ecosystemsSet].sort((a, b) => a.localeCompare(b));
1886
+ const suggestedDomains = buildDomainRanking({ frameworks, entrypoints, routes, specs, manifests });
1887
+ const primaryDomain = suggestedDomains[0] ?? null;
1888
+ const slices = buildSliceSuggestions({ suggestedDomains, entrypoints, routes, specs, frameworks });
1889
+ const commands = buildCommandSuggestions({
1890
+ suggestedDomains,
1891
+ entrypoints,
1892
+ routes,
1893
+ specs,
1894
+ ports,
1895
+ frameworks,
1896
+ ...(testRootDir ? { testRootDir, testFileCount: totalTestFiles } : {})
1897
+ });
1898
+ const projectName = sanitizeDisplayName(detectedProjectName ?? (path.basename(realRoot) || "project")) || "project";
1899
+ return {
1900
+ ok: true,
1901
+ schemaVersion: "1.0.0",
1902
+ rootDir: realRoot.split(path.sep).join("/"),
1903
+ projectName,
1904
+ ecosystems,
1905
+ manifests,
1906
+ frameworks,
1907
+ entrypoints,
1908
+ routes,
1909
+ specs,
1910
+ ports,
1911
+ suggestedDomains,
1912
+ primaryDomain,
1913
+ slices,
1914
+ commands,
1915
+ stats,
1916
+ warnings
1917
+ };
1918
+ }
1919
+ function methodColor(method) {
1920
+ switch (method.toUpperCase()) {
1921
+ case "GET":
1922
+ case "HEAD":
1923
+ case "OPTIONS":
1924
+ return ANSI.green;
1925
+ case "POST":
1926
+ return ANSI.cyan;
1927
+ case "PUT":
1928
+ case "PATCH":
1929
+ return ANSI.yellow;
1930
+ case "DELETE":
1931
+ return ANSI.red;
1932
+ default:
1933
+ return ANSI.bold;
1934
+ }
1935
+ }
1936
+ /**
1937
+ * Render a concise, human-friendly terminal summary for `vibecode-anything discover --pretty`.
1938
+ */
1939
+ export function formatPrettyDiscovery(report, options = {}) {
1940
+ const useColor = options.color === true;
1941
+ const maxRoutes = clampInt(options.maxRoutes, 20, 1, 200);
1942
+ const maxCommands = clampInt(options.maxCommands, 8, 1, 50);
1943
+ const lines = [];
1944
+ const domainBadge = report.primaryDomain
1945
+ ? styleAnsi(`[${report.primaryDomain.toUpperCase()}]`, `${ANSI.bold}${ANSI.green}`, useColor)
1946
+ : styleAnsi("[UNKNOWN]", `${ANSI.bold}${ANSI.yellow}`, useColor);
1947
+ lines.push(`${styleAnsi("vibecode-anything discover", `${ANSI.bold}${ANSI.cyan}`, useColor)} ${styleAnsi(redactSensitiveText(report.projectName), ANSI.bold, useColor)} ${domainBadge}`);
1948
+ lines.push(`Ecosystems: ${report.ecosystems.length > 0 ? report.ecosystems.join(", ") : "none"} | Domains: ${report.suggestedDomains.length > 0 ? report.suggestedDomains.join(", ") : "none"} | Ports: ${report.ports.length > 0 ? report.ports.join(", ") : "none"}`);
1949
+ if (report.frameworks.length > 0) {
1950
+ const fwSummary = report.frameworks.map((f) => `${f.name} (${f.category})`).join(", ");
1951
+ lines.push(`Frameworks: ${fwSummary}`);
1952
+ }
1953
+ if (report.manifests.length > 0) {
1954
+ const mfSummary = report.manifests
1955
+ .map((m) => (m.targets && m.targets.length > 0 ? `${m.path} (${m.targets.length} targets)` : m.path))
1956
+ .join(", ");
1957
+ lines.push(`Manifests: ${mfSummary}`);
1958
+ }
1959
+ if (report.entrypoints.length > 0) {
1960
+ lines.push("");
1961
+ lines.push(styleAnsi(`Entrypoints (${report.entrypoints.length}):`, ANSI.bold, useColor));
1962
+ for (const ep of report.entrypoints.slice(0, 12)) {
1963
+ const kindTag = styleAnsi(`[${ep.kind.toUpperCase()}]`.padEnd(8), ANSI.cyan, useColor);
1964
+ const detail = redactSensitiveText(ep.path && ep.command ? `${ep.path} -> ${ep.command}` : ep.path ?? ep.command ?? ep.name);
1965
+ lines.push(` ${kindTag} ${redactSensitiveText(ep.name)} ${styleAnsi(`(${detail})`, ANSI.dim, useColor)}`);
1966
+ }
1967
+ if (report.entrypoints.length > 12) {
1968
+ lines.push(styleAnsi(` ... and ${report.entrypoints.length - 12} more`, ANSI.dim, useColor));
1969
+ }
1970
+ }
1971
+ if (report.specs.length > 0) {
1972
+ lines.push("");
1973
+ lines.push(styleAnsi(`Spec Artifacts (${report.specs.length}):`, ANSI.bold, useColor));
1974
+ for (const spec of report.specs) {
1975
+ const badge = styleAnsi(`[${spec.kind.toUpperCase()}]`.padEnd(11), ANSI.green, useColor);
1976
+ lines.push(` ${badge} ${spec.path} ${styleAnsi(`(domain: ${spec.ingestDomain})`, ANSI.dim, useColor)}`);
1977
+ }
1978
+ }
1979
+ if (report.routes.length > 0) {
1980
+ lines.push("");
1981
+ lines.push(styleAnsi(`Discovered Routes (${report.routes.length}):`, ANSI.bold, useColor));
1982
+ for (const route of report.routes.slice(0, maxRoutes)) {
1983
+ const m = styleAnsi(route.method.padEnd(7), `${ANSI.bold}${methodColor(route.method)}`, useColor);
1984
+ const meta = route.framework ? `${route.source} [${route.framework}]` : route.source;
1985
+ lines.push(` ${m} ${redactSensitiveText(route.path)} ${styleAnsi(`(${meta})`, ANSI.dim, useColor)}`);
1986
+ }
1987
+ if (report.routes.length > maxRoutes) {
1988
+ lines.push(styleAnsi(` ... and ${report.routes.length - maxRoutes} more`, ANSI.dim, useColor));
1989
+ }
1990
+ }
1991
+ if (report.slices.length > 0) {
1992
+ lines.push("");
1993
+ lines.push(styleAnsi(`Suggested Slices (${report.slices.length}):`, ANSI.bold, useColor));
1994
+ for (const slice of report.slices) {
1995
+ lines.push(` ${slice.priority}. ${styleAnsi(slice.id, ANSI.bold, useColor)} ${styleAnsi(`[${slice.domain}]`, ANSI.cyan, useColor)} ${slice.title} ${styleAnsi(`(${slice.items.length} items)`, ANSI.dim, useColor)}`);
1996
+ }
1997
+ }
1998
+ if (report.commands.length > 0) {
1999
+ lines.push("");
2000
+ lines.push(styleAnsi("Ready-to-Run Commands:", ANSI.bold, useColor));
2001
+ for (const cmd of report.commands.slice(0, maxCommands)) {
2002
+ const actionTag = styleAnsi(`[${cmd.action.toUpperCase()}]`.padEnd(8), cmd.action === "lock" ? `${ANSI.bold}${ANSI.green}` : `${ANSI.bold}${ANSI.cyan}`, useColor);
2003
+ lines.push(` ${actionTag} ${redactSensitiveText(cmd.command)}`);
2004
+ }
2005
+ }
2006
+ if (report.warnings.length > 0) {
2007
+ lines.push("");
2008
+ lines.push(styleAnsi(`Warnings (${report.warnings.length}):`, `${ANSI.bold}${ANSI.yellow}`, useColor));
2009
+ for (const warn of report.warnings) {
2010
+ lines.push(` ${styleAnsi("[WARN]", `${ANSI.bold}${ANSI.yellow}`, useColor)} ${redactSensitiveText(warn)}`);
2011
+ }
2012
+ }
2013
+ lines.push("");
2014
+ const truncNote = report.stats.truncated ? " (truncated at maxFiles)" : "";
2015
+ lines.push(styleAnsi(`Scan: ${report.stats.filesScanned} files in ${report.stats.directoriesVisited} dirs${truncNote}, ${report.stats.symlinksSkipped} symlinks skipped, ${report.stats.oversizedFilesSkipped} oversized skipped.`, ANSI.dim, useColor));
2016
+ return lines.join("\n");
2017
+ }