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.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,1412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency, fail-closed diff-driven impact analysis.
|
|
3
|
+
*
|
|
4
|
+
* Maps changed workspace files (from git or live `watch`) to the contract invariants and
|
|
5
|
+
* slices they can affect. Whenever the mapping cannot be trusted (contract edits, global
|
|
6
|
+
* config/entrypoints, shared hubs, unmapped code, truncated import graphs, oversized
|
|
7
|
+
* inputs) it falls back to a full run instead of silently skipping regressions.
|
|
8
|
+
*/
|
|
9
|
+
import { execFileSync } from "node:child_process";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { VibecodeError, errorMessage } from "./errors.js";
|
|
13
|
+
import { ANSI, clampInt, hasCrossPlatformPathEscape, hasVaultOrHoldoutSegment, isInsideVaultDirectory, isPathWithinDir, isRecordSafe, isSecretRelativePath, redactSensitiveText, safeIsArray, safeOwnProp, safeString, sanitizeSingleLine, styleAnsi } from "./security.js";
|
|
14
|
+
import { inferDomainForInvariant } from "./target-map.js";
|
|
15
|
+
export const MAX_IMPACT_GRAPH_FILES = 1500;
|
|
16
|
+
export const MAX_IMPACT_FILE_BYTES = 256 * 1024;
|
|
17
|
+
export const MAX_IMPACT_FILES_INPUT = 500;
|
|
18
|
+
const CONTRACT_PATH = ".vibecode/contract.json";
|
|
19
|
+
const VIBECODE_EPHEMERAL_FILES = new Set([
|
|
20
|
+
".vibecode/last-report.json",
|
|
21
|
+
".vibecode/report.html",
|
|
22
|
+
".vibecode/history.json",
|
|
23
|
+
".vibecode/cache.json",
|
|
24
|
+
".vibecode/trends.ndjson",
|
|
25
|
+
".vibecode/spec.md",
|
|
26
|
+
".vibecode/results.sarif",
|
|
27
|
+
".vibecode/junit.xml",
|
|
28
|
+
".vibecode/parity-badge.svg",
|
|
29
|
+
".vibecode/pr-comment.md"
|
|
30
|
+
]);
|
|
31
|
+
const BASE_REF_RE = /^[A-Za-z0-9._/~^-]{1,128}$/;
|
|
32
|
+
const SKIP_DIRS = new Set([
|
|
33
|
+
".git",
|
|
34
|
+
"node_modules",
|
|
35
|
+
".vibecode",
|
|
36
|
+
".vibecode-vault",
|
|
37
|
+
"dist",
|
|
38
|
+
"build",
|
|
39
|
+
"coverage"
|
|
40
|
+
]);
|
|
41
|
+
const CODE_EXTS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]);
|
|
42
|
+
const RESOLVE_EXTS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".json"];
|
|
43
|
+
const INDEX_FILES = ["index.ts", "index.tsx", "index.js", "index.jsx", "index.mjs", "index.cjs"];
|
|
44
|
+
const MATCH_KIND_ORDER = ["explicit_path", "route_token", "domain_affinity", "previous_failure"];
|
|
45
|
+
const FILE_REF_KEYS = ["file", "path", "module", "modulePath", "svgPath", "statePath", "script", "entry"];
|
|
46
|
+
const COMMAND_KEYS = ["command", "cmd", "args"];
|
|
47
|
+
const ROUTE_KEYS = ["path", "url", "urlPath", "startPath", "triggerPath", "href", "route", "endpoint"];
|
|
48
|
+
const MAX_REF_TOKENS = 256;
|
|
49
|
+
const MAX_ROUTE_STRINGS = 512;
|
|
50
|
+
const MAX_LIST_IN_PRETTY = 50;
|
|
51
|
+
const GLOBAL_BASENAMES = new Set([
|
|
52
|
+
"package.json",
|
|
53
|
+
"package-lock.json",
|
|
54
|
+
"npm-shrinkwrap.json",
|
|
55
|
+
"pnpm-lock.yaml",
|
|
56
|
+
"pnpm-workspace.yaml",
|
|
57
|
+
"yarn.lock",
|
|
58
|
+
"bun.lockb",
|
|
59
|
+
".npmrc",
|
|
60
|
+
".nvmrc",
|
|
61
|
+
".node-version"
|
|
62
|
+
]);
|
|
63
|
+
const GLOBAL_CONFIG_RE = /^(?:vite|vitest|next|webpack|rollup|nuxt|astro|svelte)\.config\.[a-z0-9]+$/;
|
|
64
|
+
const TSCONFIG_RE = /^(?:ts|js)config(?:[._-][a-z0-9._-]*)?\.json$/;
|
|
65
|
+
const ENTRYPOINT_RE = /^(?:src\/)?(?:index|server|app)\.[a-z0-9]+$/;
|
|
66
|
+
const GENERIC_STEMS = new Set([
|
|
67
|
+
"index", "main", "mod", "app", "server", "src", "lib", "libs", "util", "utils", "helper", "helpers",
|
|
68
|
+
"type", "types", "common", "shared", "core", "config", "constants", "component", "components",
|
|
69
|
+
"page", "pages", "route", "routes", "api", "controller", "controllers", "handler", "handlers",
|
|
70
|
+
"view", "views", "web", "ui", "cli", "bin", "test", "tests", "spec", "specs", "public", "static",
|
|
71
|
+
"assets", "style", "styles", "hooks", "service", "services", "model", "models", "dist", "build",
|
|
72
|
+
"layout", "layouts", "default", "endpoints", "commands", "scripts"
|
|
73
|
+
]);
|
|
74
|
+
const WEB_AFFINITY_EXTS = new Set([".css", ".scss", ".sass", ".less", ".html", ".htm", ".vue", ".svelte"]);
|
|
75
|
+
const WEB_AFFINITY_SEGMENTS = new Set(["web", "ui", "components", "pages", "views", "styles", "layouts", "public"]);
|
|
76
|
+
const CLI_AFFINITY_SEGMENTS = new Set(["cli", "bin", "commands"]);
|
|
77
|
+
const HTTP_AFFINITY_SEGMENTS = new Set(["api", "routes", "controllers", "handlers", "endpoints"]);
|
|
78
|
+
const HTTP_TYPES = new Set(["http", "http_workflow", "http_stream", "ws_protocol"]);
|
|
79
|
+
/** Graphs whose scan hit a size/read bound and therefore may be missing edges. */
|
|
80
|
+
const TRUNCATED_GRAPHS = new WeakSet();
|
|
81
|
+
// eslint-disable-next-line no-control-regex
|
|
82
|
+
const PATH_CONTROL_RE = /[\x00-\x1f\x7f]/;
|
|
83
|
+
const REGEX_PRECEDING_KEYWORDS = new Set([
|
|
84
|
+
"return",
|
|
85
|
+
"throw",
|
|
86
|
+
"case",
|
|
87
|
+
"in",
|
|
88
|
+
"instanceof",
|
|
89
|
+
"typeof",
|
|
90
|
+
"void",
|
|
91
|
+
"delete",
|
|
92
|
+
"new",
|
|
93
|
+
"yield",
|
|
94
|
+
"await",
|
|
95
|
+
"of",
|
|
96
|
+
"else",
|
|
97
|
+
"do"
|
|
98
|
+
]);
|
|
99
|
+
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
100
|
+
const isRecord = isRecordSafe;
|
|
101
|
+
const own = safeOwnProp;
|
|
102
|
+
function safeInferDomain(inv) {
|
|
103
|
+
const rawDomain = own(inv, "domain");
|
|
104
|
+
const rawType = own(inv, "type");
|
|
105
|
+
return inferDomainForInvariant({
|
|
106
|
+
...(typeof rawDomain === "string" ? { domain: rawDomain } : {}),
|
|
107
|
+
...(typeof rawType === "string" ? { type: rawType } : {})
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function configError(message, details) {
|
|
111
|
+
return new VibecodeError("CONFIG_INVALID", message, details !== undefined ? { details } : {});
|
|
112
|
+
}
|
|
113
|
+
function sortedUnique(items) {
|
|
114
|
+
return [...new Set(items)].sort(cmp);
|
|
115
|
+
}
|
|
116
|
+
function baseName(p) {
|
|
117
|
+
const idx = p.lastIndexOf("/");
|
|
118
|
+
return idx < 0 ? p : p.slice(idx + 1);
|
|
119
|
+
}
|
|
120
|
+
function extOf(p) {
|
|
121
|
+
return path.posix.extname(p).toLowerCase();
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Normalizes a changed/referenced path to a forward-slash workspace-relative path.
|
|
125
|
+
* Returns null for empty, escaping, absolute (outside `cwd`), or vault/holdout paths.
|
|
126
|
+
*/
|
|
127
|
+
function normalizeRelPath(raw, cwd) {
|
|
128
|
+
if (typeof raw !== "string")
|
|
129
|
+
return null;
|
|
130
|
+
let p = raw.trim();
|
|
131
|
+
if (!p || p.length > 4096 || p.includes("://"))
|
|
132
|
+
return null;
|
|
133
|
+
const absLike = path.isAbsolute(p) || /^[A-Za-z]:[\\/]/.test(p);
|
|
134
|
+
if (absLike) {
|
|
135
|
+
if (!cwd || !isPathWithinDir(p, cwd))
|
|
136
|
+
return null;
|
|
137
|
+
p = path.relative(path.resolve(cwd), path.resolve(p));
|
|
138
|
+
if (!p)
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
if (hasCrossPlatformPathEscape(p))
|
|
142
|
+
return null;
|
|
143
|
+
p = path.posix.normalize(p.replace(/\\/g, "/"));
|
|
144
|
+
while (p.startsWith("./"))
|
|
145
|
+
p = p.slice(2);
|
|
146
|
+
if (p.endsWith("/"))
|
|
147
|
+
p = p.slice(0, -1);
|
|
148
|
+
if (!p || p === "." || p === ".." || p.startsWith("../") || p.startsWith("/") || /^[A-Za-z]:/.test(p))
|
|
149
|
+
return null;
|
|
150
|
+
if (hasVaultOrHoldoutSegment(p))
|
|
151
|
+
return null;
|
|
152
|
+
if (cwd && process.env.VIBECODE_VAULT_DIR?.trim() && isInsideVaultDirectory(path.resolve(cwd, p)))
|
|
153
|
+
return null;
|
|
154
|
+
return p;
|
|
155
|
+
}
|
|
156
|
+
function normalizeList(raw, cwd) {
|
|
157
|
+
const out = new Set();
|
|
158
|
+
for (const item of raw) {
|
|
159
|
+
const norm = normalizeRelPath(item, cwd);
|
|
160
|
+
if (norm)
|
|
161
|
+
out.add(norm);
|
|
162
|
+
}
|
|
163
|
+
return [...out].sort(cmp);
|
|
164
|
+
}
|
|
165
|
+
function isDocFile(p) {
|
|
166
|
+
const lower = p.toLowerCase();
|
|
167
|
+
const base = baseName(lower);
|
|
168
|
+
if (lower.startsWith("docs/"))
|
|
169
|
+
return true;
|
|
170
|
+
if (base === "cmakelists.txt" || /^requirements.*\.txt$/.test(base))
|
|
171
|
+
return false; // runtime build inputs
|
|
172
|
+
if (base.endsWith(".md") || base.endsWith(".markdown") || base.endsWith(".txt"))
|
|
173
|
+
return true;
|
|
174
|
+
return base === "license" || base.startsWith("license.") || base === ".gitignore" || base === ".editorconfig";
|
|
175
|
+
}
|
|
176
|
+
function isGlobalConfigFile(p) {
|
|
177
|
+
const lower = p.toLowerCase();
|
|
178
|
+
const base = baseName(lower);
|
|
179
|
+
if (GLOBAL_BASENAMES.has(base))
|
|
180
|
+
return true;
|
|
181
|
+
if (base === "dockerfile" || base.startsWith("dockerfile."))
|
|
182
|
+
return true;
|
|
183
|
+
if (TSCONFIG_RE.test(base) || GLOBAL_CONFIG_RE.test(base))
|
|
184
|
+
return true;
|
|
185
|
+
if (base === ".env" || base.startsWith(".env."))
|
|
186
|
+
return true;
|
|
187
|
+
return ENTRYPOINT_RE.test(lower) && !isDocFile(lower);
|
|
188
|
+
}
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
// git
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
function runGit(cwd, args) {
|
|
193
|
+
try {
|
|
194
|
+
return execFileSync("git", ["-c", "core.fsmonitor=false", "-c", "core.quotepath=off", ...args], {
|
|
195
|
+
cwd,
|
|
196
|
+
encoding: "utf8",
|
|
197
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
198
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
199
|
+
windowsHide: true,
|
|
200
|
+
timeout: 30_000,
|
|
201
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
const stderr = err?.stderr;
|
|
206
|
+
const detail = typeof stderr === "string" && stderr.trim() ? stderr : errorMessage(err);
|
|
207
|
+
throw new VibecodeError("EXEC_ERROR", `git ${args[0]} failed: ${sanitizeSingleLine(detail, 300)}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function splitNul(out) {
|
|
211
|
+
return out.split("\0").filter((s) => s.length > 0);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Lists changed files (staged + unstaged + optional `baseRef...HEAD` + optional untracked)
|
|
215
|
+
* as sorted, deduplicated, forward-slash paths relative to `cwd`. Never uses a shell.
|
|
216
|
+
*/
|
|
217
|
+
export function getGitChangedFiles(cwd, options = {}) {
|
|
218
|
+
if (typeof cwd !== "string" || !cwd.trim() || PATH_CONTROL_RE.test(cwd)) {
|
|
219
|
+
throw configError("getGitChangedFiles requires a valid working directory.");
|
|
220
|
+
}
|
|
221
|
+
let baseRef;
|
|
222
|
+
let includeUntracked;
|
|
223
|
+
if (options !== undefined && options !== null) {
|
|
224
|
+
if (!isRecord(options))
|
|
225
|
+
throw configError("getGitChangedFiles options must be an object.");
|
|
226
|
+
try {
|
|
227
|
+
baseRef = Object.prototype.hasOwnProperty.call(options, "baseRef") ? options.baseRef : undefined;
|
|
228
|
+
includeUntracked = Object.prototype.hasOwnProperty.call(options, "includeUntracked")
|
|
229
|
+
? options.includeUntracked
|
|
230
|
+
: undefined;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
throw configError("getGitChangedFiles options could not be read safely.");
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (baseRef !== undefined) {
|
|
237
|
+
if (typeof baseRef !== "string" ||
|
|
238
|
+
!BASE_REF_RE.test(baseRef) ||
|
|
239
|
+
baseRef.startsWith("-") ||
|
|
240
|
+
baseRef.startsWith("/") ||
|
|
241
|
+
baseRef.startsWith(".") ||
|
|
242
|
+
baseRef.startsWith("^") ||
|
|
243
|
+
baseRef.startsWith("~") ||
|
|
244
|
+
baseRef.includes("..") ||
|
|
245
|
+
baseRef.includes("//") ||
|
|
246
|
+
baseRef.includes("/.") ||
|
|
247
|
+
baseRef.endsWith("/") ||
|
|
248
|
+
baseRef.endsWith(".") ||
|
|
249
|
+
baseRef.endsWith(".lock")) {
|
|
250
|
+
const preview = typeof baseRef === "string" ? sanitizeSingleLine(baseRef, 80) : typeof baseRef;
|
|
251
|
+
throw configError(`Invalid git baseRef ${JSON.stringify(preview)}: must match /^[A-Za-z0-9._/~^-]{1,128}$/ and must not start with "-".`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const dir = path.resolve(cwd);
|
|
255
|
+
let isDir = false;
|
|
256
|
+
try {
|
|
257
|
+
isDir = fs.statSync(dir).isDirectory();
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
isDir = false;
|
|
261
|
+
}
|
|
262
|
+
if (!isDir)
|
|
263
|
+
throw new VibecodeError("EXEC_ERROR", "git changed-file detection failed: working directory does not exist.");
|
|
264
|
+
const inside = runGit(dir, ["rev-parse", "--is-inside-work-tree"]).trim();
|
|
265
|
+
if (inside !== "true")
|
|
266
|
+
throw new VibecodeError("EXEC_ERROR", "git changed-file detection failed: not inside a git work tree.");
|
|
267
|
+
const diffBase = ["diff", "--name-only", "--relative", "--no-renames", "--no-ext-diff", "-z"];
|
|
268
|
+
const collected = [];
|
|
269
|
+
collected.push(...splitNul(runGit(dir, [...diffBase, "--"])));
|
|
270
|
+
collected.push(...splitNul(runGit(dir, [...diffBase, "--cached", "--"])));
|
|
271
|
+
if (baseRef !== undefined) {
|
|
272
|
+
collected.push(...splitNul(runGit(dir, [...diffBase, `${baseRef}...HEAD`, "--"])));
|
|
273
|
+
}
|
|
274
|
+
if (includeUntracked !== false) {
|
|
275
|
+
collected.push(...splitNul(runGit(dir, ["ls-files", "--others", "--exclude-standard", "-z"])));
|
|
276
|
+
}
|
|
277
|
+
return normalizeList(collected, dir);
|
|
278
|
+
}
|
|
279
|
+
// ---------------------------------------------------------------------------
|
|
280
|
+
// import graph
|
|
281
|
+
// ---------------------------------------------------------------------------
|
|
282
|
+
function isWs(c) {
|
|
283
|
+
return c === 32 || c === 9 || c === 10 || c === 13 || c === 11 || c === 12;
|
|
284
|
+
}
|
|
285
|
+
function isIdent(c) {
|
|
286
|
+
return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36;
|
|
287
|
+
}
|
|
288
|
+
const LOOKBACK_LIMIT = 256;
|
|
289
|
+
function prevNonSpace(text, idx) {
|
|
290
|
+
let k = idx - 1;
|
|
291
|
+
const stop = Math.max(-1, idx - 1 - LOOKBACK_LIMIT);
|
|
292
|
+
while (k > stop && isWs(text.charCodeAt(k)))
|
|
293
|
+
k--;
|
|
294
|
+
return k > stop ? k : -1;
|
|
295
|
+
}
|
|
296
|
+
function wordEndingAt(text, end) {
|
|
297
|
+
if (end < 0)
|
|
298
|
+
return "";
|
|
299
|
+
let k = end;
|
|
300
|
+
const stop = Math.max(-1, end - 16);
|
|
301
|
+
while (k > stop && isIdent(text.charCodeAt(k)))
|
|
302
|
+
k--;
|
|
303
|
+
if (k >= 0 && (isIdent(text.charCodeAt(k)) || text.charCodeAt(k) === 46))
|
|
304
|
+
return ""; // too long or `.member`
|
|
305
|
+
return text.slice(k + 1, end + 1);
|
|
306
|
+
}
|
|
307
|
+
function isImportContext(text, quoteIdx) {
|
|
308
|
+
const k = prevNonSpace(text, quoteIdx);
|
|
309
|
+
if (k < 0)
|
|
310
|
+
return false;
|
|
311
|
+
if (text.charCodeAt(k) === 40 /* ( */) {
|
|
312
|
+
const w = wordEndingAt(text, prevNonSpace(text, k));
|
|
313
|
+
return w === "import" || w === "require";
|
|
314
|
+
}
|
|
315
|
+
const w = wordEndingAt(text, k);
|
|
316
|
+
return w === "from" || w === "import";
|
|
317
|
+
}
|
|
318
|
+
function isLocalSpecifier(s) {
|
|
319
|
+
if (!s || s.length > 1024 || s.includes("\0"))
|
|
320
|
+
return false;
|
|
321
|
+
return s === "." || s === ".." || s.startsWith("./") || s.startsWith("../");
|
|
322
|
+
}
|
|
323
|
+
function isIdentStart(c) {
|
|
324
|
+
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Extracts static local relative import specifiers (`import/export ... from "./x"`,
|
|
328
|
+
* `import "./x"`, `import("./x")`, `require("./x")`) with a single strict-O(N) linear scan
|
|
329
|
+
* that skips comments, nested template literals (`${...}`), and regex literals.
|
|
330
|
+
*/
|
|
331
|
+
export function extractLocalImportSpecifiers(source) {
|
|
332
|
+
const text = typeof source === "string" ? source : "";
|
|
333
|
+
const n = text.length;
|
|
334
|
+
const out = [];
|
|
335
|
+
const seen = new Set();
|
|
336
|
+
const templateBraceStack = [];
|
|
337
|
+
let regexAllowed = true;
|
|
338
|
+
let regexFailLineEnd = -1;
|
|
339
|
+
let i = 0;
|
|
340
|
+
const scanTemplateText = () => {
|
|
341
|
+
while (i < n) {
|
|
342
|
+
const ch = text.charCodeAt(i);
|
|
343
|
+
if (ch === 92 /* \ */) {
|
|
344
|
+
i += 2;
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (ch === 96 /* ` */) {
|
|
348
|
+
i++;
|
|
349
|
+
regexAllowed = false;
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (ch === 36 /* $ */ && text.charCodeAt(i + 1) === 123 /* { */) {
|
|
353
|
+
i += 2;
|
|
354
|
+
templateBraceStack.push(0);
|
|
355
|
+
regexAllowed = true;
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
i++;
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
while (i < n) {
|
|
362
|
+
const c = text.charCodeAt(i);
|
|
363
|
+
if (isWs(c)) {
|
|
364
|
+
i++;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (c === 47 /* / */) {
|
|
368
|
+
const nx = text.charCodeAt(i + 1);
|
|
369
|
+
if (nx === 47) {
|
|
370
|
+
const e = text.indexOf("\n", i + 2);
|
|
371
|
+
i = e < 0 ? n : e + 1;
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (nx === 42) {
|
|
375
|
+
const e = text.indexOf("*/", i + 2);
|
|
376
|
+
i = e < 0 ? n : e + 2;
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
if (regexAllowed && i >= regexFailLineEnd) {
|
|
380
|
+
let j = i + 1;
|
|
381
|
+
let inClass = false;
|
|
382
|
+
let closed = false;
|
|
383
|
+
while (j < n) {
|
|
384
|
+
const ch = text.charCodeAt(j);
|
|
385
|
+
if (ch === 92 /* \ */) {
|
|
386
|
+
const escaped = text.charCodeAt(j + 1);
|
|
387
|
+
if (escaped === 10 || escaped === 13 || j + 1 >= n)
|
|
388
|
+
break;
|
|
389
|
+
j += 2;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (ch === 10 || ch === 13)
|
|
393
|
+
break;
|
|
394
|
+
if (ch === 91 /* [ */) {
|
|
395
|
+
inClass = true;
|
|
396
|
+
j++;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
if (ch === 93 /* ] */ && inClass) {
|
|
400
|
+
inClass = false;
|
|
401
|
+
j++;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (ch === 47 /* / */ && !inClass) {
|
|
405
|
+
closed = true;
|
|
406
|
+
j++;
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
j++;
|
|
410
|
+
}
|
|
411
|
+
if (closed) {
|
|
412
|
+
i = j;
|
|
413
|
+
regexAllowed = false;
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
// Failed scan reached EOL/EOF without closing `/`; never re-scan this line (guarantees <= 2N).
|
|
417
|
+
regexFailLineEnd = j;
|
|
418
|
+
}
|
|
419
|
+
i++;
|
|
420
|
+
regexAllowed = true;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (c === 60 /* < */ && text.charCodeAt(i + 1) === 47 /* / */) {
|
|
424
|
+
// JSX closing tag `</tag>` or fragment `</>` is never a `< /regex/`.
|
|
425
|
+
i += 2;
|
|
426
|
+
regexAllowed = false;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (c === 96 /* ` */) {
|
|
430
|
+
i++;
|
|
431
|
+
scanTemplateText();
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (c === 123 /* { */) {
|
|
435
|
+
if (templateBraceStack.length > 0)
|
|
436
|
+
templateBraceStack[templateBraceStack.length - 1]++;
|
|
437
|
+
i++;
|
|
438
|
+
regexAllowed = true;
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (c === 125 /* } */) {
|
|
442
|
+
if (templateBraceStack.length > 0) {
|
|
443
|
+
const top = templateBraceStack[templateBraceStack.length - 1];
|
|
444
|
+
if (top > 0) {
|
|
445
|
+
templateBraceStack[templateBraceStack.length - 1] = top - 1;
|
|
446
|
+
i++;
|
|
447
|
+
regexAllowed = true;
|
|
448
|
+
}
|
|
449
|
+
else {
|
|
450
|
+
templateBraceStack.pop();
|
|
451
|
+
i++;
|
|
452
|
+
scanTemplateText();
|
|
453
|
+
}
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
i++;
|
|
457
|
+
regexAllowed = true;
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
if (c === 39 || c === 34) {
|
|
461
|
+
let j = i + 1;
|
|
462
|
+
let closed = false;
|
|
463
|
+
let escaped = false;
|
|
464
|
+
while (j < n) {
|
|
465
|
+
const ch = text.charCodeAt(j);
|
|
466
|
+
if (ch === 92) {
|
|
467
|
+
escaped = true;
|
|
468
|
+
j += 2;
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (ch === c) {
|
|
472
|
+
closed = true;
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
if (ch === 10 || ch === 13)
|
|
476
|
+
break;
|
|
477
|
+
j++;
|
|
478
|
+
}
|
|
479
|
+
if (closed && !escaped) {
|
|
480
|
+
const value = text.slice(i + 1, j);
|
|
481
|
+
if (isLocalSpecifier(value) && !seen.has(value) && isImportContext(text, i)) {
|
|
482
|
+
seen.add(value);
|
|
483
|
+
out.push(value);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
i = closed ? j + 1 : Math.min(n, j);
|
|
487
|
+
regexAllowed = false;
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (isIdentStart(c)) {
|
|
491
|
+
let j = i + 1;
|
|
492
|
+
while (j < n && isIdent(text.charCodeAt(j)))
|
|
493
|
+
j++;
|
|
494
|
+
const len = j - i;
|
|
495
|
+
regexAllowed = len <= 10 && REGEX_PRECEDING_KEYWORDS.has(text.slice(i, j));
|
|
496
|
+
i = j;
|
|
497
|
+
continue;
|
|
498
|
+
}
|
|
499
|
+
if (c >= 48 && c <= 57) {
|
|
500
|
+
let j = i + 1;
|
|
501
|
+
while (j < n) {
|
|
502
|
+
const ch = text.charCodeAt(j);
|
|
503
|
+
if (isIdent(ch) || ch === 46)
|
|
504
|
+
j++;
|
|
505
|
+
else
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
i = j;
|
|
509
|
+
regexAllowed = false;
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (c === 41 /* ) */ || c === 93 /* ] */) {
|
|
513
|
+
i++;
|
|
514
|
+
regexAllowed = false;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if ((c === 43 || c === 45) && text.charCodeAt(i + 1) === c) {
|
|
518
|
+
i += 2;
|
|
519
|
+
regexAllowed = false;
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
if (c === 40 || c === 91 || c === 59 || c === 44 || c === 58 || c === 63 || c === 61 ||
|
|
523
|
+
c === 33 || c === 38 || c === 124 || c === 94 || c === 126 || c === 42 || c === 37 ||
|
|
524
|
+
c === 43 || c === 45 || c === 60 || c === 62) {
|
|
525
|
+
i++;
|
|
526
|
+
regexAllowed = true;
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
i++;
|
|
530
|
+
}
|
|
531
|
+
return out;
|
|
532
|
+
}
|
|
533
|
+
function resolveLocalImport(fromRel, spec, files) {
|
|
534
|
+
const cleaned = spec.split(/[?#]/)[0] ?? "";
|
|
535
|
+
const dir = path.posix.dirname(fromRel);
|
|
536
|
+
let base = path.posix.normalize(path.posix.join(dir === "." ? "" : dir, cleaned));
|
|
537
|
+
if (base.endsWith("/"))
|
|
538
|
+
base = base.slice(0, -1);
|
|
539
|
+
if (base === ".")
|
|
540
|
+
base = "";
|
|
541
|
+
if (base === ".." || base.startsWith("../") || base.startsWith("/"))
|
|
542
|
+
return null;
|
|
543
|
+
const candidates = [];
|
|
544
|
+
if (base) {
|
|
545
|
+
candidates.push(base);
|
|
546
|
+
const ext = path.posix.extname(base);
|
|
547
|
+
const stem = base.slice(0, base.length - ext.length);
|
|
548
|
+
if (ext === ".js")
|
|
549
|
+
candidates.push(`${stem}.ts`, `${stem}.tsx`);
|
|
550
|
+
else if (ext === ".jsx")
|
|
551
|
+
candidates.push(`${stem}.tsx`);
|
|
552
|
+
else if (ext === ".mjs")
|
|
553
|
+
candidates.push(`${stem}.mts`);
|
|
554
|
+
else if (ext === ".cjs")
|
|
555
|
+
candidates.push(`${stem}.cts`);
|
|
556
|
+
for (const e of RESOLVE_EXTS)
|
|
557
|
+
candidates.push(base + e);
|
|
558
|
+
}
|
|
559
|
+
const prefix = base ? `${base}/` : "";
|
|
560
|
+
for (const idx of INDEX_FILES)
|
|
561
|
+
candidates.push(prefix + idx);
|
|
562
|
+
for (const cand of candidates) {
|
|
563
|
+
if (files.has(cand))
|
|
564
|
+
return cand;
|
|
565
|
+
}
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
function readPrefix(abs, maxBytes) {
|
|
569
|
+
const fd = fs.openSync(abs, "r");
|
|
570
|
+
try {
|
|
571
|
+
const st = fs.fstatSync(fd);
|
|
572
|
+
if (!st.isFile())
|
|
573
|
+
return { text: "", truncated: true };
|
|
574
|
+
const size = st.size;
|
|
575
|
+
const len = Math.min(size, maxBytes);
|
|
576
|
+
const buf = Buffer.alloc(len);
|
|
577
|
+
let off = 0;
|
|
578
|
+
while (off < len) {
|
|
579
|
+
const read = fs.readSync(fd, buf, off, len - off, off);
|
|
580
|
+
if (read <= 0)
|
|
581
|
+
break;
|
|
582
|
+
off += read;
|
|
583
|
+
}
|
|
584
|
+
return { text: buf.toString("utf8", 0, off), truncated: size > maxBytes };
|
|
585
|
+
}
|
|
586
|
+
finally {
|
|
587
|
+
fs.closeSync(fd);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/** True when `buildLocalImportGraph` hit a file-count/size/read bound, so edges may be missing. */
|
|
591
|
+
export function isImportGraphTruncated(graph) {
|
|
592
|
+
return !!graph && typeof graph === "object" && TRUNCATED_GRAPHS.has(graph);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Bounded BFS scan of `cwd` building `Map<fileRelPosix, Set<importedFileRelPosix>>` from
|
|
596
|
+
* static local relative imports. Skips build/vendor/vault dirs and symlinks escaping `cwd`
|
|
597
|
+
* or targeting vault/holdout/skipped directories or already-visited directories (cycle-safe).
|
|
598
|
+
*/
|
|
599
|
+
export function buildLocalImportGraph(cwd, options = {}) {
|
|
600
|
+
if (typeof cwd !== "string" || !cwd.trim() || PATH_CONTROL_RE.test(cwd)) {
|
|
601
|
+
throw configError("buildLocalImportGraph requires a directory.");
|
|
602
|
+
}
|
|
603
|
+
const maxFiles = clampInt(own(options, "maxFiles"), MAX_IMPACT_GRAPH_FILES, 1, 100_000);
|
|
604
|
+
const maxFileBytes = clampInt(own(options, "maxFileBytes"), MAX_IMPACT_FILE_BYTES, 1, 64 * 1024 * 1024);
|
|
605
|
+
const maxEntries = maxFiles * 50;
|
|
606
|
+
const root = path.resolve(cwd);
|
|
607
|
+
let rootReal;
|
|
608
|
+
try {
|
|
609
|
+
rootReal = fs.realpathSync(root);
|
|
610
|
+
if (!fs.statSync(rootReal).isDirectory())
|
|
611
|
+
throw new Error("not a directory");
|
|
612
|
+
}
|
|
613
|
+
catch {
|
|
614
|
+
throw configError("Impact graph root is not a readable directory.");
|
|
615
|
+
}
|
|
616
|
+
const dirKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
|
617
|
+
const hasActiveVaultEnv = Boolean(process.env.VIBECODE_VAULT_DIR?.trim());
|
|
618
|
+
const visitedRealDirs = new Set([dirKey(rootReal)]);
|
|
619
|
+
const codeFiles = [];
|
|
620
|
+
const allFiles = new Set();
|
|
621
|
+
const queue = [{ rel: "", real: rootReal }];
|
|
622
|
+
let truncated = false;
|
|
623
|
+
let entries = 0;
|
|
624
|
+
scan: for (let qi = 0; qi < queue.length; qi++) {
|
|
625
|
+
const current = queue[qi];
|
|
626
|
+
if (!current)
|
|
627
|
+
continue;
|
|
628
|
+
const relDir = current.rel;
|
|
629
|
+
const absDir = current.real;
|
|
630
|
+
let dirents;
|
|
631
|
+
try {
|
|
632
|
+
dirents = fs.readdirSync(absDir, { withFileTypes: true });
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
truncated = true;
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
dirents.sort((a, b) => cmp(a.name, b.name));
|
|
639
|
+
for (const d of dirents) {
|
|
640
|
+
if (++entries > maxEntries) {
|
|
641
|
+
truncated = true;
|
|
642
|
+
break scan;
|
|
643
|
+
}
|
|
644
|
+
const name = d.name;
|
|
645
|
+
if (hasVaultOrHoldoutSegment(name))
|
|
646
|
+
continue;
|
|
647
|
+
const rel = relDir ? `${relDir}/${name}` : name;
|
|
648
|
+
const childAbs = path.join(absDir, name);
|
|
649
|
+
let isDir = d.isDirectory();
|
|
650
|
+
let isFile = d.isFile();
|
|
651
|
+
let resolvedDirReal = childAbs;
|
|
652
|
+
if (d.isSymbolicLink()) {
|
|
653
|
+
let real;
|
|
654
|
+
try {
|
|
655
|
+
real = fs.realpathSync(childAbs);
|
|
656
|
+
}
|
|
657
|
+
catch {
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
if (!isPathWithinDir(real, rootReal))
|
|
661
|
+
continue; // refuse symlinks escaping cwd
|
|
662
|
+
const realRelPosix = path.relative(rootReal, real).replace(/\\/g, "/");
|
|
663
|
+
if (realRelPosix) {
|
|
664
|
+
if (hasVaultOrHoldoutSegment(realRelPosix))
|
|
665
|
+
continue; // refuse symlinks into .vibecode-vault / holdouts
|
|
666
|
+
if (realRelPosix.split("/").some((seg) => SKIP_DIRS.has(seg)))
|
|
667
|
+
continue;
|
|
668
|
+
if (isSecretRelativePath(realRelPosix, { allowEnvExample: true }))
|
|
669
|
+
continue; // refuse symlinks into .env / secret files
|
|
670
|
+
}
|
|
671
|
+
if (isInsideVaultDirectory(real))
|
|
672
|
+
continue;
|
|
673
|
+
try {
|
|
674
|
+
const st = fs.statSync(real);
|
|
675
|
+
isDir = st.isDirectory();
|
|
676
|
+
isFile = st.isFile();
|
|
677
|
+
}
|
|
678
|
+
catch {
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
resolvedDirReal = real;
|
|
682
|
+
}
|
|
683
|
+
else if (hasActiveVaultEnv && isInsideVaultDirectory(childAbs)) {
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (isDir) {
|
|
687
|
+
if (SKIP_DIRS.has(name))
|
|
688
|
+
continue;
|
|
689
|
+
const key = dirKey(resolvedDirReal);
|
|
690
|
+
if (visitedRealDirs.has(key))
|
|
691
|
+
continue;
|
|
692
|
+
visitedRealDirs.add(key);
|
|
693
|
+
queue.push({ rel, real: resolvedDirReal });
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (!isFile || isSecretRelativePath(rel, { allowEnvExample: true }))
|
|
697
|
+
continue;
|
|
698
|
+
allFiles.add(rel);
|
|
699
|
+
const lowerName = name.toLowerCase();
|
|
700
|
+
if (CODE_EXTS.has(extOf(lowerName)) && !lowerName.endsWith(".min.js")) {
|
|
701
|
+
if (codeFiles.length >= maxFiles) {
|
|
702
|
+
truncated = true;
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
codeFiles.push(rel);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
const graph = new Map();
|
|
710
|
+
for (const rel of codeFiles) {
|
|
711
|
+
let text = "";
|
|
712
|
+
try {
|
|
713
|
+
const res = readPrefix(path.join(root, ...rel.split("/")), maxFileBytes);
|
|
714
|
+
text = res.text;
|
|
715
|
+
if (res.truncated)
|
|
716
|
+
truncated = true;
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
truncated = true;
|
|
720
|
+
}
|
|
721
|
+
const deps = [];
|
|
722
|
+
for (const spec of extractLocalImportSpecifiers(text)) {
|
|
723
|
+
const resolved = resolveLocalImport(rel, spec, allFiles);
|
|
724
|
+
if (resolved && resolved !== rel)
|
|
725
|
+
deps.push(resolved);
|
|
726
|
+
}
|
|
727
|
+
graph.set(rel, new Set(sortedUnique(deps)));
|
|
728
|
+
}
|
|
729
|
+
if (truncated)
|
|
730
|
+
TRUNCATED_GRAPHS.add(graph);
|
|
731
|
+
return graph;
|
|
732
|
+
}
|
|
733
|
+
function buildReverseGraph(graph) {
|
|
734
|
+
const reverse = new Map();
|
|
735
|
+
try {
|
|
736
|
+
if (!graph || typeof graph.forEach !== "function")
|
|
737
|
+
return reverse;
|
|
738
|
+
graph.forEach((deps, importer) => {
|
|
739
|
+
if (typeof importer !== "string" || hasVaultOrHoldoutSegment(importer))
|
|
740
|
+
return;
|
|
741
|
+
if (!deps || typeof deps.forEach !== "function")
|
|
742
|
+
return;
|
|
743
|
+
deps.forEach((dep) => {
|
|
744
|
+
if (typeof dep !== "string" || hasVaultOrHoldoutSegment(dep))
|
|
745
|
+
return;
|
|
746
|
+
const list = reverse.get(dep);
|
|
747
|
+
if (list)
|
|
748
|
+
list.push(importer);
|
|
749
|
+
else
|
|
750
|
+
reverse.set(dep, [importer]);
|
|
751
|
+
});
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
catch {
|
|
755
|
+
// Hostile or malformed graph maps degrade safely to an empty reverse map.
|
|
756
|
+
}
|
|
757
|
+
return reverse;
|
|
758
|
+
}
|
|
759
|
+
function countGraphNodes(graph) {
|
|
760
|
+
const nodes = new Set();
|
|
761
|
+
try {
|
|
762
|
+
if (!graph || typeof graph.forEach !== "function")
|
|
763
|
+
return nodes;
|
|
764
|
+
graph.forEach((deps, importer) => {
|
|
765
|
+
if (typeof importer === "string" && !hasVaultOrHoldoutSegment(importer))
|
|
766
|
+
nodes.add(importer);
|
|
767
|
+
if (deps && typeof deps.forEach === "function") {
|
|
768
|
+
deps.forEach((d) => {
|
|
769
|
+
if (typeof d === "string" && !hasVaultOrHoldoutSegment(d))
|
|
770
|
+
nodes.add(d);
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
// Ignore hostile graph traps.
|
|
777
|
+
}
|
|
778
|
+
return nodes;
|
|
779
|
+
}
|
|
780
|
+
function bfsImporters(reverse, starts) {
|
|
781
|
+
const seen = new Set(starts);
|
|
782
|
+
const queue = [...starts];
|
|
783
|
+
for (let qi = 0; qi < queue.length; qi++) {
|
|
784
|
+
const importers = reverse.get(queue[qi] ?? "");
|
|
785
|
+
if (!importers)
|
|
786
|
+
continue;
|
|
787
|
+
for (const imp of importers) {
|
|
788
|
+
if (!seen.has(imp)) {
|
|
789
|
+
seen.add(imp);
|
|
790
|
+
queue.push(imp);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return seen;
|
|
795
|
+
}
|
|
796
|
+
/** Cycle-safe reverse-import BFS; returns sorted unique paths including the changed files. */
|
|
797
|
+
export function collectTransitiveImporters(changedFiles, graph) {
|
|
798
|
+
let raw = [];
|
|
799
|
+
if (safeIsArray(changedFiles)) {
|
|
800
|
+
try {
|
|
801
|
+
raw = [...changedFiles];
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
raw = [];
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const starts = normalizeList(raw);
|
|
808
|
+
return [...bfsImporters(buildReverseGraph(graph), starts)].sort(cmp);
|
|
809
|
+
}
|
|
810
|
+
function tokenize(s) {
|
|
811
|
+
return s.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
812
|
+
}
|
|
813
|
+
function looksLikeFileToken(tok) {
|
|
814
|
+
if (!tok || tok.includes("://") || tok.startsWith("-"))
|
|
815
|
+
return false;
|
|
816
|
+
return tok.includes("/") || tok.includes("\\") || /\.[A-Za-z0-9]{1,8}$/.test(tok);
|
|
817
|
+
}
|
|
818
|
+
function fileTokensFromCommand(value, push) {
|
|
819
|
+
const parts = [];
|
|
820
|
+
const pushSplit = (str) => {
|
|
821
|
+
const bounded = str.length > 8192 ? str.slice(0, 8192) : str;
|
|
822
|
+
for (const piece of bounded.split(/\s+/)) {
|
|
823
|
+
if (parts.length >= MAX_REF_TOKENS)
|
|
824
|
+
return;
|
|
825
|
+
if (piece)
|
|
826
|
+
parts.push(piece);
|
|
827
|
+
}
|
|
828
|
+
};
|
|
829
|
+
if (typeof value === "string") {
|
|
830
|
+
pushSplit(value);
|
|
831
|
+
}
|
|
832
|
+
else if (safeIsArray(value)) {
|
|
833
|
+
try {
|
|
834
|
+
for (const v of value) {
|
|
835
|
+
if (parts.length >= MAX_REF_TOKENS)
|
|
836
|
+
break;
|
|
837
|
+
if (typeof v === "string")
|
|
838
|
+
pushSplit(v);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
catch {
|
|
842
|
+
// Ignore hostile array traps.
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
for (let raw of parts) {
|
|
846
|
+
raw = raw.replace(/^['"]+|['"]+$/g, "");
|
|
847
|
+
if (raw.startsWith("-")) {
|
|
848
|
+
const eq = raw.indexOf("=");
|
|
849
|
+
if (eq < 0)
|
|
850
|
+
continue;
|
|
851
|
+
raw = raw.slice(eq + 1);
|
|
852
|
+
}
|
|
853
|
+
if (looksLikeFileToken(raw))
|
|
854
|
+
push(raw);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function collectRouteStrings(value, out, depth, seen) {
|
|
858
|
+
if (out.length >= MAX_ROUTE_STRINGS || depth > 3 || value === null || typeof value !== "object")
|
|
859
|
+
return;
|
|
860
|
+
if (seen.has(value))
|
|
861
|
+
return;
|
|
862
|
+
seen.add(value);
|
|
863
|
+
if (safeIsArray(value)) {
|
|
864
|
+
try {
|
|
865
|
+
let count = 0;
|
|
866
|
+
for (const item of value) {
|
|
867
|
+
if (count++ >= MAX_ROUTE_STRINGS || out.length >= MAX_ROUTE_STRINGS)
|
|
868
|
+
break;
|
|
869
|
+
collectRouteStrings(item, out, depth + 1, seen);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
catch {
|
|
873
|
+
// Ignore hostile array traps.
|
|
874
|
+
}
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (!isRecord(value))
|
|
878
|
+
return;
|
|
879
|
+
for (const key of ROUTE_KEYS) {
|
|
880
|
+
const v = own(value, key);
|
|
881
|
+
if (typeof v === "string" && out.length < MAX_ROUTE_STRINGS)
|
|
882
|
+
out.push(v.slice(0, 2048));
|
|
883
|
+
}
|
|
884
|
+
for (const nested of ["request", "steps", "finallySteps"]) {
|
|
885
|
+
const nv = own(value, nested);
|
|
886
|
+
if (nv !== undefined)
|
|
887
|
+
collectRouteStrings(nv, out, depth + 1, seen);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
function jsToTsVariants(ref) {
|
|
891
|
+
const ext = path.posix.extname(ref);
|
|
892
|
+
const stem = ref.slice(0, ref.length - ext.length);
|
|
893
|
+
if (ext === ".js")
|
|
894
|
+
return [ref, `${stem}.ts`, `${stem}.tsx`];
|
|
895
|
+
if (ext === ".jsx")
|
|
896
|
+
return [ref, `${stem}.tsx`];
|
|
897
|
+
if (ext === ".mjs")
|
|
898
|
+
return [ref, `${stem}.mts`];
|
|
899
|
+
if (ext === ".cjs")
|
|
900
|
+
return [ref, `${stem}.cts`];
|
|
901
|
+
return [ref];
|
|
902
|
+
}
|
|
903
|
+
function prepareInvariants(contract, entries, cwd) {
|
|
904
|
+
const target = own(contract, "target");
|
|
905
|
+
const rawSources = own(target, "sources");
|
|
906
|
+
const sources = [];
|
|
907
|
+
if (safeIsArray(rawSources)) {
|
|
908
|
+
try {
|
|
909
|
+
for (const s of rawSources)
|
|
910
|
+
sources.push(s);
|
|
911
|
+
}
|
|
912
|
+
catch {
|
|
913
|
+
// Ignore hostile sources array traps.
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const sourceRefs = new Map();
|
|
917
|
+
for (const src of sources) {
|
|
918
|
+
const srcId = own(src, "id");
|
|
919
|
+
if (typeof srcId !== "string")
|
|
920
|
+
continue;
|
|
921
|
+
const refs = [];
|
|
922
|
+
fileTokensFromCommand(own(src, "ref"), (tok) => {
|
|
923
|
+
const norm = normalizeRelPath(tok, cwd);
|
|
924
|
+
if (norm)
|
|
925
|
+
refs.push(...jsToTsVariants(norm));
|
|
926
|
+
});
|
|
927
|
+
const srcKind = own(src, "kind");
|
|
928
|
+
sourceRefs.set(srcId, { kind: typeof srcKind === "string" ? srcKind : "", refs });
|
|
929
|
+
}
|
|
930
|
+
return entries.map(({ inv, id, domain }, index) => {
|
|
931
|
+
const rawInput = own(inv, "input");
|
|
932
|
+
const input = isRecord(rawInput) ? rawInput : {};
|
|
933
|
+
const refs = new Set();
|
|
934
|
+
const addRef = (raw) => {
|
|
935
|
+
const norm = normalizeRelPath(raw, cwd);
|
|
936
|
+
if (norm)
|
|
937
|
+
for (const v of jsToTsVariants(norm))
|
|
938
|
+
refs.add(v);
|
|
939
|
+
};
|
|
940
|
+
// URL paths like "/users" normalize to null unless they are real files inside `cwd`.
|
|
941
|
+
for (const key of FILE_REF_KEYS)
|
|
942
|
+
addRef(own(input, key));
|
|
943
|
+
for (const key of COMMAND_KEYS)
|
|
944
|
+
fileTokensFromCommand(own(input, key), addRef);
|
|
945
|
+
const invSourceId = own(inv, "sourceId");
|
|
946
|
+
for (const [srcId, src] of sourceRefs) {
|
|
947
|
+
const applies = typeof invSourceId === "string" ? invSourceId === srcId : src.kind === domain || sources.length === 1;
|
|
948
|
+
if (applies)
|
|
949
|
+
for (const r of src.refs)
|
|
950
|
+
refs.add(r);
|
|
951
|
+
}
|
|
952
|
+
const routeStrings = [];
|
|
953
|
+
collectRouteStrings(input, routeStrings, 0, new WeakSet());
|
|
954
|
+
routeStrings.push(id);
|
|
955
|
+
const desc = own(inv, "description");
|
|
956
|
+
if (typeof desc === "string")
|
|
957
|
+
routeStrings.push(desc.slice(0, 4096));
|
|
958
|
+
const tags = own(inv, "tags");
|
|
959
|
+
if (safeIsArray(tags)) {
|
|
960
|
+
try {
|
|
961
|
+
let count = 0;
|
|
962
|
+
for (const t of tags) {
|
|
963
|
+
if (count++ >= 64)
|
|
964
|
+
break;
|
|
965
|
+
if (typeof t === "string")
|
|
966
|
+
routeStrings.push(t.slice(0, 256));
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
catch {
|
|
970
|
+
// Ignore hostile tags array traps.
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
const routeTokens = routeStrings.map(tokenize).filter((t) => t.length > 0);
|
|
974
|
+
const rawType = own(inv, "type");
|
|
975
|
+
const type = typeof rawType === "string" ? rawType : "";
|
|
976
|
+
const rawPerfKind = type === "perf_budget" ? own(input, "kind") : undefined;
|
|
977
|
+
const perfKind = typeof rawPerfKind === "string" ? rawPerfKind.trim().toLowerCase() : undefined;
|
|
978
|
+
return {
|
|
979
|
+
index,
|
|
980
|
+
id,
|
|
981
|
+
domain,
|
|
982
|
+
type,
|
|
983
|
+
...(perfKind ? { perfKind } : {}),
|
|
984
|
+
refs: [...refs],
|
|
985
|
+
routeTokens
|
|
986
|
+
};
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
function refMatchesFile(ref, file) {
|
|
990
|
+
return file === ref || file.startsWith(`${ref}/`) || file.endsWith(`/${ref}`);
|
|
991
|
+
}
|
|
992
|
+
function pluralEq(a, b) {
|
|
993
|
+
return a === b || `${a}s` === b || a === `${b}s` || `${a}es` === b || a === `${b}es`;
|
|
994
|
+
}
|
|
995
|
+
function windowMatches(tokens, stem) {
|
|
996
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
997
|
+
let acc = "";
|
|
998
|
+
for (let j = i; j < tokens.length; j++) {
|
|
999
|
+
acc += tokens[j];
|
|
1000
|
+
if (pluralEq(acc, stem))
|
|
1001
|
+
return true;
|
|
1002
|
+
if (acc.length > stem.length + 2)
|
|
1003
|
+
break;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
return false;
|
|
1007
|
+
}
|
|
1008
|
+
/** Route stems for a file: the first dotted basename segment plus up to two non-generic parent dirs. */
|
|
1009
|
+
function routeStemsForFile(file) {
|
|
1010
|
+
const segs = file.toLowerCase().split("/");
|
|
1011
|
+
const base = segs[segs.length - 1] ?? "";
|
|
1012
|
+
const candidates = [base.split(".")[0] ?? "", segs[segs.length - 2] ?? "", segs[segs.length - 3] ?? ""];
|
|
1013
|
+
const out = [];
|
|
1014
|
+
for (const cand of candidates) {
|
|
1015
|
+
const joined = tokenize(cand).join("");
|
|
1016
|
+
if (joined.length >= 3 && !GENERIC_STEMS.has(joined) && !out.includes(joined))
|
|
1017
|
+
out.push(joined);
|
|
1018
|
+
}
|
|
1019
|
+
return out;
|
|
1020
|
+
}
|
|
1021
|
+
function affinityMatches(file, inv) {
|
|
1022
|
+
const { type, domain, perfKind } = inv;
|
|
1023
|
+
const lower = file.toLowerCase();
|
|
1024
|
+
const segs = lower.split("/");
|
|
1025
|
+
const base = segs[segs.length - 1] ?? "";
|
|
1026
|
+
const names = new Set(segs.slice(0, -1));
|
|
1027
|
+
names.add(base.split(".")[0] ?? "");
|
|
1028
|
+
const ext = extOf(base);
|
|
1029
|
+
const has = (set) => {
|
|
1030
|
+
for (const n of names)
|
|
1031
|
+
if (set.has(n))
|
|
1032
|
+
return true;
|
|
1033
|
+
return false;
|
|
1034
|
+
};
|
|
1035
|
+
const isCliPerf = type === "perf_budget" && (perfKind === "command" || (perfKind !== "http" && domain === "cli"));
|
|
1036
|
+
const isHttpPerf = type === "perf_budget" && !isCliPerf;
|
|
1037
|
+
if ((WEB_AFFINITY_EXTS.has(ext) || has(WEB_AFFINITY_SEGMENTS)) &&
|
|
1038
|
+
(type.startsWith("web_") || type.startsWith("image_") || (isHttpPerf && domain === "web"))) {
|
|
1039
|
+
return true;
|
|
1040
|
+
}
|
|
1041
|
+
if (has(CLI_AFFINITY_SEGMENTS) && (type === "command" || isCliPerf))
|
|
1042
|
+
return true;
|
|
1043
|
+
if (has(HTTP_AFFINITY_SEGMENTS) && (HTTP_TYPES.has(type) || isHttpPerf))
|
|
1044
|
+
return true;
|
|
1045
|
+
if (ext === ".svg" && type === "plugin_svg_a11y")
|
|
1046
|
+
return true;
|
|
1047
|
+
if (ext === ".json" && type === "plugin_state_file")
|
|
1048
|
+
return true;
|
|
1049
|
+
return false;
|
|
1050
|
+
}
|
|
1051
|
+
/** Tiered matching: explicit path + route token first; domain affinity only when nothing more precise matched. */
|
|
1052
|
+
function matchFile(file, prepared, explicitOnly) {
|
|
1053
|
+
const out = [];
|
|
1054
|
+
const stems = explicitOnly ? [] : routeStemsForFile(file);
|
|
1055
|
+
for (const inv of prepared) {
|
|
1056
|
+
if (inv.refs.some((r) => refMatchesFile(r, file)))
|
|
1057
|
+
out.push({ index: inv.index, kind: "explicit_path" });
|
|
1058
|
+
else if (stems.some((s) => inv.routeTokens.some((t) => windowMatches(t, s))))
|
|
1059
|
+
out.push({ index: inv.index, kind: "route_token" });
|
|
1060
|
+
}
|
|
1061
|
+
if (out.length > 0 || explicitOnly)
|
|
1062
|
+
return out;
|
|
1063
|
+
for (const inv of prepared) {
|
|
1064
|
+
if (affinityMatches(file, inv))
|
|
1065
|
+
out.push({ index: inv.index, kind: "domain_affinity" });
|
|
1066
|
+
}
|
|
1067
|
+
return out;
|
|
1068
|
+
}
|
|
1069
|
+
// ---------------------------------------------------------------------------
|
|
1070
|
+
// analysis
|
|
1071
|
+
// ---------------------------------------------------------------------------
|
|
1072
|
+
function isContractFile(p) {
|
|
1073
|
+
const lower = p.toLowerCase();
|
|
1074
|
+
return (lower === CONTRACT_PATH ||
|
|
1075
|
+
lower.endsWith(`/${CONTRACT_PATH}`) ||
|
|
1076
|
+
lower === ".vibecode/contract.lock.json" ||
|
|
1077
|
+
lower.endsWith("/.vibecode/contract.lock.json"));
|
|
1078
|
+
}
|
|
1079
|
+
function isVibecodeEphemeralOutput(p) {
|
|
1080
|
+
const lower = p.toLowerCase();
|
|
1081
|
+
const base = lower.endsWith(".tmp") ? lower.slice(0, -4) : lower;
|
|
1082
|
+
if (VIBECODE_EPHEMERAL_FILES.has(base))
|
|
1083
|
+
return true;
|
|
1084
|
+
if (lower.startsWith(".vibecode/trends.ndjson.tmp") || (lower.startsWith(".vibecode/trends.ndjson.") && lower.endsWith(".tmp"))) {
|
|
1085
|
+
return true;
|
|
1086
|
+
}
|
|
1087
|
+
return lower.startsWith(".vibecode/cache/") || lower.startsWith(".vibecode/artifacts/");
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Maps changed files to impacted invariants/slices with fail-closed fallbacks to a full run.
|
|
1091
|
+
*/
|
|
1092
|
+
export function analyzeImpact(contract, changedFiles, options = {}) {
|
|
1093
|
+
const rawInvariants = own(contract, "invariants");
|
|
1094
|
+
if (!isRecord(contract) || !safeIsArray(rawInvariants)) {
|
|
1095
|
+
throw new VibecodeError("CONTRACT_INVALID", "analyzeImpact requires a contract with an invariants array.");
|
|
1096
|
+
}
|
|
1097
|
+
const seenIds = new Set();
|
|
1098
|
+
const entries = [];
|
|
1099
|
+
try {
|
|
1100
|
+
for (const inv of rawInvariants) {
|
|
1101
|
+
const id = own(inv, "id");
|
|
1102
|
+
if (isRecord(inv) && typeof id === "string" && id && !seenIds.has(id)) {
|
|
1103
|
+
seenIds.add(id);
|
|
1104
|
+
entries.push({ inv, id, domain: safeInferDomain(inv) });
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
catch {
|
|
1109
|
+
throw new VibecodeError("CONTRACT_INVALID", "analyzeImpact could not read contract.invariants safely.");
|
|
1110
|
+
}
|
|
1111
|
+
const indexById = new Map(entries.map((entry, i) => [entry.id, i]));
|
|
1112
|
+
const prevFailedSet = new Set();
|
|
1113
|
+
const rawPrevFailed = own(options, "previousFailedIds");
|
|
1114
|
+
if (safeIsArray(rawPrevFailed)) {
|
|
1115
|
+
try {
|
|
1116
|
+
for (const id of rawPrevFailed) {
|
|
1117
|
+
const idx = typeof id === "string" ? indexById.get(id) : undefined;
|
|
1118
|
+
if (idx !== undefined)
|
|
1119
|
+
prevFailedSet.add(idx);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
catch {
|
|
1123
|
+
// Ignore hostile previousFailedIds traps.
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
const rawCwd = own(options, "cwd");
|
|
1127
|
+
const cwd = typeof rawCwd === "string" && rawCwd.trim() ? rawCwd : undefined;
|
|
1128
|
+
const selectAllOnEmpty = own(options, "selectAllOnEmpty") === true;
|
|
1129
|
+
const includeSlices = own(options, "includeSlices") !== false;
|
|
1130
|
+
const rawGraph = own(options, "graph");
|
|
1131
|
+
let rawList = [];
|
|
1132
|
+
let tooMany = false;
|
|
1133
|
+
if (safeIsArray(changedFiles)) {
|
|
1134
|
+
try {
|
|
1135
|
+
let count = 0;
|
|
1136
|
+
for (const item of changedFiles) {
|
|
1137
|
+
if (count >= MAX_IMPACT_FILES_INPUT) {
|
|
1138
|
+
tooMany = true;
|
|
1139
|
+
break;
|
|
1140
|
+
}
|
|
1141
|
+
rawList.push(item);
|
|
1142
|
+
count++;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
catch {
|
|
1146
|
+
rawList = [];
|
|
1147
|
+
tooMany = true; // Fail closed if changedFiles array throws during iteration.
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
const changed = normalizeList(rawList, cwd).filter((p) => !isVibecodeEphemeralOutput(p));
|
|
1151
|
+
const changedSet = new Set(changed);
|
|
1152
|
+
const records = new Map();
|
|
1153
|
+
const record = (index, kind, file) => {
|
|
1154
|
+
let rec = records.get(index);
|
|
1155
|
+
if (!rec) {
|
|
1156
|
+
rec = { kinds: new Set(), files: new Set() };
|
|
1157
|
+
records.set(index, rec);
|
|
1158
|
+
}
|
|
1159
|
+
rec.kinds.add(kind);
|
|
1160
|
+
if (file)
|
|
1161
|
+
rec.files.add(file);
|
|
1162
|
+
};
|
|
1163
|
+
for (const idx of prevFailedSet)
|
|
1164
|
+
record(idx, "previous_failure");
|
|
1165
|
+
let transitive = [];
|
|
1166
|
+
const finalize = (fallbackReason, docsOnly = false) => {
|
|
1167
|
+
const fallbackToFull = fallbackReason !== "none";
|
|
1168
|
+
const selectedIdx = fallbackToFull ? new Set(entries.map((_, i) => i)) : new Set(records.keys());
|
|
1169
|
+
const selectedInvariantIds = [];
|
|
1170
|
+
const skippedInvariantIds = [];
|
|
1171
|
+
entries.forEach((entry, i) => (selectedIdx.has(i) ? selectedInvariantIds : skippedInvariantIds).push(entry.id));
|
|
1172
|
+
const matches = [];
|
|
1173
|
+
entries.forEach((entry, i) => {
|
|
1174
|
+
const rec = records.get(i);
|
|
1175
|
+
if (!rec)
|
|
1176
|
+
return;
|
|
1177
|
+
matches.push({
|
|
1178
|
+
id: sanitizeSingleLine(entry.id, 240) || `invariant-${i + 1}`,
|
|
1179
|
+
domain: entry.domain,
|
|
1180
|
+
matchedBy: MATCH_KIND_ORDER.filter((k) => rec.kinds.has(k)),
|
|
1181
|
+
files: sortedUnique([...rec.files].map((f) => redactSensitiveText(f)))
|
|
1182
|
+
});
|
|
1183
|
+
});
|
|
1184
|
+
const affectedSliceIds = [];
|
|
1185
|
+
const seenSlices = new Set();
|
|
1186
|
+
const rawSlices = includeSlices ? own(contract, "slices") : undefined;
|
|
1187
|
+
if (safeIsArray(rawSlices)) {
|
|
1188
|
+
const selectedIds = new Set(selectedInvariantIds);
|
|
1189
|
+
try {
|
|
1190
|
+
for (const slice of rawSlices) {
|
|
1191
|
+
const sliceId = own(slice, "id");
|
|
1192
|
+
const sliceInvIds = own(slice, "invariantIds");
|
|
1193
|
+
if (typeof sliceId !== "string" || !safeIsArray(sliceInvIds) || seenSlices.has(sliceId))
|
|
1194
|
+
continue;
|
|
1195
|
+
let hit = false;
|
|
1196
|
+
try {
|
|
1197
|
+
for (const id of sliceInvIds) {
|
|
1198
|
+
if (typeof id === "string" && selectedIds.has(id)) {
|
|
1199
|
+
hit = true;
|
|
1200
|
+
break;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
catch {
|
|
1205
|
+
hit = false;
|
|
1206
|
+
}
|
|
1207
|
+
if (hit) {
|
|
1208
|
+
seenSlices.add(sliceId);
|
|
1209
|
+
affectedSliceIds.push(sliceId);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
catch {
|
|
1214
|
+
// Ignore hostile slices traps.
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
const total = entries.length;
|
|
1218
|
+
const skipped = skippedInvariantIds.length;
|
|
1219
|
+
return {
|
|
1220
|
+
changedFiles: changed.map((f) => redactSensitiveText(f)),
|
|
1221
|
+
transitiveFiles: transitive.map((f) => redactSensitiveText(f)),
|
|
1222
|
+
selectedInvariantIds,
|
|
1223
|
+
skippedInvariantIds,
|
|
1224
|
+
affectedSliceIds,
|
|
1225
|
+
fallbackToFull,
|
|
1226
|
+
fallbackReason,
|
|
1227
|
+
docsOnly,
|
|
1228
|
+
matches,
|
|
1229
|
+
summary: {
|
|
1230
|
+
total,
|
|
1231
|
+
selected: selectedInvariantIds.length,
|
|
1232
|
+
skipped,
|
|
1233
|
+
reductionPct: total > 0 ? Math.round((skipped / total) * 1000) / 10 : 0
|
|
1234
|
+
}
|
|
1235
|
+
};
|
|
1236
|
+
};
|
|
1237
|
+
// ponytail: an oversized change set is treated as a broad blast radius rather than partially analyzed.
|
|
1238
|
+
if (tooMany)
|
|
1239
|
+
return finalize("shared_hub");
|
|
1240
|
+
if (changed.some(isContractFile))
|
|
1241
|
+
return finalize("contract_changed");
|
|
1242
|
+
if (changed.some(isGlobalConfigFile))
|
|
1243
|
+
return finalize("global_config");
|
|
1244
|
+
if (changed.length === 0)
|
|
1245
|
+
return finalize(selectAllOnEmpty ? "empty_selection_full" : "none");
|
|
1246
|
+
const prepared = prepareInvariants(contract, entries, cwd);
|
|
1247
|
+
const docFiles = changed.filter(isDocFile);
|
|
1248
|
+
const codeFiles = changed.filter((f) => !isDocFile(f));
|
|
1249
|
+
let docMatched = false;
|
|
1250
|
+
for (const doc of docFiles) {
|
|
1251
|
+
for (const m of matchFile(doc, prepared, true)) {
|
|
1252
|
+
docMatched = true;
|
|
1253
|
+
record(m.index, m.kind, doc);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
if (codeFiles.length === 0 && !docMatched)
|
|
1257
|
+
return finalize("none", true);
|
|
1258
|
+
let graph = new Map();
|
|
1259
|
+
let hasGraphForEach = false;
|
|
1260
|
+
try {
|
|
1261
|
+
hasGraphForEach = Boolean(rawGraph && typeof rawGraph.forEach === "function");
|
|
1262
|
+
}
|
|
1263
|
+
catch {
|
|
1264
|
+
hasGraphForEach = false;
|
|
1265
|
+
}
|
|
1266
|
+
if (hasGraphForEach && rawGraph)
|
|
1267
|
+
graph = rawGraph;
|
|
1268
|
+
else if (cwd && codeFiles.length > 0)
|
|
1269
|
+
graph = buildLocalImportGraph(cwd);
|
|
1270
|
+
const reverse = buildReverseGraph(graph);
|
|
1271
|
+
const nodes = countGraphNodes(graph);
|
|
1272
|
+
const fileMatchCache = new Map();
|
|
1273
|
+
const transitiveSet = new Set();
|
|
1274
|
+
let sharedHub = false;
|
|
1275
|
+
let unmapped = false;
|
|
1276
|
+
for (const file of codeFiles) {
|
|
1277
|
+
const closure = bfsImporters(reverse, [file]);
|
|
1278
|
+
const matched = new Set();
|
|
1279
|
+
let inGraph = 0;
|
|
1280
|
+
for (const f of closure) {
|
|
1281
|
+
if (nodes.has(f))
|
|
1282
|
+
inGraph++;
|
|
1283
|
+
if (!changedSet.has(f))
|
|
1284
|
+
transitiveSet.add(f);
|
|
1285
|
+
let fm = fileMatchCache.get(f);
|
|
1286
|
+
if (!fm) {
|
|
1287
|
+
fm = matchFile(f, prepared, isDocFile(f));
|
|
1288
|
+
fileMatchCache.set(f, fm);
|
|
1289
|
+
}
|
|
1290
|
+
for (const m of fm) {
|
|
1291
|
+
matched.add(m.index);
|
|
1292
|
+
record(m.index, m.kind, f);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
if (matched.size === 0)
|
|
1296
|
+
unmapped = true;
|
|
1297
|
+
if (nodes.size >= 6 && inGraph / nodes.size > 0.6) {
|
|
1298
|
+
const domains = new Set();
|
|
1299
|
+
for (const idx of matched) {
|
|
1300
|
+
const p = prepared[idx];
|
|
1301
|
+
if (p)
|
|
1302
|
+
domains.add(p.domain);
|
|
1303
|
+
}
|
|
1304
|
+
if (domains.size >= 2)
|
|
1305
|
+
sharedHub = true;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
transitive = [...transitiveSet].sort(cmp);
|
|
1309
|
+
if (sharedHub)
|
|
1310
|
+
return finalize("shared_hub");
|
|
1311
|
+
if (unmapped || (codeFiles.length > 0 && isImportGraphTruncated(graph)))
|
|
1312
|
+
return finalize("unmapped_code_change");
|
|
1313
|
+
if (records.size === 0 && selectAllOnEmpty)
|
|
1314
|
+
return finalize("empty_selection_full");
|
|
1315
|
+
return finalize("none");
|
|
1316
|
+
}
|
|
1317
|
+
// ---------------------------------------------------------------------------
|
|
1318
|
+
// formatting
|
|
1319
|
+
// ---------------------------------------------------------------------------
|
|
1320
|
+
/** Renders an impact report for terminals: no ANSI unless `color: true`, all dynamic text sanitized. */
|
|
1321
|
+
export function formatPrettyImpact(report, options = {}) {
|
|
1322
|
+
const color = own(options, "color") === true;
|
|
1323
|
+
const paint = (code, text) => styleAnsi(text, code, color);
|
|
1324
|
+
const clean = (v, max = 240) => sanitizeSingleLine(safeString(v), max);
|
|
1325
|
+
const list = (items) => {
|
|
1326
|
+
if (!safeIsArray(items))
|
|
1327
|
+
return [];
|
|
1328
|
+
const out = [];
|
|
1329
|
+
try {
|
|
1330
|
+
for (const x of items)
|
|
1331
|
+
out.push(clean(x));
|
|
1332
|
+
}
|
|
1333
|
+
catch {
|
|
1334
|
+
// Ignore hostile array traps.
|
|
1335
|
+
}
|
|
1336
|
+
return out;
|
|
1337
|
+
};
|
|
1338
|
+
const r = isRecord(report) ? report : {};
|
|
1339
|
+
const rawSummary = own(r, "summary");
|
|
1340
|
+
const summary = isRecord(rawSummary) ? rawSummary : { total: 0, selected: 0, skipped: 0, reductionPct: 0 };
|
|
1341
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
1342
|
+
const lines = [];
|
|
1343
|
+
lines.push(paint(ANSI.bold, "Impact analysis: ") +
|
|
1344
|
+
`${num(own(summary, "selected"))}/${num(own(summary, "total"))} invariants selected, ${num(own(summary, "skipped"))} skipped (${num(own(summary, "reductionPct"))}% reduction)`);
|
|
1345
|
+
let mode;
|
|
1346
|
+
if (own(r, "fallbackToFull") === true)
|
|
1347
|
+
mode = paint(ANSI.yellow, `FULL RUN (fallback: ${clean(own(r, "fallbackReason"), 40)})`);
|
|
1348
|
+
else if (own(r, "docsOnly") === true)
|
|
1349
|
+
mode = paint(ANSI.green, "docs-only (re-checking previously failed invariants only)");
|
|
1350
|
+
else
|
|
1351
|
+
mode = paint(ANSI.green, "targeted");
|
|
1352
|
+
lines.push(`Mode: ${mode}`);
|
|
1353
|
+
const section = (title, items) => {
|
|
1354
|
+
lines.push(paint(ANSI.cyan, `${title} (${items.length}):`));
|
|
1355
|
+
if (items.length === 0) {
|
|
1356
|
+
lines.push(paint(ANSI.dim, " (none)"));
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
for (const item of items.slice(0, MAX_LIST_IN_PRETTY))
|
|
1360
|
+
lines.push(` - ${item}`);
|
|
1361
|
+
if (items.length > MAX_LIST_IN_PRETTY)
|
|
1362
|
+
lines.push(paint(ANSI.dim, ` ... and ${items.length - MAX_LIST_IN_PRETTY} more`));
|
|
1363
|
+
};
|
|
1364
|
+
section("Changed files", list(own(r, "changedFiles")));
|
|
1365
|
+
const transitiveFiles = list(own(r, "transitiveFiles"));
|
|
1366
|
+
if (transitiveFiles.length > 0)
|
|
1367
|
+
section("Transitive importers", transitiveFiles);
|
|
1368
|
+
const matchesById = new Map();
|
|
1369
|
+
const rawMatches = own(r, "matches");
|
|
1370
|
+
if (safeIsArray(rawMatches)) {
|
|
1371
|
+
try {
|
|
1372
|
+
for (const m of rawMatches) {
|
|
1373
|
+
const mId = own(m, "id");
|
|
1374
|
+
if (isRecord(m) && typeof mId === "string") {
|
|
1375
|
+
matchesById.set(mId, m);
|
|
1376
|
+
const cleanedId = clean(mId);
|
|
1377
|
+
if (cleanedId && !matchesById.has(cleanedId))
|
|
1378
|
+
matchesById.set(cleanedId, m);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
catch {
|
|
1383
|
+
// Ignore hostile matches array traps.
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
const selectedIds = [];
|
|
1387
|
+
const rawSelected = own(r, "selectedInvariantIds");
|
|
1388
|
+
if (safeIsArray(rawSelected)) {
|
|
1389
|
+
try {
|
|
1390
|
+
for (const id of rawSelected)
|
|
1391
|
+
selectedIds.push(id);
|
|
1392
|
+
}
|
|
1393
|
+
catch {
|
|
1394
|
+
// Ignore hostile array traps.
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const selectedLines = selectedIds.map((id) => {
|
|
1398
|
+
const cleanedId = clean(id);
|
|
1399
|
+
const m = (typeof id === "string" ? matchesById.get(id) : undefined) ?? matchesById.get(cleanedId);
|
|
1400
|
+
if (!m)
|
|
1401
|
+
return cleanedId;
|
|
1402
|
+
const via = list(own(m, "matchedBy")).join(", ");
|
|
1403
|
+
const files = list(own(m, "files"));
|
|
1404
|
+
const fileText = files.length ? `: ${files.slice(0, 5).join(", ")}${files.length > 5 ? ", ..." : ""}` : "";
|
|
1405
|
+
return `${cleanedId} [${clean(own(m, "domain"), 20)}] via ${via}${fileText}`;
|
|
1406
|
+
});
|
|
1407
|
+
section("Selected invariants", selectedLines);
|
|
1408
|
+
const slices = list(own(r, "affectedSliceIds"));
|
|
1409
|
+
if (slices.length > 0)
|
|
1410
|
+
lines.push(`${paint(ANSI.cyan, "Affected slices:")} ${slices.slice(0, MAX_LIST_IN_PRETTY).join(", ")}`);
|
|
1411
|
+
return `${lines.join("\n")}\n`;
|
|
1412
|
+
}
|